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.Framework.Communications.Cache;
namespace OpenSim.Region.Framework.Scenes
{
public partial class Scene
{
protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, 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.
if (broadcast)
EventManager.TriggerOnChatBroadcast(this, args);
else
EventManager.TriggerOnChatFromWorld(this, args);
}
/// <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>
/// Invoked when the client requests a prim.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void RequestPrim(uint primLocalID, IClientAPI remoteClient)
{
List<EntityBase> EntityList = GetEntities();
foreach (EntityBase ent in EntityList)
{
if (ent is SceneObjectGroup)
{
if (((SceneObjectGroup)ent).LocalId == primLocalID)
{
((SceneObjectGroup)ent).SendFullUpdateToClient(remoteClient);
return;
}
}
}
}
/// <summary>
/// Invoked when the client selects a prim.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void SelectPrim(uint primLocalID, IClientAPI remoteClient)
{
List<EntityBase> EntityList = GetEntities();
foreach (EntityBase ent in EntityList)
{
if (ent is SceneObjectGroup)
{
if (((SceneObjectGroup) ent).LocalId == primLocalID)
{
((SceneObjectGroup) ent).GetProperties(remoteClient);
((SceneObjectGroup) ent).IsSelected = true;
// A prim is only tainted if it's allowed to be edited by the person clicking it.
if (Permissions.CanEditObject(((SceneObjectGroup)ent).UUID, remoteClient.AgentId)
|| Permissions.CanMoveObject(((SceneObjectGroup)ent).UUID, remoteClient.AgentId))
{
EventManager.TriggerParcelPrimCountTainted();
}
break;
}
else
{
// We also need to check the children of this prim as they
// can be selected as well and send property information
bool foundPrim = false;
foreach (KeyValuePair<UUID, SceneObjectPart> child in ((SceneObjectGroup) ent).Children)
{
if (child.Value.LocalId == primLocalID)
{
child.Value.GetProperties(remoteClient);
foundPrim = true;
break;
}
}
if (foundPrim) break;
}
}
}
}
/// <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;
// The prim is in the process of being deleted.
if (null == part.ParentGroup.RootPart)
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;
bool isAttachment = false;
// 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;
if (part.ParentGroup.IsAttachment)
isAttachment = true;
else
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 (!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)
{
List<EntityBase> EntityList = GetEntities();
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
foreach (EntityBase ent in EntityList)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup obj = ent as SceneObjectGroup;
if (obj != null)
{
// Is this prim part of the group
if (obj.HasChildPrim(localID))
{
// Currently only grab/touch for the single prim
// the client handles rez correctly
obj.ObjectGrabHandler(localID, offsetPos, remoteClient);
SceneObjectPart part = obj.GetChildPart(localID);
// 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);
}
return;
}
}
}
}
}
public virtual void ProcessObjectDeGrab(uint localID, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
List<EntityBase> EntityList = GetEntities();
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
foreach (EntityBase ent in EntityList)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup obj = ent as SceneObjectGroup;
// Is this prim part of the group
if (obj.HasChildPrim(localID))
{
SceneObjectPart part=obj.GetChildPart(localID);
if (part != null)
{
// 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);
return;
}
return;
}
}
}
}
public void ProcessAvatarPickerRequest(IClientAPI client, UUID avatarID, UUID RequestID, string query)
{
//EventManager.TriggerAvatarPickerRequest();
List<AvatarPickerAvatar> AvatarResponses = new List<AvatarPickerAvatar>();
AvatarResponses = m_sceneGridService.GenerateAgentPickerRequestResponse(RequestID, query);
AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket) PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply);
// TODO: don't create new blocks if recycling an old packet
AvatarPickerReplyPacket.DataBlock[] searchData =
new AvatarPickerReplyPacket.DataBlock[AvatarResponses.Count];
AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock();
agentData.AgentID = avatarID;
agentData.QueryID = RequestID;
replyPacket.AgentData = agentData;
//byte[] bytes = new byte[AvatarResponses.Count*32];
int i = 0;
foreach (AvatarPickerAvatar item in AvatarResponses)
{
UUID translatedIDtem = item.AvatarID;
searchData[i] = new AvatarPickerReplyPacket.DataBlock();
searchData[i].AvatarID = translatedIDtem;
searchData[i].FirstName = Utils.StringToBytes((string) item.firstName);
searchData[i].LastName = Utils.StringToBytes((string) item.lastName);
i++;
}
if (AvatarResponses.Count == 0)
{
searchData = new AvatarPickerReplyPacket.DataBlock[0];
}
replyPacket.Data = searchData;
AvatarPickerReplyAgentDataArgs agent_data = new AvatarPickerReplyAgentDataArgs();
agent_data.AgentID = replyPacket.AgentData.AgentID;
agent_data.QueryID = replyPacket.AgentData.QueryID;
List<AvatarPickerReplyDataArgs> data_args = new List<AvatarPickerReplyDataArgs>();
for (i = 0; i < replyPacket.Data.Length; i++)
{
AvatarPickerReplyDataArgs data_arg = new AvatarPickerReplyDataArgs();
data_arg.AvatarID = replyPacket.Data[i].AvatarID;
data_arg.FirstName = replyPacket.Data[i].FirstName;
data_arg.LastName = replyPacket.Data[i].LastName;
data_args.Add(data_arg);
}
client.SendAvatarPickerReply(agent_data, data_args);
}
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
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;
}
ForEachClient(
delegate(IClientAPI client)
{
if (client.AgentId != remoteClient.AgentId)
client.SendViewerEffect(effectBlockArray);
}
);
}
/// <summary>
/// Handle a fetch inventory request from the client
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemID"></param>
/// <param name="ownerID"></param>
public void HandleFetchInventory(IClientAPI remoteClient, UUID itemID, UUID ownerID)
{
if (ownerID == CommsManager.UserProfileCacheService.LibraryRoot.Owner)
{
//m_log.Debug("request info for library item");
return;
}
InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
if (item != null)
{
remoteClient.SendInventoryItemDetails(ownerID, item);
}
// else shouldn't we send an alert message?
}
/// <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)
{
// FIXME MAYBE: We're not handling sortOrder!
// TODO: This code for looking in the folder for the library should be folded back into the
// CachedUserInfo 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 ((fold = CommsManager.UserProfileCacheService.LibraryRoot.FindFolder(folderID)) != null)
{
remoteClient.SendInventoryFolderDetails(
fold.Owner, folderID, fold.RequestListOfItems(),
fold.RequestListOfFolders(), 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 the caps inventory descendents fetch.
///
/// Since the folder structure is sent to the client on login, I believe we only need to handle items.
/// Diva comment 8/13/2009: what if someone gave us a folder in the meantime??
/// </summary>
/// <param name="agentID"></param>
/// <param name="folderID"></param>
/// <param name="ownerID"></param>
/// <param name="fetchFolders"></param>
/// <param name="fetchItems"></param>
/// <param name="sortOrder"></param>
/// <returns>null if the inventory look up failed</returns>
public InventoryCollection HandleFetchInventoryDescendentsCAPS(UUID agentID, UUID folderID, UUID ownerID,
bool fetchFolders, bool fetchItems, int sortOrder, out int version)
{
m_log.DebugFormat(
"[INVENTORY CACHE]: Fetching folders ({0}), items ({1}) from {2} for agent {3}",
fetchFolders, fetchItems, folderID, agentID);
// FIXME MAYBE: We're not handling sortOrder!
// TODO: This code for looking in the folder for the library should be folded back into the
// CachedUserInfo so that this class doesn't have to know the details (and so that multiple libraries, etc.
// can be handled transparently).
InventoryFolderImpl fold;
if ((fold = CommsManager.UserProfileCacheService.LibraryRoot.FindFolder(folderID)) != null)
{
version = 0;
InventoryCollection ret = new InventoryCollection();
ret.Folders = new List<InventoryFolderBase>();
ret.Items = fold.RequestListOfItems();
return ret;
}
InventoryCollection contents = new InventoryCollection();
if (folderID != UUID.Zero)
{
contents = InventoryService.GetFolderContent(agentID, folderID);
InventoryFolderBase containingFolder = new InventoryFolderBase();
containingFolder.ID = folderID;
containingFolder.Owner = agentID;
containingFolder = InventoryService.GetFolder(containingFolder);
version = containingFolder.Version;
}
else
{
// Lost itemsm don't really need a version
version = 1;
}
return contents;
}
/// <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 move 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);
}
}
/// <summary>
/// This should delete all the items and folders in the given directory.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
delegate void PurgeFolderDelegate(UUID userID, UUID folder);
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);
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public delegate AssemblyDefinition AssemblyResolveEventHandler (object sender, AssemblyNameReference reference);
public sealed class AssemblyResolveEventArgs : EventArgs {
readonly AssemblyNameReference reference;
public AssemblyNameReference AssemblyReference {
get { return reference; }
}
public AssemblyResolveEventArgs (AssemblyNameReference reference)
{
this.reference = reference;
}
}
#if !SILVERLIGHT && !CF
[Serializable]
#endif
public class AssemblyResolutionException : FileNotFoundException {
readonly AssemblyNameReference reference;
public AssemblyNameReference AssemblyReference {
get { return reference; }
}
public AssemblyResolutionException (AssemblyNameReference reference)
: base (string.Format ("Failed to resolve assembly: '{0}'", reference))
{
this.reference = reference;
}
#if !SILVERLIGHT && !CF
protected AssemblyResolutionException (
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base (info, context)
{
}
#endif
}
public abstract class BaseAssemblyResolver : IAssemblyResolver {
static readonly bool on_mono = Type.GetType ("Mono.Runtime") != null;
readonly Collection<string> directories;
#if !SILVERLIGHT && !CF
Collection<string> gac_paths;
#endif
public void AddSearchDirectory (string directory)
{
directories.Add (directory);
}
public void RemoveSearchDirectory (string directory)
{
directories.Remove (directory);
}
public string [] GetSearchDirectories ()
{
var directories = new string [this.directories.size];
Array.Copy (this.directories.items, directories, directories.Length);
return directories;
}
public virtual AssemblyDefinition Resolve (string fullName)
{
return Resolve (fullName, new ReaderParameters ());
}
public virtual AssemblyDefinition Resolve (string fullName, ReaderParameters parameters)
{
if (fullName == null)
throw new ArgumentNullException ("fullName");
return Resolve (AssemblyNameReference.Parse (fullName), parameters);
}
public event AssemblyResolveEventHandler ResolveFailure;
protected BaseAssemblyResolver ()
{
directories = new Collection<string> (2) { ".", "bin" };
}
AssemblyDefinition GetAssembly (string file, ReaderParameters parameters)
{
if (parameters.AssemblyResolver == null)
parameters.AssemblyResolver = this;
return ModuleDefinition.ReadModule (file, parameters).Assembly;
}
public virtual AssemblyDefinition Resolve (AssemblyNameReference name)
{
return Resolve (name, new ReaderParameters ());
}
public virtual AssemblyDefinition Resolve (AssemblyNameReference name, ReaderParameters parameters)
{
if (name == null)
throw new ArgumentNullException ("name");
if (parameters == null)
parameters = new ReaderParameters ();
var assembly = SearchDirectory (name, directories, parameters);
if (assembly != null)
return assembly;
#if !SILVERLIGHT && !CF
if (name.IsRetargetable) {
// if the reference is retargetable, zero it
name = new AssemblyNameReference (name.Name, Mixin.ZeroVersion) {
PublicKeyToken = Empty<byte>.Array,
};
}
var framework_dir = Path.GetDirectoryName (typeof (object).Module.FullyQualifiedName);
if (IsZero (name.Version)) {
assembly = SearchDirectory (name, new [] { framework_dir }, parameters);
if (assembly != null)
return assembly;
}
if (name.Name == "mscorlib") {
assembly = GetCorlib (name, parameters);
if (assembly != null)
return assembly;
}
assembly = GetAssemblyInGac (name, parameters);
if (assembly != null)
return assembly;
assembly = SearchDirectory (name, new [] { framework_dir }, parameters);
if (assembly != null)
return assembly;
#endif
if (ResolveFailure != null) {
assembly = ResolveFailure (this, name);
if (assembly != null)
return assembly;
}
throw new AssemblyResolutionException (name);
}
AssemblyDefinition SearchDirectory (AssemblyNameReference name, IEnumerable<string> directories, ReaderParameters parameters)
{
var extensions = new [] { ".exe", ".dll" };
foreach (var directory in directories) {
foreach (var extension in extensions) {
string file = Path.Combine (directory, name.Name + extension);
if (File.Exists (file))
return GetAssembly (file, parameters);
}
}
return null;
}
static bool IsZero (Version version)
{
return version.Major == 0 && version.Minor == 0 && version.Build == 0 && version.Revision == 0;
}
#if !SILVERLIGHT && !CF
AssemblyDefinition GetCorlib (AssemblyNameReference reference, ReaderParameters parameters)
{
var version = reference.Version;
var corlib = typeof (object).Assembly.GetName ();
if (corlib.Version == version || IsZero (version))
return GetAssembly (typeof (object).Module.FullyQualifiedName, parameters);
var path = Directory.GetParent (
Directory.GetParent (
typeof (object).Module.FullyQualifiedName).FullName
).FullName;
if (on_mono) {
if (version.Major == 1)
path = Path.Combine (path, "1.0");
else if (version.Major == 2) {
if (version.MajorRevision == 5)
path = Path.Combine (path, "2.1");
else
path = Path.Combine (path, "2.0");
} else if (version.Major == 4)
path = Path.Combine (path, "4.0");
else
throw new NotSupportedException ("Version not supported: " + version);
} else {
switch (version.Major) {
case 1:
if (version.MajorRevision == 3300)
path = Path.Combine (path, "v1.0.3705");
else
path = Path.Combine (path, "v1.0.5000.0");
break;
case 2:
path = Path.Combine (path, "v2.0.50727");
break;
case 4:
path = Path.Combine (path, "v4.0.30319");
break;
default:
throw new NotSupportedException ("Version not supported: " + version);
}
}
var file = Path.Combine (path, "mscorlib.dll");
if (File.Exists (file))
return GetAssembly (file, parameters);
return null;
}
static Collection<string> GetGacPaths ()
{
if (on_mono)
return GetDefaultMonoGacPaths ();
var paths = new Collection<string> (2);
var windir = Environment.GetEnvironmentVariable ("WINDIR");
if (windir == null)
return paths;
paths.Add (Path.Combine (windir, "assembly"));
paths.Add (Path.Combine (windir, Path.Combine ("Microsoft.NET", "assembly")));
return paths;
}
static Collection<string> GetDefaultMonoGacPaths ()
{
var paths = new Collection<string> (1);
var gac = GetCurrentMonoGac ();
if (gac != null)
paths.Add (gac);
var gac_paths_env = Environment.GetEnvironmentVariable ("MONO_GAC_PREFIX");
if (string.IsNullOrEmpty (gac_paths_env))
return paths;
var prefixes = gac_paths_env.Split (Path.PathSeparator);
foreach (var prefix in prefixes) {
if (string.IsNullOrEmpty (prefix))
continue;
var gac_path = Path.Combine (Path.Combine (Path.Combine (prefix, "lib"), "mono"), "gac");
if (Directory.Exists (gac_path) && !paths.Contains (gac))
paths.Add (gac_path);
}
return paths;
}
static string GetCurrentMonoGac ()
{
return Path.Combine (
Directory.GetParent (
Path.GetDirectoryName (typeof (object).Module.FullyQualifiedName)).FullName,
"gac");
}
AssemblyDefinition GetAssemblyInGac (AssemblyNameReference reference, ReaderParameters parameters)
{
if (reference.PublicKeyToken == null || reference.PublicKeyToken.Length == 0)
return null;
if (gac_paths == null)
gac_paths = GetGacPaths ();
if (on_mono)
return GetAssemblyInMonoGac (reference, parameters);
return GetAssemblyInNetGac (reference, parameters);
}
AssemblyDefinition GetAssemblyInMonoGac (AssemblyNameReference reference, ReaderParameters parameters)
{
for (int i = 0; i < gac_paths.Count; i++) {
var gac_path = gac_paths [i];
var file = GetAssemblyFile (reference, string.Empty, gac_path);
if (File.Exists (file))
return GetAssembly (file, parameters);
}
return null;
}
AssemblyDefinition GetAssemblyInNetGac (AssemblyNameReference reference, ReaderParameters parameters)
{
var gacs = new [] { "GAC_MSIL", "GAC_32", "GAC_64", "GAC" };
var prefixes = new [] { string.Empty, "v4.0_" };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < gacs.Length; j++) {
var gac = Path.Combine (gac_paths [i], gacs [j]);
var file = GetAssemblyFile (reference, prefixes [i], gac);
if (Directory.Exists (gac) && File.Exists (file))
return GetAssembly (file, parameters);
}
}
return null;
}
static string GetAssemblyFile (AssemblyNameReference reference, string prefix, string gac)
{
var gac_folder = new StringBuilder ()
.Append (prefix)
.Append (reference.Version)
.Append ("__");
for (int i = 0; i < reference.PublicKeyToken.Length; i++)
gac_folder.Append (reference.PublicKeyToken [i].ToString ("x2"));
return Path.Combine (
Path.Combine (
Path.Combine (gac, reference.Name), gac_folder.ToString ()),
reference.Name + ".dll");
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class ElementFindingTest : DriverTestFixture
{
// By.id positive
[Test]
public void ShouldBeAbleToFindASingleElementById()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.Id("linkId"));
Assert.AreEqual("linkId", element.GetAttribute("id"));
}
[Test]
[IgnoreBrowser(Browser.Android, "Bug in Android's XPath library.")]
public void ShouldBeAbleToFindMultipleElementsById()
{
driver.Url = nestedPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("2"));
Assert.AreEqual(8, elements.Count);
}
// By.id negative
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToLocateByIdASingleElementThatDoesNotExist()
{
driver.Url = formsPage;
driver.FindElement(By.Id("nonExistentButton"));
}
[Test]
public void ShouldNotBeAbleToLocateByIdMultipleElementsThatDoNotExist()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("nonExistentButton"));
Assert.AreEqual(0, elements.Count);
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void FindingASingleElementByEmptyIdShouldThrow()
{
driver.Url = formsPage;
driver.FindElement(By.Id(""));
}
[Test]
public void FindingMultipleElementsByEmptyIdShouldThrow()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id(""));
Assert.AreEqual(0, elements.Count);
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void FindingASingleElementByIdWithSpaceShouldThrow()
{
driver.Url = formsPage;
driver.FindElement(By.Id("nonexistent button"));
}
[Test]
public void FindingMultipleElementsByIdWithSpaceShouldThrow()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("nonexistent button"));
Assert.AreEqual(0, elements.Count);
}
// By.Name positive
[Test]
public void ShouldBeAbleToFindASingleElementByName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("checky"));
Assert.AreEqual("furrfu", element.GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByName()
{
driver.Url = nestedPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name("checky"));
Assert.Greater(elements.Count, 1);
}
[Test]
public void ShouldBeAbleToFindAnElementThatDoesNotSupportTheNameProperty()
{
driver.Url = nestedPage;
IWebElement element = driver.FindElement(By.Name("div1"));
Assert.AreEqual("div1", element.GetAttribute("name"));
}
// By.Name negative
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToLocateByNameASingleElementThatDoesNotExist()
{
driver.Url = formsPage;
driver.FindElement(By.Name("nonExistentButton"));
}
[Test]
public void ShouldNotBeAbleToLocateByNameMultipleElementsThatDoNotExist()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name("nonExistentButton"));
Assert.AreEqual(0, elements.Count);
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void FindingASingleElementByEmptyNameShouldThrow()
{
driver.Url = formsPage;
driver.FindElement(By.Name(""));
}
[Test]
public void FindingMultipleElementsByEmptyNameShouldThrow()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name(""));
Assert.AreEqual(0, elements.Count);
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void FindingASingleElementByNameWithSpaceShouldThrow()
{
driver.Url = formsPage;
driver.FindElement(By.Name("nonexistent button"));
}
[Test]
public void FindingMultipleElementsByNameWithSpaceShouldThrow()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name("nonexistent button"));
Assert.AreEqual(0, elements.Count);
}
// By.tagName positive
[Test]
public void ShouldBeAbleToFindASingleElementByTagName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.TagName("input"));
Assert.AreEqual("input", element.TagName.ToLower());
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByTagName()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("input"));
Assert.Greater(elements.Count, 1);
}
// By.tagName negative
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToLocateByTagNameASingleElementThatDoesNotExist()
{
driver.Url = formsPage;
driver.FindElement(By.TagName("nonExistentButton"));
}
[Test]
public void ShouldNotBeAbleToLocateByTagNameMultipleElementsThatDoNotExist()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("nonExistentButton"));
Assert.AreEqual(0, elements.Count);
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void FindingASingleElementByEmptyTagNameShouldThrow()
{
driver.Url = formsPage;
driver.FindElement(By.TagName(""));
}
[Test]
public void FindingMultipleElementsByEmptyTagNameShouldThrow()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName(""));
Assert.AreEqual(0, elements.Count);
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void FindingASingleElementByTagNameWithSpaceShouldThrow()
{
driver.Url = formsPage;
driver.FindElement(By.TagName("nonexistent button"));
}
[Test]
public void FindingMultipleElementsByTagNameWithSpaceShouldThrow()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("nonexistent button"));
Assert.AreEqual(0, elements.Count);
}
// By.ClassName positive
[Test]
public void ShouldBeAbleToFindASingleElementByClass()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("extraDiv"));
Assert.IsTrue(element.Text.StartsWith("Another div starts here."));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByClassName()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("nameC"));
Assert.Greater(elements.Count, 1);
}
[Test]
public void ShouldFindElementByClassWhenItIsTheFirstNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameA"));
Assert.AreEqual("An H2 title", element.Text);
}
[Test]
public void ShouldFindElementByClassWhenItIsTheLastNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameC"));
Assert.AreEqual("An H2 title", element.Text);
}
[Test]
public void ShouldFindElementByClassWhenItIsInTheMiddleAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameBnoise"));
Assert.AreEqual("An H2 title", element.Text);
}
[Test]
public void ShouldFindElementByClassWhenItsNameIsSurroundedByWhitespace()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("spaceAround"));
Assert.AreEqual("Spaced out", element.Text);
}
[Test]
public void ShouldFindElementsByClassWhenItsNameIsSurroundedByWhitespace()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("spaceAround"));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("Spaced out", elements[0].Text);
}
// By.ClassName negative
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotFindElementByClassWhenTheNameQueriedIsShorterThanCandidateName()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.ClassName("nameB"));
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
public void FindingASingleElementByEmptyClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElement(By.ClassName("")); });
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingMultipleElementsByEmptyClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElements(By.ClassName("")); });
}
[Test]
[ExpectedException(typeof(IllegalLocatorException))]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingASingleElementByCompoundClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.ClassName("a b"));
}
[Test]
[ExpectedException(typeof(IllegalLocatorException))]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingMultipleElementsByCompoundClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
driver.FindElements(By.ClassName("a b"));
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingASingleElementByInvalidClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElement(By.ClassName("!@#$%^&*")); });
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingMultipleElementsByInvalidClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElements(By.ClassName("!@#$%^&*")); });
}
// By.XPath positive
[Test]
public void ShouldBeAbleToFindASingleElementByXPath()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.XPath("//h1"));
Assert.AreEqual("XHTML Might Be The Future", element.Text);
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByXPath()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("//div"));
Assert.AreEqual(13, elements.Count);
}
[Test]
public void ShouldBeAbleToFindManyElementsRepeatedlyByXPath()
{
driver.Url = xhtmlTestPage;
String xpathString = "//node()[contains(@id,'id')]";
Assert.AreEqual(3, driver.FindElements(By.XPath(xpathString)).Count);
xpathString = "//node()[contains(@id,'nope')]";
Assert.AreEqual(0, driver.FindElements(By.XPath(xpathString)).Count);
}
[Test]
public void ShouldBeAbleToIdentifyElementsByClass()
{
driver.Url = xhtmlTestPage;
IWebElement header = driver.FindElement(By.XPath("//h1[@class='header']"));
Assert.AreEqual("XHTML Might Be The Future", header.Text);
}
[Test]
public void ShouldBeAbleToFindAnElementByXPathWithMultipleAttributes()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(
By.XPath("//form[@name='optional']/input[@type='submit' and @value='Click!']"));
Assert.AreEqual("input", element.TagName.ToLower());
Assert.AreEqual("Click!", element.GetAttribute("value"));
}
[Test]
public void FindingALinkByXpathShouldLocateAnElementWithTheGivenText()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.XPath("//a[text()='click me']"));
Assert.AreEqual("click me", element.Text);
}
[Test]
public void FindingALinkByXpathUsingContainsKeywordShouldWork()
{
driver.Url = nestedPage;
IWebElement element = driver.FindElement(By.XPath("//a[contains(.,'hello world')]"));
Assert.IsTrue(element.Text.Contains("hello world"));
}
// By.XPath negative
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldThrowAnExceptionWhenThereIsNoLinkToClick()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.XPath("//a[@id='Not here']"));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
[ExpectedException(typeof(InvalidSelectorException))]
public void ShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInDriverFindElement()
{
driver.Url = formsPage;
driver.FindElement(By.XPath("this][isnot][valid"));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
[ExpectedException(typeof(InvalidSelectorException))]
public void ShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInDriverFindElements()
{
if (TestUtilities.IsIE6(driver))
{
// Ignoring xpath error test in IE6
return;
}
driver.Url = formsPage;
driver.FindElements(By.XPath("this][isnot][valid"));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
[ExpectedException(typeof(InvalidSelectorException))]
public void ShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInElementFindElement()
{
driver.Url = formsPage;
IWebElement body = driver.FindElement(By.TagName("body"));
body.FindElement(By.XPath("this][isnot][valid"));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
[ExpectedException(typeof(InvalidSelectorException))]
public void ShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInElementFindElements()
{
driver.Url = formsPage;
IWebElement body = driver.FindElement(By.TagName("body"));
body.FindElements(By.XPath("this][isnot][valid"));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
[ExpectedException(typeof(InvalidSelectorException))]
public void ShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInDriverFindElement()
{
driver.Url = formsPage;
driver.FindElement(By.XPath("count(//input)"));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
[ExpectedException(typeof(InvalidSelectorException))]
public void ShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInDriverFindElements()
{
if (TestUtilities.IsIE6(driver))
{
// Ignoring xpath error test in IE6
return;
}
driver.Url = formsPage;
driver.FindElements(By.XPath("count(//input)"));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
[ExpectedException(typeof(InvalidSelectorException))]
public void ShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInElementFindElement()
{
driver.Url = formsPage;
IWebElement body = driver.FindElement(By.TagName("body"));
body.FindElement(By.XPath("count(//input)"));
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
[ExpectedException(typeof(InvalidSelectorException))]
public void ShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInElementFindElements()
{
if (TestUtilities.IsIE6(driver))
{
// Ignoring xpath error test in IE6
return;
}
driver.Url = formsPage;
IWebElement body = driver.FindElement(By.TagName("body"));
body.FindElements(By.XPath("count(//input)"));
}
// By.CssSelector positive
[Test]
public void ShouldBeAbleToFindASingleElementByCssSelector()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.CssSelector("div.content"));
Assert.AreEqual("div", element.TagName.ToLower());
Assert.AreEqual("content", element.GetAttribute("class"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByCssSelector()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.CssSelector("p"));
Assert.Greater(elements.Count, 1);
}
[Test]
public void ShouldBeAbleToFindASingleElementByCompoundCssSelector()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.CssSelector("div.extraDiv, div.content"));
Assert.AreEqual("div", element.TagName.ToLower());
Assert.AreEqual("content", element.GetAttribute("class"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByCompoundCssSelector()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.CssSelector("div.extraDiv, div.content"));
Assert.Greater(elements.Count, 1);
Assert.AreEqual("content", elements[0].GetAttribute("class"));
Assert.AreEqual("extraDiv", elements[1].GetAttribute("class"));
}
[Test]
[IgnoreBrowser(Browser.IE, "IE supports only short version option[selected]")]
public void ShouldBeAbleToFindAnElementByBooleanAttributeUsingCssSelector()
{
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("locators_tests/boolean_attribute_selected.html"));
IWebElement element = driver.FindElement(By.CssSelector("option[selected='selected']"));
Assert.AreEqual("two", element.GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToFindAnElementByBooleanAttributeUsingShortCssSelector()
{
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("locators_tests/boolean_attribute_selected.html"));
IWebElement element = driver.FindElement(By.CssSelector("option[selected]"));
Assert.AreEqual("two", element.GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToFindAnElementByBooleanAttributeUsingShortCssSelectorOnHtml4Page()
{
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("locators_tests/boolean_attribute_selected_html4.html"));
IWebElement element = driver.FindElement(By.CssSelector("option[selected]"));
Assert.AreEqual("two", element.GetAttribute("value"));
}
// By.CssSelector negative
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotFindElementByCssSelectorWhenThereIsNoSuchElement()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.CssSelector(".there-is-no-such-class"));
}
[Test]
public void ShouldNotFindElementsByCssSelectorWhenThereIsNoSuchElement()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.CssSelector(".there-is-no-such-class"));
Assert.AreEqual(0, elements.Count);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
public void FindingASingleElementByEmptyCssSelectorShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElement(By.CssSelector("")); });
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws WebDriverException")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingMultipleElementsByEmptyCssSelectorShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElements(By.CssSelector("")); });
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws InvalidElementStateException")]
public void FindingASingleElementByInvalidCssSelectorShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElement(By.CssSelector("//a/b/c[@id='1']")); });
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Throws InvalidElementStateException")]
[IgnoreBrowser(Browser.Opera, "Throws InvalidElementStateException")]
public void FindingMultipleElementsByInvalidCssSelectorShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.Throws(Is.InstanceOf<NoSuchElementException>(), () => { driver.FindElements(By.CssSelector("//a/b/c[@id='1']")); });
}
// By.linkText positive
[Test]
public void ShouldBeAbleToFindALinkByText()
{
driver.Url = xhtmlTestPage;
IWebElement link = driver.FindElement(By.LinkText("click me"));
Assert.AreEqual("click me", link.Text);
}
[Test]
public void ShouldBeAbleToFindMultipleLinksByText()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("click me"));
Assert.AreEqual(2, elements.Count, "Expected 2 links, got " + elements.Count);
}
[Test]
public void ShouldFindElementByLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.LinkText("Link=equalssign"));
Assert.AreEqual("linkWithEqualsSign", element.GetAttribute("id"));
}
[Test]
public void ShouldFindMultipleElementsByLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("Link=equalssign"));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("linkWithEqualsSign", elements[0].GetAttribute("id"));
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void FindsByLinkTextOnXhtmlPage()
{
if (TestUtilities.IsOldIE(driver))
{
// Old IE doesn't render XHTML pages, don't try loading XHTML pages in it
return;
}
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("actualXhtmlPage.xhtml"));
string linkText = "Foo";
IWebElement element = driver.FindElement(By.LinkText(linkText));
Assert.AreEqual(linkText, element.Text);
}
[Test]
[IgnoreBrowser(Browser.Remote)]
public void LinkWithFormattingTags()
{
driver.Url = (simpleTestPage);
IWebElement elem = driver.FindElement(By.Id("links"));
IWebElement res = elem.FindElement(By.PartialLinkText("link with formatting tags"));
Assert.AreEqual("link with formatting tags", res.Text);
}
[Test]
public void DriverCanGetLinkByLinkTestIgnoringTrailingWhitespace()
{
driver.Url = simpleTestPage;
IWebElement link = driver.FindElement(By.LinkText("link with trailing space"));
Assert.AreEqual("linkWithTrailingSpace", link.GetAttribute("id"));
Assert.AreEqual("link with trailing space", link.Text);
}
// By.linkText negative
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToLocateByLinkTextASingleElementThatDoesNotExist()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.LinkText("Not here either"));
}
[Test]
public void ShouldNotBeAbleToLocateByLinkTextMultipleElementsThatDoNotExist()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("Not here either"));
Assert.AreEqual(0, elements.Count);
}
// By.partialLinkText positive
[Test]
public void ShouldBeAbleToFindMultipleElementsByPartialLinkText()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.PartialLinkText("ick me"));
Assert.AreEqual(2, elements.Count);
}
[Test]
public void ShouldBeAbleToFindASingleElementByPartialLinkText()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.PartialLinkText("anon"));
Assert.IsTrue(element.Text.Contains("anon"));
}
[Test]
public void ShouldFindElementByPartialLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.PartialLinkText("Link="));
Assert.AreEqual("linkWithEqualsSign", element.GetAttribute("id"));
}
[Test]
public void ShouldFindMultipleElementsByPartialLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.PartialLinkText("Link="));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("linkWithEqualsSign", elements[0].GetAttribute("id"));
}
// Misc tests
[Test]
public void DriverShouldBeAbleToFindElementsAfterLoadingMoreThanOnePageAtATime()
{
driver.Url = formsPage;
driver.Url = xhtmlTestPage;
IWebElement link = driver.FindElement(By.LinkText("click me"));
Assert.AreEqual("click me", link.Text);
}
// You don't want to ask why this is here
[Test]
public void WhenFindingByNameShouldNotReturnById()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("id-name1"));
Assert.AreEqual("name", element.GetAttribute("value"));
element = driver.FindElement(By.Id("id-name1"));
Assert.AreEqual("id", element.GetAttribute("value"));
element = driver.FindElement(By.Name("id-name2"));
Assert.AreEqual("name", element.GetAttribute("value"));
element = driver.FindElement(By.Id("id-name2"));
Assert.AreEqual("id", element.GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToFindAHiddenElementsByName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("hidden"));
Assert.AreEqual("hidden", element.GetAttribute("name"));
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToFindAnElementOnABlankPage()
{
driver.Url = "about:blank";
driver.FindElement(By.TagName("a"));
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
[NeedsFreshDriver(BeforeTest = true)]
[IgnoreBrowser(Browser.IPhone)]
public void ShouldNotBeAbleToLocateASingleElementOnABlankPage()
{
// Note we're on the default start page for the browser at this point.
driver.FindElement(By.Id("nonExistantButton"));
}
[Test]
[IgnoreBrowser(Browser.Android, "Just not working")]
[IgnoreBrowser(Browser.Opera, "Just not working")]
[ExpectedException(typeof(StaleElementReferenceException))]
public void AnElementFoundInADifferentFrameIsStale()
{
driver.Url = missedJsReferencePage;
driver.SwitchTo().Frame("inner");
IWebElement element = driver.FindElement(By.Id("oneline"));
driver.SwitchTo().DefaultContent();
string foo = element.Text;
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void AnElementFoundInADifferentFrameViaJsCanBeUsed()
{
driver.Url = missedJsReferencePage;
try
{
driver.SwitchTo().Frame("inner");
IWebElement first = driver.FindElement(By.Id("oneline"));
driver.SwitchTo().DefaultContent();
IWebElement element = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(
"return frames[0].document.getElementById('oneline');");
driver.SwitchTo().Frame("inner");
IWebElement second = driver.FindElement(By.Id("oneline"));
Assert.AreEqual(first, element);
Assert.AreEqual(second, element);
}
finally
{
driver.SwitchTo().DefaultContent();
}
}
/////////////////////////////////////////////////
// Tests unique to the .NET bindings
/////////////////////////////////////////////////
[Test]
public void ShouldReturnTitleOfPageIfSet()
{
driver.Url = xhtmlTestPage;
Assert.AreEqual(driver.Title, "XHTML Test Page");
driver.Url = simpleTestPage;
Assert.AreEqual(driver.Title, "Hello WebDriver");
}
[Test]
public void ShouldBeAbleToClickOnLinkIdentifiedByText()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.LinkText("click me")).Click();
WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title is not 'We Arrive Here'");
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldBeAbleToClickOnLinkIdentifiedById()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.Id("linkId")).Click();
WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title is not 'We Arrive Here'");
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldFindAnElementBasedOnId()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("checky"));
Assert.IsFalse(element.Selected);
}
[Test]
public void ShouldBeAbleToFindChildrenOfANode()
{
driver.Url = selectableItemsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("/html/head"));
IWebElement head = elements[0];
ReadOnlyCollection<IWebElement> importedScripts = head.FindElements(By.TagName("script"));
Assert.AreEqual(importedScripts.Count, 3);
}
[Test]
public void ReturnAnEmptyListWhenThereAreNoChildrenOfANode()
{
driver.Url = xhtmlTestPage;
IWebElement table = driver.FindElement(By.Id("table"));
ReadOnlyCollection<IWebElement> rows = table.FindElements(By.TagName("tr"));
Assert.AreEqual(rows.Count, 0);
}
[Test]
public void ShouldFindElementsByName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("checky"));
Assert.AreEqual(element.GetAttribute("value"), "furrfu");
}
[Test]
public void ShouldFindElementsByClassWhenItIsTheFirstNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameA"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindElementsByClassWhenItIsTheLastNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameC"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindElementsByClassWhenItIsInTheMiddleAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameBnoise"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindGrandChildren()
{
driver.Url = formsPage;
IWebElement form = driver.FindElement(By.Id("nested_form"));
form.FindElement(By.Name("x"));
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotFindElementOutSideTree()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("login"));
element.FindElement(By.Name("x"));
}
[Test]
public void ShouldReturnElementsThatDoNotSupportTheNameProperty()
{
driver.Url = nestedPage;
driver.FindElement(By.Name("div1"));
// If this works, we're all good
}
[Test]
[Category("Javascript")]
public void ShouldBeAbleToClickOnLinksWithNoHrefAttribute()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.LinkText("No href"));
element.Click();
// if any exception is thrown, we won't get this far. Sanity check
Assert.AreEqual("Changed", driver.Title);
}
[Test]
[Category("Javascript")]
[ExpectedException(typeof(StaleElementReferenceException))]
public void RemovingAnElementDynamicallyFromTheDomShouldCauseAStaleRefException()
{
driver.Url = javascriptPage;
IWebElement toBeDeleted = driver.FindElement(By.Id("deleted"));
Assert.IsTrue(toBeDeleted.Displayed);
driver.FindElement(By.Id("delete")).Click();
bool displayedAfterDelete = toBeDeleted.Displayed;
}
[Test]
public void FindingByTagNameShouldNotIncludeParentElementIfSameTagType()
{
driver.Url = xhtmlTestPage;
IWebElement parent = driver.FindElement(By.Id("my_span"));
Assert.AreEqual(2, parent.FindElements(By.TagName("div")).Count);
Assert.AreEqual(2, parent.FindElements(By.TagName("span")).Count);
}
[Test]
public void FindingByCssShouldNotIncludeParentElementIfSameTagType()
{
driver.Url = xhtmlTestPage;
IWebElement parent = driver.FindElement(By.CssSelector("div#parent"));
IWebElement child = parent.FindElement(By.CssSelector("div"));
Assert.AreEqual("child", child.GetAttribute("id"));
}
[Test]
public void FindingByXPathShouldNotIncludeParentElementIfSameTagType()
{
driver.Url = xhtmlTestPage;
IWebElement parent = driver.FindElement(By.Id("my_span"));
Assert.AreEqual(2, parent.FindElements(By.TagName("div")).Count);
Assert.AreEqual(2, parent.FindElements(By.TagName("span")).Count);
}
[Test]
public void ShouldBeAbleToInjectXPathEngineIfNeeded()
{
driver.Url = alertsPage;
driver.FindElement(By.XPath("//body"));
driver.FindElement(By.XPath("//h1"));
driver.FindElement(By.XPath("//div"));
driver.FindElement(By.XPath("//p"));
driver.FindElement(By.XPath("//a"));
}
[Test]
public void ShouldFindElementByLinkTextContainingDoubleQuote()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.LinkText("link with \" (double quote)"));
Assert.AreEqual("quote", element.GetAttribute("id"));
}
[Test]
public void ShouldFindElementByLinkTextContainingBackslash()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.LinkText("link with \\ (backslash)"));
Assert.AreEqual("backslash", element.GetAttribute("id"));
}
private bool SupportsSelectorApi()
{
IJavaScriptExecutor javascriptDriver = driver as IJavaScriptExecutor;
IFindsByCssSelector cssSelectorDriver = driver as IFindsByCssSelector;
return (cssSelectorDriver != null) && (javascriptDriver != null);
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// ________ _____ __
// / _____/_______ _____ ____ ____ _/ ____\__ __ | |
// / \ ___\_ __ \\__ \ _/ ___\_/ __ \\ __\| | \| |
// \ \_\ \| | \/ / __ \_\ \___\ ___/ | | | | /| |__
// \______ /|__| (____ / \___ >\___ >|__| |____/ |____/
// \/ \/ \/ \/
// =============================================================================
// Designed & Developed by Brad Jones <brad @="bjc.id.au" />
// =============================================================================
////////////////////////////////////////////////////////////////////////////////
namespace Graceful.Tests
{
using Xunit;
using System;
using Graceful.Utils;
using System.Collections.Generic;
public class RelationshipDiscovererTests
{
[Fact]
public void SimpleManyToManyTest()
{
var discoverer = new RelationshipDiscoverer(new HashSet<Type>
{
typeof(Models.SimpleManyToManyTestModel1),
typeof(Models.SimpleManyToManyTestModel2)
});
Assert.Equal(2, discoverer.Discovered.Count);
var relation1 = discoverer.Discovered[0];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.MtoM, relation1.Type);
Assert.Equal(typeof(Models.SimpleManyToManyTestModel1), relation1.LocalType);
Assert.Equal(typeof(Models.SimpleManyToManyTestModel2), relation1.ForeignType);
Assert.Equal(typeof(Models.SimpleManyToManyTestModel1).GetProperty("Foos"), relation1.LocalProperty);
Assert.Equal(typeof(Models.SimpleManyToManyTestModel2).GetProperty("Bars"), relation1.ForeignProperty);
Assert.Equal("SimpleManyToManyTestModel1s", relation1.LocalTableName);
Assert.Equal("SimpleManyToManyTestModel2s", relation1.ForeignTableName);
Assert.Equal("SimpleManyToManyTestModel1", relation1.LocalTableNameSingular);
Assert.Equal("SimpleManyToManyTestModel2", relation1.ForeignTableNameSingular);
Assert.Equal(null, relation1.ForeignKeyTableName);
Assert.Equal(null, relation1.ForeignKeyColumnName);
Assert.Equal("SimpleManyToManyTestModel1sToSimpleManyToManyTestModel2s", relation1.PivotTableName);
Assert.Equal("SimpleManyToManyTestModel1Id", relation1.PivotTableFirstColumnName);
Assert.Equal("SimpleManyToManyTestModel2Id", relation1.PivotTableSecondColumnName);
Assert.Equal(null, relation1.LinkIdentifier);
var relation2 = discoverer.Discovered[1];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.MtoM, relation2.Type);
Assert.Equal(typeof(Models.SimpleManyToManyTestModel2), relation2.LocalType);
Assert.Equal(typeof(Models.SimpleManyToManyTestModel1), relation2.ForeignType);
Assert.Equal(typeof(Models.SimpleManyToManyTestModel2).GetProperty("Bars"), relation2.LocalProperty);
Assert.Equal(typeof(Models.SimpleManyToManyTestModel1).GetProperty("Foos"), relation2.ForeignProperty);
Assert.Equal("SimpleManyToManyTestModel2s", relation2.LocalTableName);
Assert.Equal("SimpleManyToManyTestModel1s", relation2.ForeignTableName);
Assert.Equal("SimpleManyToManyTestModel2", relation2.LocalTableNameSingular);
Assert.Equal("SimpleManyToManyTestModel1", relation2.ForeignTableNameSingular);
Assert.Equal(null, relation2.ForeignKeyTableName);
Assert.Equal(null, relation2.ForeignKeyColumnName);
Assert.Equal("SimpleManyToManyTestModel1sToSimpleManyToManyTestModel2s", relation2.PivotTableName);
Assert.Equal("SimpleManyToManyTestModel1Id", relation2.PivotTableFirstColumnName);
Assert.Equal("SimpleManyToManyTestModel2Id", relation2.PivotTableSecondColumnName);
Assert.Equal(null, relation2.LinkIdentifier);
}
[Fact]
public void MultipleManyToManyTest()
{
var discoverer = new RelationshipDiscoverer(new HashSet<Type>
{
typeof(Models.MultipleManyToManyTestModel1),
typeof(Models.MultipleManyToManyTestModel2)
});
Assert.Equal(4, discoverer.Discovered.Count);
var relation1 = discoverer.Discovered[0];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.MtoM, relation1.Type);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel1), relation1.LocalType);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel2), relation1.ForeignType);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel1).GetProperty("FooMultipleManyToManyTestModel2s"), relation1.LocalProperty);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel2).GetProperty("FooMultipleManyToManyTestModel1s"), relation1.ForeignProperty);
Assert.Equal("MultipleManyToManyTestModel1s", relation1.LocalTableName);
Assert.Equal("MultipleManyToManyTestModel2s", relation1.ForeignTableName);
Assert.Equal("MultipleManyToManyTestModel1", relation1.LocalTableNameSingular);
Assert.Equal("MultipleManyToManyTestModel2", relation1.ForeignTableNameSingular);
Assert.Equal(null, relation1.ForeignKeyTableName);
Assert.Equal(null, relation1.ForeignKeyColumnName);
Assert.Equal("MultipleManyToManyTestModel1sFooMultipleManyToManyTestModel2s", relation1.PivotTableName);
Assert.Equal("MultipleManyToManyTestModel1Id", relation1.PivotTableFirstColumnName);
Assert.Equal("MultipleManyToManyTestModel2Id", relation1.PivotTableSecondColumnName);
Assert.Equal("Foo", relation1.LinkIdentifier);
var relation2 = discoverer.Discovered[1];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.MtoM, relation2.Type);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel1), relation2.LocalType);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel2), relation2.ForeignType);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel1).GetProperty("BarMultipleManyToManyTestModel2s"), relation2.LocalProperty);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel2).GetProperty("BarMultipleManyToManyTestModel1s"), relation2.ForeignProperty);
Assert.Equal("MultipleManyToManyTestModel1s", relation2.LocalTableName);
Assert.Equal("MultipleManyToManyTestModel2s", relation2.ForeignTableName);
Assert.Equal("MultipleManyToManyTestModel1", relation2.LocalTableNameSingular);
Assert.Equal("MultipleManyToManyTestModel2", relation2.ForeignTableNameSingular);
Assert.Equal(null, relation2.ForeignKeyTableName);
Assert.Equal(null, relation2.ForeignKeyColumnName);
Assert.Equal("MultipleManyToManyTestModel1sBarMultipleManyToManyTestModel2s", relation2.PivotTableName);
Assert.Equal("MultipleManyToManyTestModel1Id", relation2.PivotTableFirstColumnName);
Assert.Equal("MultipleManyToManyTestModel2Id", relation2.PivotTableSecondColumnName);
Assert.Equal("Bar", relation2.LinkIdentifier);
var relation3 = discoverer.Discovered[2];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.MtoM, relation3.Type);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel2), relation3.LocalType);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel1), relation3.ForeignType);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel2).GetProperty("FooMultipleManyToManyTestModel1s"), relation3.LocalProperty);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel1).GetProperty("FooMultipleManyToManyTestModel2s"), relation3.ForeignProperty);
Assert.Equal("MultipleManyToManyTestModel2s", relation3.LocalTableName);
Assert.Equal("MultipleManyToManyTestModel1s", relation3.ForeignTableName);
Assert.Equal("MultipleManyToManyTestModel2", relation3.LocalTableNameSingular);
Assert.Equal("MultipleManyToManyTestModel1", relation3.ForeignTableNameSingular);
Assert.Equal(null, relation3.ForeignKeyTableName);
Assert.Equal(null, relation3.ForeignKeyColumnName);
Assert.Equal("MultipleManyToManyTestModel1sFooMultipleManyToManyTestModel2s", relation3.PivotTableName);
Assert.Equal("MultipleManyToManyTestModel1Id", relation3.PivotTableFirstColumnName);
Assert.Equal("MultipleManyToManyTestModel2Id", relation3.PivotTableSecondColumnName);
Assert.Equal("Foo", relation3.LinkIdentifier);
var relation4 = discoverer.Discovered[3];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.MtoM, relation4.Type);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel2), relation4.LocalType);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel1), relation4.ForeignType);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel2).GetProperty("BarMultipleManyToManyTestModel1s"), relation4.LocalProperty);
Assert.Equal(typeof(Models.MultipleManyToManyTestModel1).GetProperty("BarMultipleManyToManyTestModel2s"), relation4.ForeignProperty);
Assert.Equal("MultipleManyToManyTestModel2s", relation4.LocalTableName);
Assert.Equal("MultipleManyToManyTestModel1s", relation4.ForeignTableName);
Assert.Equal("MultipleManyToManyTestModel2", relation4.LocalTableNameSingular);
Assert.Equal("MultipleManyToManyTestModel1", relation4.ForeignTableNameSingular);
Assert.Equal(null, relation4.ForeignKeyTableName);
Assert.Equal(null, relation4.ForeignKeyColumnName);
Assert.Equal("MultipleManyToManyTestModel1sBarMultipleManyToManyTestModel2s", relation4.PivotTableName);
Assert.Equal("MultipleManyToManyTestModel1Id", relation4.PivotTableFirstColumnName);
Assert.Equal("MultipleManyToManyTestModel2Id", relation4.PivotTableSecondColumnName);
Assert.Equal("Bar", relation4.LinkIdentifier);
}
[Fact]
public void SimpleManyToOneTest()
{
var discoverer = new RelationshipDiscoverer(new HashSet<Type>
{
typeof(Models.SimpleManyToOneTestModel1),
typeof(Models.SimpleManyToOneTestModel2)
});
Assert.Equal(2, discoverer.Discovered.Count);
var relation1 = discoverer.Discovered[0];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.MtoO, relation1.Type);
Assert.Equal(typeof(Models.SimpleManyToOneTestModel1), relation1.LocalType);
Assert.Equal(typeof(Models.SimpleManyToOneTestModel2), relation1.ForeignType);
Assert.Equal(typeof(Models.SimpleManyToOneTestModel1).GetProperty("Foos"), relation1.LocalProperty);
Assert.Equal(typeof(Models.SimpleManyToOneTestModel2).GetProperty("Bar"), relation1.ForeignProperty);
Assert.Equal("SimpleManyToOneTestModel1s", relation1.LocalTableName);
Assert.Equal("SimpleManyToOneTestModel2s", relation1.ForeignTableName);
Assert.Equal("SimpleManyToOneTestModel1", relation1.LocalTableNameSingular);
Assert.Equal("SimpleManyToOneTestModel2", relation1.ForeignTableNameSingular);
Assert.Equal("SimpleManyToOneTestModel2s", relation1.ForeignKeyTableName);
Assert.Equal("SimpleManyToOneTestModel1Id", relation1.ForeignKeyColumnName);
Assert.Equal(null, relation1.PivotTableName);
Assert.Equal(null, relation1.PivotTableFirstColumnName);
Assert.Equal(null, relation1.PivotTableSecondColumnName);
Assert.Equal(null, relation1.LinkIdentifier);
var relation2 = discoverer.Discovered[1];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.OtoM, relation2.Type);
Assert.Equal(typeof(Models.SimpleManyToOneTestModel2), relation2.LocalType);
Assert.Equal(typeof(Models.SimpleManyToOneTestModel1), relation2.ForeignType);
Assert.Equal(typeof(Models.SimpleManyToOneTestModel2).GetProperty("Bar"), relation2.LocalProperty);
Assert.Equal(typeof(Models.SimpleManyToOneTestModel1).GetProperty("Foos"), relation2.ForeignProperty);
Assert.Equal("SimpleManyToOneTestModel2s", relation2.LocalTableName);
Assert.Equal("SimpleManyToOneTestModel1s", relation2.ForeignTableName);
Assert.Equal("SimpleManyToOneTestModel2", relation2.LocalTableNameSingular);
Assert.Equal("SimpleManyToOneTestModel1", relation2.ForeignTableNameSingular);
Assert.Equal("SimpleManyToOneTestModel2s", relation2.ForeignKeyTableName);
Assert.Equal("SimpleManyToOneTestModel1Id", relation2.ForeignKeyColumnName);
Assert.Equal(null, relation2.PivotTableName);
Assert.Equal(null, relation2.PivotTableFirstColumnName);
Assert.Equal(null, relation2.PivotTableSecondColumnName);
Assert.Equal(null, relation2.LinkIdentifier);
}
[Fact]
public void MultipleManyToOneTest()
{
var discoverer = new RelationshipDiscoverer(new HashSet<Type>
{
typeof(Models.MultipleManyToOneTestModel1),
typeof(Models.MultipleManyToOneTestModel2)
});
Assert.Equal(4, discoverer.Discovered.Count);
var relation1 = discoverer.Discovered[0];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.MtoO, relation1.Type);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel1), relation1.LocalType);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel2), relation1.ForeignType);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel1).GetProperty("FooMultipleManyToOneTestModel2s"), relation1.LocalProperty);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel2).GetProperty("FooMultipleManyToOneTestModel1"), relation1.ForeignProperty);
Assert.Equal("MultipleManyToOneTestModel1s", relation1.LocalTableName);
Assert.Equal("MultipleManyToOneTestModel2s", relation1.ForeignTableName);
Assert.Equal("MultipleManyToOneTestModel1", relation1.LocalTableNameSingular);
Assert.Equal("MultipleManyToOneTestModel2", relation1.ForeignTableNameSingular);
Assert.Equal("MultipleManyToOneTestModel2s", relation1.ForeignKeyTableName);
Assert.Equal("MultipleManyToOneTestModel1FooId", relation1.ForeignKeyColumnName);
Assert.Equal(null, relation1.PivotTableName);
Assert.Equal(null, relation1.PivotTableFirstColumnName);
Assert.Equal(null, relation1.PivotTableSecondColumnName);
Assert.Equal("Foo", relation1.LinkIdentifier);
var relation2 = discoverer.Discovered[1];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.MtoO, relation2.Type);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel1), relation2.LocalType);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel2), relation2.ForeignType);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel1).GetProperty("BarMultipleManyToOneTestModel2s"), relation2.LocalProperty);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel2).GetProperty("BarMultipleManyToOneTestModel1"), relation2.ForeignProperty);
Assert.Equal("MultipleManyToOneTestModel1s", relation2.LocalTableName);
Assert.Equal("MultipleManyToOneTestModel2s", relation2.ForeignTableName);
Assert.Equal("MultipleManyToOneTestModel1", relation2.LocalTableNameSingular);
Assert.Equal("MultipleManyToOneTestModel2", relation2.ForeignTableNameSingular);
Assert.Equal("MultipleManyToOneTestModel2s", relation2.ForeignKeyTableName);
Assert.Equal("MultipleManyToOneTestModel1BarId", relation2.ForeignKeyColumnName);
Assert.Equal(null, relation2.PivotTableName);
Assert.Equal(null, relation2.PivotTableFirstColumnName);
Assert.Equal(null, relation2.PivotTableSecondColumnName);
Assert.Equal("Bar", relation2.LinkIdentifier);
var relation3 = discoverer.Discovered[2];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.OtoM, relation3.Type);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel2), relation3.LocalType);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel1), relation3.ForeignType);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel2).GetProperty("FooMultipleManyToOneTestModel1"), relation3.LocalProperty);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel1).GetProperty("FooMultipleManyToOneTestModel2s"), relation3.ForeignProperty);
Assert.Equal("MultipleManyToOneTestModel2s", relation3.LocalTableName);
Assert.Equal("MultipleManyToOneTestModel1s", relation3.ForeignTableName);
Assert.Equal("MultipleManyToOneTestModel2", relation3.LocalTableNameSingular);
Assert.Equal("MultipleManyToOneTestModel1", relation3.ForeignTableNameSingular);
Assert.Equal("MultipleManyToOneTestModel2s", relation3.ForeignKeyTableName);
Assert.Equal("MultipleManyToOneTestModel1FooId", relation3.ForeignKeyColumnName);
Assert.Equal(null, relation3.PivotTableName);
Assert.Equal(null, relation3.PivotTableFirstColumnName);
Assert.Equal(null, relation3.PivotTableSecondColumnName);
Assert.Equal("Foo", relation3.LinkIdentifier);
var relation4 = discoverer.Discovered[3];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.OtoM, relation4.Type);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel2), relation4.LocalType);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel1), relation4.ForeignType);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel2).GetProperty("BarMultipleManyToOneTestModel1"), relation4.LocalProperty);
Assert.Equal(typeof(Models.MultipleManyToOneTestModel1).GetProperty("BarMultipleManyToOneTestModel2s"), relation4.ForeignProperty);
Assert.Equal("MultipleManyToOneTestModel2s", relation4.LocalTableName);
Assert.Equal("MultipleManyToOneTestModel1s", relation4.ForeignTableName);
Assert.Equal("MultipleManyToOneTestModel2", relation4.LocalTableNameSingular);
Assert.Equal("MultipleManyToOneTestModel1", relation4.ForeignTableNameSingular);
Assert.Equal("MultipleManyToOneTestModel2s", relation4.ForeignKeyTableName);
Assert.Equal("MultipleManyToOneTestModel1BarId", relation4.ForeignKeyColumnName);
Assert.Equal(null, relation4.PivotTableName);
Assert.Equal(null, relation4.PivotTableFirstColumnName);
Assert.Equal(null, relation4.PivotTableSecondColumnName);
Assert.Equal("Bar", relation4.LinkIdentifier);
}
[Fact]
public void SimpleOneToOneTest()
{
var discoverer = new RelationshipDiscoverer(new HashSet<Type>
{
typeof(Models.SimpleOneToOneTestModel1),
typeof(Models.SimpleOneToOneTestModel2)
});
Assert.Equal(2, discoverer.Discovered.Count);
var relation1 = discoverer.Discovered[0];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.OtoO, relation1.Type);
Assert.Equal(typeof(Models.SimpleOneToOneTestModel1), relation1.LocalType);
Assert.Equal(typeof(Models.SimpleOneToOneTestModel2), relation1.ForeignType);
Assert.Equal(typeof(Models.SimpleOneToOneTestModel1).GetProperty("Foo"), relation1.LocalProperty);
Assert.Equal(typeof(Models.SimpleOneToOneTestModel2).GetProperty("Bar"), relation1.ForeignProperty);
Assert.Equal("SimpleOneToOneTestModel1s", relation1.LocalTableName);
Assert.Equal("SimpleOneToOneTestModel2s", relation1.ForeignTableName);
Assert.Equal("SimpleOneToOneTestModel1", relation1.LocalTableNameSingular);
Assert.Equal("SimpleOneToOneTestModel2", relation1.ForeignTableNameSingular);
Assert.Equal("SimpleOneToOneTestModel1s", relation1.ForeignKeyTableName);
Assert.Equal("SimpleOneToOneTestModel2Id", relation1.ForeignKeyColumnName);
Assert.Equal(null, relation1.PivotTableName);
Assert.Equal(null, relation1.PivotTableFirstColumnName);
Assert.Equal(null, relation1.PivotTableSecondColumnName);
Assert.Equal(null, relation1.LinkIdentifier);
var relation2 = discoverer.Discovered[1];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.OtoO, relation2.Type);
Assert.Equal(typeof(Models.SimpleOneToOneTestModel2), relation2.LocalType);
Assert.Equal(typeof(Models.SimpleOneToOneTestModel1), relation2.ForeignType);
Assert.Equal(typeof(Models.SimpleOneToOneTestModel2).GetProperty("Bar"), relation2.LocalProperty);
Assert.Equal(typeof(Models.SimpleOneToOneTestModel1).GetProperty("Foo"), relation2.ForeignProperty);
Assert.Equal("SimpleOneToOneTestModel2s", relation2.LocalTableName);
Assert.Equal("SimpleOneToOneTestModel1s", relation2.ForeignTableName);
Assert.Equal("SimpleOneToOneTestModel2", relation2.LocalTableNameSingular);
Assert.Equal("SimpleOneToOneTestModel1", relation2.ForeignTableNameSingular);
Assert.Equal("SimpleOneToOneTestModel1s", relation2.ForeignKeyTableName);
Assert.Equal("SimpleOneToOneTestModel2Id", relation2.ForeignKeyColumnName);
Assert.Equal(null, relation2.PivotTableName);
Assert.Equal(null, relation2.PivotTableFirstColumnName);
Assert.Equal(null, relation2.PivotTableSecondColumnName);
Assert.Equal(null, relation2.LinkIdentifier);
}
[Fact]
public void MultipleOneToOneTest()
{
var discoverer = new RelationshipDiscoverer(new HashSet<Type>
{
typeof(Models.MultipleOneToOneTestModel1),
typeof(Models.MultipleOneToOneTestModel2)
});
Assert.Equal(4, discoverer.Discovered.Count);
var relation1 = discoverer.Discovered[0];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.OtoO, relation1.Type);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel1), relation1.LocalType);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel2), relation1.ForeignType);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel1).GetProperty("FooMultipleOneToOneTestModel2"), relation1.LocalProperty);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel2).GetProperty("FooMultipleOneToOneTestModel1"), relation1.ForeignProperty);
Assert.Equal("MultipleOneToOneTestModel1s", relation1.LocalTableName);
Assert.Equal("MultipleOneToOneTestModel2s", relation1.ForeignTableName);
Assert.Equal("MultipleOneToOneTestModel1", relation1.LocalTableNameSingular);
Assert.Equal("MultipleOneToOneTestModel2", relation1.ForeignTableNameSingular);
Assert.Equal("MultipleOneToOneTestModel1s", relation1.ForeignKeyTableName);
Assert.Equal("MultipleOneToOneTestModel2FooId", relation1.ForeignKeyColumnName);
Assert.Equal(null, relation1.PivotTableName);
Assert.Equal(null, relation1.PivotTableFirstColumnName);
Assert.Equal(null, relation1.PivotTableSecondColumnName);
Assert.Equal("Foo", relation1.LinkIdentifier);
var relation2 = discoverer.Discovered[1];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.OtoO, relation2.Type);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel1), relation2.LocalType);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel2), relation2.ForeignType);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel1).GetProperty("BarMultipleOneToOneTestModel2"), relation2.LocalProperty);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel2).GetProperty("BarMultipleOneToOneTestModel1"), relation2.ForeignProperty);
Assert.Equal("MultipleOneToOneTestModel1s", relation2.LocalTableName);
Assert.Equal("MultipleOneToOneTestModel2s", relation2.ForeignTableName);
Assert.Equal("MultipleOneToOneTestModel1", relation2.LocalTableNameSingular);
Assert.Equal("MultipleOneToOneTestModel2", relation2.ForeignTableNameSingular);
Assert.Equal("MultipleOneToOneTestModel1s", relation2.ForeignKeyTableName);
Assert.Equal("MultipleOneToOneTestModel2BarId", relation2.ForeignKeyColumnName);
Assert.Equal(null, relation2.PivotTableName);
Assert.Equal(null, relation2.PivotTableFirstColumnName);
Assert.Equal(null, relation2.PivotTableSecondColumnName);
Assert.Equal("Bar", relation2.LinkIdentifier);
var relation3 = discoverer.Discovered[2];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.OtoO, relation3.Type);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel2), relation3.LocalType);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel1), relation3.ForeignType);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel2).GetProperty("FooMultipleOneToOneTestModel1"), relation3.LocalProperty);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel1).GetProperty("FooMultipleOneToOneTestModel2"), relation3.ForeignProperty);
Assert.Equal("MultipleOneToOneTestModel2s", relation3.LocalTableName);
Assert.Equal("MultipleOneToOneTestModel1s", relation3.ForeignTableName);
Assert.Equal("MultipleOneToOneTestModel2", relation3.LocalTableNameSingular);
Assert.Equal("MultipleOneToOneTestModel1", relation3.ForeignTableNameSingular);
Assert.Equal("MultipleOneToOneTestModel1s", relation3.ForeignKeyTableName);
Assert.Equal("MultipleOneToOneTestModel2FooId", relation3.ForeignKeyColumnName);
Assert.Equal(null, relation3.PivotTableName);
Assert.Equal(null, relation3.PivotTableFirstColumnName);
Assert.Equal(null, relation3.PivotTableSecondColumnName);
Assert.Equal("Foo", relation3.LinkIdentifier);
var relation4 = discoverer.Discovered[3];
Assert.Equal(RelationshipDiscoverer.Relation.RelationType.OtoO, relation4.Type);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel2), relation4.LocalType);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel1), relation4.ForeignType);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel2).GetProperty("BarMultipleOneToOneTestModel1"), relation4.LocalProperty);
Assert.Equal(typeof(Models.MultipleOneToOneTestModel1).GetProperty("BarMultipleOneToOneTestModel2"), relation4.ForeignProperty);
Assert.Equal("MultipleOneToOneTestModel2s", relation4.LocalTableName);
Assert.Equal("MultipleOneToOneTestModel1s", relation4.ForeignTableName);
Assert.Equal("MultipleOneToOneTestModel2", relation4.LocalTableNameSingular);
Assert.Equal("MultipleOneToOneTestModel1", relation4.ForeignTableNameSingular);
Assert.Equal("MultipleOneToOneTestModel1s", relation4.ForeignKeyTableName);
Assert.Equal("MultipleOneToOneTestModel2BarId", relation4.ForeignKeyColumnName);
Assert.Equal(null, relation4.PivotTableName);
Assert.Equal(null, relation4.PivotTableFirstColumnName);
Assert.Equal(null, relation4.PivotTableSecondColumnName);
Assert.Equal("Bar", relation4.LinkIdentifier);
}
}
}
| |
// Copyright (c) 2013-2015 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
// Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
using System;
using SharpNav.Geometry;
#if MONOGAME
using Vector3 = Microsoft.Xna.Framework.Vector3;
#elif OPENTK
using Vector3 = OpenTK.Vector3;
#elif SHARPDX
using Vector3 = SharpDX.Vector3;
#endif
namespace SharpNav
{
/// <summary>
/// A class where all the small, miscellaneous math functions are stored.
/// </summary>
internal static class MathHelper
{
/// <summary>
/// Clamps an integer value to be within a specified range.
/// </summary>
/// <param name="val">The value to clamp.</param>
/// <param name="min">The inclusive minimum of the range.</param>
/// <param name="max">The inclusive maximum of the range.</param>
/// <returns>The clamped value.</returns>
internal static int Clamp(int val, int min, int max)
{
return val < min ? min : (val > max ? max : val);
}
/// <summary>
/// Clamps an integer value to be within a specified range.
/// </summary>
/// <param name="val">The value to clamp.</param>
/// <param name="min">The inclusive minimum of the range.</param>
/// <param name="max">The inclusive maximum of the range.</param>
internal static void Clamp(ref int val, int min, int max)
{
val = val < min ? min : (val > max ? max : val);
}
/// <summary>
/// Clamps an integer value to be within a specified range.
/// </summary>
/// <param name="val">The value to clamp.</param>
/// <param name="min">The inclusive minimum of the range.</param>
/// <param name="max">The inclusive maximum of the range.</param>
/// <returns>The clamped value.</returns>
internal static uint Clamp(uint val, uint min, uint max)
{
return val < min ? min : (val > max ? max : val);
}
/// <summary>
/// Clamps an integer value to be within a specified range.
/// </summary>
/// <param name="val">The value to clamp.</param>
/// <param name="min">The inclusive minimum of the range.</param>
/// <param name="max">The inclusive maximum of the range.</param>
internal static void Clamp(ref uint val, uint min, uint max)
{
val = val < min ? min : (val > max ? max : val);
}
/// <summary>
/// Clamps an integer value to be within a specified range.
/// </summary>
/// <param name="val">The value to clamp.</param>
/// <param name="min">The inclusive minimum of the range.</param>
/// <param name="max">The inclusive maximum of the range.</param>
/// <returns>The clamped value.</returns>
internal static float Clamp(float val, float min, float max)
{
return val < min ? min : (val > max ? max : val);
}
/// <summary>
/// Clamps an integer value to be within a specified range.
/// </summary>
/// <param name="val">The value to clamp.</param>
/// <param name="min">The inclusive minimum of the range.</param>
/// <param name="max">The inclusive maximum of the range.</param>
internal static void Clamp(ref float val, float min, float max)
{
val = val < min ? min : (val > max ? max : val);
}
/// <summary>
/// Normalizes a value in a specified range to be between 0 and 1.
/// </summary>
/// <param name="t">The value</param>
/// <param name="t0">The lower bound of the range.</param>
/// <param name="t1">The upper bound of the range.</param>
/// <returns>A normalized value.</returns>
public static float Normalize(float t, float t0, float t1)
{
return MathHelper.Clamp((t - t0) / (t1 - t0), 0.0f, 1.0f);
}
/// <summary>
/// Calculates the next highest power of two.
/// </summary>
/// <remarks>
/// This is a minimal method meant to be fast. There is a known edge case where an input of 0 will output 0
/// instead of the mathematically correct value of 1. It will not be fixed.
/// </remarks>
/// <param name="v">A value.</param>
/// <returns>The next power of two after the value.</returns>
internal static int NextPowerOfTwo(int v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
/// <summary>
/// Calculates the next highest power of two.
/// </summary>
/// <remarks>
/// This is a minimal method meant to be fast. There is a known edge case where an input of 0 will output 0
/// instead of the mathematically correct value of 1. It will not be fixed.
/// </remarks>
/// <param name="v">A value.</param>
/// <returns>The next power of two after the value.</returns>
internal static uint NextPowerOfTwo(uint v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
/// <summary>
/// Calculates the binary logarithm of the input.
/// </summary>
/// <remarks>
/// Inputs 0 and below have undefined output.
/// </remarks>
/// <param name="v">A value.</param>
/// <returns>The binary logarithm of v.</returns>
internal static int Log2(int v)
{
int r;
int shift;
r = (v > 0xffff) ? 1 << 4 : 0 << 4;
v >>= r;
shift = (v > 0xff) ? 1 << 3 : 0 << 3;
v >>= shift;
r |= shift;
shift = (v > 0xf) ? 1 << 2 : 0 << 2;
v >>= shift;
r |= shift;
shift = (v > 0x3) ? 1 << 1 : 0 << 1;
v >>= shift;
r |= shift;
r |= v >> 1;
return r;
}
/// <summary>
/// Calculates the binary logarithm of the input.
/// </summary>
/// <remarks>
/// An input of 0 has an undefined output.
/// </remarks>
/// <param name="v">A value.</param>
/// <returns>The binary logarithm of v.</returns>
internal static uint Log2(uint v)
{
uint r;
int shift;
r = (uint)((v > 0xffff) ? 1 << 4 : 0 << 4);
v >>= (int)r;
shift = (v > 0xff) ? 1 << 3 : 0 << 3;
v >>= shift;
r |= (uint)shift;
shift = (v > 0xf) ? 1 << 2 : 0 << 2;
v >>= shift;
r |= (uint)shift;
shift = (v > 0x3) ? 1 << 1 : 0 << 1;
v >>= shift;
r |= (uint)shift;
r |= v >> 1;
return r;
}
/// <summary>
/// Clips a polygon to a plane using the Sutherland-Hodgman algorithm.
/// </summary>
/// <param name="inVertices">The input array of vertices.</param>
/// <param name="outVertices">The output array of vertices.</param>
/// <param name="numVerts">The number of vertices to read from the arrays.</param>
/// <param name="planeX">The clip plane's X component.</param>
/// <param name="planeZ">The clip plane's Z component.</param>
/// <param name="planeD">The clip plane's D component.</param>
/// <returns>The number of vertices stored in outVertices.</returns>
internal static int ClipPolygonToPlane(Vector3[] inVertices, Vector3[] outVertices, int numVerts, float planeX, float planeZ, float planeD)
{
float[] distances = new float[12];
return ClipPolygonToPlane(inVertices, outVertices, distances, numVerts, planeX, planeZ, planeD);
}
/// <summary>
/// Clips a polygon to a plane using the Sutherland-Hodgman algorithm.
/// </summary>
/// <param name="inVertices">The input array of vertices.</param>
/// <param name="outVertices">The output array of vertices.</param>
/// <param name="distances">A buffer that stores intermediate data</param>
/// <param name="numVerts">The number of vertices to read from the arrays.</param>
/// <param name="planeX">The clip plane's X component.</param>
/// <param name="planeZ">The clip plane's Z component.</param>
/// <param name="planeD">The clip plane's D component.</param>
/// <returns>The number of vertices stored in outVertices.</returns>
internal static int ClipPolygonToPlane(Vector3[] inVertices, Vector3[] outVertices, float[] distances, int numVerts, float planeX, float planeZ, float planeD)
{
for (int i = 0; i < numVerts; i++)
distances[i] = planeX * inVertices[i].X + planeZ * inVertices[i].Z + planeD;
int m = 0;
Vector3 temp;
for (int i = 0, j = numVerts - 1; i < numVerts; j = i, i++)
{
bool inj = distances[j] >= 0;
bool ini = distances[i] >= 0;
if (inj != ini)
{
float s = distances[j] / (distances[j] - distances[i]);
Vector3.Subtract(ref inVertices[i], ref inVertices[j], out temp);
Vector3.Multiply(ref temp, s, out temp);
Vector3.Add(ref inVertices[j], ref temp, out outVertices[m]);
m++;
}
if (ini)
{
outVertices[m] = inVertices[i];
m++;
}
}
return m;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClosedXML.Excel;
using System.IO;
using MoreLinq;
namespace ClosedXML_Examples
{
public class AddingComments : IXLExample
{
public void Create(string filePath)
{
var wb = new XLWorkbook {Author = "Manuel"};
AddMiscComments(wb);
AddVisibilityComments(wb);
AddPosition(wb);
AddSignatures(wb);
AddStyleAlignment(wb);
AddColorsAndLines(wb);
AddMagins(wb);
AddProperties(wb);
AddProtection(wb);
AddSize(wb);
AddWeb(wb);
wb.SaveAs(filePath);
}
private void AddWeb(XLWorkbook wb)
{
var ws = wb.Worksheets.Add("Web");
ws.Cell("A1").Comment.Style.Web.AlternateText = "The alternate text in case you need it.";
}
private void AddSize(XLWorkbook wb)
{
var ws = wb.Worksheets.Add("Size");
// Automatic size is a copy of the property comment.Style.Alignment.AutomaticSize
// I created the duplicate because it makes more sense for it to be in Size
// but Excel has it under the Alignment tab.
ws.Cell("A2").Comment.AddText("Things are very tight around here.");
ws.Cell("A2").Comment.Style.Size.SetAutomaticSize();
ws.Cell("A4").Comment.AddText("Different size");
ws.Cell("A4").Comment.Style
.Size.SetHeight(30) // The height is set in the same units as row.Height
.Size.SetWidth(30); // The width is set in the same units as row.Width
// Set all comments to visible
ws.CellsUsed(true, c => c.HasComment).ForEach(c => c.Comment.SetVisible());
}
private void AddProtection(XLWorkbook wb)
{
var ws = wb.Worksheets.Add("Protection");
ws.Cell("A1").Comment.Style
.Protection.SetLocked(false)
.Protection.SetLockText(false);
}
private void AddProperties(XLWorkbook wb)
{
var ws = wb.Worksheets.Add("Properties");
ws.Cell("A1").Comment.Style.Properties.Positioning = XLDrawingAnchor.Absolute;
ws.Cell("A2").Comment.Style.Properties.Positioning = XLDrawingAnchor.MoveAndSizeWithCells;
ws.Cell("A3").Comment.Style.Properties.Positioning = XLDrawingAnchor.MoveWithCells;
}
private void AddMagins(XLWorkbook wb)
{
var ws = wb.Worksheets.Add("Margins");
ws.Cell("A2").Comment
.SetVisible()
.AddText("Lorem ipsum dolor sit amet, adipiscing elit. ").AddNewLine()
.AddText("Nunc elementum, sapien a ultrices, commodo nisl. ").AddNewLine()
.AddText("Consequat erat lectus a nisi. Aliquam facilisis.");
ws.Cell("A2").Comment.Style
.Margins.SetAll(0.25)
.Size.SetAutomaticSize();
}
private void AddColorsAndLines(XLWorkbook wb)
{
var ws = wb.Worksheets.Add("Colors and Lines");
ws.Cell("A2").Comment
.AddText("Now ")
.AddText("THIS").SetBold().SetFontColor(XLColor.Red)
.AddText(" is colorful!");
ws.Cell("A2").Comment.Style
.ColorsAndLines.SetFillColor(XLColor.RichCarmine)
.ColorsAndLines.SetFillTransparency(0.25) // 25% opaque
.ColorsAndLines.SetLineColor(XLColor.Blue)
.ColorsAndLines.SetLineTransparency(0.75) // 75% opaque
.ColorsAndLines.SetLineDash(XLDashStyle.LongDash)
.ColorsAndLines.SetLineStyle(XLLineStyle.ThickBetweenThin)
.ColorsAndLines.SetLineWeight(7.5);
// Set all comments to visible
ws.CellsUsed(true, c => c.HasComment).ForEach(c => c.Comment.SetVisible());
}
private void AddStyleAlignment(XLWorkbook wb)
{
var ws = wb.Worksheets.Add("Alignment");
// Automagically adjust the size of the comment to fit the contents
ws.Cell("A1").Comment.Style.Alignment.SetAutomaticSize();
ws.Cell("A1").Comment.AddText("Things are pretty tight around here");
// Default values
ws.Cell("A3").Comment
.AddText("Default Alignments:").AddNewLine()
.AddText("Vertical = Top").AddNewLine()
.AddText("Horizontal = Left").AddNewLine()
.AddText("Orientation = Left to Right");
// Let's change the alignments
ws.Cell("A8").Comment
.AddText("Vertical = Bottom").AddNewLine()
.AddText("Horizontal = Right");
ws.Cell("A8").Comment.Style
.Alignment.SetVertical(XLDrawingVerticalAlignment.Bottom)
.Alignment.SetHorizontal(XLDrawingHorizontalAlignment.Right);
// And now the orientation...
ws.Cell("D3").Comment.AddText("Orientation = Bottom to Top");
ws.Cell("D3").Comment.Style
.Alignment.SetOrientation(XLDrawingTextOrientation.BottomToTop)
.Alignment.SetAutomaticSize();
ws.Cell("E3").Comment.AddText("Orientation = Top to Bottom");
ws.Cell("E3").Comment.Style
.Alignment.SetOrientation(XLDrawingTextOrientation.TopToBottom)
.Alignment.SetAutomaticSize();
ws.Cell("F3").Comment.AddText("Orientation = Vertical");
ws.Cell("F3").Comment.Style
.Alignment.SetOrientation(XLDrawingTextOrientation.Vertical)
.Alignment.SetAutomaticSize();
// Set all comments to visible
ws.CellsUsed(true, c => c.HasComment).ForEach(c => c.Comment.SetVisible());
}
private static void AddMiscComments(XLWorkbook wb)
{
var ws = wb.Worksheets.Add("Comments");
ws.Cell("A1").SetValue("Hidden").Comment.AddText("Hidden");
ws.Cell("A2").SetValue("Visible").Comment.AddText("Visible");
ws.Cell("A3").SetValue("On Top").Comment.AddText("On Top");
ws.Cell("A4").SetValue("Underneath").Comment.AddText("Underneath");
ws.Cell("A4").Comment.Style.Alignment.SetVertical(XLDrawingVerticalAlignment.Bottom);
ws.Cell("A3").Comment.SetZOrder(ws.Cell("A4").Comment.ZOrder + 1);
ws.Cell("D9").Comment.AddText("Vertical");
ws.Cell("D9").Comment.Style.Alignment.Orientation = XLDrawingTextOrientation.Vertical;
ws.Cell("D9").Comment.Style.Size.SetAutomaticSize();
ws.Cell("E9").Comment.AddText("Top to Bottom");
ws.Cell("E9").Comment.Style.Alignment.Orientation = XLDrawingTextOrientation.TopToBottom;
ws.Cell("E9").Comment.Style.Size.SetAutomaticSize();
ws.Cell("F9").Comment.AddText("Bottom to Top");
ws.Cell("F9").Comment.Style.Alignment.Orientation = XLDrawingTextOrientation.BottomToTop;
ws.Cell("F9").Comment.Style.Size.SetAutomaticSize();
ws.Cell("E1").Comment.Position.SetColumn(5);
ws.Cell("E1").Comment.AddText("Start on Col E, on top border");
ws.Cell("E1").Comment.Style.Size.SetWidth(10);
var cE3 = ws.Cell("E3").Comment;
cE3.AddText("Size and position");
cE3.Position.SetColumn(5).SetRow(4).SetColumnOffset(7).SetRowOffset(10);
cE3.Style.Size.SetHeight(25).Size.SetWidth(10);
var cE7 = ws.Cell("E7").Comment;
cE7.Position.SetColumn(6).SetRow(7).SetColumnOffset(0).SetRowOffset(0);
cE7.Style.Size.SetHeight(ws.Row(7).Height).Size.SetWidth(ws.Column(6).Width);
ws.Cell("G1").Comment.AddText("Automatic Size");
ws.Cell("G1").Comment.Style.Alignment.SetAutomaticSize();
var cG3 = ws.Cell("G3").Comment;
cG3.SetAuthor("MDeLeon");
cG3.AddSignature();
cG3.AddText("This is a test of the emergency broadcast system.");
cG3.AddNewLine();
cG3.AddText("Do ");
cG3.AddText("NOT").SetFontColor(XLColor.RadicalRed).SetUnderline().SetBold();
cG3.AddText(" forget it.");
cG3.Style
.Size.SetWidth(25)
.Size.SetHeight(100)
.Alignment.SetDirection(XLDrawingTextDirection.LeftToRight)
.Alignment.SetHorizontal(XLDrawingHorizontalAlignment.Distributed)
.Alignment.SetVertical(XLDrawingVerticalAlignment.Center)
.Alignment.SetOrientation(XLDrawingTextOrientation.LeftToRight)
.ColorsAndLines.SetFillColor(XLColor.Cyan)
.ColorsAndLines.SetFillTransparency(0.25)
.ColorsAndLines.SetLineColor(XLColor.DarkBlue)
.ColorsAndLines.SetLineTransparency(0.75)
.ColorsAndLines.SetLineDash(XLDashStyle.DashDot)
.ColorsAndLines.SetLineStyle(XLLineStyle.ThinThick)
.ColorsAndLines.SetLineWeight(5)
.Margins.SetAll(0.25)
.Properties.SetPositioning(XLDrawingAnchor.MoveAndSizeWithCells)
.Protection.SetLocked(false)
.Protection.SetLockText(false)
.Web.SetAlternateText("This won't be released to the web");
ws.Cell("A9").Comment.SetAuthor("MDeLeon").AddSignature().AddText("Something");
ws.Cell("A9").Comment.SetBold().SetFontColor(XLColor.DarkBlue);
ws.CellsUsed(true, c => !c.Address.ToStringRelative().Equals("A1") && c.HasComment).ForEach(c => c.Comment.SetVisible());
}
private static void AddVisibilityComments(XLWorkbook wb)
{
var ws = wb.Worksheets.Add("Visibility");
// By default comments are hidden
ws.Cell("A1").SetValue("I have a hidden comment").Comment.AddText("Hidden");
// Set the comment as visible
ws.Cell("A2").Comment.SetVisible().AddText("Visible");
// The ZOrder on previous comments were 1 and 2 respectively
// here we're explicit about the ZOrder
ws.Cell("A3").Comment.SetZOrder(5).SetVisible().AddText("On Top");
// We want this comment to appear underneath the one for A3
// so we set the ZOrder to something lower
ws.Cell("A4").Comment.SetZOrder(4).SetVisible().AddText("Underneath");
ws.Cell("A4").Comment.Style.Alignment.SetVertical(XLDrawingVerticalAlignment.Bottom);
// Alternatively you could set all comments to visible with the following line:
// ws.CellsUsed(true, c => c.HasComment).ForEach(c => c.Comment.SetVisible());
ws.Columns().AdjustToContents();
}
private void AddPosition(XLWorkbook wb)
{
var ws = wb.Worksheets.Add("Position");
ws.Columns().Width = 10;
ws.Cell("A1").Comment.AddText("This is an unusual place for a comment...");
ws.Cell("A1").Comment.Position
.SetColumn(3) // Starting from the third column
.SetColumnOffset(5) // The comment will start in the middle of the third column
.SetRow(5) // Starting from the fifth row
.SetRowOffset(7.5); // The comment will start in the middle of the fifth row
// Set all comments to visible
ws.CellsUsed(true, c => c.HasComment).ForEach(c => c.Comment.SetVisible());
}
private void AddSignatures(XLWorkbook wb)
{
var ws = wb.Worksheets.Add("Signatures");
// By default the signature will be with the logged user
// ws.Cell("A2").Comment.AddSignature().AddText("Hello World!");
// You can override this by specifying the comment's author:
ws.Cell("A2").Comment
.SetAuthor("MDeLeon")
.AddSignature()
.AddText("Hello World!");
// Set all comments to visible
ws.CellsUsed(true, c => c.HasComment).ForEach(c => c.Comment.SetVisible());
}
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript {
using System;
using System.Collections;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
public class ArrayObject : JSObject{
internal const int MaxIndex = 100000;
internal const int MinDenseSize = 128;
internal uint len;
internal Object[] denseArray;
internal uint denseArrayLength;
internal ArrayObject(ScriptObject prototype)
: base(prototype){
this.len = 0;
this.denseArray = null;
this.denseArrayLength = 0;
this.noExpando = false;
}
internal ArrayObject(ScriptObject prototype, Type subType)
: base(prototype, subType) {
this.len = 0;
this.denseArray = null;
this.denseArrayLength = 0;
this.noExpando = false;
}
internal static long Array_index_for(Object index){
if (index is Int32) return (int)index;
IConvertible ic = Convert.GetIConvertible(index);
switch (Convert.GetTypeCode(index, ic)){
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Decimal:
case TypeCode.Single:
case TypeCode.Double:
double d = ic.ToDouble(null);
long l = (long)d;
if (l >= 0 && (double)l == d)
return l;
break;
}
return -1;
}
internal static long Array_index_for(String name){
int len = name.Length;
if (len <= 0) return -1;
Char ch = name[0];
if (ch < '1' || ch > '9')
if (ch == '0' && len == 1)
return 0;
else
return -1;
long result = ch - '0';
for (int i = 1; i < len; i++){
ch = name[i];
if (ch < '0' || ch > '9') return -1;
result = result*10 + (ch - '0');
if (result > UInt32.MaxValue) return -1;
}
return result;
}
internal virtual void Concat(ArrayObject source){
uint sourceLength = source.len;
if (sourceLength == 0)
return;
uint oldLength = this.len;
this.SetLength(oldLength + (ulong)sourceLength);
uint slen = sourceLength;
if (!(source is ArrayWrapper) && sourceLength > source.denseArrayLength)
slen = source.denseArrayLength;
uint j = oldLength;
for (uint i = 0; i < slen; i++)
this.SetValueAtIndex(j++, source.GetValueAtIndex(i));
if (slen == sourceLength) return;
//Iterate over the sparse indices of source
IDictionaryEnumerator e = source.NameTable.GetEnumerator();
while (e.MoveNext()){
long i = ArrayObject.Array_index_for(e.Key.ToString());
if (i >= 0)
this.SetValueAtIndex(oldLength+(uint)i, ((JSField)e.Value).GetValue(null));
}
}
internal virtual void Concat(Object value){
Array arr = value as Array;
if (arr != null && arr.Rank == 1)
this.Concat(new ArrayWrapper(ArrayPrototype.ob, arr, true));
else {
uint oldLength = this.len;
this.SetLength(1 + (ulong)oldLength);
this.SetValueAtIndex(oldLength, value);
}
}
internal override bool DeleteMember(String name){
long i = ArrayObject.Array_index_for(name);
if (i >= 0)
return this.DeleteValueAtIndex((uint)i);
else
return base.DeleteMember(name);
}
internal virtual bool DeleteValueAtIndex(uint index){
if (index < this.denseArrayLength)
if (this.denseArray[(int)index] is Missing)
return false;
else{
this.denseArray[(int)index] = Missing.Value;
return true;
}
else
return base.DeleteMember(index.ToString(CultureInfo.InvariantCulture));
}
private void DeleteRange(uint start, uint end){
uint denseEnd = this.denseArrayLength;
if (denseEnd > end)
denseEnd = end;
for (; start < denseEnd; start++)
denseArray[(int)start] = Missing.Value;
if (denseEnd == end) return;
//Go through the field table entries, deleting those with names that are indices between start and end
IDictionaryEnumerator e = this.NameTable.GetEnumerator();
ArrayList arr = new ArrayList(this.name_table.count);
while (e.MoveNext()){
long i = ArrayObject.Array_index_for(e.Key.ToString());
if (i >= start && i <= end)
arr.Add(e.Key);
}
IEnumerator ae = arr.GetEnumerator();
while (ae.MoveNext())
this.DeleteMember((String)ae.Current);
}
internal override String GetClassName(){
return "Array";
}
internal override Object GetDefaultValue(PreferredType preferred_type){
if (this.GetParent() is LenientArrayPrototype) return base.GetDefaultValue(preferred_type);
if (preferred_type == PreferredType.String){
if (!this.noExpando){
Object field = this.NameTable["toString"];
if (field != null) return base.GetDefaultValue(preferred_type);
}
return ArrayPrototype.toString(this);
}else if (preferred_type == PreferredType.LocaleString){
if (!this.noExpando){
Object field = this.NameTable["toLocaleString"];
if (field != null) return base.GetDefaultValue(preferred_type);
}
return ArrayPrototype.toLocaleString(this);
}else{
if (!this.noExpando){
Object field = this.NameTable["valueOf"];
if (field == null && preferred_type == PreferredType.Either)
field = this.NameTable["toString"];
if (field != null) return base.GetDefaultValue(preferred_type);
}
return ArrayPrototype.toString(this);
}
}
internal override void GetPropertyEnumerator(ArrayList enums, ArrayList objects){
if (this.field_table == null) this.field_table = new ArrayList();
enums.Add(new ArrayEnumerator(this, new ListEnumerator(this.field_table)));
objects.Add(this);
if (this.parent != null)
this.parent.GetPropertyEnumerator(enums, objects);
}
internal override Object GetValueAtIndex(uint index){
if (index < this.denseArrayLength){
Object result = this.denseArray[(int)index];
if (result != Missing.Value)
return result;
}
return base.GetValueAtIndex(index);
}
#if !DEBUG
[DebuggerStepThroughAttribute]
[DebuggerHiddenAttribute]
#endif
internal override Object GetMemberValue(String name){
long index = ArrayObject.Array_index_for(name);
if (index < 0)
return base.GetMemberValue(name);
else
return this.GetValueAtIndex((uint)index);
}
public virtual Object length{
get{
//Convert the length from a uint to either an int or a double. The latter two are special cased in arith operations.
if (this.len < Int32.MaxValue)
return (int)this.len;
else
return (double)this.len;
}
set{
IConvertible ic = Convert.GetIConvertible(value);
uint newLength = Convert.ToUint32(value, ic);
if ((double)newLength != Convert.ToNumber(value, ic))
throw new JScriptException(JSError.ArrayLengthAssignIncorrect);
this.SetLength(newLength);
}
}
private void Realloc(uint newLength){
Debug.PreCondition(this.denseArrayLength >= this.len);
Debug.PreCondition(newLength <= ArrayObject.MaxIndex);
uint oldDenseLength = this.denseArrayLength;
uint newDenseLength = oldDenseLength*2;
if (newDenseLength < newLength) newDenseLength = newLength;
Object[] newArray = new Object[(int)newDenseLength];
if (oldDenseLength > 0)
ArrayObject.Copy(this.denseArray, newArray, (int)oldDenseLength);
for (int i = (int)oldDenseLength; i < newDenseLength; i++)
newArray[i] = Missing.Value;
this.denseArray = newArray;
this.denseArrayLength = newDenseLength;
}
private void SetLength(ulong newLength){
uint oldLength = this.len;
if (newLength < oldLength)
this.DeleteRange((uint)newLength, oldLength);
else if (newLength > UInt32.MaxValue)
throw new JScriptException(JSError.ArrayLengthAssignIncorrect);
else if (newLength > this.denseArrayLength && oldLength <= this.denseArrayLength //The array is dense, try to keep it dense
&& newLength <= ArrayObject.MaxIndex //Small enough to keep dense
&& (newLength <= ArrayObject.MinDenseSize || newLength <= oldLength * 2)) //Close enough to existing dense part
this.Realloc((uint)newLength);
this.len = (uint)newLength;
}
#if !DEBUG
[DebuggerStepThroughAttribute]
[DebuggerHiddenAttribute]
#endif
internal override void SetMemberValue(String name, Object value){
if (name.Equals("length")){
this.length = value;
return;
}
long index = ArrayObject.Array_index_for(name);
if (index < 0)
base.SetMemberValue(name, value);
else
this.SetValueAtIndex((uint)index, value);
}
internal override void SetValueAtIndex(uint index, Object value){
if (index >= this.len && index < UInt32.MaxValue)
this.SetLength(index + 1);
if (index < this.denseArrayLength)
this.denseArray[(int)index] = value;
else
base.SetMemberValue(index.ToString(CultureInfo.InvariantCulture), value);
}
internal virtual Object Shift(){
Object res = null;
uint thisLength = this.len;
if (thisLength == 0)
return res;
uint lastItemInDense = (this.denseArrayLength >= thisLength) ? thisLength : this.denseArrayLength;
if (lastItemInDense > 0){
res = this.denseArray[0];
ArrayObject.Copy(this.denseArray, 1, this.denseArray, 0, (int)(lastItemInDense-1));
}else
res = base.GetValueAtIndex(0);
for (uint i = lastItemInDense; i < thisLength; i++)
this.SetValueAtIndex(i-1, this.GetValueAtIndex(i));
this.SetValueAtIndex(thisLength-1, Missing.Value);
SetLength(thisLength - 1);
if (res is Missing) return null;
return res;
}
internal virtual void Sort(ScriptFunction compareFn){
QuickSort qs = new QuickSort(this, compareFn);
uint length = this.len;
if (length <= this.denseArrayLength)
qs.SortArray(0, (int)length - 1);
else
qs.SortObject(0, length - 1);
}
internal virtual void Splice(uint start, uint deleteCount, Object[] args, ArrayObject outArray, uint oldLength, uint newLength){
if (oldLength > this.denseArrayLength){
SpliceSlowly(start, deleteCount, args, outArray, oldLength, newLength);
return;
}
if (newLength > oldLength){
this.SetLength(newLength);
if (newLength > this.denseArrayLength){
SpliceSlowly(start, deleteCount, args, outArray, oldLength, newLength);
return;
}
}
if (deleteCount > oldLength)
deleteCount = oldLength;
if (deleteCount > 0)
ArrayObject.Copy(this.denseArray, (int)start, outArray.denseArray, 0, (int)deleteCount);
if (oldLength > 0)
ArrayObject.Copy(this.denseArray, (int)(start+deleteCount), this.denseArray, (int)(start)+args.Length, (int)(oldLength-start-deleteCount));
if (args != null){
int n = args.Length;
if (n > 0)
ArrayObject.Copy(args, 0, this.denseArray, (int)start, n);
if (n < deleteCount)
this.SetLength(newLength);
}else if (deleteCount > 0)
this.SetLength(newLength);
}
protected void SpliceSlowly(uint start, uint deleteCount, Object[] args, ArrayObject outArray, uint oldLength, uint newLength){
for (uint i = 0; i < deleteCount; i++)
outArray.SetValueAtIndex(i, this.GetValueAtIndex(i+start));
uint n = oldLength-start-deleteCount;
if (newLength < oldLength){
for (uint i = 0; i < n; i++)
this.SetValueAtIndex(i+start+(uint)args.Length, this.GetValueAtIndex(i+start+deleteCount));
this.SetLength(newLength);
}else{
if (newLength > oldLength)
this.SetLength(newLength);
for (uint i = n; i > 0; i--)
this.SetValueAtIndex(i+start+(uint)args.Length-1, this.GetValueAtIndex(i+start+deleteCount-1));
}
int m = args == null ? 0 : args.Length;
for (uint i = 0; i < m; i++)
this.SetValueAtIndex(i+start, args[i]);
}
internal override void SwapValues(uint pi, uint qi){
if (pi > qi)
this.SwapValues(qi, pi);
else if (pi >= this.denseArrayLength)
base.SwapValues(pi, qi);
else{
Object temp = this.denseArray[(int)pi];
this.denseArray[(int)pi] = this.GetValueAtIndex(qi);
if (temp == Missing.Value)
this.DeleteValueAtIndex(qi);
else
this.SetValueAtIndex(qi, temp);
}
}
internal virtual Object[] ToArray(){
int thisLength = (int)this.len;
if (thisLength == 0)
return new Object[0];
else if (thisLength == this.denseArrayLength)
return this.denseArray;
else if (thisLength < this.denseArrayLength){
Object[] result = new Object[thisLength];
ArrayObject.Copy(this.denseArray, 0, result, 0, thisLength);
return result;
}else{
Object[] result = new Object[thisLength];
ArrayObject.Copy(this.denseArray, 0, result, 0, (int)this.denseArrayLength);
for (uint i = this.denseArrayLength; i < thisLength; i++)
result[i] = this.GetValueAtIndex(i);
return result;
}
}
internal virtual Array ToNativeArray(Type elementType){
uint n = this.len;
if (n > Int32.MaxValue)
throw new JScriptException(JSError.OutOfMemory);
if (elementType == null) elementType = typeof(Object);
uint m = this.denseArrayLength;
if (m > n) m = n;
Array result = Array.CreateInstance(elementType, (int)n);
for (int i = 0; i < m; i++)
result.SetValue(Convert.CoerceT(this.denseArray[i], elementType), i);
for (int i = (int)m; i < n; i++)
result.SetValue(Convert.CoerceT(this.GetValueAtIndex((uint)i), elementType), i);
return result;
}
internal static void Copy(Object[] source, Object[] target, int n){
ArrayObject.Copy(source, 0, target, 0, n);
}
internal static void Copy(Object[] source, int i, Object[] target, int j, int n){
if (i < j)
for (int m = n-1; m >= 0; m--)
target[j+m] = source[i+m];
else
for (int m = 0; m < n; m++)
target[j+m] = source[i+m];
}
internal virtual ArrayObject Unshift(Object[] args){
Debug.PreCondition(args != null && args.Length > 0);
uint oldLength = this.len;
int numArgs = args.Length;
ulong newLength = oldLength + (ulong)numArgs;
this.SetLength(newLength);
if (newLength <= this.denseArrayLength){
for (int i = (int)(oldLength - 1); i >= 0; i--)
this.denseArray[i+numArgs] = this.denseArray[i];
ArrayObject.Copy(args, 0, this.denseArray, 0, args.Length);
}else{
for (long i = oldLength - 1; i >= 0; i--)
this.SetValueAtIndex((uint)(i + numArgs), this.GetValueAtIndex((uint)i));
for (uint i = 0; i < numArgs; i++)
this.SetValueAtIndex(i, args[i]);
}
return this;
}
// For temporary use of the debugger - a bug in the COM+ debug API's
// causes 64 bit literal values to be not passed properly as an argument
// to a func-eval.
internal Object DebugGetValueAtIndex(int index){
return this.GetValueAtIndex((uint)index);
}
internal void DebugSetValueAtIndex(int index, Object value){
this.SetValueAtIndex((uint)index, value);
}
}
internal sealed class QuickSort{
internal ScriptFunction compareFn;
internal Object obj;
internal QuickSort(Object obj, ScriptFunction compareFn){
this.compareFn = compareFn;
this.obj = obj;
}
private int Compare(Object x, Object y){
if (x == null || x is Missing)
if (y == null || y is Missing)
return 0;
else
return 1;
else if (y == null || y is Missing)
return -1;
if (this.compareFn != null){
double result = Convert.ToNumber(this.compareFn.Call(new Object[]{x, y}, null));
if (result != result)
throw new JScriptException(JSError.NumberExpected);
return (int)Runtime.DoubleToInt64(result);
}else
return String.CompareOrdinal(Convert.ToString(x), Convert.ToString(y));
}
internal void SortObject(long left, long right){ //left and right are longs to allow for values < 0. Their positives values are always < UInt32.MaxValue.
Object x, y;
if (right > left){
long piv = left + (long)((right - left)*MathObject.random());
LateBinding.SwapValues(this.obj, (uint)piv, (uint)right);
x = LateBinding.GetValueAtIndex(this.obj, (ulong)right);
long i = left - 1, j = right;
while(true){
do{
y = LateBinding.GetValueAtIndex(this.obj, (ulong)++i);
}while(i < j && this.Compare(x, y) >= 0);
do{
y = LateBinding.GetValueAtIndex(this.obj, (ulong)--j);
}while(j > i && this.Compare(x, y) <= 0);
if (i >= j)
break;
LateBinding.SwapValues(this.obj, (uint)i, (uint)j);
}
LateBinding.SwapValues(this.obj, (uint)i, (uint)right);
this.SortObject(left, i-1);
this.SortObject(i+1, right);
}
}
internal void SortArray(int left, int right){
ArrayObject array = (ArrayObject)this.obj;
Object x, y;
if (right > left){
int piv = left + (int)((right - left)*MathObject.random());
x = array.denseArray[piv];
array.denseArray[piv] = array.denseArray[right];
array.denseArray[right] = x;
int i = left - 1, j = right;
while(true){
do{
y = array.denseArray[++i];
}while(i < j && this.Compare(x, y) >= 0);
do{
y = array.denseArray[--j];
}while(j > i && this.Compare(x, y) <= 0);
if (i >= j)
break;
QuickSort.Swap(array.denseArray, i, j);
}
QuickSort.Swap(array.denseArray, i, right);
this.SortArray(left, i-1);
this.SortArray(i+1, right);
}
}
private static void Swap(Object[] array, int i, int j){
Object temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Reflection;
namespace Microsoft.CSharp.RuntimeBinder
{
internal static class BinderHelper
{
private static MethodInfo s_DoubleIsNaN;
private static MethodInfo s_SingleIsNaN;
internal static DynamicMetaObject Bind(
DynamicMetaObjectBinder action,
RuntimeBinder binder,
DynamicMetaObject[] args,
IEnumerable<CSharpArgumentInfo> arginfos,
DynamicMetaObject onBindingError)
{
Expression[] parameters = new Expression[args.Length];
BindingRestrictions restrictions = BindingRestrictions.Empty;
ICSharpInvokeOrInvokeMemberBinder callPayload = action as ICSharpInvokeOrInvokeMemberBinder;
ParameterExpression tempForIncrement = null;
IEnumerator<CSharpArgumentInfo> arginfosEnum = (arginfos ?? Array.Empty<CSharpArgumentInfo>()).GetEnumerator();
for (int index = 0; index < args.Length; ++index)
{
DynamicMetaObject o = args[index];
// Our contract with the DLR is such that we will not enter a bind unless we have
// values for the meta-objects involved.
Debug.Assert(o.HasValue);
CSharpArgumentInfo info = arginfosEnum.MoveNext() ? arginfosEnum.Current : null;
if (index == 0 && IsIncrementOrDecrementActionOnLocal(action))
{
// We have an inc or a dec operation. Insert the temp local instead.
//
// We need to do this because for value types, the object will come
// in boxed, and we'd need to unbox it to get the original type in order
// to increment. The only way to do that is to create a new temporary.
object value = o.Value;
tempForIncrement = Expression.Variable(value != null ? value.GetType() : typeof(object), "t0");
parameters[0] = tempForIncrement;
}
else
{
parameters[index] = o.Expression;
}
BindingRestrictions r = DeduceArgumentRestriction(index, callPayload, o, info);
restrictions = restrictions.Merge(r);
// Here we check the argument info. If the argument info shows that the current argument
// is a literal constant, then we also add an instance restriction on the value of
// the constant.
if (info != null && info.LiteralConstant)
{
if (o.Value is double && double.IsNaN((double)o.Value))
{
MethodInfo isNaN = s_DoubleIsNaN ?? (s_DoubleIsNaN = typeof(double).GetMethod("IsNaN"));
Expression e = Expression.Call(null, isNaN, o.Expression);
restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction(e));
}
else if (o.Value is float && float.IsNaN((float)o.Value))
{
MethodInfo isNaN = s_SingleIsNaN ?? (s_SingleIsNaN = typeof(float).GetMethod("IsNaN"));
Expression e = Expression.Call(null, isNaN, o.Expression);
restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction(e));
}
else
{
Expression e = Expression.Equal(o.Expression, Expression.Constant(o.Value, o.Expression.Type));
r = BindingRestrictions.GetExpressionRestriction(e);
restrictions = restrictions.Merge(r);
}
}
}
// Get the bound expression.
try
{
DynamicMetaObject deferredBinding;
Expression expression = binder.Bind(action, parameters, args, out deferredBinding);
if (deferredBinding != null)
{
expression = ConvertResult(deferredBinding.Expression, action);
restrictions = deferredBinding.Restrictions.Merge(restrictions);
return new DynamicMetaObject(expression, restrictions);
}
if (tempForIncrement != null)
{
// If we have a ++ or -- payload, we need to do some temp rewriting.
// We rewrite to the following:
//
// temp = (type)o;
// temp++;
// o = temp;
// return o;
DynamicMetaObject arg0 = args[0];
expression = Expression.Block(
new[] {tempForIncrement},
Expression.Assign(tempForIncrement, Expression.Convert(arg0.Expression, arg0.Value.GetType())),
expression,
Expression.Assign(arg0.Expression, Expression.Convert(tempForIncrement, arg0.Expression.Type)));
}
expression = ConvertResult(expression, action);
return new DynamicMetaObject(expression, restrictions);
}
catch (RuntimeBinderException e)
{
if (onBindingError != null)
{
return onBindingError;
}
return new DynamicMetaObject(
Expression.Throw(
Expression.New(
typeof(RuntimeBinderException).GetConstructor(new Type[] { typeof(string) }),
Expression.Constant(e.Message)
),
GetTypeForErrorMetaObject(action, args)
),
restrictions
);
}
}
public static void ValidateBindArgument(DynamicMetaObject argument, string paramName)
{
if (argument == null)
{
throw Error.ArgumentNull(paramName);
}
if (!argument.HasValue)
{
throw Error.DynamicArgumentNeedsValue(paramName);
}
}
public static void ValidateBindArgument(DynamicMetaObject[] arguments, string paramName)
{
if (arguments != null) // null is treated as empty, so not invalid
{
for (int i = 0; i != arguments.Length; ++i)
{
ValidateBindArgument(arguments[i], $"{paramName}[{i}]");
}
}
}
/////////////////////////////////////////////////////////////////////////////////
private static bool IsTypeOfStaticCall(
int parameterIndex,
ICSharpInvokeOrInvokeMemberBinder callPayload)
{
return parameterIndex == 0 && callPayload != null && callPayload.StaticCall;
}
/////////////////////////////////////////////////////////////////////////////////
private static bool IsComObject(object obj)
{
return obj != null && Marshal.IsComObject(obj);
}
#if ENABLECOMBINDER
/////////////////////////////////////////////////////////////////////////////////
// Try to determine if this object represents a WindowsRuntime object - i.e. it either
// is coming from a WinMD file or is derived from a class coming from a WinMD.
// The logic here matches the CLR's logic of finding a WinRT object.
internal static bool IsWindowsRuntimeObject(DynamicMetaObject obj)
{
Type curType = obj?.RuntimeType;
while (curType != null)
{
TypeAttributes attributes = curType.Attributes;
if ((attributes & TypeAttributes.WindowsRuntime) == TypeAttributes.WindowsRuntime)
{
// Found a WinRT COM object
return true;
}
if ((attributes & TypeAttributes.Import) == TypeAttributes.Import)
{
// Found a class that is actually imported from COM but not WinRT
// this is definitely a non-WinRT COM object
return false;
}
curType = curType.BaseType;
}
return false;
}
#endif
/////////////////////////////////////////////////////////////////////////////////
private static bool IsTransparentProxy(object obj)
{
// In the full framework, this checks:
// return obj != null && RemotingServices.IsTransparentProxy(obj);
// but transparent proxies don't exist in .NET Core.
return false;
}
/////////////////////////////////////////////////////////////////////////////////
private static bool IsDynamicallyTypedRuntimeProxy(DynamicMetaObject argument, CSharpArgumentInfo info)
{
// This detects situations where, although the argument has a value with
// a given type, that type is insufficient to determine, statically, the
// set of reference conversions that are going to exist at bind time for
// different values. For instance, one __ComObject may allow a conversion
// to IFoo while another does not.
bool isDynamicObject =
info != null &&
!info.UseCompileTimeType &&
(IsComObject(argument.Value) || IsTransparentProxy(argument.Value));
return isDynamicObject;
}
/////////////////////////////////////////////////////////////////////////////////
private static BindingRestrictions DeduceArgumentRestriction(
int parameterIndex,
ICSharpInvokeOrInvokeMemberBinder callPayload,
DynamicMetaObject argument,
CSharpArgumentInfo info)
{
// Here we deduce what predicates the DLR can apply to future calls in order to
// determine whether to use the previously-computed-and-cached delegate, or
// whether we need to bind the site again. Ideally we would like the
// predicate to be as broad as is possible; if we can re-use analysis based
// solely on the type of the argument, that is preferable to re-using analysis
// based on object identity with a previously-analyzed argument.
// The times when we need to restrict re-use to a particular instance, rather
// than its type, are:
//
// * if the argument is a null reference then we have no type information.
//
// * if we are making a static call then the first argument is
// going to be a Type object. In this scenario we should always check
// for a specific Type object rather than restricting to the Type type.
//
// * if the argument was dynamic at compile time and it is a dynamic proxy
// object that the runtime manages, such as COM RCWs and transparent
// proxies.
//
// ** there is also a case for constant values (such as literals) to use
// something like value restrictions, and that is accomplished in Bind().
bool useValueRestriction =
argument.Value == null ||
IsTypeOfStaticCall(parameterIndex, callPayload) ||
IsDynamicallyTypedRuntimeProxy(argument, info);
return useValueRestriction ?
BindingRestrictions.GetInstanceRestriction(argument.Expression, argument.Value) :
BindingRestrictions.GetTypeRestriction(argument.Expression, argument.RuntimeType);
}
/////////////////////////////////////////////////////////////////////////////////
private static Expression ConvertResult(Expression binding, DynamicMetaObjectBinder action)
{
// Need to handle the following cases:
// (1) Call to a constructor: no conversions.
// (2) Call to a void-returning method: return null iff result is discarded.
// (3) Call to a value-type returning method: box to object.
//
// In all other cases, binding.Type should be equivalent or
// reference assignable to resultType.
var invokeConstructor = action as CSharpInvokeConstructorBinder;
if (invokeConstructor != null)
{
// No conversions needed, the call site has the correct type.
return binding;
}
if (binding.Type == typeof(void))
{
var invoke = action as ICSharpInvokeOrInvokeMemberBinder;
if (invoke != null && invoke.ResultDiscarded)
{
Debug.Assert(action.ReturnType == typeof(object));
return Expression.Block(binding, Expression.Default(action.ReturnType));
}
else
{
throw Error.BindToVoidMethodButExpectResult();
}
}
if (binding.Type.IsValueType && !action.ReturnType.IsValueType)
{
Debug.Assert(action.ReturnType == typeof(object));
return Expression.Convert(binding, action.ReturnType);
}
return binding;
}
/////////////////////////////////////////////////////////////////////////////////
private static Type GetTypeForErrorMetaObject(DynamicMetaObjectBinder action, DynamicMetaObject[] args)
{
// This is similar to ConvertResult but has fewer things to worry about.
if (action is CSharpInvokeConstructorBinder)
{
Debug.Assert(args != null);
Debug.Assert(args.Length != 0);
Debug.Assert(args[0].Value is Type);
return args[0].Value as Type;
}
return action.ReturnType;
}
/////////////////////////////////////////////////////////////////////////////////
private static bool IsIncrementOrDecrementActionOnLocal(DynamicMetaObjectBinder action)
{
CSharpUnaryOperationBinder operatorPayload = action as CSharpUnaryOperationBinder;
return operatorPayload != null &&
(operatorPayload.Operation == ExpressionType.Increment || operatorPayload.Operation == ExpressionType.Decrement);
}
/////////////////////////////////////////////////////////////////////////////////
internal static T[] Cons<T>(T sourceHead, T[] sourceTail)
{
if (sourceTail?.Length != 0)
{
T[] array = new T[sourceTail.Length + 1];
array[0] = sourceHead;
sourceTail.CopyTo(array, 1);
return array;
}
return new[] { sourceHead };
}
internal static T[] Cons<T>(T sourceHead, T[] sourceMiddle, T sourceLast)
{
if (sourceMiddle?.Length != 0)
{
T[] array = new T[sourceMiddle.Length + 2];
array[0] = sourceHead;
array[array.Length - 1] = sourceLast;
sourceMiddle.CopyTo(array, 1);
return array;
}
return new[] {sourceHead, sourceLast};
}
/////////////////////////////////////////////////////////////////////////////////
internal static T[] ToArray<T>(IEnumerable<T> source) => source == null ? Array.Empty<T>() : source.ToArray();
/////////////////////////////////////////////////////////////////////////////////
internal static CallInfo CreateCallInfo(ref IEnumerable<CSharpArgumentInfo> argInfos, int discard)
{
// This function converts the C# Binder's notion of argument information to the
// DLR's notion. The DLR counts arguments differently than C#. Here are some
// examples:
// Expression Binder C# ArgInfos DLR CallInfo
//
// d.M(1, 2, 3); CSharpInvokeMemberBinder 4 3
// d(1, 2, 3); CSharpInvokeBinder 4 3
// d[1, 2] = 3; CSharpSetIndexBinder 4 2
// d[1, 2, 3] CSharpGetIndexBinder 4 3
//
// The "discard" parameter tells this function how many of the C# arg infos it
// should not count as DLR arguments.
int argCount = 0;
List<string> argNames = new List<string>();
CSharpArgumentInfo[] infoArray = ToArray(argInfos);
argInfos = infoArray; // Write back the array to allow single enumeration.
foreach (CSharpArgumentInfo info in infoArray)
{
if (info.NamedArgument)
{
argNames.Add(info.Name);
}
++argCount;
}
Debug.Assert(discard <= argCount);
Debug.Assert(argNames.Count <= argCount - discard);
return new CallInfo(argCount - discard, argNames);
}
internal static string GetCLROperatorName(this ExpressionType p)
{
switch (p)
{
default:
return null;
// Binary Operators
case ExpressionType.Add:
return SpecialNames.CLR_Add;
case ExpressionType.Subtract:
return SpecialNames.CLR_Subtract;
case ExpressionType.Multiply:
return SpecialNames.CLR_Multiply;
case ExpressionType.Divide:
return SpecialNames.CLR_Division;
case ExpressionType.Modulo:
return SpecialNames.CLR_Modulus;
case ExpressionType.LeftShift:
return SpecialNames.CLR_LShift;
case ExpressionType.RightShift:
return SpecialNames.CLR_RShift;
case ExpressionType.LessThan:
return SpecialNames.CLR_LT;
case ExpressionType.GreaterThan:
return SpecialNames.CLR_GT;
case ExpressionType.LessThanOrEqual:
return SpecialNames.CLR_LTE;
case ExpressionType.GreaterThanOrEqual:
return SpecialNames.CLR_GTE;
case ExpressionType.Equal:
return SpecialNames.CLR_Equality;
case ExpressionType.NotEqual:
return SpecialNames.CLR_Inequality;
case ExpressionType.And:
return SpecialNames.CLR_BitwiseAnd;
case ExpressionType.ExclusiveOr:
return SpecialNames.CLR_ExclusiveOr;
case ExpressionType.Or:
return SpecialNames.CLR_BitwiseOr;
// "op_LogicalNot";
case ExpressionType.AddAssign:
return SpecialNames.CLR_InPlaceAdd;
case ExpressionType.SubtractAssign:
return SpecialNames.CLR_InPlaceSubtract;
case ExpressionType.MultiplyAssign:
return SpecialNames.CLR_InPlaceMultiply;
case ExpressionType.DivideAssign:
return SpecialNames.CLR_InPlaceDivide;
case ExpressionType.ModuloAssign:
return SpecialNames.CLR_InPlaceModulus;
case ExpressionType.AndAssign:
return SpecialNames.CLR_InPlaceBitwiseAnd;
case ExpressionType.ExclusiveOrAssign:
return SpecialNames.CLR_InPlaceExclusiveOr;
case ExpressionType.OrAssign:
return SpecialNames.CLR_InPlaceBitwiseOr;
case ExpressionType.LeftShiftAssign:
return SpecialNames.CLR_InPlaceLShift;
case ExpressionType.RightShiftAssign:
return SpecialNames.CLR_InPlaceRShift;
// Unary Operators
case ExpressionType.Negate:
return SpecialNames.CLR_UnaryNegation;
case ExpressionType.UnaryPlus:
return SpecialNames.CLR_UnaryPlus;
case ExpressionType.Not:
return SpecialNames.CLR_LogicalNot;
case ExpressionType.OnesComplement:
return SpecialNames.CLR_OnesComplement;
case ExpressionType.IsTrue:
return SpecialNames.CLR_True;
case ExpressionType.IsFalse:
return SpecialNames.CLR_False;
case ExpressionType.Increment:
return SpecialNames.CLR_PreIncrement;
case ExpressionType.Decrement:
return SpecialNames.CLR_PreDecrement;
}
}
}
}
| |
// 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.Concurrent;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Transactions.Tests
{
public class AsyncTransactionScopeTests
{
private readonly ITestOutputHelper output;
// Number of threads to create
private const int iterations = 5;
// The work queue that requests will be placed in to be serviced by the background thread
private static BlockingCollection<Tuple<int, TaskCompletionSource<object>, Transaction>> s_workQueue = new BlockingCollection<Tuple<int, TaskCompletionSource<object>, Transaction>>();
private static bool s_throwExceptionDefaultOrBeforeAwait;
private static bool s_throwExceptionAfterAwait;
public AsyncTransactionScopeTests(ITestOutputHelper output)
{
this.output = output;
}
/// <summary>
/// This test case will verify various Async TransactionScope usage with task and async/await and also nested mixed mode(legacy TS and async TS) usage.
/// </summary>
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
[InlineData(5)]
[InlineData(6)]
[InlineData(7)]
[InlineData(8)]
[InlineData(9)]
[InlineData(10)]
[InlineData(11)]
[InlineData(12)]
[InlineData(13)]
[InlineData(14)]
[InlineData(15)]
[InlineData(16)]
[InlineData(17)]
[InlineData(18)]
[InlineData(19)]
[InlineData(20)]
[InlineData(21)]
[InlineData(22)]
[InlineData(23)]
[InlineData(24)]
[InlineData(25)]
[InlineData(26)]
[InlineData(27)]
[InlineData(28)]
[InlineData(29)]
[InlineData(30)]
[InlineData(31)]
[InlineData(32)]
[InlineData(33)]
[InlineData(34)]
[InlineData(35)]
[InlineData(36)]
[InlineData(37)]
[InlineData(38)]
[InlineData(39)]
[InlineData(40)]
[InlineData(41)]
[InlineData(42)]
[InlineData(43)]
[InlineData(44)]
[InlineData(45)]
[InlineData(46)]
[InlineData(47)]
[InlineData(48)]
[InlineData(49)]
[InlineData(50)]
[InlineData(51)]
[InlineData(52)]
[InlineData(53)]
[InlineData(54)]
public void AsyncTSTest(int variation)
{
using (var listener = new TestEventListener(new Guid("8ac2d80a-1f1a-431b-ace4-bff8824aef0b"), System.Diagnostics.Tracing.EventLevel.Verbose))
{
var events = new ConcurrentQueue<EventWrittenEventArgs>();
bool success = false;
try
{
listener.RunWithCallback(events.Enqueue, () =>
{
switch (variation)
{
// Running exception test first to make sure any unintentional leak in ambient transaction during exception will be detected when subsequent test are run.
case 0:
{
HandleException(true, false, () => DoSyncTxWork(true, null));
break;
}
case 1:
{
HandleException(true, false, () => AssertTransactionNullAndWaitTask(DoAsyncTxWorkAsync(true, null)));
break;
}
case 2:
{
HandleException(true, false, () => SyncTSL2NestedTxWork(false, false, true, null));
break;
}
case 3:
{
HandleException(false, true, () => AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(false, true, false, true, false, null)));
break;
}
case 4:
{
HandleException(true, false, () => AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(false, true, true, false, false, null)));
break;
}
case 5:
{
HandleException(true, false, () => AssertTransactionNullAndWaitTask(DoAsyncTSL3SyncTSL2NestedTxWorkAsync(false, true, true, false, true, false, null)));
break;
}
case 6:
{
HandleException(false, true, () => AssertTransactionNullAndWaitTask(DoTaskWorkAsync(false, false, null)));
break;
}
case 7:
{
HandleException(false, true, () => SyncTSTaskWork(false, null));
break;
}
// The following test has Task under TransactionScope and has few variations.
case 8:
{
DoTaskUnderAsyncTS(false, null);
break;
}
case 9:
{
Task.Factory.StartNew(() => DoTaskUnderAsyncTS(false, null)).Wait();
break;
}
case 10:
{
SyncTSDoTaskUnderAsyncTS(false, false, null);
break;
}
case 11:
{
SyncTSDoTaskUnderAsyncTS(false, true, null);
break;
}
case 12:
{
Task.Factory.StartNew(() => SyncTSDoTaskUnderAsyncTS(false, true, null)).Wait();
break;
}
// Simple Sync TS test
case 13:
{
DoSyncTxWork(false, null);
break;
}
case 14:
{
DoSyncTxWork(true, null);
break;
}
// Simple Async TS test. "await" points explicitly switches threads across continuations.
case 15:
{
AssertTransactionNullAndWaitTask(DoAsyncTxWorkAsync(false, null));
break;
}
case 16:
{
AssertTransactionNullAndWaitTask(DoAsyncTxWorkAsync(true, null));
break;
}
// Nested TS test. Parent is Sync TS, child TS can be sync or async.
case 17:
{
SyncTSL2NestedTxWork(false, false, false, null);
break;
}
case 18:
{
SyncTSL2NestedTxWork(false, false, true, null);
break;
}
case 19:
{
SyncTSL2NestedTxWork(false, true, false, null);
break;
}
case 20:
{
SyncTSL2NestedTxWork(false, true, true, null);
break;
}
case 21:
{
SyncTSL2NestedTxWork(true, false, false, null);
break;
}
case 22:
{
SyncTSL2NestedTxWork(true, false, true, null);
break;
}
case 23:
{
SyncTSL2NestedTxWork(true, true, false, null);
break;
}
case 24:
{
SyncTSL2NestedTxWork(true, true, true, null);
break;
}
// 2 level deep nested TS test. Parent is Aync TS, child TS can be sync or async.
case 25:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(false, false, false, false, false, null));
break;
}
case 26:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(false, false, true, false, false, null));
break;
}
case 27:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(false, true, false, false, false, null));
break;
}
case 28:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(false, true, true, false, false, null));
break;
}
case 29:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(true, false, false, false, false, null));
break;
}
case 30:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(true, false, true, false, false, null));
break;
}
case 31:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(true, true, false, false, false, null));
break;
}
case 32:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(true, true, true, false, false, null));
break;
}
// Introduce various "await" points to switch threads before/after child TransactionScope.
// Introduce some Task variations by running the test under Task.
case 33:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(false, true, false, true, false, null));
break;
}
case 34:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(false, true, false, false, true, null));
break;
}
case 35:
{
Task.Factory.StartNew(() => AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(false, true, false, false, true, null))).Wait();
break;
}
case 36:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL2NestedTxWorkAsync(false, true, false, true, true, null));
break;
}
// 3 level deep nested TS test.
case 37:
{
SyncTSL3AsyncTSL2NestedTxWork(false, false, true, false, false, true, null);
break;
}
case 38:
{
Task.Factory.StartNew(() => SyncTSL3AsyncTSL2NestedTxWork(false, false, true, false, false, true, null)).Wait();
break;
}
case 39:
{
SyncTSL3AsyncTSL2NestedTxWork(false, false, true, false, true, false, null);
break;
}
case 40:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL3SyncTSL2NestedTxWorkAsync(false, false, false, true, false, false, null));
break;
}
case 41:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL3SyncTSL2NestedTxWorkAsync(false, false, true, false, false, true, null));
break;
}
case 42:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL3SyncTSL2NestedTxWorkAsync(false, false, true, false, true, false, null));
break;
}
case 43:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL3SyncTSL2NestedTxWorkAsync(false, false, true, false, true, true, null));
break;
}
case 44:
{
Task.Factory.StartNew(() => AssertTransactionNullAndWaitTask(DoAsyncTSL3SyncTSL2NestedTxWorkAsync(false, false, true, false, true, true, null))).Wait();
break;
}
case 45:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL3SyncTSL2NestedTxWorkAsync(false, true, true, false, false, true, null));
break;
}
case 46:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL3SyncTSL2NestedTxWorkAsync(false, true, true, false, true, false, null));
break;
}
case 47:
{
AssertTransactionNullAndWaitTask(DoAsyncTSL3SyncTSL2NestedTxWorkAsync(false, true, true, false, true, true, null));
break;
}
case 48:
{
Task.Factory.StartNew(() => AssertTransactionNullAndWaitTask(DoAsyncTSL3SyncTSL2NestedTxWorkAsync(false, true, true, false, true, true, null))).Wait();
break;
}
// Have bunch of parallel tasks running various nested TS test cases. There parallel tasks are wrapped by a TransactionScope.
case 49:
{
AssertTransactionNullAndWaitTask(DoTaskWorkAsync(false, false, null));
break;
}
case 50:
{
SyncTSTaskWork(false, null);
break;
}
case 51:
{
SyncTSTaskWork(true, null);
break;
}
case 52:
{
AssertTransactionNullAndWaitTask(DoAsyncTSTaskWorkAsync(false, false, null));
break;
}
case 53:
{
AssertTransactionNullAndWaitTask(DoAsyncTSTaskWorkAsync(true, false, null));
break;
}
// Final test - wrap the DoAsyncTSTaskWorkAsync in syncronous scope
case 54:
{
string txId1 = null;
string txId2 = null;
using (TransactionScope scope = new TransactionScope())
{
txId1 = AssertAndGetCurrentTransactionId();
Task task = DoAsyncTSTaskWorkAsync(false, false, txId1);
txId2 = AssertAndGetCurrentTransactionId();
task.Wait();
scope.Complete();
}
VerifyTxId(false, null, txId1, txId2);
break;
}
}
});
success = true;
}
finally
{
if (!success)
{
HelperFunctions.DisplaySysTxTracing(output, events);
}
}
}
}
[Theory]
[InlineData(true, false, null)]
[InlineData(true, true, null)]
public void AsyncTSAndDependantClone(bool requiresNew, bool syncronizeScope, string txId)
{
string txId1 = null;
string txId2 = null;
string txId3 = null;
string txId4 = null;
string txId5 = null;
string txId6 = null;
string txId7 = null;
Task task2;
AssertTransaction(txId);
using (TransactionScope scope1 = new TransactionScope(requiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
txId1 = AssertAndGetCurrentTransactionId();
DependentTransaction dependentTx = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
Task task1 = Task.Run(delegate
{
try
{
// Since we use BlockCommitUntilComplete dependent transaction to syncronize the root TransactionScope, the ambient Tx may not be available and will be be disposed and block on Commit.
// The flag will ensure we explicitly syncronize before disposing the root TransactionScope and the ambient transaction will still be available in the Task.
if (syncronizeScope)
{
txId2 = AssertAndGetCurrentTransactionId();
}
using (TransactionScope scope2 = new TransactionScope(dependentTx))
{
txId3 = AssertAndGetCurrentTransactionId();
Task.Delay(10).Wait();
scope2.Complete();
}
if (syncronizeScope)
{
txId4 = AssertAndGetCurrentTransactionId();
}
}
finally
{
dependentTx.Complete();
dependentTx.Dispose();
}
if (syncronizeScope)
{
txId5 = AssertAndGetCurrentTransactionId();
}
});
task2 = Task.Run(delegate
{
using (TransactionScope scope3 = new TransactionScope(TransactionScopeOption.RequiresNew))
{
txId7 = AssertAndGetCurrentTransactionId();
scope3.Complete();
}
});
txId6 = AssertAndGetCurrentTransactionId();
if (syncronizeScope)
{
task1.Wait();
}
scope1.Complete();
}
task2.Wait();
VerifyTxId(requiresNew, txId, txId1, txId6);
Assert.Equal(txId1, txId3);
Assert.Equal(txId3, txId6);
if (syncronizeScope)
{
Assert.Equal(txId1, txId2);
Assert.Equal(txId1, txId4);
Assert.Equal(txId4, txId5);
}
Assert.NotEqual(txId1, txId7);
AssertTransaction(txId);
}
[Theory]
[InlineData(true, false, null)]
[InlineData(true, true, null)]
public void NestedAsyncTSAndDependantClone(bool parentrequiresNew, bool childRequiresNew, string txId)
{
string txId1;
string txId2;
AssertTransaction(txId);
using (TransactionScope scope = new TransactionScope(parentrequiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required))
{
txId1 = AssertAndGetCurrentTransactionId();
AsyncTSAndDependantClone(childRequiresNew, true, txId1);
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
AssertTransaction(txId);
VerifyTxId(parentrequiresNew, txId, txId1, txId2);
}
private async Task DoAsyncTSTaskWorkAsync(bool requiresNew, bool parentAsync, string txId)
{
string txId1 = null;
string txId2 = null;
string txId3 = null;
string txId4 = null;
string txId5 = null;
Task task1;
int startThreadId, endThreadId;
bool parentScopePresent = false;
if (!string.IsNullOrEmpty(txId))
{
parentScopePresent = true;
}
startThreadId = Environment.CurrentManagedThreadId;
AssertTransaction(txId);
using (TransactionScope scope = new TransactionScope(requiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
txId1 = AssertAndGetCurrentTransactionId();
task1 = Task.Run(delegate
{
txId3 = AssertAndGetCurrentTransactionId();
SyncTSTaskWork(requiresNew, txId1);
txId4 = AssertAndGetCurrentTransactionId();
});
await DoTaskWorkAsync(requiresNew, true, txId1);
txId5 = AssertAndGetCurrentTransactionId();
await task1;
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
VerifyTxId(requiresNew, txId, txId1, txId2);
Assert.Equal(txId1, txId5);
endThreadId = Environment.CurrentManagedThreadId;
if (parentScopePresent)
{
if (parentAsync)
{
AssertTransaction(txId);
}
else
{
if (startThreadId != endThreadId)
{
AssertTransactionNull();
}
else
{
AssertTransaction(txId);
}
}
}
else
{
AssertTransactionNull();
}
}
private void SyncTSTaskWork(bool requiresNew, string txId)
{
string txId1 = null;
string txId2 = null;
using (TransactionScope scope = new TransactionScope(requiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required))
{
txId1 = AssertAndGetCurrentTransactionId();
Task task = DoTaskWorkAsync(requiresNew, false, txId1);
txId2 = AssertAndGetCurrentTransactionId();
task.Wait();
scope.Complete();
}
VerifyTxId(requiresNew, txId, txId1, txId2);
}
private async Task DoTaskWorkAsync(bool requiresNew, bool parentAsync, string txId)
{
string txId1 = null;
string txId2 = null;
string txId3 = null;
string txId4 = null;
string txId5 = null;
string txId6 = null;
string txId7 = null;
string txId8 = null;
string txId9 = null;
string txId10 = null;
string txId11 = null;
string txId12 = null;
string txId13 = null;
string txId14 = null;
string txId15 = null;
Task task1, task2, task3, task4, task5, task6;
int startThreadId, endThreadId;
bool parentScopePresent = false;
if (!string.IsNullOrEmpty(txId))
{
parentScopePresent = true;
}
startThreadId = Environment.CurrentManagedThreadId;
AssertTransaction(txId);
using (TransactionScope scope = new TransactionScope(requiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
txId1 = AssertAndGetCurrentTransactionId();
task1 = Task.Run(async delegate
{
txId3 = AssertAndGetCurrentTransactionId();
await DoAsyncTSL2NestedTxWorkAsync(false, false, true, false, false, txId1);
txId4 = AssertAndGetCurrentTransactionId();
});
task2 = Task.Run(async delegate
{
txId5 = AssertAndGetCurrentTransactionId();
await DoAsyncTSL2NestedTxWorkAsync(true, false, true, false, false, txId5);
txId6 = AssertAndGetCurrentTransactionId();
});
task3 = Task.Run(delegate
{
txId7 = AssertAndGetCurrentTransactionId();
NestedAsyncTSAndDependantClone(false, true, txId7);
txId8 = AssertAndGetCurrentTransactionId();
});
task4 = Task.Run(delegate
{
txId9 = AssertAndGetCurrentTransactionId();
SyncTSL2NestedTxWork(false, false, true, txId6);
txId10 = AssertAndGetCurrentTransactionId();
Task.Run(delegate
{
txId15 = AssertAndGetCurrentTransactionId();
}).Wait();
});
task5 = Task.Run(async delegate
{
txId11 = AssertAndGetCurrentTransactionId();
await DoAsyncTSL2NestedTxWorkAsync(false, true, false, false, true, txId11);
txId12 = AssertAndGetCurrentTransactionId();
});
task6 = Task.Run(delegate
{
txId13 = AssertAndGetCurrentTransactionId();
SyncTSL3AsyncTSL2NestedTxWork(false, false, true, false, false, true, txId13);
txId14 = AssertAndGetCurrentTransactionId();
});
await DoAsyncTSL2NestedTxWorkAsync(false, false, true, false, false, txId1);
txId2 = AssertAndGetCurrentTransactionId();
Task.WaitAll(task1, task2, task3, task4, task5, task6);
scope.Complete();
}
VerifyTxId(requiresNew, txId, txId1, txId2);
VerifyTxId(false, txId1, txId3, txId4);
VerifyTxId(false, txId1, txId5, txId6);
VerifyTxId(false, txId1, txId7, txId8);
VerifyTxId(false, txId1, txId9, txId10);
VerifyTxId(false, txId1, txId11, txId12);
VerifyTxId(false, txId1, txId13, txId14);
Assert.Equal(txId1, txId15);
endThreadId = Environment.CurrentManagedThreadId;
if (parentScopePresent)
{
if (parentAsync)
{
AssertTransaction(txId);
}
else
{
if (startThreadId != endThreadId)
{
AssertTransactionNull();
}
else
{
AssertTransaction(txId);
}
}
}
else
{
AssertTransactionNull();
}
}
[Fact]
public void LegacyNestedTxScope()
{
string txId1 = null;
string txId2 = null;
string txId3 = null;
string txId4 = null;
string txId5 = null;
string txId6 = null;
Debug.WriteLine("Running NestedScopeTest");
AssertTransactionNull();
// Test Sync nested TransactionScope behavior.
using (TransactionScope scope = new TransactionScope())
{
txId1 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
AssertTransactionNull();
using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Required))
{
txId2 = AssertAndGetCurrentTransactionId();
using (TransactionScope scope3 = new TransactionScope(TransactionScopeOption.Suppress))
{
AssertTransactionNull();
scope3.Complete();
}
txId6 = AssertAndGetCurrentTransactionId();
using (TransactionScope scope4 = new TransactionScope(TransactionScopeOption.RequiresNew))
{
txId3 = AssertAndGetCurrentTransactionId();
scope4.Complete();
}
txId4 = AssertAndGetCurrentTransactionId();
scope2.Complete();
}
AssertTransactionNull();
using (TransactionScope scope = new TransactionScope())
{
txId5 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
AssertTransactionNull();
Assert.Equal(txId2, txId4);
Assert.Equal(txId2, txId6);
Assert.NotEqual(txId1, txId2);
Assert.NotEqual(txId2, txId3);
Assert.NotEqual(txId1, txId5);
}
[Theory]
// Async TS nested inside Sync TS
[InlineData(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)]
// Sync TS nested inside Async TS.
[InlineData(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Suppress)]
// Async TS nested inside Async TS
[InlineData(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)]
public void VerifyNestedTxScope(TransactionScopeOption parentScopeOption, TransactionScopeAsyncFlowOption parentAsyncFlowOption, TransactionScopeOption childScopeOption, TransactionScopeAsyncFlowOption childAsyncFlowOption)
{
string txId1;
string txId2;
string txId3;
AssertTransactionNull();
using (TransactionScope parent = new TransactionScope(parentScopeOption, parentAsyncFlowOption))
{
txId1 = AssertAndGetCurrentTransactionId(parentScopeOption);
using (TransactionScope child = new TransactionScope(childScopeOption, childAsyncFlowOption))
{
txId2 = AssertAndGetCurrentTransactionId(childScopeOption);
child.Complete();
}
txId3 = AssertAndGetCurrentTransactionId(parentScopeOption);
parent.Complete();
}
AssertTransactionNull();
Assert.Equal(txId1, txId3);
switch (childScopeOption)
{
case TransactionScopeOption.Required:
if (parentScopeOption == TransactionScopeOption.Suppress)
{
Assert.NotEqual(txId1, txId2);
}
else
{
Assert.Equal(txId1, txId2);
}
break;
case TransactionScopeOption.RequiresNew:
Assert.NotEqual(txId1, txId2);
break;
case TransactionScopeOption.Suppress:
if (parentScopeOption == TransactionScopeOption.Suppress)
{
Assert.Equal(txId1, txId2);
}
else
{
Assert.NotEqual(txId1, txId2);
}
break;
}
}
[Theory]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Suppress)]
public void VerifyParentTwoChildTest(TransactionScopeAsyncFlowOption parentAsyncFlowOption, TransactionScopeOption child1ScopeOption, TransactionScopeAsyncFlowOption child1AsyncFlowOption, TransactionScopeOption child2ScopeOption, TransactionScopeAsyncFlowOption child2AsyncFlowOption)
{
string txId1;
string txId2;
string txId3;
string txId4;
string txId5;
AssertTransactionNull();
using (TransactionScope parent = new TransactionScope(parentAsyncFlowOption))
{
txId1 = AssertAndGetCurrentTransactionId();
using (TransactionScope child1 = new TransactionScope(child1ScopeOption, child1AsyncFlowOption))
{
txId2 = AssertAndGetCurrentTransactionId(child1ScopeOption);
child1.Complete();
}
txId3 = AssertAndGetCurrentTransactionId();
using (TransactionScope child2 = new TransactionScope(child2ScopeOption, child2AsyncFlowOption))
{
txId4 = AssertAndGetCurrentTransactionId(child2ScopeOption);
child2.Complete();
}
txId5 = AssertAndGetCurrentTransactionId();
parent.Complete();
}
AssertTransactionNull();
Assert.Equal(txId1, txId3);
Assert.Equal(txId3, txId5);
if (child1ScopeOption == TransactionScopeOption.Required)
{
Assert.Equal(txId1, txId2);
}
else
{
Assert.NotEqual(txId1, txId2);
if (child1ScopeOption == TransactionScopeOption.Suppress)
{
Assert.Equal(null, txId2);
}
}
if (child2ScopeOption == TransactionScopeOption.Required)
{
Assert.Equal(txId1, txId4);
}
else
{
Assert.NotEqual(txId1, txId4);
if (child2ScopeOption == TransactionScopeOption.Suppress)
{
Assert.Equal(null, txId4);
}
}
}
[Theory]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, false)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, false)]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Required, true)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, true)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, false)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Required, true)]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.RequiresNew, true)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.RequiresNew, true)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.RequiresNew, true)]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Suppress, false)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Suppress, false)]
[InlineData(TransactionScopeAsyncFlowOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeOption.Suppress, true)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Suppress, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Suppress, true)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Suppress, false)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeAsyncFlowOption.Enabled, TransactionScopeOption.Suppress, true)]
public void VerifyThreeTxScope(TransactionScopeAsyncFlowOption asyncFlowOption1, TransactionScopeAsyncFlowOption asyncFlowOption2, TransactionScopeAsyncFlowOption asyncFlowOption3, TransactionScopeOption scopeOption, bool nested)
{
string txId1;
string txId2;
string txId3;
string txId4;
string txId5;
AssertTransactionNull();
if (nested)
{
using (TransactionScope scope1 = new TransactionScope(scopeOption, asyncFlowOption1))
{
txId1 = AssertAndGetCurrentTransactionId(scopeOption);
using (TransactionScope scope2 = new TransactionScope(scopeOption, asyncFlowOption2))
{
txId2 = AssertAndGetCurrentTransactionId(scopeOption);
using (TransactionScope scope3 = new TransactionScope(scopeOption, asyncFlowOption3))
{
txId3 = AssertAndGetCurrentTransactionId(scopeOption);
scope3.Complete();
}
txId4 = AssertAndGetCurrentTransactionId(scopeOption);
scope2.Complete();
}
txId5 = AssertAndGetCurrentTransactionId(scopeOption);
scope1.Complete();
}
AssertTransactionNull();
Assert.Equal(txId1, txId5);
Assert.Equal(txId2, txId4);
if (scopeOption == TransactionScopeOption.RequiresNew)
{
Assert.NotEqual(txId1, txId2);
Assert.NotEqual(txId2, txId3);
}
else
{
Assert.Equal(txId1, txId2);
Assert.Equal(txId2, txId3);
}
}
else
{
using (TransactionScope scope1 = new TransactionScope(scopeOption, asyncFlowOption1))
{
txId1 = AssertAndGetCurrentTransactionId(scopeOption);
scope1.Complete();
}
AssertTransactionNull();
using (TransactionScope scope2 = new TransactionScope(scopeOption, asyncFlowOption2))
{
txId2 = AssertAndGetCurrentTransactionId(scopeOption);
scope2.Complete();
}
AssertTransactionNull();
using (TransactionScope scope3 = new TransactionScope(scopeOption, asyncFlowOption3))
{
txId3 = AssertAndGetCurrentTransactionId(scopeOption);
scope3.Complete();
}
if (scopeOption == TransactionScopeOption.Suppress)
{
Assert.Equal(null, txId1);
Assert.Equal(txId1, txId2);
Assert.Equal(txId2, txId3);
}
else
{
Assert.NotEqual(txId1, txId2);
Assert.NotEqual(txId2, txId3);
}
}
AssertTransactionNull();
}
[Theory]
[InlineData(TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled)]
public void VerifyBYOT(TransactionScopeAsyncFlowOption asyncFlowOption)
{
string txId1;
string txId2;
string txId3;
AssertTransactionNull();
CommittableTransaction tx = new CommittableTransaction();
Transaction.Current = tx;
txId1 = AssertAndGetCurrentTransactionId();
using (TransactionScope scope = new TransactionScope(asyncFlowOption))
{
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
txId3 = AssertAndGetCurrentTransactionId();
Transaction.Current = null;
tx.Commit();
Assert.Equal(txId1, txId2);
Assert.Equal(txId2, txId3);
AssertTransactionNull();
}
[Fact]
public void VerifyBYOTOpenConnSimulationTest()
{
// Create threads to do work
Task[] threads = new Task[iterations];
for (int i = 0; i < iterations; i++)
{
threads[i] = Task.Factory.StartNew((object o) => { SimulateOpenConnTestAsync((int)o).Wait(); }, i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Wait();
}
}
[Fact]
public void VerifyBYOTSyncTSNestedAsync()
{
string txId1;
string txId2;
AssertTransactionNull();
CommittableTransaction tx = new CommittableTransaction();
Transaction.Current = tx;
txId1 = AssertAndGetCurrentTransactionId();
SyncTSL3AsyncTSL2NestedTxWork(false, false, false, true, false, false, txId1);
txId2 = AssertAndGetCurrentTransactionId();
Transaction.Current = null;
tx.Commit();
Assert.Equal(txId1, txId2);
AssertTransactionNull();
}
[Fact]
public void VerifyBYOTAsyncTSNestedAsync()
{
string txId1;
string txId2;
AssertTransactionNull();
CommittableTransaction tx = new CommittableTransaction();
Transaction.Current = tx;
txId1 = AssertAndGetCurrentTransactionId();
Task<string> task = DoAsyncTSL3AsyncTSL2NestedTxWorkAsync(false, false, false, true, false, false, txId1);
txId2 = AssertAndGetCurrentTransactionId();
string result = task.Result;
Transaction.Current = null;
tx.Commit();
Assert.Equal(txId1, txId2);
AssertTransactionNull();
}
[Theory]
[InlineData(TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled)]
public void DoTxQueueWorkItem(TransactionScopeAsyncFlowOption asyncFlowOption)
{
string txId1;
string txId2;
ManualResetEvent waitCompletion = new ManualResetEvent(false);
AssertTransactionNull();
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, asyncFlowOption))
{
txId1 = AssertAndGetCurrentTransactionId();
ThreadSyncObject context = new ThreadSyncObject()
{
Id = txId1,
Event = waitCompletion,
RootAsyncFlowOption = asyncFlowOption
};
Task.Factory.StartNew(DoTxWork, context, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
waitCompletion.WaitOne();
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
Assert.Equal(txId1, txId2);
AssertTransactionNull();
}
[Theory]
[InlineData(TransactionScopeAsyncFlowOption.Suppress)]
[InlineData(TransactionScopeAsyncFlowOption.Enabled)]
public void DoTxNewThread(TransactionScopeAsyncFlowOption asyncFlowOption)
{
string txId1;
string txId2;
ManualResetEvent waitCompletion = new ManualResetEvent(false);
AssertTransactionNull();
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, asyncFlowOption))
{
txId1 = AssertAndGetCurrentTransactionId();
ThreadSyncObject context = new ThreadSyncObject()
{
Id = txId1,
RootAsyncFlowOption = asyncFlowOption
};
Task.Factory.StartNew(DoTxWork, context, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Wait();
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
AssertTransactionNull();
Assert.Equal(txId1, txId2);
}
private static async Task SimulateOpenConnTestAsync(int i)
{
string txId1;
string txId2;
TaskCompletionSource<object> completionSource = new TaskCompletionSource<object>();
// Start a transaction - presumably the customer would do this in our code
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
{
txId1 = AssertAndGetCurrentTransactionId();
// At some point we realize that we can't complete our work, so enqueue it to be completed later
s_workQueue.Add(Tuple.Create(i, completionSource, Transaction.Current));
// If we are the first thread kicked off, then we are also resposible to kick of the background thread which will do the work for us
if (i == 0)
{
StartWorkProcessingThread();
}
// Await for our work to be completed by the background thread, then finish the Tx
await completionSource.Task;
txId2 = AssertAndGetCurrentTransactionId();
ts.Complete();
}
Assert.Equal(txId1, txId2);
}
private static void StartWorkProcessingThread()
{
Task.Factory.StartNew(() =>
{
for (int j = 0; j < iterations; j++)
{
//Get the next item of work
var work = s_workQueue.Take();
// Set the current transaction, such that anything we call will be aware of it
Transaction.Current = work.Item3;
// Read the current transaction back and check to see if it is what we set
Assert.Equal(Transaction.Current, work.Item3);
Debug.WriteLine("{0}: {1}", work.Item1, Transaction.Current == work.Item3);
// Tell the other thread that we completed its work
work.Item2.SetResult(null);
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
private static void DoTxWork(object obj)
{
string txId1 = null;
string txId2 = null;
ThreadSyncObject context = (ThreadSyncObject)obj;
if (context.RootAsyncFlowOption == TransactionScopeAsyncFlowOption.Enabled)
{
txId1 = AssertAndGetCurrentTransactionId();
Assert.Equal(context.Id, txId1);
}
else
{
AssertTransactionNull();
}
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
if (context.RootAsyncFlowOption == TransactionScopeAsyncFlowOption.Enabled)
{
string txId3 = AssertAndGetCurrentTransactionId();
Assert.Equal(txId1, txId2);
Assert.Equal(txId1, txId3);
}
else
{
AssertTransactionNull();
}
if (context.Event != null)
{
context.Event.Set();
}
}
private static string DoSyncTxWork(bool requiresNew, string txId)
{
string txId1 = null;
string txId2 = null;
string result;
using (TransactionScope scope = new TransactionScope(requiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required))
{
txId1 = AssertAndGetCurrentTransactionId();
result = DoWork(txId1);
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
VerifyTxId(requiresNew, txId, txId1, txId2);
return result;
}
private static string DoWork(string txId)
{
string txId1 = Transaction.Current != null ? Transaction.Current.TransactionInformation.LocalIdentifier : null;
Assert.Equal(txId, txId1);
if (s_throwExceptionDefaultOrBeforeAwait)
{
throw new Exception("Sync DoWork exception!");
}
return "Hello" + " World";
}
private static async Task<string> DoAsyncTxWorkAsync(bool requiresNew, string txId)
{
string txId1 = null;
string txId2 = null;
string result;
using (TransactionScope scope = new TransactionScope(requiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
txId1 = AssertAndGetCurrentTransactionId();
result = await DoAsyncWorkAsync(txId1);
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
VerifyTxId(requiresNew, txId, txId1, txId2);
return result;
}
private static async Task<string> DoAsyncTSL2NestedTxWorkAsync(bool parentRequiresNew, bool childRequiresNew, bool asyncChild, bool asyncWorkBeforeChild, bool asyncWorkAfterChild, string txId)
{
string txId1 = null;
string txId2 = null;
string txId3 = null;
string result;
using (TransactionScope scope = new TransactionScope(parentRequiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
txId1 = AssertAndGetCurrentTransactionId();
if (asyncWorkBeforeChild)
{
result = await DoAsyncWorkAsync(txId1);
}
if (asyncChild)
{
result = await DoAsyncTxWorkAsync(childRequiresNew, txId1);
}
else
{
result = DoSyncTxWork(childRequiresNew, txId1);
}
txId3 = AssertAndGetCurrentTransactionId();
if (asyncWorkAfterChild)
{
result = await DoAsyncWorkAsync(txId1);
}
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
VerifyTxId(parentRequiresNew, txId, txId1, txId2);
VerifyTxId(parentRequiresNew, txId, txId1, txId3);
return result;
}
private static string SyncTSL2NestedTxWork(bool parentRequiresNew, bool childRequiresNew, bool asyncChild, string txId)
{
string txId1 = null;
string txId2 = null;
Task<string> task = null;
string result = null;
using (TransactionScope scope = new TransactionScope(parentRequiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required))
{
txId1 = AssertAndGetCurrentTransactionId();
if (asyncChild)
{
task = DoAsyncTxWorkAsync(childRequiresNew, txId1);
}
else
{
result = DoSyncTxWork(childRequiresNew, txId1);
}
if (asyncChild)
{
result = task.Result;
}
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
VerifyTxId(parentRequiresNew, txId, txId1, txId2);
return result;
}
private static void SyncTSL3AsyncTSL2NestedTxWork(bool parentRequiresNew, bool childL2RequiresNew, bool childL3RequiresNew, bool asyncChildL3, bool asyncWorkBeforeChildL3, bool asyncWorkAfterChildL3, string txId)
{
string txId1;
string txId2;
AssertTransaction(txId);
using (TransactionScope scope = new TransactionScope(parentRequiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required))
{
txId1 = AssertAndGetCurrentTransactionId();
Task<string> task = DoAsyncTSL2NestedTxWorkAsync(childL2RequiresNew, childL3RequiresNew, asyncChildL3, asyncWorkBeforeChildL3, asyncWorkAfterChildL3, txId1);
txId2 = AssertAndGetCurrentTransactionId();
task.Wait();
scope.Complete();
}
VerifyTxId(parentRequiresNew, txId, txId1, txId2);
AssertTransaction(txId);
}
private static void SyncTSL3SyncTSL2NestedTxWork(bool parentRequiresNew, bool childL2RequiresNew, bool childL3RequiresNew, bool asyncChildL3, string txId)
{
string txId1;
string txId2;
AssertTransaction(txId);
using (TransactionScope scope = new TransactionScope(parentRequiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required))
{
txId1 = AssertAndGetCurrentTransactionId();
SyncTSL2NestedTxWork(childL2RequiresNew, childL3RequiresNew, asyncChildL3, txId1);
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
VerifyTxId(parentRequiresNew, txId, txId1, txId2);
AssertTransaction(txId);
}
private static async Task<string> DoAsyncTSL3AsyncTSL2NestedTxWorkAsync(bool parentRequiresNew, bool childL2RequiresNew, bool childL3RequiresNew, bool asyncChildL3, bool asyncWorkBeforeChildL3, bool asyncWorkAfterChildL3, string txId)
{
string txId1;
string txId2;
string result = null;
AssertTransaction(txId);
using (TransactionScope scope = new TransactionScope(parentRequiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
txId1 = AssertAndGetCurrentTransactionId();
result = await DoAsyncTSL2NestedTxWorkAsync(childL2RequiresNew, childL3RequiresNew, asyncChildL3, asyncWorkBeforeChildL3, asyncWorkAfterChildL3, txId1);
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
VerifyTxId(parentRequiresNew, txId, txId1, txId2);
return result;
}
private static async Task<string> DoAsyncTSL3SyncTSL2NestedTxWorkAsync(bool parentRequiresNew, bool childL2RequiresNew, bool childL3RequiresNew, bool asyncChildL3, bool asyncWorkBeforeChildL2, bool asyncWorkAfterChildL2, string txId)
{
string txId1;
string txId2;
string txId3;
string result = null;
AssertTransaction(txId);
using (TransactionScope scope = new TransactionScope(parentRequiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
txId1 = AssertAndGetCurrentTransactionId();
if (asyncWorkBeforeChildL2)
{
await DoAsyncWorkAsync(txId1);
}
result = SyncTSL2NestedTxWork(childL2RequiresNew, childL3RequiresNew, asyncChildL3, txId1);
txId3 = AssertAndGetCurrentTransactionId();
if (asyncWorkAfterChildL2)
{
await DoAsyncWorkAsync(txId1);
}
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
VerifyTxId(parentRequiresNew, txId, txId1, txId2);
VerifyTxId(parentRequiresNew, txId, txId1, txId3);
AssertTransaction(txId);
return result;
}
private static async Task<string> DoAsyncWorkAsync(string txId)
{
string txId1 = Transaction.Current != null ? Transaction.Current.TransactionInformation.LocalIdentifier : null;
Assert.Equal(txId, txId1);
if (s_throwExceptionDefaultOrBeforeAwait)
{
throw new Exception("DoAsyncWorkAsync exception before await");
}
await Task.Delay(2);
Task<string> getString = Task.Run(delegate
{
txId1 = Transaction.Current != null ? Transaction.Current.TransactionInformation.LocalIdentifier : null;
Assert.Equal(txId, txId1);
return DoWork(txId);
});
if (s_throwExceptionAfterAwait)
{
throw new Exception("DoAsyncWorkAsync exception after await");
}
string result = await getString;
txId1 = Transaction.Current != null ? Transaction.Current.TransactionInformation.LocalIdentifier : null;
Assert.Equal(txId, txId1);
return result;
}
private static void SyncTSDoTaskUnderAsyncTS(bool parentRequiresNew, bool childRequiresNew, string txId)
{
string txId1 = null;
string txId2 = null;
AssertTransaction(txId);
using (TransactionScope scope = new TransactionScope(parentRequiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required))
{
txId1 = AssertAndGetCurrentTransactionId();
DoTaskUnderAsyncTS(childRequiresNew, txId1);
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
VerifyTxId(parentRequiresNew, txId, txId1, txId2);
AssertTransaction(txId);
}
private static void DoTaskUnderAsyncTS(bool requiresNew, string txId)
{
string txId1 = null;
string txId2 = null;
AssertTransaction(txId);
using (TransactionScope scope = new TransactionScope(requiresNew ? TransactionScopeOption.RequiresNew : TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
txId1 = AssertAndGetCurrentTransactionId();
DoALotOfWork(txId1);
txId2 = AssertAndGetCurrentTransactionId();
scope.Complete();
}
VerifyTxId(requiresNew, txId, txId1, txId2);
AssertTransaction(txId);
}
private static void DoALotOfWork(string txId)
{
Task[] a = new Task[32];
for (int i = 0; i < 32; i++)
{
a[i] = new Task(() => DoWork(txId));
a[i].Start();
}
Task.WaitAll(a);
}
public static void VerifyTxId(bool requiresNew, string parentTxId, string beforeTxId, string afterTxId)
{
Assert.Equal(beforeTxId, afterTxId);
if (requiresNew)
{
Assert.NotEqual(parentTxId, beforeTxId);
}
else
{
if (!string.IsNullOrEmpty(parentTxId))
{
Assert.Equal(parentTxId, beforeTxId);
}
}
}
public static void AssertTransaction(string txId)
{
if (string.IsNullOrEmpty(txId))
{
AssertTransactionNull();
}
else
{
Assert.Equal(txId, AssertAndGetCurrentTransactionId());
}
}
public static void AssertTransactionNull()
{
Assert.Equal(null, Transaction.Current);
}
public static void AssertTransactionNotNull()
{
Assert.NotEqual(null, Transaction.Current);
}
public static string AssertAndGetCurrentTransactionId()
{
AssertTransactionNotNull();
return Transaction.Current.TransactionInformation.LocalIdentifier;
}
public static string AssertAndGetCurrentTransactionId(TransactionScopeOption scopeOption)
{
if (scopeOption == TransactionScopeOption.Suppress)
{
AssertTransactionNull();
return null;
}
else
{
AssertTransactionNotNull();
return Transaction.Current.TransactionInformation.LocalIdentifier;
}
}
public static void AssertTransactionNullAndWaitTask(Task<string> task)
{
AssertTransactionNull();
task.Wait();
AssertTransactionNull();
}
public static void AssertTransactionNullAndWaitTask(Task task)
{
AssertTransactionNull();
task.Wait();
AssertTransactionNull();
}
public static void SetExceptionInjection(bool exceptionDefaultOrBeforeAwait, bool exceptionAfterAwait)
{
s_throwExceptionDefaultOrBeforeAwait = exceptionDefaultOrBeforeAwait;
s_throwExceptionAfterAwait = exceptionAfterAwait;
}
public static void ResetExceptionInjection()
{
s_throwExceptionDefaultOrBeforeAwait = false;
s_throwExceptionAfterAwait = false;
}
public static void HandleException(bool exceptionDefaultOrBeforeAwait, bool exceptionAfterAwait, Action action)
{
bool hasException = false;
SetExceptionInjection(exceptionDefaultOrBeforeAwait, exceptionAfterAwait);
try
{
action.Invoke();
}
catch (Exception ex)
{
hasException = true;
Debug.WriteLine("Exception: {0}", ex.Message);
}
AssertTransactionNull();
Assert.Equal<bool>(hasException, true);
ResetExceptionInjection();
}
}
public class ThreadSyncObject
{
public string Id
{
get;
set;
}
public ManualResetEvent Event
{
get;
set;
}
public TransactionScopeAsyncFlowOption RootAsyncFlowOption
{
get;
set;
}
}
public interface IStatus
{
string GetStatus(string id, bool fail);
}
}
| |
#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
using System;
using System.Collections;
using System.IO;
using log4net.Core;
using log4net.Layout.Pattern;
using log4net.Util;
using log4net.Util.PatternStringConverters;
using AppDomainPatternConverter=log4net.Layout.Pattern.AppDomainPatternConverter;
using DatePatternConverter=log4net.Layout.Pattern.DatePatternConverter;
using IdentityPatternConverter=log4net.Layout.Pattern.IdentityPatternConverter;
using PropertyPatternConverter=log4net.Layout.Pattern.PropertyPatternConverter;
using UserNamePatternConverter=log4net.Layout.Pattern.UserNamePatternConverter;
using UtcDatePatternConverter=log4net.Layout.Pattern.UtcDatePatternConverter;
namespace log4net.Layout
{
/// <summary>
/// A flexible layout configurable with pattern string.
/// </summary>
/// <remarks>
/// <para>
/// The goal of this class is to <see cref="PatternLayout.Format(TextWriter,LoggingEvent)"/> a
/// <see cref="LoggingEvent"/> as a string. The results
/// depend on the <i>conversion pattern</i>.
/// </para>
/// <para>
/// The conversion pattern is closely related to the conversion
/// pattern of the printf function in C. A conversion pattern is
/// composed of literal text and format control expressions called
/// <i>conversion specifiers</i>.
/// </para>
/// <para>
/// <i>You are free to insert any literal text within the conversion
/// pattern.</i>
/// </para>
/// <para>
/// Each conversion specifier starts with a percent sign (%) and is
/// followed by optional <i>format modifiers</i> and a <i>conversion
/// pattern name</i>. The conversion pattern name specifies the type of
/// data, e.g. logger, level, date, thread name. The format
/// modifiers control such things as field width, padding, left and
/// right justification. The following is a simple example.
/// </para>
/// <para>
/// Let the conversion pattern be <b>"%-5level [%thread]: %message%newline"</b> and assume
/// that the log4net environment was set to use a PatternLayout. Then the
/// statements
/// </para>
/// <code lang="C#">
/// ILog log = LogManager.GetLogger(typeof(TestApp));
/// log.Debug("Message 1");
/// log.Warn("Message 2");
/// </code>
/// <para>would yield the output</para>
/// <code>
/// DEBUG [main]: Message 1
/// WARN [main]: Message 2
/// </code>
/// <para>
/// Note that there is no explicit separator between text and
/// conversion specifiers. The pattern parser knows when it has reached
/// the end of a conversion specifier when it reads a conversion
/// character. In the example above the conversion specifier
/// <b>%-5level</b> means the level of the logging event should be left
/// justified to a width of five characters.
/// </para>
/// <para>
/// The recognized conversion pattern names are:
/// </para>
/// <list type="table">
/// <listheader>
/// <term>Conversion Pattern Name</term>
/// <description>Effect</description>
/// </listheader>
/// <item>
/// <term>a</term>
/// <description>Equivalent to <b>appdomain</b></description>
/// </item>
/// <item>
/// <term>appdomain</term>
/// <description>
/// Used to output the friendly name of the AppDomain where the
/// logging event was generated.
/// </description>
/// </item>
/// <item>
/// <term>aspnet-cache</term>
/// <description>
/// TODO
/// </description>
/// </item>
/// <item>
/// <term>aspnet-context</term>
/// <description>
/// TODO
/// </description>
/// </item>
/// <item>
/// <term>aspnet-request</term>
/// <description>
/// TODO
/// </description>
/// </item>
/// <item>
/// <term>aspnet-session</term>
/// <description>
/// TODO
/// </description>
/// </item>
/// <item>
/// <term>c</term>
/// <description>Equivalent to <b>logger</b></description>
/// </item>
/// <item>
/// <term>C</term>
/// <description>Equivalent to <b>type</b></description>
/// </item>
/// <item>
/// <term>class</term>
/// <description>Equivalent to <b>type</b></description>
/// </item>
/// <item>
/// <term>d</term>
/// <description>Equivalent to <b>date</b></description>
/// </item>
/// <item>
/// <term>date</term>
/// <description>
/// <para>
/// Used to output the date of the logging event in the local time zone.
/// To output the date in universal time use the <c>%utcdate</c> pattern.
/// The date conversion
/// specifier may be followed by a <i>date format specifier</i> enclosed
/// between braces. For example, <b>%date{HH:mm:ss,fff}</b> or
/// <b>%date{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is
/// given then ISO8601 format is
/// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>).
/// </para>
/// <para>
/// The date format specifier admits the same syntax as the
/// time pattern string of the <see cref="DateTime.ToString(string)"/>.
/// </para>
/// <para>
/// For better results it is recommended to use the log4net date
/// formatters. These can be specified using one of the strings
/// "ABSOLUTE", "DATE" and "ISO8601" for specifying
/// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>,
/// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively
/// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example,
/// <b>%date{ISO8601}</b> or <b>%date{ABSOLUTE}</b>.
/// </para>
/// <para>
/// These dedicated date formatters perform significantly
/// better than <see cref="DateTime.ToString(string)"/>.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>exception</term>
/// <description>
/// <para>
/// Used to output the exception passed in with the log message.
/// </para>
/// <para>
/// If an exception object is stored in the logging event
/// it will be rendered into the pattern output with a
/// trailing newline.
/// If there is no exception then nothing will be output
/// and no trailing newline will be appended.
/// It is typical to put a newline before the exception
/// and to have the exception as the last data in the pattern.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>F</term>
/// <description>Equivalent to <b>file</b></description>
/// </item>
/// <item>
/// <term>file</term>
/// <description>
/// <para>
/// Used to output the file name where the logging request was
/// issued.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller location information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>identity</term>
/// <description>
/// <para>
/// Used to output the user name for the currently active user
/// (Principal.Identity.Name).
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>l</term>
/// <description>Equivalent to <b>location</b></description>
/// </item>
/// <item>
/// <term>L</term>
/// <description>Equivalent to <b>line</b></description>
/// </item>
/// <item>
/// <term>location</term>
/// <description>
/// <para>
/// Used to output location information of the caller which generated
/// the logging event.
/// </para>
/// <para>
/// The location information depends on the CLI implementation but
/// usually consists of the fully qualified name of the calling
/// method followed by the callers source the file name and line
/// number between parentheses.
/// </para>
/// <para>
/// The location information can be very useful. However, its
/// generation is <b>extremely</b> slow. Its use should be avoided
/// unless execution speed is not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>level</term>
/// <description>
/// <para>
/// Used to output the level of the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>line</term>
/// <description>
/// <para>
/// Used to output the line number from where the logging request
/// was issued.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller location information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>logger</term>
/// <description>
/// <para>
/// Used to output the logger of the logging event. The
/// logger conversion specifier can be optionally followed by
/// <i>precision specifier</i>, that is a decimal constant in
/// brackets.
/// </para>
/// <para>
/// If a precision specifier is given, then only the corresponding
/// number of right most components of the logger name will be
/// printed. By default the logger name is printed in full.
/// </para>
/// <para>
/// For example, for the logger name "a.b.c" the pattern
/// <b>%logger{2}</b> will output "b.c".
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>m</term>
/// <description>Equivalent to <b>message</b></description>
/// </item>
/// <item>
/// <term>M</term>
/// <description>Equivalent to <b>method</b></description>
/// </item>
/// <item>
/// <term>message</term>
/// <description>
/// <para>
/// Used to output the application supplied message associated with
/// the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>mdc</term>
/// <description>
/// <para>
/// The MDC (old name for the ThreadContext.Properties) is now part of the
/// combined event properties. This pattern is supported for compatibility
/// but is equivalent to <b>property</b>.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>method</term>
/// <description>
/// <para>
/// Used to output the method name where the logging request was
/// issued.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller location information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>n</term>
/// <description>Equivalent to <b>newline</b></description>
/// </item>
/// <item>
/// <term>newline</term>
/// <description>
/// <para>
/// Outputs the platform dependent line separator character or
/// characters.
/// </para>
/// <para>
/// This conversion pattern offers the same performance as using
/// non-portable line separator strings such as "\n", or "\r\n".
/// Thus, it is the preferred way of specifying a line separator.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>ndc</term>
/// <description>
/// <para>
/// Used to output the NDC (nested diagnostic context) associated
/// with the thread that generated the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>p</term>
/// <description>Equivalent to <b>level</b></description>
/// </item>
/// <item>
/// <term>P</term>
/// <description>Equivalent to <b>property</b></description>
/// </item>
/// <item>
/// <term>properties</term>
/// <description>Equivalent to <b>property</b></description>
/// </item>
/// <item>
/// <term>property</term>
/// <description>
/// <para>
/// Used to output the an event specific property. The key to
/// lookup must be specified within braces and directly following the
/// pattern specifier, e.g. <b>%property{user}</b> would include the value
/// from the property that is keyed by the string 'user'. Each property value
/// that is to be included in the log must be specified separately.
/// Properties are added to events by loggers or appenders. By default
/// the <c>log4net:HostName</c> property is set to the name of machine on
/// which the event was originally logged.
/// </para>
/// <para>
/// If no key is specified, e.g. <b>%property</b> then all the keys and their
/// values are printed in a comma separated list.
/// </para>
/// <para>
/// The properties of an event are combined from a number of different
/// contexts. These are listed below in the order in which they are searched.
/// </para>
/// <list type="definition">
/// <item>
/// <term>the event properties</term>
/// <description>
/// The event has <see cref="LoggingEvent.Properties"/> that can be set. These
/// properties are specific to this event only.
/// </description>
/// </item>
/// <item>
/// <term>the thread properties</term>
/// <description>
/// The <see cref="ThreadContext.Properties"/> that are set on the current
/// thread. These properties are shared by all events logged on this thread.
/// </description>
/// </item>
/// <item>
/// <term>the global properties</term>
/// <description>
/// The <see cref="GlobalContext.Properties"/> that are set globally. These
/// properties are shared by all the threads in the AppDomain.
/// </description>
/// </item>
/// </list>
///
/// </description>
/// </item>
/// <item>
/// <term>r</term>
/// <description>Equivalent to <b>timestamp</b></description>
/// </item>
/// <item>
/// <term>stacktrace</term>
/// <description>
/// <para>
/// Used to output the stack trace of the logging event
/// The stack trace level specifier may be enclosed
/// between braces. For example, <b>%stacktrace{level}</b>.
/// If no stack trace level specifier is given then 1 is assumed
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>t</term>
/// <description>Equivalent to <b>thread</b></description>
/// </item>
/// <item>
/// <term>timestamp</term>
/// <description>
/// <para>
/// Used to output the number of milliseconds elapsed since the start
/// of the application until the creation of the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>thread</term>
/// <description>
/// <para>
/// Used to output the name of the thread that generated the
/// logging event. Uses the thread number if no name is available.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>type</term>
/// <description>
/// <para>
/// Used to output the fully qualified type name of the caller
/// issuing the logging request. This conversion specifier
/// can be optionally followed by <i>precision specifier</i>, that
/// is a decimal constant in brackets.
/// </para>
/// <para>
/// If a precision specifier is given, then only the corresponding
/// number of right most components of the class name will be
/// printed. By default the class name is output in fully qualified form.
/// </para>
/// <para>
/// For example, for the class name "log4net.Layout.PatternLayout", the
/// pattern <b>%type{1}</b> will output "PatternLayout".
/// </para>
/// <para>
/// <b>WARNING</b> Generating the caller class information is
/// slow. Thus, its use should be avoided unless execution speed is
/// not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>u</term>
/// <description>Equivalent to <b>identity</b></description>
/// </item>
/// <item>
/// <term>username</term>
/// <description>
/// <para>
/// Used to output the WindowsIdentity for the currently
/// active user.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller WindowsIdentity information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>utcdate</term>
/// <description>
/// <para>
/// Used to output the date of the logging event in universal time.
/// The date conversion
/// specifier may be followed by a <i>date format specifier</i> enclosed
/// between braces. For example, <b>%utcdate{HH:mm:ss,fff}</b> or
/// <b>%utcdate{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is
/// given then ISO8601 format is
/// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>).
/// </para>
/// <para>
/// The date format specifier admits the same syntax as the
/// time pattern string of the <see cref="DateTime.ToString(string)"/>.
/// </para>
/// <para>
/// For better results it is recommended to use the log4net date
/// formatters. These can be specified using one of the strings
/// "ABSOLUTE", "DATE" and "ISO8601" for specifying
/// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>,
/// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively
/// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example,
/// <b>%utcdate{ISO8601}</b> or <b>%utcdate{ABSOLUTE}</b>.
/// </para>
/// <para>
/// These dedicated date formatters perform significantly
/// better than <see cref="DateTime.ToString(string)"/>.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>w</term>
/// <description>Equivalent to <b>username</b></description>
/// </item>
/// <item>
/// <term>x</term>
/// <description>Equivalent to <b>ndc</b></description>
/// </item>
/// <item>
/// <term>X</term>
/// <description>Equivalent to <b>mdc</b></description>
/// </item>
/// <item>
/// <term>%</term>
/// <description>
/// <para>
/// The sequence %% outputs a single percent sign.
/// </para>
/// </description>
/// </item>
/// </list>
/// <para>
/// The single letter patterns are deprecated in favor of the
/// longer more descriptive pattern names.
/// </para>
/// <para>
/// By default the relevant information is output as is. However,
/// with the aid of format modifiers it is possible to change the
/// minimum field width, the maximum field width and justification.
/// </para>
/// <para>
/// The optional format modifier is placed between the percent sign
/// and the conversion pattern name.
/// </para>
/// <para>
/// The first optional format modifier is the <i>left justification
/// flag</i> which is just the minus (-) character. Then comes the
/// optional <i>minimum field width</i> modifier. This is a decimal
/// constant that represents the minimum number of characters to
/// output. If the data item requires fewer characters, it is padded on
/// either the left or the right until the minimum width is
/// reached. The default is to pad on the left (right justify) but you
/// can specify right padding with the left justification flag. The
/// padding character is space. If the data item is larger than the
/// minimum field width, the field is expanded to accommodate the
/// data. The value is never truncated.
/// </para>
/// <para>
/// This behavior can be changed using the <i>maximum field
/// width</i> modifier which is designated by a period followed by a
/// decimal constant. If the data item is longer than the maximum
/// field, then the extra characters are removed from the
/// <i>beginning</i> of the data item and not from the end. For
/// example, it the maximum field width is eight and the data item is
/// ten characters long, then the first two characters of the data item
/// are dropped. This behavior deviates from the printf function in C
/// where truncation is done from the end.
/// </para>
/// <para>
/// Below are various format modifier examples for the logger
/// conversion specifier.
/// </para>
/// <div class="tablediv">
/// <table class="dtTABLE" cellspacing="0">
/// <tr>
/// <th>Format modifier</th>
/// <th>left justify</th>
/// <th>minimum width</th>
/// <th>maximum width</th>
/// <th>comment</th>
/// </tr>
/// <tr>
/// <td align="center">%20logger</td>
/// <td align="center">false</td>
/// <td align="center">20</td>
/// <td align="center">none</td>
/// <td>
/// <para>
/// Left pad with spaces if the logger name is less than 20
/// characters long.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%-20logger</td>
/// <td align="center">true</td>
/// <td align="center">20</td>
/// <td align="center">none</td>
/// <td>
/// <para>
/// Right pad with spaces if the logger
/// name is less than 20 characters long.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%.30logger</td>
/// <td align="center">NA</td>
/// <td align="center">none</td>
/// <td align="center">30</td>
/// <td>
/// <para>
/// Truncate from the beginning if the logger
/// name is longer than 30 characters.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center"><nobr>%20.30logger</nobr></td>
/// <td align="center">false</td>
/// <td align="center">20</td>
/// <td align="center">30</td>
/// <td>
/// <para>
/// Left pad with spaces if the logger name is shorter than 20
/// characters. However, if logger name is longer than 30 characters,
/// then truncate from the beginning.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%-20.30logger</td>
/// <td align="center">true</td>
/// <td align="center">20</td>
/// <td align="center">30</td>
/// <td>
/// <para>
/// Right pad with spaces if the logger name is shorter than 20
/// characters. However, if logger name is longer than 30 characters,
/// then truncate from the beginning.
/// </para>
/// </td>
/// </tr>
/// </table>
/// </div>
/// <para>
/// <b>Note about caller location information.</b><br />
/// The following patterns <c>%type %file %line %method %location %class %C %F %L %l %M</c>
/// all generate caller location information.
/// Location information uses the <c>System.Diagnostics.StackTrace</c> class to generate
/// a call stack. The caller's information is then extracted from this stack.
/// </para>
/// <note type="caution">
/// <para>
/// The <c>System.Diagnostics.StackTrace</c> class is not supported on the
/// .NET Compact Framework 1.0 therefore caller location information is not
/// available on that framework.
/// </para>
/// </note>
/// <note type="caution">
/// <para>
/// The <c>System.Diagnostics.StackTrace</c> class has this to say about Release builds:
/// </para>
/// <para>
/// "StackTrace information will be most informative with Debug build configurations.
/// By default, Debug builds include debug symbols, while Release builds do not. The
/// debug symbols contain most of the file, method name, line number, and column
/// information used in constructing StackFrame and StackTrace objects. StackTrace
/// might not report as many method calls as expected, due to code transformations
/// that occur during optimization."
/// </para>
/// <para>
/// This means that in a Release build the caller information may be incomplete or may
/// not exist at all! Therefore caller location information cannot be relied upon in a Release build.
/// </para>
/// </note>
/// <para>
/// Additional pattern converters may be registered with a specific <see cref="PatternLayout"/>
/// instance using the <see cref="AddConverter(string, Type)"/> method.
/// </para>
/// </remarks>
/// <example>
/// This is a more detailed pattern.
/// <code><b>%timestamp [%thread] %level %logger %ndc - %message%newline</b></code>
/// </example>
/// <example>
/// A similar pattern except that the relative time is
/// right padded if less than 6 digits, thread name is right padded if
/// less than 15 characters and truncated if longer and the logger
/// name is left padded if shorter than 30 characters and truncated if
/// longer.
/// <code><b>%-6timestamp [%15.15thread] %-5level %30.30logger %ndc - %message%newline</b></code>
/// </example>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Douglas de la Torre</author>
/// <author>Daniel Cazzulino</author>
public class PatternLayout : LayoutSkeleton
{
#region Constants
/// <summary>
/// Default pattern string for log output.
/// </summary>
/// <remarks>
/// <para>
/// Default pattern string for log output.
/// Currently set to the string <b>"%message%newline"</b>
/// which just prints the application supplied message.
/// </para>
/// </remarks>
public const string DefaultConversionPattern ="%message%newline";
/// <summary>
/// A detailed conversion pattern
/// </summary>
/// <remarks>
/// <para>
/// A conversion pattern which includes Time, Thread, Logger, and Nested Context.
/// Current value is <b>%timestamp [%thread] %level %logger %ndc - %message%newline</b>.
/// </para>
/// </remarks>
public const string DetailConversionPattern = "%timestamp [%thread] %level %logger %ndc - %message%newline";
#endregion
#region Static Fields
/// <summary>
/// Internal map of converter identifiers to converter types.
/// </summary>
/// <remarks>
/// <para>
/// This static map is overridden by the m_converterRegistry instance map
/// </para>
/// </remarks>
private static Hashtable s_globalRulesRegistry;
#endregion Static Fields
#region Member Variables
/// <summary>
/// the pattern
/// </summary>
private string m_pattern;
/// <summary>
/// the head of the pattern converter chain
/// </summary>
private PatternConverter m_head;
/// <summary>
/// patterns defined on this PatternLayout only
/// </summary>
private Hashtable m_instanceRulesRegistry = new Hashtable();
#endregion
#region Static Constructor
/// <summary>
/// Initialize the global registry
/// </summary>
/// <remarks>
/// <para>
/// Defines the builtin global rules.
/// </para>
/// </remarks>
static PatternLayout()
{
s_globalRulesRegistry = new Hashtable(45);
s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter));
s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter));
s_globalRulesRegistry.Add("n", typeof(NewLinePatternConverter));
// .NET Compact Framework 1.0 has no support for ASP.NET
// SSCLI 1.0 has no support for ASP.NET
#if !NETCF && !SSCLI
s_globalRulesRegistry.Add("aspnet-cache", typeof(AspNetCachePatternConverter));
s_globalRulesRegistry.Add("aspnet-context", typeof(AspNetContextPatternConverter));
s_globalRulesRegistry.Add("aspnet-request", typeof(AspNetRequestPatternConverter));
s_globalRulesRegistry.Add("aspnet-session", typeof(AspNetSessionPatternConverter));
#endif
s_globalRulesRegistry.Add("c", typeof(LoggerPatternConverter));
s_globalRulesRegistry.Add("logger", typeof(LoggerPatternConverter));
s_globalRulesRegistry.Add("C", typeof(TypeNamePatternConverter));
s_globalRulesRegistry.Add("class", typeof(TypeNamePatternConverter));
s_globalRulesRegistry.Add("type", typeof(TypeNamePatternConverter));
s_globalRulesRegistry.Add("d", typeof(DatePatternConverter));
s_globalRulesRegistry.Add("date", typeof(DatePatternConverter));
s_globalRulesRegistry.Add("exception", typeof(ExceptionPatternConverter));
s_globalRulesRegistry.Add("F", typeof(FileLocationPatternConverter));
s_globalRulesRegistry.Add("file", typeof(FileLocationPatternConverter));
s_globalRulesRegistry.Add("l", typeof(FullLocationPatternConverter));
s_globalRulesRegistry.Add("location", typeof(FullLocationPatternConverter));
s_globalRulesRegistry.Add("L", typeof(LineLocationPatternConverter));
s_globalRulesRegistry.Add("line", typeof(LineLocationPatternConverter));
s_globalRulesRegistry.Add("m", typeof(MessagePatternConverter));
s_globalRulesRegistry.Add("message", typeof(MessagePatternConverter));
s_globalRulesRegistry.Add("M", typeof(MethodLocationPatternConverter));
s_globalRulesRegistry.Add("method", typeof(MethodLocationPatternConverter));
s_globalRulesRegistry.Add("p", typeof(LevelPatternConverter));
s_globalRulesRegistry.Add("level", typeof(LevelPatternConverter));
s_globalRulesRegistry.Add("P", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("properties", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("r", typeof(RelativeTimePatternConverter));
s_globalRulesRegistry.Add("timestamp", typeof(RelativeTimePatternConverter));
s_globalRulesRegistry.Add("stacktrace", typeof(StackTracePatternConverter));
s_globalRulesRegistry.Add("stacktracedetail", typeof(StackTraceDetailPatternConverter));
s_globalRulesRegistry.Add("t", typeof(ThreadPatternConverter));
s_globalRulesRegistry.Add("thread", typeof(ThreadPatternConverter));
// For backwards compatibility the NDC patterns
s_globalRulesRegistry.Add("x", typeof(NdcPatternConverter));
s_globalRulesRegistry.Add("ndc", typeof(NdcPatternConverter));
// For backwards compatibility the MDC patterns just do a property lookup
s_globalRulesRegistry.Add("X", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("mdc", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("a", typeof(AppDomainPatternConverter));
s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter));
s_globalRulesRegistry.Add("u", typeof(IdentityPatternConverter));
s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter));
s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter));
s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter));
s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter));
s_globalRulesRegistry.Add("w", typeof(UserNamePatternConverter));
s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter));
}
#endregion Static Constructor
#region Constructors
/// <summary>
/// Constructs a PatternLayout using the DefaultConversionPattern
/// </summary>
/// <remarks>
/// <para>
/// The default pattern just produces the application supplied message.
/// </para>
/// <para>
/// Note to Inheritors: This constructor calls the virtual method
/// <see cref="CreatePatternParser"/>. If you override this method be
/// aware that it will be called before your is called constructor.
/// </para>
/// <para>
/// As per the <see cref="IOptionHandler"/> contract the <see cref="ActivateOptions"/>
/// method must be called after the properties on this object have been
/// configured.
/// </para>
/// </remarks>
public PatternLayout() : this(DefaultConversionPattern)
{
}
/// <summary>
/// Constructs a PatternLayout using the supplied conversion pattern
/// </summary>
/// <param name="pattern">the pattern to use</param>
/// <remarks>
/// <para>
/// Note to Inheritors: This constructor calls the virtual method
/// <see cref="CreatePatternParser"/>. If you override this method be
/// aware that it will be called before your is called constructor.
/// </para>
/// <para>
/// When using this constructor the <see cref="ActivateOptions"/> method
/// need not be called. This may not be the case when using a subclass.
/// </para>
/// </remarks>
public PatternLayout(string pattern)
{
// By default we do not process the exception
IgnoresException = true;
m_pattern = pattern;
if (m_pattern == null)
{
m_pattern = DefaultConversionPattern;
}
ActivateOptions();
}
#endregion
/// <summary>
/// The pattern formatting string
/// </summary>
/// <remarks>
/// <para>
/// The <b>ConversionPattern</b> option. This is the string which
/// controls formatting and consists of a mix of literal content and
/// conversion specifiers.
/// </para>
/// </remarks>
public string ConversionPattern
{
get { return m_pattern; }
set { m_pattern = value; }
}
/// <summary>
/// Create the pattern parser instance
/// </summary>
/// <param name="pattern">the pattern to parse</param>
/// <returns>The <see cref="PatternParser"/> that will format the event</returns>
/// <remarks>
/// <para>
/// Creates the <see cref="PatternParser"/> used to parse the conversion string. Sets the
/// global and instance rules on the <see cref="PatternParser"/>.
/// </para>
/// </remarks>
virtual protected PatternParser CreatePatternParser(string pattern)
{
PatternParser patternParser = new PatternParser(pattern);
// Add all the builtin patterns
foreach(DictionaryEntry entry in s_globalRulesRegistry)
{
ConverterInfo converterInfo = new ConverterInfo();
converterInfo.Name = (string)entry.Key;
converterInfo.Type = (Type)entry.Value;
patternParser.PatternConverters[entry.Key] = converterInfo;
}
// Add the instance patterns
foreach(DictionaryEntry entry in m_instanceRulesRegistry)
{
patternParser.PatternConverters[entry.Key] = entry.Value;
}
return patternParser;
}
#region Implementation of IOptionHandler
/// <summary>
/// Initialize layout options
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
override public void ActivateOptions()
{
m_head = CreatePatternParser(m_pattern).Parse();
PatternConverter curConverter = m_head;
while(curConverter != null)
{
PatternLayoutConverter layoutConverter = curConverter as PatternLayoutConverter;
if (layoutConverter != null)
{
if (!layoutConverter.IgnoresException)
{
// Found converter that handles the exception
this.IgnoresException = false;
break;
}
}
curConverter = curConverter.Next;
}
}
#endregion
#region Override implementation of LayoutSkeleton
/// <summary>
/// Produces a formatted string as specified by the conversion pattern.
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <param name="writer">The TextWriter to write the formatted event to</param>
/// <remarks>
/// <para>
/// Parse the <see cref="LoggingEvent"/> using the patter format
/// specified in the <see cref="ConversionPattern"/> property.
/// </para>
/// </remarks>
override public void Format(TextWriter writer, LoggingEvent loggingEvent)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
if (loggingEvent == null)
{
throw new ArgumentNullException("loggingEvent");
}
PatternConverter c = m_head;
// loop through the chain of pattern converters
while(c != null)
{
c.Format(writer, loggingEvent);
c = c.Next;
}
}
#endregion
/// <summary>
/// Add a converter to this PatternLayout
/// </summary>
/// <param name="converterInfo">the converter info</param>
/// <remarks>
/// <para>
/// This version of the method is used by the configurator.
/// Programmatic users should use the alternative <see cref="AddConverter(string,Type)"/> method.
/// </para>
/// </remarks>
public void AddConverter(ConverterInfo converterInfo)
{
if (converterInfo == null) throw new ArgumentNullException("converterInfo");
if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type))
{
throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo");
}
m_instanceRulesRegistry[converterInfo.Name] = converterInfo;
}
/// <summary>
/// Add a converter to this PatternLayout
/// </summary>
/// <param name="name">the name of the conversion pattern for this converter</param>
/// <param name="type">the type of the converter</param>
/// <remarks>
/// <para>
/// Add a named pattern converter to this instance. This
/// converter will be used in the formatting of the event.
/// This method must be called before <see cref="ActivateOptions"/>.
/// </para>
/// <para>
/// The <paramref name="type"/> specified must extend the
/// <see cref="PatternConverter"/> type.
/// </para>
/// </remarks>
public void AddConverter(string name, Type type)
{
if (name == null) throw new ArgumentNullException("name");
if (type == null) throw new ArgumentNullException("type");
ConverterInfo converterInfo = new ConverterInfo();
converterInfo.Name = name;
converterInfo.Type = type;
AddConverter(converterInfo);
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2015 Patricio Zavolinsky
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Reflection;
namespace BoundedLayers.Models
{
/// <summary>
/// Layer configuration interface.
/// </summary>
public interface IConfiguration
{
/// <summary>
/// Define a new layer.
/// </summary>
/// <param name="name">Layer name.</param>
IRule Layer(string name);
/// <summary>
/// Define a new component.
/// </summary>
/// <param name="name">Component name.</param>
IRule Component(string name);
/// <summary>
/// Define an example.
/// </summary>
/// <param name="name">Project name.</param>
IExample ForExample(string name);
/// <summary>
/// Validate the solution file in the specified path.
/// </summary>
/// <param name="solutionPath">Solution path.</param>
/// <returns>A list of validation exceptions.</returns>
IEnumerable<ProjectException> Validate(string solutionPath);
/// <summary>
/// Validate the specified solution.
/// </summary>
/// <param name="solution">Solution.</param>
/// <returns>A list of validation exceptions.</returns>
IEnumerable<ProjectException> Validate(Solution solution);
}
/// <summary>
/// Configuration implementation.
/// </summary>
public class Configuration : IConfiguration
{
private readonly List<Rule> _layerRules = new List<Rule>();
private readonly List<Rule> _componentRules = new List<Rule>();
private readonly Expression.Type _expType;
/// <summary>
/// Initializes a new instance of the <see cref="BoundedLayers.Models.Configuration"/> class.
/// </summary>
/// <param name="expType">Expression type.</param>
public Configuration(Expression.Type expType)
{
_expType = expType;
}
/// <see cref="BoundedLayers.Models.IConfiguration.Layer"/>
public IRule Layer(string name)
{
var rule = new Rule(this, name);
_layerRules.Add(rule);
return rule;
}
/// <see cref="BoundedLayers.Models.IConfiguration.Component"/>
public IRule Component(string name)
{
var rule = new Rule(this, name);
_componentRules.Add(rule);
return rule;
}
/// <see cref="BoundedLayers.Models.IConfiguration.ForExample"/>
public IExample ForExample(string name)
{
return new Example(this, name);
}
/// <summary>
/// Creates a new expression using the pattern specified.
/// </summary>
/// <returns>The expression.</returns>
/// <param name="pattern">Pattern.</param>
public IExpression CreateExpression(string pattern)
{
return Expression.Create(_expType, pattern);
}
/// <see cref="BoundedLayers.Models.IConfiguration.Validate(string)"/>
public IEnumerable<ProjectException> Validate(string solutionPath)
{
if (!Path.IsPathRooted(solutionPath))
{
var codeBaseUrl = new Uri(Assembly.GetExecutingAssembly().CodeBase);
var codeBasePath = Uri.UnescapeDataString(codeBaseUrl.AbsolutePath);
var dirPath = Path.GetDirectoryName(codeBasePath);
solutionPath = Path.Combine(dirPath, solutionPath);
}
return Validate(new Solution(solutionPath));
}
/// <see cref="BoundedLayers.Models.IConfiguration.Validate(Solution)"/>
public IEnumerable<ProjectException> Validate(Solution solution)
{
return solution
.Projects
.SelectMany(project =>
Validate(project.Name, project.References.Select(id => solution.Find(id).Name).ToArray()));
}
/// <summary>
/// Validate the specified project reference.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="referenced">The referenced projects.</param>
/// <returns>A list of validation exceptions.</returns>
public IEnumerable<ProjectException> Validate(string project, params string[] referenced)
{
var layers = _layerRules.Where(r => r.Matches(project)).ToArray();
var components = _componentRules.Where(r => r.Matches(project)).ToArray();
return Validate (layers, components, project)
.Concat (referenced.SelectMany (r => Validate (layers, components, project, r)));
}
/// <summary>
/// Validate the specified project reference.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="referenced">The referenced projects.</param>
/// <returns>A list of validation exceptions and the rules that allow each reference.</returns>
public Tuple<IEnumerable<ProjectException>,IEnumerable<AllowingRules>> ValidateExtended(string project, params string[] referenced)
{
var layers = _layerRules.Where(r => r.Matches(project)).ToArray();
var components = _componentRules.Where(r => r.Matches(project)).ToArray();
return new Tuple<IEnumerable<ProjectException>, IEnumerable<AllowingRules>> (
Validate(layers, components, project),
referenced.Select(r => AllowedBy(layers, components, r))
);
}
private IEnumerable<ProjectException> Validate(Rule[] layers, Rule[] components, string project)
{
if (!layers.Any())
{
yield return new UnknownLayerException(project);
}
if (!components.Any())
{
yield return new UnknownComponentException(project);
}
}
private IEnumerable<ProjectException> Validate(Rule[] layers, Rule[] components, string project, string referenced)
{
var allowedBy = AllowedBy(layers, components, referenced);
if (layers.Any() && allowedBy.Layer == null)
{
yield return new LayerViolationException(project, referenced);
}
if (components.Any() && allowedBy.Component == null)
{
yield return new ComponentViolationException(project, referenced);
}
}
private AllowingRules AllowedBy(Rule[] layers, Rule[] components, string referenced)
{
return new AllowingRules(
layers.FirstOrDefault(r => r.Allows (referenced)),
components.FirstOrDefault(r => r.Allows (referenced))
);
}
}
}
| |
namespace ERY.EMath
{
public partial class Graph
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Graph));
this.txtMaxX = new System.Windows.Forms.TextBox();
this.txtMinX = new System.Windows.Forms.TextBox();
this.txtMaxY = new System.Windows.Forms.TextBox();
this.txtMinY = new System.Windows.Forms.TextBox();
this.menu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.editDatasetsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.mnuShowTitle = new System.Windows.Forms.ToolStripMenuItem();
this.titleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.txtTitle = new System.Windows.Forms.ToolStripTextBox();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.horizontalAxisToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.verticalAxisToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.autoScaleAxesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exportDataToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.textToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.graphToagrusedByXMGraceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.imageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.encapsulatedPostScriptToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.pageSetupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printPreviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printDialog = new System.Windows.Forms.PrintDialog();
this.printDocument = new System.Drawing.Printing.PrintDocument();
this.printPreviewDialog = new System.Windows.Forms.PrintPreviewDialog();
this.pageSetupDialog = new System.Windows.Forms.PageSetupDialog();
this.saveFile = new System.Windows.Forms.SaveFileDialog();
this.menu.SuspendLayout();
this.SuspendLayout();
//
// txtMaxX
//
this.txtMaxX.AcceptsReturn = true;
this.txtMaxX.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.txtMaxX.Location = new System.Drawing.Point(217, 187);
this.txtMaxX.Name = "txtMaxX";
this.txtMaxX.Size = new System.Drawing.Size(40, 20);
this.txtMaxX.TabIndex = 3;
this.txtMaxX.Visible = false;
this.txtMaxX.VisibleChanged += new System.EventHandler(this.txtBox_VisibleChanged);
this.txtMaxX.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtMaxX_KeyPress);
this.txtMaxX.Validating += new System.ComponentModel.CancelEventHandler(this.txtMaxX_Validating);
this.txtMaxX.Validated += new System.EventHandler(this.txtMaxX_Validated);
//
// txtMinX
//
this.txtMinX.AcceptsReturn = true;
this.txtMinX.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.txtMinX.Location = new System.Drawing.Point(34, 187);
this.txtMinX.Name = "txtMinX";
this.txtMinX.Size = new System.Drawing.Size(40, 20);
this.txtMinX.TabIndex = 4;
this.txtMinX.Visible = false;
this.txtMinX.VisibleChanged += new System.EventHandler(this.txtBox_VisibleChanged);
this.txtMinX.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtMinX_KeyPress);
this.txtMinX.Validating += new System.ComponentModel.CancelEventHandler(this.txtMinX_Validating);
this.txtMinX.Validated += new System.EventHandler(this.txtMinX_Validated);
//
// txtMaxY
//
this.txtMaxY.AcceptsReturn = true;
this.txtMaxY.Location = new System.Drawing.Point(0, 3);
this.txtMaxY.Name = "txtMaxY";
this.txtMaxY.Size = new System.Drawing.Size(40, 20);
this.txtMaxY.TabIndex = 5;
this.txtMaxY.Visible = false;
this.txtMaxY.VisibleChanged += new System.EventHandler(this.txtBox_VisibleChanged);
this.txtMaxY.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtMaxY_KeyPress);
this.txtMaxY.Validating += new System.ComponentModel.CancelEventHandler(this.txtMaxY_Validating);
this.txtMaxY.Validated += new System.EventHandler(this.txtMaxY_Validated);
//
// txtMinY
//
this.txtMinY.AcceptsReturn = true;
this.txtMinY.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.txtMinY.Location = new System.Drawing.Point(0, 172);
this.txtMinY.Name = "txtMinY";
this.txtMinY.Size = new System.Drawing.Size(40, 20);
this.txtMinY.TabIndex = 6;
this.txtMinY.Visible = false;
this.txtMinY.VisibleChanged += new System.EventHandler(this.txtBox_VisibleChanged);
this.txtMinY.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtMinY_KeyPress);
this.txtMinY.Validating += new System.ComponentModel.CancelEventHandler(this.txtMinY_Validating);
this.txtMinY.Validated += new System.EventHandler(this.txtMinY_Validated);
//
// menu
//
this.menu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.editDatasetsToolStripMenuItem,
this.toolStripSeparator4,
this.mnuShowTitle,
this.titleToolStripMenuItem,
this.toolStripSeparator2,
this.horizontalAxisToolStripMenuItem,
this.verticalAxisToolStripMenuItem,
this.autoScaleAxesToolStripMenuItem,
this.toolStripSeparator1,
this.exportDataToolStripMenuItem,
this.toolStripSeparator3,
this.pageSetupToolStripMenuItem,
this.printPreviewToolStripMenuItem,
this.printToolStripMenuItem});
this.menu.Name = "menu";
this.menu.Size = new System.Drawing.Size(186, 248);
//
// editDatasetsToolStripMenuItem
//
this.editDatasetsToolStripMenuItem.Name = "editDatasetsToolStripMenuItem";
this.editDatasetsToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.editDatasetsToolStripMenuItem.Text = "Edit Datasets...";
this.editDatasetsToolStripMenuItem.Click += new System.EventHandler(this.editDatasetsToolStripMenuItem_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(182, 6);
//
// mnuShowTitle
//
this.mnuShowTitle.Name = "mnuShowTitle";
this.mnuShowTitle.Size = new System.Drawing.Size(185, 22);
this.mnuShowTitle.Text = "Show Title";
this.mnuShowTitle.Click += new System.EventHandler(this.mnuShowTitle_Click);
//
// titleToolStripMenuItem
//
this.titleToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.txtTitle});
this.titleToolStripMenuItem.Name = "titleToolStripMenuItem";
this.titleToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.titleToolStripMenuItem.Text = "Title Text";
//
// txtTitle
//
this.txtTitle.Name = "txtTitle";
this.txtTitle.Size = new System.Drawing.Size(100, 23);
this.txtTitle.Text = "Enter Title Text";
this.txtTitle.TextChanged += new System.EventHandler(this.txtTitle_TextChanged);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(182, 6);
//
// horizontalAxisToolStripMenuItem
//
this.horizontalAxisToolStripMenuItem.Name = "horizontalAxisToolStripMenuItem";
this.horizontalAxisToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.horizontalAxisToolStripMenuItem.Text = "Edit Horizontal Axis...";
this.horizontalAxisToolStripMenuItem.Click += new System.EventHandler(this.horizontalAxisToolStripMenuItem_Click);
//
// verticalAxisToolStripMenuItem
//
this.verticalAxisToolStripMenuItem.Name = "verticalAxisToolStripMenuItem";
this.verticalAxisToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.verticalAxisToolStripMenuItem.Text = "Edit Vertical Axis...";
this.verticalAxisToolStripMenuItem.Click += new System.EventHandler(this.verticalAxisToolStripMenuItem_Click);
//
// autoScaleAxesToolStripMenuItem
//
this.autoScaleAxesToolStripMenuItem.Name = "autoScaleAxesToolStripMenuItem";
this.autoScaleAxesToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.autoScaleAxesToolStripMenuItem.Text = "Auto Scale Axes";
this.autoScaleAxesToolStripMenuItem.Click += new System.EventHandler(this.autoScaleAxesToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(182, 6);
//
// exportDataToolStripMenuItem
//
this.exportDataToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.textToolStripMenuItem,
this.graphToagrusedByXMGraceToolStripMenuItem,
this.imageToolStripMenuItem,
this.encapsulatedPostScriptToolStripMenuItem});
this.exportDataToolStripMenuItem.Name = "exportDataToolStripMenuItem";
this.exportDataToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.exportDataToolStripMenuItem.Text = "Export";
//
// textToolStripMenuItem
//
this.textToolStripMenuItem.Name = "textToolStripMenuItem";
this.textToolStripMenuItem.Size = new System.Drawing.Size(260, 22);
this.textToolStripMenuItem.Text = "Datasets to .txt...";
this.textToolStripMenuItem.Click += new System.EventHandler(this.textToolStripMenuItem_Click);
//
// graphToagrusedByXMGraceToolStripMenuItem
//
this.graphToagrusedByXMGraceToolStripMenuItem.Name = "graphToagrusedByXMGraceToolStripMenuItem";
this.graphToagrusedByXMGraceToolStripMenuItem.Size = new System.Drawing.Size(260, 22);
this.graphToagrusedByXMGraceToolStripMenuItem.Text = "Graph to .agr (used by XM/Grace)...";
this.graphToagrusedByXMGraceToolStripMenuItem.Click += new System.EventHandler(this.graphToagrusedByXMGraceToolStripMenuItem_Click);
//
// imageToolStripMenuItem
//
this.imageToolStripMenuItem.Name = "imageToolStripMenuItem";
this.imageToolStripMenuItem.Size = new System.Drawing.Size(260, 22);
this.imageToolStripMenuItem.Text = "Image...";
this.imageToolStripMenuItem.Click += new System.EventHandler(this.imageToolStripMenuItem_Click);
//
// encapsulatedPostScriptToolStripMenuItem
//
this.encapsulatedPostScriptToolStripMenuItem.Name = "encapsulatedPostScriptToolStripMenuItem";
this.encapsulatedPostScriptToolStripMenuItem.Size = new System.Drawing.Size(260, 22);
this.encapsulatedPostScriptToolStripMenuItem.Text = "Encapsulated PostScript (EPS)...";
this.encapsulatedPostScriptToolStripMenuItem.Click += new System.EventHandler(this.encapsulatedPostScriptToolStripMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(182, 6);
//
// pageSetupToolStripMenuItem
//
this.pageSetupToolStripMenuItem.Name = "pageSetupToolStripMenuItem";
this.pageSetupToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.pageSetupToolStripMenuItem.Text = "Page Setup...";
this.pageSetupToolStripMenuItem.Click += new System.EventHandler(this.pageSetupToolStripMenuItem_Click);
//
// printPreviewToolStripMenuItem
//
this.printPreviewToolStripMenuItem.Name = "printPreviewToolStripMenuItem";
this.printPreviewToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.printPreviewToolStripMenuItem.Text = "Print Preview...";
this.printPreviewToolStripMenuItem.Click += new System.EventHandler(this.printPreviewToolStripMenuItem_Click);
//
// printToolStripMenuItem
//
this.printToolStripMenuItem.Name = "printToolStripMenuItem";
this.printToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.printToolStripMenuItem.Text = "Print...";
this.printToolStripMenuItem.Click += new System.EventHandler(this.printToolStripMenuItem_Click);
//
// printDialog
//
this.printDialog.Document = this.printDocument;
this.printDialog.UseEXDialog = true;
//
// printDocument
//
this.printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDocument_PrintPage);
//
// printPreviewDialog
//
this.printPreviewDialog.AutoScrollMargin = new System.Drawing.Size(0, 0);
this.printPreviewDialog.AutoScrollMinSize = new System.Drawing.Size(0, 0);
this.printPreviewDialog.ClientSize = new System.Drawing.Size(400, 300);
this.printPreviewDialog.Document = this.printDocument;
this.printPreviewDialog.Enabled = true;
this.printPreviewDialog.Icon = ((System.Drawing.Icon)(resources.GetObject("printPreviewDialog.Icon")));
this.printPreviewDialog.Name = "printPreviewDialog";
this.printPreviewDialog.Visible = false;
//
// pageSetupDialog
//
this.pageSetupDialog.Document = this.printDocument;
//
// Graph
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ContextMenuStrip = this.menu;
this.Controls.Add(this.txtMinY);
this.Controls.Add(this.txtMaxY);
this.Controls.Add(this.txtMinX);
this.Controls.Add(this.txtMaxX);
this.DoubleBuffered = true;
this.Name = "Graph";
this.Size = new System.Drawing.Size(260, 229);
this.Load += new System.EventHandler(this.Graph_Load);
this.Click += new System.EventHandler(this.ClickOffTextBox);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Graph_Paint);
this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.Graph_MouseClick);
this.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.Graph_MouseDoubleClick);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Graph_MouseDown);
this.MouseEnter += new System.EventHandler(this.Graph_MouseEnter);
this.MouseLeave += new System.EventHandler(this.Graph_MouseLeave);
this.MouseHover += new System.EventHandler(this.Graph_MouseHover);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Graph_MouseMove);
this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Graph_MouseUp);
this.Resize += new System.EventHandler(this.Graph_Resize);
this.menu.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtMaxX;
private System.Windows.Forms.TextBox txtMinX;
private System.Windows.Forms.TextBox txtMaxY;
private System.Windows.Forms.TextBox txtMinY;
private System.Windows.Forms.ContextMenuStrip menu;
private System.Windows.Forms.ToolStripMenuItem mnuShowTitle;
private System.Windows.Forms.ToolStripMenuItem titleToolStripMenuItem;
private System.Windows.Forms.ToolStripTextBox txtTitle;
private System.Windows.Forms.ToolStripMenuItem autoScaleAxesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem exportDataToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem textToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem graphToagrusedByXMGraceToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem horizontalAxisToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem verticalAxisToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem;
private System.Windows.Forms.PrintDialog printDialog;
private System.Windows.Forms.ToolStripMenuItem printPreviewToolStripMenuItem;
private System.Windows.Forms.PrintPreviewDialog printPreviewDialog;
private System.Drawing.Printing.PrintDocument printDocument;
private System.Windows.Forms.PageSetupDialog pageSetupDialog;
private System.Windows.Forms.ToolStripMenuItem pageSetupToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editDatasetsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem imageToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem encapsulatedPostScriptToolStripMenuItem;
private System.Windows.Forms.SaveFileDialog saveFile;
}
}
| |
//
// SCSharp.UI.ReadyRoomScreen
//
// Authors:
// Chris Toshok (toshok@gmail.com)
//
// Copyright 2006-2010 Chris Toshok
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using SdlDotNet.Core;
using SdlDotNet.Graphics;
using System.Drawing;
namespace SCSharp.UI
{
public class ReadyRoomScreen : UIScreen
{
public ReadyRoomScreen (Mpq mpq,
string scenario_prefix,
int start_element_index,
int cancel_element_index,
int skiptutorial_element_index,
int replay_element_index,
int transmission_element_index,
int objectives_element_index,
int first_portrait_element_index)
: base (mpq,
String.Format ("glue\\Ready{0}", Util.RaceChar[(int)Game.Instance.Race]),
String.Format (Builtins.rez_GluRdyBin, Util.RaceCharLower[(int)Game.Instance.Race]))
{
background_path = String.Format ("glue\\PalR{0}\\Backgnd.pcx", Util.RaceCharLower[(int)Game.Instance.Race]);
fontpal_path = String.Format ("glue\\PalR{0}\\tFont.pcx", Util.RaceCharLower[(int)Game.Instance.Race]);
effectpal_path = String.Format ("glue\\PalR{0}\\tEffect.pcx", Util.RaceCharLower[(int)Game.Instance.Race]);
arrowgrp_path = String.Format ("glue\\PalR{0}\\arrow.grp", Util.RaceCharLower[(int)Game.Instance.Race]);
this.start_element_index = start_element_index;
this.cancel_element_index = cancel_element_index;
this.skiptutorial_element_index = skiptutorial_element_index;
this.replay_element_index = replay_element_index;
this.transmission_element_index = transmission_element_index;
this.objectives_element_index = objectives_element_index;
this.first_portrait_element_index = first_portrait_element_index;
this.scenario = (Chk)mpq.GetResource (scenario_prefix + "\\staredit\\scenario.chk");
this.scenario_prefix = scenario_prefix;
}
BriefingRunner runner;
Chk scenario;
string scenario_prefix;
int start_element_index;
int cancel_element_index;
int skiptutorial_element_index;
int replay_element_index;
int transmission_element_index;
int objectives_element_index;
int first_portrait_element_index;
List<MovieElement> portraits;
List<ImageElement> hframes;
List<ImageElement> frames;
protected override void ResourceLoader ()
{
TranslucentIndex = 138;
base.ResourceLoader ();
for (int i = 0; i < Elements.Count; i ++)
Console.WriteLine ("{0}: {1} '{2}' {3}", i, Elements[i].Type, Elements[i].Text, Elements[i].Flags);
if (scenario_prefix.EndsWith ("tutorial")) {
Elements[skiptutorial_element_index].Visible = true;
/* XXX Activate */
}
Elements[cancel_element_index].Activate +=
delegate () {
StopBriefing ();
Game.Instance.SwitchToScreen (UIScreenType.Login);
};
Elements[replay_element_index].Activate +=
delegate () {
StopBriefing ();
PlayBriefing ();
};
Elements[start_element_index].Activate +=
delegate () {
StopBriefing ();
Game.Instance.SwitchToScreen (new GameScreen (mpq, scenario_prefix, scenario));
};
runner = new BriefingRunner (this, scenario, scenario_prefix);
portraits = new List<MovieElement> ();
hframes = new List<ImageElement> ();
frames = new List<ImageElement> ();
for (int i = 0; i < 4; i ++) {
MovieElement m = new MovieElement (this,
Elements[first_portrait_element_index + i].BinElement,
Elements[first_portrait_element_index + i].Palette,
true);
m.X1 += 3;
m.Y1 += 3;
m.Width -= 6;
m.Height -= 6;
ImageElement f = new ImageElement (this,
Elements[first_portrait_element_index + i].BinElement,
Elements[first_portrait_element_index + i].Palette,
TranslucentIndex);
f.Text = String.Format ("glue\\Ready{0}\\{0}Frame{1}.pcx",
Util.RaceChar[(int)Game.Instance.Race],
i + 1);
ImageElement h = new ImageElement (this,
Elements[first_portrait_element_index + i].BinElement,
Elements[first_portrait_element_index + i].Palette,
TranslucentIndex);
h.Text = String.Format ("glue\\Ready{0}\\{0}FrameH{1}.pcx",
Util.RaceChar[(int)Game.Instance.Race],
i + 1);
f.Visible = false;
h.Visible = false;
m.Visible = false;
portraits.Add (m);
hframes.Add (h);
frames.Add (f);
Elements.Add (m);
Elements.Add (h);
Elements.Add (f);
}
}
void StopBriefing ()
{
Events.Tick -= runner.Tick;
runner.Stop ();
Elements[transmission_element_index].Visible = false;
Elements[transmission_element_index].Text = "";
Elements[objectives_element_index].Visible = false;
Elements[objectives_element_index].Text = "";
for (int i = 0; i < 4; i ++) {
Elements[first_portrait_element_index + i].Visible = false;
portraits[i].Visible = false;
}
}
void PlayBriefing ()
{
runner.Play ();
}
public override void AddToPainter ()
{
base.AddToPainter ();
}
public override void RemoveFromPainter ()
{
base.RemoveFromPainter ();
foreach (UIElement el in Elements) {
if (el is MovieElement)
((MovieElement)el).Stop ();
}
}
protected override void FirstPaint (object sender, EventArgs args)
{
base.FirstPaint (sender, args);
Events.Tick += runner.Tick;
}
public void SetObjectives (string str)
{
Elements[objectives_element_index].Visible = true;
Elements[objectives_element_index].Text = str;
}
public void SetTransmissionText (string str)
{
Elements[transmission_element_index].Visible = true;
Elements[transmission_element_index].Text = str;
}
int highlightedPortrait = -1;
public void HighlightPortrait (int slot)
{
if (highlightedPortrait != -1)
UnhighlightPortrait (highlightedPortrait);
hframes[slot].Visible = true;
frames[slot].Visible = false;
highlightedPortrait = slot;
portraits[highlightedPortrait].Dim (0);
}
public void UnhighlightPortrait (int slot)
{
if (portraits[slot].Visible) {
hframes[slot].Visible = false;
frames[slot].Visible = true;
portraits[highlightedPortrait].Dim (100);
}
}
public void ShowPortrait (int unit, int slot)
{
Console.WriteLine ("showing portrait {0} (unit {1}, portrait index {2}) in slot {3}",
"" /*portrait_resource*/, unit,
GlobalResources.Instance.PortDataDat.PortraitIndexes [unit],
slot);
uint portraitIndex = GlobalResources.Instance.UnitsDat.Portraits [unit];
string portrait_resource = String.Format ("portrait\\{0}0.smk",
GlobalResources.Instance.PortDataTbl[(int)GlobalResources.Instance.PortDataDat.PortraitIndexes [(int)portraitIndex]]);
portraits[slot].Player = new SmackerPlayer ((Stream)Mpq.GetResource (portrait_resource), 1);
portraits[slot].Dim (100);
portraits[slot].Play ();
portraits[slot].Visible = true;
hframes[slot].Visible = false;
frames[slot].Visible = true;
}
public void HidePortrait (int slot)
{
portraits[slot].Visible = false;
hframes[slot].Visible = false;
frames[slot].Visible = true;
portraits[slot].Stop ();
}
public static ReadyRoomScreen Create (Mpq mpq,
string scenario_prefix)
{
switch (Game.Instance.Race) {
case Race.Terran:
return new TerranReadyRoomScreen (mpq, scenario_prefix);
case Race.Protoss:
return new ProtossReadyRoomScreen (mpq, scenario_prefix);
case Race.Zerg:
return new ZergReadyRoomScreen (mpq, scenario_prefix);
default:
return null;
}
}
}
class TerranReadyRoomScreen : ReadyRoomScreen
{
public TerranReadyRoomScreen (Mpq mpq,
string scenario_prefix)
: base (mpq,
scenario_prefix,
START_ELEMENT_INDEX,
CANCEL_ELEMENT_INDEX,
SKIPTUTORIAL_ELEMENT_INDEX,
REPLAY_ELEMENT_INDEX,
TRANSMISSION_ELEMENT_INDEX,
OBJECTIVES_ELEMENT_INDEX,
FIRST_PORTRAIT_ELEMENT_INDEX)
{
}
const int START_ELEMENT_INDEX = 1;
const int CANCEL_ELEMENT_INDEX = 9;
const int SKIPTUTORIAL_ELEMENT_INDEX = 11;
const int REPLAY_ELEMENT_INDEX = 12;
const int FIRST_PORTRAIT_ELEMENT_INDEX = 13;
const int TRANSMISSION_ELEMENT_INDEX = 17;
const int OBJECTIVES_ELEMENT_INDEX = 18;
}
class ProtossReadyRoomScreen : ReadyRoomScreen
{
public ProtossReadyRoomScreen (Mpq mpq,
string scenario_prefix)
: base (mpq,
scenario_prefix,
START_ELEMENT_INDEX,
CANCEL_ELEMENT_INDEX,
SKIPTUTORIAL_ELEMENT_INDEX,
REPLAY_ELEMENT_INDEX,
TRANSMISSION_ELEMENT_INDEX,
OBJECTIVES_ELEMENT_INDEX,
FIRST_PORTRAIT_ELEMENT_INDEX)
{
}
const int START_ELEMENT_INDEX = 1;
const int CANCEL_ELEMENT_INDEX = 9;
const int SKIPTUTORIAL_ELEMENT_INDEX = 11;
const int REPLAY_ELEMENT_INDEX = 12;
const int FIRST_PORTRAIT_ELEMENT_INDEX = 13;
const int TRANSMISSION_ELEMENT_INDEX = 17;
const int OBJECTIVES_ELEMENT_INDEX = 18;
}
class ZergReadyRoomScreen : ReadyRoomScreen
{
public ZergReadyRoomScreen (Mpq mpq,
string scenario_prefix)
: base (mpq,
scenario_prefix,
START_ELEMENT_INDEX,
CANCEL_ELEMENT_INDEX,
SKIPTUTORIAL_ELEMENT_INDEX,
REPLAY_ELEMENT_INDEX,
TRANSMISSION_ELEMENT_INDEX,
OBJECTIVES_ELEMENT_INDEX,
FIRST_PORTRAIT_ELEMENT_INDEX)
{
}
const int START_ELEMENT_INDEX = 1;
const int CANCEL_ELEMENT_INDEX = 10;
const int SKIPTUTORIAL_ELEMENT_INDEX = 12;
const int REPLAY_ELEMENT_INDEX = 13;
const int FIRST_PORTRAIT_ELEMENT_INDEX = 14;
const int TRANSMISSION_ELEMENT_INDEX = 18;
const int OBJECTIVES_ELEMENT_INDEX = 19;
}
class BriefingRunner
{
TriggerData triggerData;
Chk scenario;
ReadyRoomScreen screen;
string prefix;
int sleepUntil;
int totalElapsed;
int current_action;
public BriefingRunner (ReadyRoomScreen screen, Chk scenario,
string scenario_prefix)
{
this.screen = screen;
this.scenario = scenario;
this.prefix = scenario_prefix;
triggerData = scenario.BriefingData;
}
public void Play ()
{
current_action = 0;
}
public void Stop ()
{
sleepUntil = 0;
}
public void Tick (object sender, TickEventArgs e)
{
TriggerAction[] actions = triggerData.Triggers[0].Actions;
if (current_action == actions.Length)
return;
totalElapsed += e.TicksElapsed;
/* if we're presently waiting, make sure
enough time has gone by. otherwise
return */
if (totalElapsed < sleepUntil)
return;
totalElapsed = 0;
while (current_action < actions.Length) {
TriggerAction action = actions[current_action];
current_action ++;
switch (action.Action) {
case 0: /* no action */
break;
case 1:
sleepUntil = (int)action.Delay;
return;
case 2:
GuiUtil.PlaySound (screen.Mpq, prefix + "\\" + scenario.GetMapString ((int)action.WavIndex));
sleepUntil = (int)action.Delay;
return;
case 3:
screen.SetTransmissionText (scenario.GetMapString ((int)action.TextIndex));
break;
case 4:
screen.SetObjectives (scenario.GetMapString ((int)action.TextIndex));
break;
case 5:
Console.WriteLine ("show portrait:");
Console.WriteLine ("location = {0}, textindex = {1}, wavindex = {2}, delay = {3}, group1 = {4}, group2 = {5}, unittype = {6}, action = {7}, switch = {8}, flags = {9}",
action.Location,
action.TextIndex,
action.WavIndex,
action.Delay,
action.Group1,
action.Group2,
action.UnitType,
action.Action,
action.Switch,
action.Flags);
screen.ShowPortrait ((int)action.UnitType, (int)action.Group1);
Console.WriteLine (scenario.GetMapString ((int)action.TextIndex));
break;
case 6:
screen.HidePortrait ((int)action.Group1);
break;
case 7:
Console.WriteLine ("Display Speaking Portrait(Slot, Time)");
Console.WriteLine (scenario.GetMapString ((int)action.TextIndex));
break;
case 8:
Console.WriteLine ("Transmission(Text, Slot, Time, Modifier, Wave, WavTime)");
screen.SetTransmissionText (scenario.GetMapString ((int)action.TextIndex));
screen.HighlightPortrait ((int)action.Group1);
GuiUtil.PlaySound (screen.Mpq, prefix + "\\" + scenario.GetMapString ((int)action.WavIndex));
sleepUntil = (int)action.Delay;
return;
default:
break;
}
}
}
}
public class EstablishingShot : MarkupScreen {
string markup_resource;
string scenario_prefix;
public EstablishingShot (string markup_resource, string scenario_prefix, Mpq mpq) : base (mpq)
{
this.markup_resource = markup_resource;
this.scenario_prefix = scenario_prefix;
}
protected override void LoadMarkup ()
{
AddMarkup ((Stream)mpq.GetResource (markup_resource));
}
protected override void MarkupFinished ()
{
Game.Instance.SwitchToScreen (ReadyRoomScreen.Create (mpq, scenario_prefix));
}
}
}
| |
namespace Economy.scripts.Messages
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Economy.scripts;
using Management;
using ProtoBuf;
using Sandbox.ModAPI;
using VRage;
using VRage.Game.ModAPI;
/// <summary>
/// this is to do the actual work of setting new prices and stock levels.
/// </summary>
[ProtoContract]
public class MessageConfig : MessageBase
{
#region properties
/// <summary>
/// The key config item to set.
/// </summary>
[ProtoMember(1)]
public string ConfigName;
/// <summary>
/// The value to set the config item to.
/// </summary>
[ProtoMember(2)]
public string Value;
#endregion
public static void SendMessage(string configName, string value)
{
ConnectionHelper.SendMessageToServer(new MessageConfig { ConfigName = configName.ToLower(), Value = value });
}
public override void ProcessClient()
{
// never processed on client
}
public override void ProcessServer()
{
var player = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId);
// Only Admin can change config.
if (!player.IsAdmin())
{
EconomyScript.Instance.ServerLogger.WriteWarning("A Player without Admin \"{0}\" {1} attempted to access EConfig.", SenderDisplayName, SenderSteamId);
return;
}
MyTexts.LanguageDescription myLanguage;
// These will match with names defined in the RegEx patterm <EconomyScript.EconfigPattern>
switch (ConfigName)
{
#region language
case "language":
if (string.IsNullOrEmpty(Value))
{
myLanguage = MyTexts.Languages[EconomyScript.Instance.ServerConfig.Language];
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "Language: {0} ({1})", myLanguage.Name, myLanguage.FullCultureName);
}
else
{
int intTest;
if (int.TryParse(Value, out intTest))
{
if (MyTexts.Languages.ContainsKey(intTest))
{
EconomyScript.Instance.ServerConfig.Language = intTest;
EconomyScript.Instance.SetLanguage();
myLanguage = MyTexts.Languages[intTest];
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "Language updated to: {0} ({1})", myLanguage.Name, myLanguage.FullCultureName);
return;
}
}
foreach (var lang in MyTexts.Languages)
{
if (lang.Value.Name.Equals(Value, StringComparison.InvariantCultureIgnoreCase)
|| lang.Value.CultureName.Equals(Value, StringComparison.InvariantCultureIgnoreCase)
|| lang.Value.FullCultureName.Equals(Value, StringComparison.InvariantCultureIgnoreCase))
{
EconomyScript.Instance.ServerConfig.Language = (int)lang.Value.Id;
EconomyScript.Instance.SetLanguage();
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "Language updated to: {0} ({1})", lang.Value.Name, lang.Value.FullCultureName);
return;
}
}
myLanguage = MyTexts.Languages[EconomyScript.Instance.ServerConfig.Language];
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "Language: {0} ({1})", myLanguage.Name, myLanguage.FullCultureName);
}
break;
#endregion
#region tradenetworkname
case "tradenetworkname":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "TradenetworkName: {0}", EconomyScript.Instance.ServerConfig.TradeNetworkName);
else
{
EconomyScript.Instance.ServerConfig.TradeNetworkName = Value;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "TradenetworkName updated to: \"{0}\"", EconomyScript.Instance.ServerConfig.TradeNetworkName);
// push updates to all clients.
var listPlayers = new List<IMyPlayer>();
MyAPIGateway.Players.GetPlayers(listPlayers);
foreach (var connectedPlayer in listPlayers)
MessageUpdateClient.SendTradeNetworkName(connectedPlayer.SteamUserId, EconomyScript.Instance.ServerConfig.TradeNetworkName);
}
break;
#endregion
#region currencyname
case "currencyname":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "CurrencyName: {0}", EconomyScript.Instance.ServerConfig.CurrencyName);
else
{
EconomyScript.Instance.ServerConfig.CurrencyName = Value;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "CurrencyName updated to: \"{0}\"", EconomyScript.Instance.ServerConfig.CurrencyName);
// push updates to all clients.
var listPlayers = new List<IMyPlayer>();
MyAPIGateway.Players.GetPlayers(listPlayers);
foreach (var connectedPlayer in listPlayers)
MessageUpdateClient.SendCurrencyName(connectedPlayer.SteamUserId, EconomyScript.Instance.ServerConfig.CurrencyName);
}
break;
#endregion
#region limitedrange
case "limitedrange":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LimitedRange: {0}", EconomyScript.Instance.ServerConfig.LimitedRange ? "On" : "Off");
else
{
bool? boolTest = GetBool(Value);
if (boolTest.HasValue)
{
EconomyScript.Instance.ServerConfig.LimitedRange = boolTest.Value;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LimitedRange updated to: {0}", EconomyScript.Instance.ServerConfig.LimitedRange ? "On" : "Off");
return;
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LimitedRange: {0}", EconomyScript.Instance.ServerConfig.LimitedRange ? "On" : "Off");
}
break;
#endregion
#region limitedsupply
case "limitedsupply":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LimitedSupply: {0}", EconomyScript.Instance.ServerConfig.LimitedSupply ? "On" : "Off");
else
{
bool? boolTest = GetBool(Value);
if (boolTest.HasValue)
{
EconomyScript.Instance.ServerConfig.LimitedSupply = boolTest.Value;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LimitedSupply updated to: {0}", EconomyScript.Instance.ServerConfig.LimitedSupply ? "On" : "Off");
return;
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LimitedSupply: {0}", EconomyScript.Instance.ServerConfig.LimitedSupply ? "On" : "Off");
}
break;
#endregion
#region enablelcds
case "enablelcds":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "EnableLcds: {0}", EconomyScript.Instance.ServerConfig.EnableLcds ? "On" : "Off");
else
{
bool? boolTest = GetBool(Value);
if (boolTest.HasValue)
{
var clearRefresh = EconomyScript.Instance.ServerConfig.EnableLcds && !boolTest.Value;
EconomyScript.Instance.ServerConfig.EnableLcds = boolTest.Value;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "EnableLcds updated to: {0}", EconomyScript.Instance.ServerConfig.EnableLcds ? "On" : "Off");
if (clearRefresh)
LcdManager.BlankLcds();
return;
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "EnableLcds: {0}", EconomyScript.Instance.ServerConfig.EnableLcds ? "On" : "Off");
}
break;
#endregion
#region EnableNpcTradezones
case "enablenpctradezones":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "EnableNpcTradezones: {0}", EconomyScript.Instance.ServerConfig.EnableNpcTradezones ? "On" : "Off");
else
{
bool? boolTest = GetBool(Value);
if (boolTest.HasValue)
{
var clearRefresh = EconomyScript.Instance.ServerConfig.EnableNpcTradezones && !boolTest.Value;
EconomyScript.Instance.ServerConfig.EnableNpcTradezones = boolTest.Value;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "EnableNpcTradezones updated to: {0}", EconomyScript.Instance.ServerConfig.EnableNpcTradezones ? "On" : "Off");
if (clearRefresh)
LcdManager.BlankLcds();
return;
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "EnableNpcTradezones: {0}", EconomyScript.Instance.ServerConfig.EnableNpcTradezones ? "On" : "Off");
}
break;
#endregion
#region EnablePlayerTradezones
case "enableplayertradezones":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "EnablePlayerTradezones: {0}", EconomyScript.Instance.ServerConfig.EnablePlayerTradezones ? "On" : "Off");
else
{
bool? boolTest = GetBool(Value);
if (boolTest.HasValue)
{
var clearRefresh = EconomyScript.Instance.ServerConfig.EnablePlayerTradezones && !boolTest.Value;
EconomyScript.Instance.ServerConfig.EnablePlayerTradezones = boolTest.Value;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "EnablePlayerTradezones updated to: {0}", EconomyScript.Instance.ServerConfig.EnablePlayerTradezones ? "On" : "Off");
if (clearRefresh)
LcdManager.BlankLcds();
return;
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "EnablePlayerTradezones: {0}", EconomyScript.Instance.ServerConfig.EnablePlayerTradezones ? "On" : "Off");
}
break;
#endregion
#region EnablePlayerPayments
case "enableplayerpayments":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "EnablePlayerPayments: {0}", EconomyScript.Instance.ServerConfig.EnablePlayerPayments ? "On" : "Off");
else
{
bool? boolTest = GetBool(Value);
if (boolTest.HasValue)
{
var clearRefresh = EconomyScript.Instance.ServerConfig.EnablePlayerPayments && !boolTest.Value;
EconomyScript.Instance.ServerConfig.EnablePlayerPayments = boolTest.Value;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "EnablePlayerPayments updated to: {0}", EconomyScript.Instance.ServerConfig.EnablePlayerPayments ? "On" : "Off");
if (clearRefresh)
LcdManager.BlankLcds();
return;
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "EnablePlayerPayments: {0}", EconomyScript.Instance.ServerConfig.EnablePlayerPayments ? "On" : "Off");
}
break;
#endregion
#region tradetimeout
case "tradetimeout":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "TradeTimeout: {0}", EconomyScript.Instance.ServerConfig.TradeTimeout);
else
{
TimeSpan timeTest;
if (TimeSpan.TryParse(Value, out timeTest))
{
EconomyScript.Instance.ServerConfig.TradeTimeout = timeTest;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "TradeTimeout updated to: {0} ", EconomyScript.Instance.ServerConfig.TradeTimeout);
return;
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "TradeTimeout: {0}", EconomyScript.Instance.ServerConfig.TradeTimeout);
}
break;
#endregion
#region accountexpiry
case "accountexpiry":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "AccountExpiry: {0}", EconomyScript.Instance.ServerConfig.AccountExpiry);
else
{
TimeSpan timeTest;
if (TimeSpan.TryParse(Value, out timeTest))
{
EconomyScript.Instance.ServerConfig.AccountExpiry = timeTest;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "AccountExpiry updated to: {0} ", EconomyScript.Instance.ServerConfig.AccountExpiry);
return;
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "AccountExpiry: {0}", EconomyScript.Instance.ServerConfig.AccountExpiry);
}
break;
#endregion
#region startingbalance
case "startingbalance":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "StartingBalance: {0}", EconomyScript.Instance.ServerConfig.DefaultStartingBalance);
else
{
decimal decimalTest;
if (decimal.TryParse(Value, NumberStyles.Any, CultureInfo.InvariantCulture, out decimalTest))
{
// TODO: perhaps we should truncate the value.
if (decimalTest >= 0)
{
EconomyScript.Instance.ServerConfig.DefaultStartingBalance = decimalTest;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "StartingBalance updated to: {0} ", EconomyScript.Instance.ServerConfig.DefaultStartingBalance);
return;
}
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "StartingBalance: {0}", EconomyScript.Instance.ServerConfig.DefaultStartingBalance);
}
break;
#endregion
#region LicenceMin
case "licencemin":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LicenceMin: {0}", EconomyScript.Instance.ServerConfig.TradeZoneLicenceCostMin);
else
{
decimal decimalTest;
if (decimal.TryParse(Value, NumberStyles.Any, CultureInfo.InvariantCulture, out decimalTest))
{
// TODO: perhaps we should truncate the value.
if (decimalTest >= 0)
{
if (EconomyScript.Instance.ServerConfig.TradeZoneLicenceCostMax < decimalTest)
{
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LicenceMin cannot be more than LicenceMax.");
return;
}
EconomyScript.Instance.ServerConfig.TradeZoneLicenceCostMin = decimalTest;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LicenceMin updated to: {0} ", EconomyScript.Instance.ServerConfig.TradeZoneLicenceCostMin);
return;
}
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LicenceMin: {0}", EconomyScript.Instance.ServerConfig.TradeZoneLicenceCostMin);
}
break;
#endregion
#region LicenceMax
case "licencemax":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LicenceMax: {0}", EconomyScript.Instance.ServerConfig.TradeZoneLicenceCostMax);
else
{
decimal decimalTest;
if (decimal.TryParse(Value, NumberStyles.Any, CultureInfo.InvariantCulture, out decimalTest))
{
// TODO: perhaps we should truncate the value.
if (decimalTest >= 0)
{
if (decimalTest < EconomyScript.Instance.ServerConfig.TradeZoneLicenceCostMin)
{
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LicenceMax cannot be less than LicenceMin.");
return;
}
EconomyScript.Instance.ServerConfig.TradeZoneLicenceCostMax = decimalTest;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LicenceMax updated to: {0} ", EconomyScript.Instance.ServerConfig.TradeZoneLicenceCostMax);
return;
}
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LicenceMax: {0}", EconomyScript.Instance.ServerConfig.TradeZoneLicenceCostMax);
}
break;
#endregion
#region RelinkRatio
case "relinkratio":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "RelinkRatio: {0}", EconomyScript.Instance.ServerConfig.TradeZoneRelinkRatio);
else
{
var numFormat = CultureInfo.CurrentCulture.NumberFormat;
NumberFormatInfo nfi = new NumberFormatInfo()
{
CurrencyDecimalDigits = numFormat.PercentDecimalDigits,
CurrencyDecimalSeparator = numFormat.PercentDecimalSeparator,
CurrencyGroupSeparator = numFormat.PercentGroupSeparator,
CurrencyGroupSizes = numFormat.PercentGroupSizes,
CurrencyNegativePattern = numFormat.PercentNegativePattern,
CurrencyPositivePattern = numFormat.PercentPositivePattern,
CurrencySymbol = numFormat.PercentSymbol
};
decimal decimalTest;
if (decimal.TryParse(Value, NumberStyles.Any, CultureInfo.InvariantCulture, out decimalTest))
{
// TODO: perhaps we should truncate the value.
if (decimalTest >= 0)
{
EconomyScript.Instance.ServerConfig.TradeZoneRelinkRatio = decimalTest;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "RelinkRatio updated to: {0:P} ", EconomyScript.Instance.ServerConfig.TradeZoneRelinkRatio);
return;
}
}
else if (decimal.TryParse(Value, NumberStyles.Currency, nfi, out decimalTest))
{
// TODO: perhaps we should truncate the value.
if (decimalTest >= 0)
{
EconomyScript.Instance.ServerConfig.TradeZoneRelinkRatio = decimalTest / 100;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "RelinkRatio updated to: {0:P} ", EconomyScript.Instance.ServerConfig.TradeZoneRelinkRatio);
return;
}
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "RelinkRatio: {0:P}", EconomyScript.Instance.ServerConfig.TradeZoneRelinkRatio);
}
break;
#endregion
#region MaximumPlayerZones
case "maximumplayerzones":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "MaximumPlayerZones: {0}", EconomyScript.Instance.ServerConfig.MaximumPlayerTradeZones);
else
{
int intTest;
if (int.TryParse(Value, out intTest))
{
if (intTest >= 0)
{
EconomyScript.Instance.ServerConfig.MaximumPlayerTradeZones = intTest;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "MaximumPlayerZones updated to: {0} ", EconomyScript.Instance.ServerConfig.MaximumPlayerTradeZones);
return;
}
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "TradeZoneLicence: {0}", EconomyScript.Instance.ServerConfig.MaximumPlayerTradeZones);
}
break;
#endregion
#region pricescaling
case "pricescaling":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "PriceScaling: {0}", EconomyScript.Instance.ServerConfig.PriceScaling ? "On" : "Off");
else
{
bool? boolTest = GetBool(Value);
if (boolTest.HasValue)
{
EconomyScript.Instance.ServerConfig.PriceScaling = boolTest.Value;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "PriceScaling updated to: {0}", EconomyScript.Instance.ServerConfig.PriceScaling ? "On" : "Off");
return;
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "PriceScaling: {0}", EconomyScript.Instance.ServerConfig.PriceScaling ? "On" : "Off");
}
break;
#endregion
#region shiptrading
case "shiptrading":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "ShipTrading: {0}", EconomyScript.Instance.ServerConfig.ShipTrading ? "On" : "Off");
else
{
bool? boolTest = GetBool(Value);
if (boolTest.HasValue)
{
EconomyScript.Instance.ServerConfig.ShipTrading = boolTest.Value;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "ShipTrading updated to: {0}", EconomyScript.Instance.ServerConfig.ShipTrading ? "On" : "Off");
return;
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "ShipTrading: {0}", EconomyScript.Instance.ServerConfig.ShipTrading ? "On" : "Off");
}
break;
#endregion
#region MinimumLcdDisplayInterval
case "lcddisplayinterval":
if (string.IsNullOrEmpty(Value))
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LcdDisplayInterval: {0}", EconomyScript.Instance.ServerConfig.MinimumLcdDisplayInterval);
else
{
decimal decimalTest;
if (decimal.TryParse(Value, NumberStyles.Any, CultureInfo.InvariantCulture, out decimalTest))
{
// TODO: perhaps we should truncate the value.
if (decimalTest >= 0)
{
if (decimalTest < 1)
{
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LcdDisplayInterval cannot be less than 1 second.");
return;
}
if (decimalTest > 1000) // no particular reason for 1000, apart from it been a reasonable limit.
{
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LcdDisplayInterval cannot be more than 1000 second.");
return;
}
EconomyScript.Instance.ServerConfig.MinimumLcdDisplayInterval = decimalTest;
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LcdDisplayInterval updated to: {0} seconds", EconomyScript.Instance.ServerConfig.MinimumLcdDisplayInterval);
return;
}
}
MessageClientTextMessage.SendMessage(SenderSteamId, "ECONFIG", "LcdDisplayInterval: {0} seconds", EconomyScript.Instance.ServerConfig.MinimumLcdDisplayInterval);
}
break;
#endregion
#region default
default:
var msg = new StringBuilder();
myLanguage = MyTexts.Languages[EconomyScript.Instance.ServerConfig.Language];
msg.AppendFormat("Language: {0} ({1})\r\n", myLanguage.Name, myLanguage.FullCultureName);
msg.AppendFormat("TradenetworkName: \"{0}\"\r\n", EconomyScript.Instance.ServerConfig.TradeNetworkName);
msg.AppendFormat("LimitedRange: {0}\r\n", EconomyScript.Instance.ServerConfig.LimitedRange ? "On" : "Off");
msg.AppendFormat("LimitedSupply: {0}\r\n", EconomyScript.Instance.ServerConfig.LimitedSupply ? "On" : "Off");
msg.AppendFormat("TradeTimeout: {0} (days.hours:mins:secs)\r\n", EconomyScript.Instance.ServerConfig.TradeTimeout);
msg.AppendFormat("StartingBalance: {0:#,#.######}\r\n", EconomyScript.Instance.ServerConfig.DefaultStartingBalance);
msg.AppendFormat("CurrencyName: \"{0}\"\r\n", EconomyScript.Instance.ServerConfig.CurrencyName);
msg.AppendFormat("AccountExpiry: {0} (days.hours:mins:secs)\r\n", EconomyScript.Instance.ServerConfig.AccountExpiry);
msg.AppendFormat("EnableLcds: {0}\r\n", EconomyScript.Instance.ServerConfig.EnableLcds ? "On" : "Off");
msg.AppendFormat("EnableNpcTradezones: {0}\r\n", EconomyScript.Instance.ServerConfig.EnableNpcTradezones ? "On" : "Off");
msg.AppendFormat("PriceScaling: {0}\r\n", EconomyScript.Instance.ServerConfig.PriceScaling ? "On" : "Off");
msg.AppendFormat("ShipTrading: {0}\r\n", EconomyScript.Instance.ServerConfig.ShipTrading ? "On" : "Off");
msg.AppendFormat("LcdDisplayInterval: {0:#,#.######} seconds\r\n", EconomyScript.Instance.ServerConfig.MinimumLcdDisplayInterval);
msg.AppendLine();
msg.AppendLine("--- Player Tradezones ---");
msg.AppendFormat("EnablePlayerTradezones: {0}\r\n", EconomyScript.Instance.ServerConfig.EnablePlayerTradezones ? "On" : "Off");
msg.AppendFormat("EnablePlayerPayments: {0}\r\n", EconomyScript.Instance.ServerConfig.EnablePlayerPayments ? "On" : "Off");
msg.AppendFormat("LicenceMin: {0:#,#.######} (at {1:#,#.######}m)\r\n", EconomyScript.Instance.ServerConfig.TradeZoneLicenceCostMin, EconomyScript.Instance.ServerConfig.TradeZoneMinRadius);
msg.AppendFormat("LicenceMax: {0:#,#.######} (at {1:#,#.######}m)\r\n", EconomyScript.Instance.ServerConfig.TradeZoneLicenceCostMax, EconomyScript.Instance.ServerConfig.TradeZoneMaxRadius);
msg.AppendFormat("RelinkRatio: {0:P}\r\n", EconomyScript.Instance.ServerConfig.TradeZoneRelinkRatio);
msg.AppendFormat("MaximumPlayerZones: {0}\r\n", EconomyScript.Instance.ServerConfig.MaximumPlayerTradeZones);
MessageClientDialogMessage.SendMessage(SenderSteamId, "ECONFIG", " ", msg.ToString());
break;
#endregion
}
}
private bool? GetBool(string value)
{
bool boolTest;
if (bool.TryParse(value, out boolTest))
return boolTest;
if (value.Equals("off", StringComparison.InvariantCultureIgnoreCase) || value == "0")
return false;
if (value.Equals("on", StringComparison.InvariantCultureIgnoreCase) || value == "1")
return true;
return null;
}
}
}
| |
using PlayFab.PfEditor.EditorModels;
using PlayFab.PfEditor.Json;
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace PlayFab.PfEditor
{
[InitializeOnLoad]
public class PlayFabEditorDataService : UnityEditor.Editor
{
#region EditorPref data classes
public class PlayFab_DeveloperAccountDetails
{
public static string Name = "PlayFab_DeveloperAccountDetails";
public string email;
public string devToken;
public List<Studio> studios;
public PlayFab_DeveloperAccountDetails()
{
studios = null; // Null means not fetched, empty is a possible return result from GetStudios
}
}
public class PlayFab_DeveloperEnvironmentDetails
{
public static string Name = "PlayFab_DeveloperEnvironmentDetails";
public string selectedStudio;
public Dictionary<string, string> titleData;
public Dictionary<string, string> titleInternalData;
public string sdkPath;
public string edexPath;
public string localCloudScriptPath;
public PlayFab_DeveloperEnvironmentDetails()
{
titleData = new Dictionary<string, string>();
titleInternalData = new Dictionary<string, string>();
}
}
public class PlayFab_SharedSettingsProxy
{
private readonly PropertyInfo _titleId;
private readonly PropertyInfo _developerSecretKey;
private readonly PropertyInfo _webRequestType;
private readonly PropertyInfo _compressApiData;
private readonly PropertyInfo _keepAlive;
private readonly PropertyInfo _timeOut;
public string TitleId { get { return (string)_titleId.GetValue(null, null); } set { _titleId.SetValue(null, value, null); } }
public string DeveloperSecretKey { get { return (string)_developerSecretKey.GetValue(null, null); } set { _developerSecretKey.SetValue(null, value, null); } }
public PlayFabEditorSettings.WebRequestType WebRequestType { get { return (PlayFabEditorSettings.WebRequestType)_webRequestType.GetValue(null, null); } set { _webRequestType.SetValue(null, (int)value, null); } }
public bool CompressApiData { get { return (bool)_compressApiData.GetValue(null, null); } set { _compressApiData.SetValue(null, value, null); } }
public bool KeepAlive { get { return (bool)_keepAlive.GetValue(null, null); } set { _keepAlive.SetValue(null, value, null); } }
public int TimeOut
{
get
{
return (int)_timeOut.GetValue(null, null);
}
set
{
_timeOut.SetValue(null, value, null);
}
}
public PlayFab_SharedSettingsProxy()
{
var playFabSettingsType = PlayFabEditorSDKTools.GetPlayFabSettings();
if (playFabSettingsType == null)
return;
var settingProperties = playFabSettingsType.GetProperties();
foreach (var eachProperty in settingProperties)
{
var lcName = eachProperty.Name.ToLower();
switch (lcName)
{
case "titleid":
_titleId = eachProperty; break;
case "developersecretkey":
_developerSecretKey = eachProperty; break;
case "requesttype":
_webRequestType = eachProperty; break;
case "compressapidata":
_compressApiData = eachProperty; break;
case "requestkeepalive":
_keepAlive = eachProperty; break;
case "requesttimeout":
_timeOut = eachProperty; break;
}
}
}
}
public class PlayFab_EditorSettings
{
public static string Name = "PlayFab_EditorSettings";
private bool _isEdExShown;
private string _latestSdkVersion;
private string _latestEdExVersion;
private DateTime _lastSdkVersionCheck;
private DateTime _lastEdExVersionCheck;
public bool isEdExShown { get { return _isEdExShown; } set { _isEdExShown = value; Save(); } }
public string latestSdkVersion { get { return _latestSdkVersion; } set { _latestSdkVersion = value; _lastSdkVersionCheck = DateTime.UtcNow; Save(); } }
public string latestEdExVersion { get { return _latestEdExVersion; } set { _latestEdExVersion = value; _lastEdExVersionCheck = DateTime.UtcNow; Save(); } }
public DateTime lastSdkVersionCheck { get { return _lastSdkVersionCheck; } }
public DateTime lastEdExVersionCheck { get { return _lastEdExVersionCheck; } }
public static void Save()
{
SaveToEditorPrefs(EditorSettings, Name);
}
}
public class PlayFab_EditorView
{
public static string Name = "PlayFab_EditorView";
private int _currentMainMenu;
private int _currentSubMenu;
public int currentMainMenu { get { return _currentMainMenu; } set { _currentMainMenu = value; Save(); } }
public int currentSubMenu { get { return _currentSubMenu; } set { _currentSubMenu = value; Save(); } }
private static void Save()
{
SaveToEditorPrefs(EditorView, Name);
}
}
#endregion EditorPref data classes
public static PlayFab_DeveloperAccountDetails AccountDetails;
public static PlayFab_DeveloperEnvironmentDetails EnvDetails;
public static PlayFab_SharedSettingsProxy SharedSettings = new PlayFab_SharedSettingsProxy();
public static PlayFab_EditorSettings EditorSettings;
public static PlayFab_EditorView EditorView;
private static string KeyPrefix
{
get
{
var dataPath = Application.dataPath;
var lastIndex = dataPath.LastIndexOf('/');
var secondToLastIndex = dataPath.LastIndexOf('/', lastIndex - 1);
return dataPath.Substring(secondToLastIndex, lastIndex - secondToLastIndex);
}
}
private static bool _IsDataLoaded = false;
public static bool IsDataLoaded { get { return _IsDataLoaded && AccountDetails != null && EnvDetails != null && EditorSettings != null && EditorView != null; } }
public static Title ActiveTitle
{
get
{
if (AccountDetails != null && AccountDetails.studios != null && AccountDetails.studios.Count > 0 && EnvDetails != null)
{
if (string.IsNullOrEmpty(EnvDetails.selectedStudio) || EnvDetails.selectedStudio == PlayFabEditorHelper.STUDIO_OVERRIDE)
return new Title { Id = SharedSettings.TitleId, SecretKey = SharedSettings.DeveloperSecretKey, GameManagerUrl = PlayFabEditorHelper.GAMEMANAGER_URL };
if (string.IsNullOrEmpty(EnvDetails.selectedStudio) || string.IsNullOrEmpty(SharedSettings.TitleId))
return null;
try
{
int studioIndex; int titleIndex;
if (DoesTitleExistInStudios(SharedSettings.TitleId, out studioIndex, out titleIndex))
return AccountDetails.studios[studioIndex].Titles[titleIndex];
}
catch (Exception ex)
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, ex.Message);
}
}
return null;
}
}
private static void SaveToEditorPrefs(object obj, string key)
{
try
{
var json = JsonWrapper.SerializeObject(obj);
EditorPrefs.SetString(KeyPrefix + key, json);
}
catch (Exception ex)
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, ex.Message);
}
}
public static void SaveAccountDetails()
{
SaveToEditorPrefs(AccountDetails, PlayFab_DeveloperAccountDetails.Name);
}
public static void SaveEnvDetails(bool updateToScriptableObj = true)
{
SaveToEditorPrefs(EnvDetails, PlayFab_DeveloperEnvironmentDetails.Name);
if (updateToScriptableObj)
UpdateScriptableObject();
}
private static TResult LoadFromEditorPrefs<TResult>(string key) where TResult : class, new()
{
if (!EditorPrefs.HasKey(KeyPrefix + key))
return new TResult();
var serialized = EditorPrefs.GetString(KeyPrefix + key);
try
{
var result = JsonWrapper.DeserializeObject<TResult>(serialized);
if (result != null)
return JsonWrapper.DeserializeObject<TResult>(serialized);
}
catch (Exception ex)
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, ex.Message);
}
return new TResult();
}
public static void LoadAllData()
{
if (IsDataLoaded)
return;
AccountDetails = LoadFromEditorPrefs<PlayFab_DeveloperAccountDetails>(PlayFab_DeveloperAccountDetails.Name);
EnvDetails = LoadFromEditorPrefs<PlayFab_DeveloperEnvironmentDetails>(PlayFab_DeveloperEnvironmentDetails.Name);
EditorSettings = LoadFromEditorPrefs<PlayFab_EditorSettings>(PlayFab_EditorSettings.Name);
EditorView = LoadFromEditorPrefs<PlayFab_EditorView>(PlayFab_EditorView.Name);
_IsDataLoaded = true;
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnDataLoaded, "Complete");
}
private static void UpdateScriptableObject()
{
var playfabSettingsType = PlayFabEditorSDKTools.GetPlayFabSettings();
if (playfabSettingsType == null || !PlayFabEditorSDKTools.IsInstalled || !PlayFabEditorSDKTools.isSdkSupported)
return;
var props = playfabSettingsType.GetProperties();
foreach (var property in props)
{
switch (property.Name.ToLower())
{
case "productionenvironmenturl":
property.SetValue(null, PlayFabEditorHelper.TITLE_ENDPOINT, null); break;
}
}
var getSoMethod = playfabSettingsType.GetMethod("GetSharedSettingsObjectPrivate", BindingFlags.NonPublic | BindingFlags.Static);
if (getSoMethod != null)
{
var so = getSoMethod.Invoke(null, new object[0]) as ScriptableObject;
if (so != null)
EditorUtility.SetDirty(so);
}
AssetDatabase.SaveAssets();
}
public static void RemoveEditorPrefs()
{
EditorPrefs.DeleteKey(KeyPrefix + PlayFab_EditorSettings.Name);
EditorPrefs.DeleteKey(KeyPrefix + PlayFab_DeveloperEnvironmentDetails.Name);
EditorPrefs.DeleteKey(KeyPrefix + PlayFab_DeveloperAccountDetails.Name);
EditorPrefs.DeleteKey(KeyPrefix + PlayFab_EditorView.Name);
}
public static bool DoesTitleExistInStudios(string searchFor) //out Studio studio
{
if (AccountDetails.studios == null)
return false;
searchFor = searchFor.ToLower();
foreach (var studio in AccountDetails.studios)
if (studio.Titles != null)
foreach (var title in studio.Titles)
if (title.Id.ToLower() == searchFor)
return true;
return false;
}
private static bool DoesTitleExistInStudios(string searchFor, out int studioIndex, out int titleIndex) //out Studio studio
{
studioIndex = 0; // corresponds to our _OVERRIDE_
titleIndex = -1;
if (AccountDetails.studios == null)
return false;
for (var studioIdx = 0; studioIdx < AccountDetails.studios.Count; studioIdx++)
{
for (var titleIdx = 0; titleIdx < AccountDetails.studios[studioIdx].Titles.Length; titleIdx++)
{
if (AccountDetails.studios[studioIdx].Titles[titleIdx].Id.ToLower() == searchFor.ToLower())
{
studioIndex = studioIdx;
titleIndex = titleIdx;
return true;
}
}
}
return false;
}
public static void RefreshStudiosList()
{
if (AccountDetails.studios != null)
AccountDetails.studios.Clear();
PlayFabEditorApi.GetStudios(new GetStudiosRequest(), (getStudioResult) =>
{
if (AccountDetails.studios == null)
AccountDetails.studios = new List<Studio>();
foreach (var eachStudio in getStudioResult.Studios)
AccountDetails.studios.Add(eachStudio);
AccountDetails.studios.Add(Studio.OVERRIDE);
SaveAccountDetails();
}, PlayFabEditorHelper.SharedErrorCallback);
}
}
}
| |
//
// Mono.Tabblo.Connection
//
// Authors:
// Wojciech Dzierzanowski (wojciech.dzierzanowski@gmail.com)
//
// (C) Copyright 2009 Wojciech Dzierzanowski
//
// 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 Mono.Unix;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
namespace Mono.Tabblo {
class Connection {
private const string LoginUrl =
"https://store.tabblo.com:443/studio/authtoken";
private const string AuthorizeUrl = "https://store.tabblo.com"
+ ":443/studio/upload/getposturl";
private const string RedirUrl = "http://www.tabblo.com/studio"
+ "/token/{0}/?url=/studio"
+ "/report_upload_session";
private const string ContentTypeUrlEncoded =
"application/x-www-form-urlencoded; "
+ "charset=UTF-8";
private readonly IPreferences preferences;
private string auth_token = null;
private string session_upload_url = null;
private CookieCollection cookies;
internal Connection (IPreferences preferences)
{
Debug.Assert (null != preferences);
this.preferences = preferences;
this.cookies = new CookieCollection ();
}
internal void UploadFile (string name, Stream data_stream,
string mime_type,
string [,] arguments)
{
if (!IsAuthenticated ()) {
Login ();
}
Debug.WriteLine ("Uploading " + mime_type + " file "
+ name);
DoUploadFile (name, data_stream, mime_type, arguments);
}
private void DoUploadFile (string name, Stream data_stream,
string mime_type,
string [,] arguments)
{
string upload_url = GetUploadUrl (arguments);
HttpWebRequest http_request = CreateHttpRequest (
upload_url, "POST", true);
MultipartRequest request =
new MultipartRequest (http_request);
MemoryStream mem_stream = null;
if (null != UploadProgressChanged) {
// "Manual buffering" using a MemoryStream.
request.Request.AllowWriteStreamBuffering =
false;
mem_stream = new MemoryStream ();
request.OutputStream = mem_stream;
}
request.BeginPart (true);
request.AddHeader ("Content-Disposition",
"form-data; name=\"filename0\"; "
+ "filename=\"" + name
+ GetFileNameExtension (
mime_type)
+ '"',
false);
request.AddHeader ("Content-Type", mime_type, true);
byte [] data_buffer = new byte [8192];
int read_count;
while ((read_count = data_stream.Read (
data_buffer, 0, data_buffer.Length))
> 0) {
request.WritePartialContent (
data_buffer, 0, read_count);
}
request.EndPartialContent ();
request.EndPart (true);
if (null != UploadProgressChanged) {
int total = (int) request.OutputStream.Length;
request.Request.ContentLength = total;
string progress_title = String.Format (
Catalog.GetString ("Uploading "
+ "photo "
+ "\"{0}\""),
name);
using (Stream request_stream = request.Request
.GetRequestStream ()) {
byte [] buffer =
mem_stream.GetBuffer ();
int write_count = 0;
for (int offset = 0; offset < total;
offset += write_count) {
FireUploadProgress (
progress_title,
offset, total);
write_count = System.Math.Min (
16384,
total - offset);
request_stream.Write (buffer,
offset,
write_count);
}
FireUploadProgress (progress_title,
total, total);
}
}
SendRequest ("upload", request.Request, true);
}
private static string GetFileNameExtension(string mime_type)
{
switch (mime_type)
{
case "image/jpeg":
return ".jpeg";
case "image/png":
return ".png";
default:
Debug.WriteLine (
"Unexpected MIME type: "
+ mime_type);
return ".jpeg";
}
}
internal event UploadProgressEventHandler UploadProgressChanged;
private void FireUploadProgress (string title, int sent,
int total)
{
if (null != UploadProgressChanged) {
UploadProgressEventArgs args =
new UploadProgressEventArgs (
title, sent,
total);
UploadProgressChanged (this, args);
}
}
private bool IsAuthenticated ()
{
return null != auth_token;
}
private void Login ()
{
FireUploadProgress (Catalog.GetString (
"Logging into Tabblo"),
0, 0);
auth_token = null;
HttpWebRequest request = CreateHttpRequest (
LoginUrl, "POST");
request.ContentType = ContentTypeUrlEncoded;
string [,] arguments = {
{"username", preferences.Username},
{"password", preferences.Password}
};
try {
WriteRequestContent (request, arguments);
string response = SendRequest (
"login", request);
if ("BAD".Equals (response)) {
Debug.WriteLine (
"Invalid username or password");
throw new TabbloException (
"Login failed: Invalid username"
+ " or password");
}
auth_token = response;
} catch (TabbloException e) {
// Here's us trying to produce a more
// descriptive message when we have... trust
// issues. This doesn't work, though, at least
// as long as Mono bug #346635 is not fixed.
//
// TODO: When it _starts_ to work, we should
// think about doing the same for
// `GetUploadUrl()'.
WebException we = e.InnerException
as WebException;
if (null != we) {
Debug.WriteLine ("Caught a WebException,"
+ " status="
+ we.Status);
if (WebExceptionStatus.TrustFailure
== we.Status) {
throw new TabbloException (
"Trust failure", we);
}
}
throw;
}
Debug.WriteLineIf (null != auth_token,
"Login successful. Token: "
+ auth_token);
}
private string GetUploadUrl (string [,] arguments)
{
FireUploadProgress (Catalog.GetString (
"Obtaining URL for upload"),
0, 0);
Debug.Assert (IsAuthenticated (), "Not authenticated");
if (null == session_upload_url) {
string [,] auth_arguments = {
{"auth_token", auth_token}
};
string url = AuthorizeUrl + "/?"
+ FormatRequestArguments (
auth_arguments);
HttpWebRequest request =
CreateHttpRequest (url, "GET");
string response = SendRequest (
"getposturl", request);
if (response.StartsWith ("@")) {
session_upload_url =
response.Substring (1);
} else {
throw new TabbloException (
"Session upload URL "
+ "retrieval failed");
}
}
string upload_url = session_upload_url;
upload_url += "&redir=" + String.Format (
RedirUrl, auth_token);
if (null != arguments && arguments.GetLength (0) > 0) {
upload_url += '&' + FormatRequestArguments (
arguments);
}
Debug.WriteLine ("Upload URL: " + upload_url);
return upload_url;
}
private HttpWebRequest CreateHttpRequest (string url,
string method)
{
return CreateHttpRequest (url, method, false);
}
private HttpWebRequest CreateHttpRequest (string url,
string method,
bool with_cookies)
{
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create (url);
// For some reason, POST requests are _really_ slow with
// HTTP 1.1.
request.ProtocolVersion = HttpVersion.Version10;
request.Method = method;
if (with_cookies) {
HandleRequestCookies (request);
}
return request;
}
private void HandleRequestCookies (HttpWebRequest request)
{
request.CookieContainer = new CookieContainer ();
// Instead of just doing a
// `request.CookieContainer.Add(cookies)', add cookies
// mannually to work around the fact that some cookies
// are not properly formatted as they are received from
// the server.
foreach (Cookie c in cookies) {
Cookie new_cookie = new Cookie (c.Name, c.Value,
"/", ".tabblo.com");
request.CookieContainer.Add (new_cookie);
}
string cookie_header = request.CookieContainer
.GetCookieHeader (request.RequestUri);
Debug.WriteLineIf (cookie_header.Length > 0,
"Cookie: " + cookie_header);
}
private static void WriteRequestContent (HttpWebRequest request,
string [,] arguments)
{
WriteRequestContent (request,
FormatRequestArguments (arguments));
}
private static void WriteRequestContent (HttpWebRequest request,
string content)
{
byte [] content_bytes =
Encoding.UTF8.GetBytes (content);
request.ContentLength = content_bytes.Length;
try {
using (Stream request_stream =
request.GetRequestStream ()) {
request_stream.Write (content_bytes, 0,
content_bytes.Length);
}
} catch (WebException e) {
Debug.WriteLine (
"Error writing request content",
"ERROR");
throw new TabbloException (
"HTTP request failure: "
+ e.Message,
e);
}
char [] content_chars = new char [content_bytes.Length];
content_bytes.CopyTo (content_chars, 0);
Debug.WriteLine ("Request content: "
+ new string (content_chars));
}
private static string FormatRequestArguments (
string [,] arguments)
{
StringBuilder content = new StringBuilder ();
for (int i = 0; i < arguments.GetLength (0); ++i) {
content.AppendFormat( "{0}={1}&",
HttpUtility.UrlEncode (
arguments [i, 0]),
HttpUtility.UrlEncode (
arguments [i, 1]));
}
if (content.Length > 0) {
content.Remove (content.Length - 1, 1);
}
return content.ToString ();
}
private string SendRequest (string description,
HttpWebRequest request)
{
return SendRequest (description, request, false);
}
/// <summary>
/// Sends an HTTP request.
/// </summary>
/// <param name="description"></param>
/// <param name="request"></param>
/// <returns>the HTTP response as string</returns>
private string SendRequest (string description,
HttpWebRequest request,
bool keep_cookies)
{
Debug.WriteLine ("Sending " + description + ' '
+ request.Method + " request to "
+ request.Address);
HttpWebResponse response = null;
try {
response = (HttpWebResponse)
request.GetResponse ();
if (keep_cookies) {
cookies.Add (response.Cookies);
Debug.WriteLine (response.Cookies.Count
+ " cookie(s)");
foreach (Cookie c in response.Cookies) {
Debug.WriteLine ("Set-Cookie: "
+ c.Name + '='
+ c.Value
+ "; Domain="
+ c.Domain
+ "; expires="
+ c.Expires);
}
}
return GetResponseAsString (response);
} catch (WebException e) {
Debug.WriteLine (description + " failed: " + e);
HttpWebResponse error_response =
e.Response as HttpWebResponse;
string response_string = null != error_response
? GetResponseAsString (
error_response)
: "reason unknown";
throw new TabbloException (description
+ " failed: "
+ response_string,
e);
} finally {
if (null != response) {
response.Close ();
}
}
}
private static string GetResponseAsString (
HttpWebResponse response)
{
Debug.Write ("Response: ");
Encoding encoding = Encoding.UTF8;
if (response.ContentEncoding.Length > 0) {
try {
encoding = Encoding.GetEncoding (
response
.ContentEncoding);
} catch (ArgumentException) {
// Swallow invalid encoding exception
// and use the default one.
}
}
string response_string = null;
using (Stream stream = response.GetResponseStream ()) {
StreamReader reader = new StreamReader (
stream, encoding);
response_string = reader.ReadToEnd ();
stream.Close ();
}
Debug.WriteLineIf (null != response_string,
response_string);
return response_string;
}
}
}
| |
using System;
using Microsoft.Xna.Framework;
using QEngine.Physics.Collision.ContactSystem;
using QEngine.Physics.Collision.Shapes;
using QEngine.Physics.Shared;
using QEngine.Physics.Shared.Optimization;
using QEngine.Physics.Utilities;
namespace QEngine.Physics.Collision.Narrowphase
{
public class EPCollider
{
private Vector2 _centroidB;
private bool _front;
private Vector2 _lowerLimit, _upperLimit;
private Vector2 _normal;
private Vector2 _normal0, _normal1, _normal2;
private TempPolygon _polygonB = new TempPolygon();
private float _radius;
private Vector2 _v0, _v1, _v2, _v3;
private Transform _xf;
public void Collide(ref Manifold manifold, EdgeShape edgeA, ref Transform xfA, PolygonShape polygonB, ref Transform xfB)
{
// Algorithm:
// 1. Classify v1 and v2
// 2. Classify polygon centroid as front or back
// 3. Flip normal if necessary
// 4. Initialize normal range to [-pi, pi] about face normal
// 5. Adjust normal range according to adjacent edges
// 6. Visit each separating axes, only accept axes within the range
// 7. Return if _any_ axis indicates separation
// 8. Clip
_xf = MathUtils.MulT(xfA, xfB);
_centroidB = MathUtils.Mul(ref _xf, polygonB.MassData.Centroid);
_v0 = edgeA.Vertex0;
_v1 = edgeA._vertex1;
_v2 = edgeA._vertex2;
_v3 = edgeA.Vertex3;
bool hasVertex0 = edgeA.HasVertex0;
bool hasVertex3 = edgeA.HasVertex3;
Vector2 edge1 = _v2 - _v1;
edge1.Normalize();
_normal1 = new Vector2(edge1.Y, -edge1.X);
float offset1 = Vector2.Dot(_normal1, _centroidB - _v1);
float offset0 = 0.0f, offset2 = 0.0f;
bool convex1 = false, convex2 = false;
// Is there a preceding edge?
if (hasVertex0)
{
Vector2 edge0 = _v1 - _v0;
edge0.Normalize();
_normal0 = new Vector2(edge0.Y, -edge0.X);
convex1 = MathUtils.Cross(edge0, edge1) >= 0.0f;
offset0 = Vector2.Dot(_normal0, _centroidB - _v0);
}
// Is there a following edge?
if (hasVertex3)
{
Vector2 edge2 = _v3 - _v2;
edge2.Normalize();
_normal2 = new Vector2(edge2.Y, -edge2.X);
convex2 = MathUtils.Cross(edge1, edge2) > 0.0f;
offset2 = Vector2.Dot(_normal2, _centroidB - _v2);
}
// Determine front or back collision. Determine collision normal limits.
if (hasVertex0 && hasVertex3)
{
if (convex1 && convex2)
{
_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f;
if (_front)
{
_normal = _normal1;
_lowerLimit = _normal0;
_upperLimit = _normal2;
}
else
{
_normal = -_normal1;
_lowerLimit = -_normal1;
_upperLimit = -_normal1;
}
}
else if (convex1)
{
_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f);
if (_front)
{
_normal = _normal1;
_lowerLimit = _normal0;
_upperLimit = _normal1;
}
else
{
_normal = -_normal1;
_lowerLimit = -_normal2;
_upperLimit = -_normal1;
}
}
else if (convex2)
{
_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f);
if (_front)
{
_normal = _normal1;
_lowerLimit = _normal1;
_upperLimit = _normal2;
}
else
{
_normal = -_normal1;
_lowerLimit = -_normal1;
_upperLimit = -_normal0;
}
}
else
{
_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f;
if (_front)
{
_normal = _normal1;
_lowerLimit = _normal1;
_upperLimit = _normal1;
}
else
{
_normal = -_normal1;
_lowerLimit = -_normal2;
_upperLimit = -_normal0;
}
}
}
else if (hasVertex0)
{
if (convex1)
{
_front = offset0 >= 0.0f || offset1 >= 0.0f;
if (_front)
{
_normal = _normal1;
_lowerLimit = _normal0;
_upperLimit = -_normal1;
}
else
{
_normal = -_normal1;
_lowerLimit = _normal1;
_upperLimit = -_normal1;
}
}
else
{
_front = offset0 >= 0.0f && offset1 >= 0.0f;
if (_front)
{
_normal = _normal1;
_lowerLimit = _normal1;
_upperLimit = -_normal1;
}
else
{
_normal = -_normal1;
_lowerLimit = _normal1;
_upperLimit = -_normal0;
}
}
}
else if (hasVertex3)
{
if (convex2)
{
_front = offset1 >= 0.0f || offset2 >= 0.0f;
if (_front)
{
_normal = _normal1;
_lowerLimit = -_normal1;
_upperLimit = _normal2;
}
else
{
_normal = -_normal1;
_lowerLimit = -_normal1;
_upperLimit = _normal1;
}
}
else
{
_front = offset1 >= 0.0f && offset2 >= 0.0f;
if (_front)
{
_normal = _normal1;
_lowerLimit = -_normal1;
_upperLimit = _normal1;
}
else
{
_normal = -_normal1;
_lowerLimit = -_normal2;
_upperLimit = _normal1;
}
}
}
else
{
_front = offset1 >= 0.0f;
if (_front)
{
_normal = _normal1;
_lowerLimit = -_normal1;
_upperLimit = -_normal1;
}
else
{
_normal = -_normal1;
_lowerLimit = _normal1;
_upperLimit = _normal1;
}
}
// Get polygonB in frameA
_polygonB.Count = polygonB.Vertices.Count;
for (int i = 0; i < polygonB.Vertices.Count; ++i)
{
_polygonB.Vertices[i] = MathUtils.Mul(ref _xf, polygonB.Vertices[i]);
_polygonB.Normals[i] = MathUtils.Mul(_xf.q, polygonB.Normals[i]);
}
_radius = polygonB.Radius + edgeA.Radius;
manifold.PointCount = 0;
EPAxis edgeAxis = ComputeEdgeSeparation();
// If no valid normal can be found than this edge should not collide.
if (edgeAxis.Type == EPAxisType.Unknown)
{
return;
}
if (edgeAxis.Separation > _radius)
{
return;
}
EPAxis polygonAxis = ComputePolygonSeparation();
if (polygonAxis.Type != EPAxisType.Unknown && polygonAxis.Separation > _radius)
{
return;
}
// Use hysteresis for jitter reduction.
const float k_relativeTol = 0.98f;
const float k_absoluteTol = 0.001f;
EPAxis primaryAxis;
if (polygonAxis.Type == EPAxisType.Unknown)
{
primaryAxis = edgeAxis;
}
else if (polygonAxis.Separation > k_relativeTol * edgeAxis.Separation + k_absoluteTol)
{
primaryAxis = polygonAxis;
}
else
{
primaryAxis = edgeAxis;
}
FixedArray2<ClipVertex> ie = new FixedArray2<ClipVertex>();
ReferenceFace rf;
if (primaryAxis.Type == EPAxisType.EdgeA)
{
manifold.Type = ManifoldType.FaceA;
// Search for the polygon normal that is most anti-parallel to the edge normal.
int bestIndex = 0;
float bestValue = Vector2.Dot(_normal, _polygonB.Normals[0]);
for (int i = 1; i < _polygonB.Count; ++i)
{
float value = Vector2.Dot(_normal, _polygonB.Normals[i]);
if (value < bestValue)
{
bestValue = value;
bestIndex = i;
}
}
int i1 = bestIndex;
int i2 = i1 + 1 < _polygonB.Count ? i1 + 1 : 0;
ie.Value0.V = _polygonB.Vertices[i1];
ie.Value0.ID.ContactFeature.IndexA = 0;
ie.Value0.ID.ContactFeature.IndexB = (byte)i1;
ie.Value0.ID.ContactFeature.TypeA = ContactFeatureType.Face;
ie.Value0.ID.ContactFeature.TypeB = ContactFeatureType.Vertex;
ie.Value1.V = _polygonB.Vertices[i2];
ie.Value1.ID.ContactFeature.IndexA = 0;
ie.Value1.ID.ContactFeature.IndexB = (byte)i2;
ie.Value1.ID.ContactFeature.TypeA = ContactFeatureType.Face;
ie.Value1.ID.ContactFeature.TypeB = ContactFeatureType.Vertex;
if (_front)
{
rf.i1 = 0;
rf.i2 = 1;
rf.v1 = _v1;
rf.v2 = _v2;
rf.Normal = _normal1;
}
else
{
rf.i1 = 1;
rf.i2 = 0;
rf.v1 = _v2;
rf.v2 = _v1;
rf.Normal = -_normal1;
}
}
else
{
manifold.Type = ManifoldType.FaceB;
ie.Value0.V = _v1;
ie.Value0.ID.ContactFeature.IndexA = 0;
ie.Value0.ID.ContactFeature.IndexB = (byte)primaryAxis.Index;
ie.Value0.ID.ContactFeature.TypeA = ContactFeatureType.Vertex;
ie.Value0.ID.ContactFeature.TypeB = ContactFeatureType.Face;
ie.Value1.V = _v2;
ie.Value1.ID.ContactFeature.IndexA = 0;
ie.Value1.ID.ContactFeature.IndexB = (byte)primaryAxis.Index;
ie.Value1.ID.ContactFeature.TypeA = ContactFeatureType.Vertex;
ie.Value1.ID.ContactFeature.TypeB = ContactFeatureType.Face;
rf.i1 = primaryAxis.Index;
rf.i2 = rf.i1 + 1 < _polygonB.Count ? rf.i1 + 1 : 0;
rf.v1 = _polygonB.Vertices[rf.i1];
rf.v2 = _polygonB.Vertices[rf.i2];
rf.Normal = _polygonB.Normals[rf.i1];
}
rf.SideNormal1 = new Vector2(rf.Normal.Y, -rf.Normal.X);
rf.SideNormal2 = -rf.SideNormal1;
rf.SideOffset1 = Vector2.Dot(rf.SideNormal1, rf.v1);
rf.SideOffset2 = Vector2.Dot(rf.SideNormal2, rf.v2);
// Clip incident edge against extruded edge1 side edges.
FixedArray2<ClipVertex> clipPoints1;
FixedArray2<ClipVertex> clipPoints2;
int np;
// Clip to box side 1
np = Collision.ClipSegmentToLine(out clipPoints1, ref ie, rf.SideNormal1, rf.SideOffset1, rf.i1);
if (np < Settings.MaxManifoldPoints)
{
return;
}
// Clip to negative box side 1
np = Collision.ClipSegmentToLine(out clipPoints2, ref clipPoints1, rf.SideNormal2, rf.SideOffset2, rf.i2);
if (np < Settings.MaxManifoldPoints)
{
return;
}
// Now clipPoints2 contains the clipped points.
if (primaryAxis.Type == EPAxisType.EdgeA)
{
manifold.LocalNormal = rf.Normal;
manifold.LocalPoint = rf.v1;
}
else
{
manifold.LocalNormal = polygonB.Normals[rf.i1];
manifold.LocalPoint = polygonB.Vertices[rf.i1];
}
int pointCount = 0;
for (int i = 0; i < Settings.MaxManifoldPoints; ++i)
{
float separation = Vector2.Dot(rf.Normal, clipPoints2[i].V - rf.v1);
if (separation <= _radius)
{
ManifoldPoint cp = manifold.Points[pointCount];
if (primaryAxis.Type == EPAxisType.EdgeA)
{
cp.LocalPoint = MathUtils.MulT(ref _xf, clipPoints2[i].V);
cp.Id = clipPoints2[i].ID;
}
else
{
cp.LocalPoint = clipPoints2[i].V;
cp.Id.ContactFeature.TypeA = clipPoints2[i].ID.ContactFeature.TypeB;
cp.Id.ContactFeature.TypeB = clipPoints2[i].ID.ContactFeature.TypeA;
cp.Id.ContactFeature.IndexA = clipPoints2[i].ID.ContactFeature.IndexB;
cp.Id.ContactFeature.IndexB = clipPoints2[i].ID.ContactFeature.IndexA;
}
manifold.Points[pointCount] = cp;
++pointCount;
}
}
manifold.PointCount = pointCount;
}
private EPAxis ComputeEdgeSeparation()
{
EPAxis axis;
axis.Type = EPAxisType.EdgeA;
axis.Index = _front ? 0 : 1;
axis.Separation = Settings.MaxFloat;
for (int i = 0; i < _polygonB.Count; ++i)
{
float s = Vector2.Dot(_normal, _polygonB.Vertices[i] - _v1);
if (s < axis.Separation)
{
axis.Separation = s;
}
}
return axis;
}
private EPAxis ComputePolygonSeparation()
{
EPAxis axis;
axis.Type = EPAxisType.Unknown;
axis.Index = -1;
axis.Separation = -Settings.MaxFloat;
Vector2 perp = new Vector2(-_normal.Y, _normal.X);
for (int i = 0; i < _polygonB.Count; ++i)
{
Vector2 n = -_polygonB.Normals[i];
float s1 = Vector2.Dot(n, _polygonB.Vertices[i] - _v1);
float s2 = Vector2.Dot(n, _polygonB.Vertices[i] - _v2);
float s = Math.Min(s1, s2);
if (s > _radius)
{
// No collision
axis.Type = EPAxisType.EdgeB;
axis.Index = i;
axis.Separation = s;
return axis;
}
// Adjacency
if (Vector2.Dot(n, perp) >= 0.0f)
{
if (Vector2.Dot(n - _upperLimit, _normal) < -Settings.AngularSlop)
{
continue;
}
}
else
{
if (Vector2.Dot(n - _lowerLimit, _normal) < -Settings.AngularSlop)
{
continue;
}
}
if (s > axis.Separation)
{
axis.Type = EPAxisType.EdgeB;
axis.Index = i;
axis.Separation = s;
}
}
return axis;
}
}
}
| |
#region License
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
namespace FluentMigrator.Builders.Create.Table
{
public class CreateTableExpressionBuilder : ExpressionBuilderWithColumnTypesBase<CreateTableExpression, ICreateTableColumnOptionOrWithColumnSyntax>,
ICreateTableWithColumnOrSchemaOrDescriptionSyntax,
ICreateTableColumnAsTypeSyntax,
ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax,
IColumnExpressionBuilder
{
private readonly IMigrationContext _context;
public CreateTableExpressionBuilder(CreateTableExpression expression, IMigrationContext context)
: base(expression)
{
_context = context;
ColumnHelper = new ColumnExpressionBuilderHelper(this, context);
}
public ColumnDefinition CurrentColumn { get; set; }
public ForeignKeyDefinition CurrentForeignKey { get; set; }
public ColumnExpressionBuilderHelper ColumnHelper { get; set; }
public ICreateTableWithColumnSyntax InSchema(string schemaName)
{
Expression.SchemaName = schemaName;
return this;
}
public ICreateTableColumnAsTypeSyntax WithColumn(string name)
{
var column = new ColumnDefinition { Name = name, TableName = Expression.TableName, ModificationType = ColumnModificationType.Create };
Expression.Columns.Add(column);
CurrentColumn = column;
return this;
}
public ICreateTableWithColumnOrSchemaSyntax WithDescription(string description)
{
Expression.TableDescription = description;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax WithDefault(SystemMethods method)
{
CurrentColumn.DefaultValue = method;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax WithDefaultValue(object value)
{
CurrentColumn.DefaultValue = value;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax WithColumnDescription(string description)
{
CurrentColumn.ColumnDescription = description;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax Identity()
{
CurrentColumn.IsIdentity = true;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax Indexed()
{
return Indexed(null);
}
public ICreateTableColumnOptionOrWithColumnSyntax Indexed(string indexName)
{
ColumnHelper.Indexed(indexName);
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax PrimaryKey()
{
CurrentColumn.IsPrimaryKey = true;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax PrimaryKey(string primaryKeyName)
{
CurrentColumn.IsPrimaryKey = true;
CurrentColumn.PrimaryKeyName = primaryKeyName;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax Nullable()
{
ColumnHelper.SetNullable(true);
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax NotNullable()
{
ColumnHelper.SetNullable(false);
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax Unique()
{
ColumnHelper.Unique(null);
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax Unique(string indexName)
{
ColumnHelper.Unique(indexName);
return this;
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey(string primaryTableName, string primaryColumnName)
{
return ForeignKey(null, null, primaryTableName, primaryColumnName);
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey(string foreignKeyName, string primaryTableName, string primaryColumnName)
{
return ForeignKey(foreignKeyName, null, primaryTableName, primaryColumnName);
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey(string foreignKeyName, string primaryTableSchema,
string primaryTableName, string primaryColumnName)
{
CurrentColumn.IsForeignKey = true;
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = primaryTableName,
PrimaryTableSchema = primaryTableSchema,
ForeignTable = Expression.TableName,
ForeignTableSchema = Expression.SchemaName
}
};
fk.ForeignKey.PrimaryColumns.Add(primaryColumnName);
fk.ForeignKey.ForeignColumns.Add(CurrentColumn.Name);
_context.Expressions.Add(fk);
CurrentForeignKey = fk.ForeignKey;
CurrentColumn.ForeignKey = fk.ForeignKey;
return this;
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ReferencedBy(string foreignTableName, string foreignColumnName)
{
return ReferencedBy(null, null, foreignTableName, foreignColumnName);
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ReferencedBy(string foreignKeyName, string foreignTableName,
string foreignColumnName)
{
return ReferencedBy(foreignKeyName, null, foreignTableName, foreignColumnName);
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ReferencedBy(string foreignKeyName, string foreignTableSchema,
string foreignTableName, string foreignColumnName)
{
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = Expression.TableName,
PrimaryTableSchema = Expression.SchemaName,
ForeignTable = foreignTableName,
ForeignTableSchema = foreignTableSchema
}
};
fk.ForeignKey.PrimaryColumns.Add(CurrentColumn.Name);
fk.ForeignKey.ForeignColumns.Add(foreignColumnName);
_context.Expressions.Add(fk);
CurrentForeignKey = fk.ForeignKey;
return this;
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey()
{
CurrentColumn.IsForeignKey = true;
return this;
}
[Obsolete("Please use ReferencedBy syntax. This method will be removed in the next version")]
public ICreateTableColumnOptionOrWithColumnSyntax References(string foreignKeyName, string foreignTableName, IEnumerable<string> foreignColumnNames)
{
return References(foreignKeyName, null, foreignTableName, foreignColumnNames);
}
[Obsolete("Please use ReferencedBy syntax. This method will be removed in the next version")]
public ICreateTableColumnOptionOrWithColumnSyntax References(string foreignKeyName, string foreignTableSchema, string foreignTableName,
IEnumerable<string> foreignColumnNames)
{
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = Expression.TableName,
PrimaryTableSchema = Expression.SchemaName,
ForeignTable = foreignTableName,
ForeignTableSchema = foreignTableSchema
}
};
fk.ForeignKey.PrimaryColumns.Add(CurrentColumn.Name);
foreach (var foreignColumnName in foreignColumnNames)
fk.ForeignKey.ForeignColumns.Add(foreignColumnName);
_context.Expressions.Add(fk);
return this;
}
public override ColumnDefinition GetColumnForType()
{
return CurrentColumn;
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax OnDelete(Rule rule)
{
CurrentForeignKey.OnDelete = rule;
return this;
}
public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax OnUpdate(Rule rule)
{
CurrentForeignKey.OnUpdate = rule;
return this;
}
public ICreateTableColumnOptionOrWithColumnSyntax OnDeleteOrUpdate(Rule rule)
{
OnDelete(rule);
OnUpdate(rule);
return this;
}
string IColumnExpressionBuilder.SchemaName
{
get
{
return Expression.SchemaName;
}
}
string IColumnExpressionBuilder.TableName
{
get
{
return Expression.TableName;
}
}
ColumnDefinition IColumnExpressionBuilder.Column
{
get
{
return CurrentColumn;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
namespace libsecondlife
{
/// <summary>
///
/// </summary>
public enum PacketFrequency
{
/// <summary></summary>
Low,
/// <summary></summary>
Medium,
/// <summary></summary>
High
}
/// <summary>
///
/// </summary>
public enum FieldType
{
/// <summary></summary>
U8,
/// <summary></summary>
U16,
/// <summary></summary>
U32,
/// <summary></summary>
U64,
/// <summary></summary>
S8,
/// <summary></summary>
S16,
/// <summary></summary>
S32,
/// <summary></summary>
F32,
/// <summary></summary>
F64,
/// <summary></summary>
LLUUID,
/// <summary></summary>
BOOL,
/// <summary></summary>
LLVector3,
/// <summary></summary>
LLVector3d,
/// <summary></summary>
LLVector4,
/// <summary></summary>
LLQuaternion,
/// <summary></summary>
IPADDR,
/// <summary></summary>
IPPORT,
/// <summary></summary>
Variable,
/// <summary></summary>
Fixed,
/// <summary></summary>
Single,
/// <summary></summary>
Multiple
}
/// <summary>
///
/// </summary>
public class MapField : IComparable
{
/// <summary></summary>
public int KeywordPosition;
/// <summary></summary>
public string Name;
/// <summary></summary>
public FieldType Type;
/// <summary></summary>
public int Count;
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int CompareTo(object obj)
{
MapField temp = (MapField)obj;
if (this.KeywordPosition > temp.KeywordPosition)
{
return 1;
}
else
{
if(temp.KeywordPosition == this.KeywordPosition)
{
return 0;
}
else
{
return -1;
}
}
}
}
/// <summary>
///
/// </summary>
public class MapBlock : IComparable
{
/// <summary></summary>
public int KeywordPosition;
/// <summary></summary>
public string Name;
/// <summary></summary>
public int Count;
/// <summary></summary>
public List<MapField> Fields;
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int CompareTo(object obj)
{
MapBlock temp = (MapBlock)obj;
if (this.KeywordPosition > temp.KeywordPosition)
{
return 1;
}
else
{
if(temp.KeywordPosition == this.KeywordPosition)
{
return 0;
}
else
{
return -1;
}
}
}
}
/// <summary>
///
/// </summary>
public class MapPacket
{
/// <summary></summary>
public ushort ID;
/// <summary></summary>
public string Name;
/// <summary></summary>
public PacketFrequency Frequency;
/// <summary></summary>
public bool Trusted;
/// <summary></summary>
public bool Encoded;
/// <summary></summary>
public List<MapBlock> Blocks;
}
/// <summary>
///
/// </summary>
public class ProtocolManager
{
/// <summary></summary>
public Dictionary<FieldType, int> TypeSizes;
/// <summary></summary>
public Dictionary<string, int> KeywordPositions;
/// <summary></summary>
public MapPacket[] LowMaps;
/// <summary></summary>
public MapPacket[] MediumMaps;
/// <summary></summary>
public MapPacket[] HighMaps;
/// <summary>
///
/// </summary>
/// <param name="keywordFile"></param>
/// <param name="mapFile"></param>
/// <param name="client"></param>
public ProtocolManager(string mapFile)
{
// Initialize the map arrays
LowMaps = new MapPacket[65536];
MediumMaps = new MapPacket[256];
HighMaps = new MapPacket[256];
// Build the type size hash table
TypeSizes = new Dictionary<FieldType,int>();
TypeSizes.Add(FieldType.U8, 1);
TypeSizes.Add(FieldType.U16, 2);
TypeSizes.Add(FieldType.U32, 4);
TypeSizes.Add(FieldType.U64, 8);
TypeSizes.Add(FieldType.S8, 1);
TypeSizes.Add(FieldType.S16, 2);
TypeSizes.Add(FieldType.S32, 4);
TypeSizes.Add(FieldType.F32, 4);
TypeSizes.Add(FieldType.F64, 8);
TypeSizes.Add(FieldType.LLUUID, 16);
TypeSizes.Add(FieldType.BOOL, 1);
TypeSizes.Add(FieldType.LLVector3, 12);
TypeSizes.Add(FieldType.LLVector3d, 24);
TypeSizes.Add(FieldType.LLVector4, 16);
TypeSizes.Add(FieldType.LLQuaternion, 16);
TypeSizes.Add(FieldType.IPADDR, 4);
TypeSizes.Add(FieldType.IPPORT, 2);
TypeSizes.Add(FieldType.Variable, -1);
TypeSizes.Add(FieldType.Fixed, -2);
KeywordPositions = new Dictionary<string, int>();
LoadMapFile(mapFile);
}
/// <summary>
///
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public MapPacket Command(string command)
{
foreach (MapPacket map in HighMaps)
{
if (map != null)
{
if (command == map.Name)
{
return map;
}
}
}
foreach (MapPacket map in MediumMaps)
{
if (map != null)
{
if (command == map.Name)
{
return map;
}
}
}
foreach (MapPacket map in LowMaps)
{
if (map != null)
{
if (command == map.Name)
{
return map;
}
}
}
throw new Exception("Cannot find map for command \"" + command + "\"");
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public MapPacket Command(byte[] data)
{
ushort command;
if (data.Length < 5)
{
return null;
}
if (data[4] == 0xFF)
{
if ((byte)data[5] == 0xFF)
{
// Low frequency
command = (ushort)(data[6] * 256 + data[7]);
return Command(command, PacketFrequency.Low);
}
else
{
// Medium frequency
command = (ushort)data[5];
return Command(command, PacketFrequency.Medium);
}
}
else
{
// High frequency
command = (ushort)data[4];
return Command(command, PacketFrequency.High);
}
}
/// <summary>
///
/// </summary>
/// <param name="command"></param>
/// <param name="frequency"></param>
/// <returns></returns>
public MapPacket Command(ushort command, PacketFrequency frequency)
{
switch (frequency)
{
case PacketFrequency.High:
return HighMaps[command];
case PacketFrequency.Medium:
return MediumMaps[command];
case PacketFrequency.Low:
return LowMaps[command];
}
throw new Exception("Cannot find map for command \"" + command + "\" with frequency \"" + frequency + "\"");
}
/// <summary>
///
/// </summary>
public void PrintMap(TextWriter writer)
{
PrintOneMap(writer, LowMaps, "Low ");
PrintOneMap(writer, MediumMaps, "Medium");
PrintOneMap(writer, HighMaps, "High ");
}
/// <summary>
///
/// </summary>
/// <param name="map"></param>
/// <param name="frequency"></param>
private void PrintOneMap(TextWriter writer, MapPacket[] map, string frequency) {
int i;
for (i = 0; i < map.Length; ++i)
{
if (map[i] != null)
{
writer.WriteLine("{0} {1,5} - {2} - {3} - {4}", frequency, i, map[i].Name,
map[i].Trusted ? "Trusted" : "Untrusted",
map[i].Encoded ? "Unencoded" : "Zerocoded");
foreach (MapBlock block in map[i].Blocks)
{
if (block.Count == -1)
{
writer.WriteLine("\t{0,4} {1} (Variable)", block.KeywordPosition, block.Name);
}
else
{
writer.WriteLine("\t{0,4} {1} ({2})", block.KeywordPosition, block.Name, block.Count);
}
foreach (MapField field in block.Fields)
{
writer.WriteLine("\t\t{0,4} {1} ({2} / {3})", field.KeywordPosition, field.Name,
field.Type, field.Count);
}
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="mapFile"></param>
/// <param name="outputFile"></param>
public static void DecodeMapFile(string mapFile, string outputFile)
{
byte magicKey = 0;
byte[] buffer = new byte[2048];
int nread;
BinaryReader map;
BinaryWriter output;
try
{
map = new BinaryReader(new FileStream(mapFile, FileMode.Open));
}
catch(Exception e)
{
throw new Exception("Map file error", e);
}
try
{
output = new BinaryWriter(new FileStream(outputFile, FileMode.CreateNew));
}
catch(Exception e)
{
throw new Exception("Map file error", e);
}
while ((nread = map.Read(buffer, 0, 2048)) != 0)
{
for (int i = 0; i < nread; ++i)
{
buffer[i] ^= magicKey;
magicKey += 43;
}
output.Write(buffer, 0, nread);
}
map.Close();
output.Close();
}
/// <summary>
///
/// </summary>
/// <param name="mapFile"></param>
private void LoadMapFile(string mapFile)
{
FileStream map;
// Load the protocol map file
try
{
map = new FileStream(mapFile, FileMode.Open, FileAccess.Read);
}
catch(Exception e)
{
throw new Exception("Map file error", e);
}
try
{
StreamReader r = new StreamReader(map);
r.BaseStream.Seek(0, SeekOrigin.Begin);
string newline;
string trimmedline;
bool inPacket = false;
bool inBlock = false;
MapPacket currentPacket = null;
MapBlock currentBlock = null;
char[] trimArray = new char[] {' ', '\t'};
// While not at the end of the file
while (r.Peek() > -1)
{
#region ParseMap
newline = r.ReadLine();
trimmedline = System.Text.RegularExpressions.Regex.Replace(newline, @"\s+", " ");
trimmedline = trimmedline.Trim(trimArray);
if (!inPacket)
{
// Outside of all packet blocks
if (trimmedline == "{")
{
inPacket = true;
}
}
else
{
// Inside of a packet block
if (!inBlock)
{
// Inside a packet block, outside of the blocks
if (trimmedline == "{")
{
inBlock = true;
}
else if (trimmedline == "}")
{
// Reached the end of the packet
// currentPacket.Blocks.Sort();
inPacket = false;
}
else
{
// The packet header
#region ParsePacketHeader
// Splice the string in to tokens
string[] tokens = trimmedline.Split(new char[] {' ', '\t'});
if (tokens.Length > 3)
{
//Hash packet name to insure correct keyword ordering
KeywordPosition(tokens[0]);
uint packetID;
// Remove the leading "0x"
if (tokens[2].Length > 2 && tokens[2].Substring(0, 2) == "0x")
{
tokens[2] = tokens[2].Substring(2, tokens[2].Length - 2);
packetID = UInt32.Parse(tokens[2], System.Globalization.NumberStyles.HexNumber);
} else {
packetID = UInt32.Parse(tokens[2]);
}
if (tokens[1] == "Fixed")
{
// Truncate the id to a short
packetID &= 0xFFFF;
LowMaps[packetID] = new MapPacket();
LowMaps[packetID].ID = (ushort)packetID;
LowMaps[packetID].Frequency = PacketFrequency.Low;
LowMaps[packetID].Name = tokens[0];
LowMaps[packetID].Trusted = (tokens[3] == "Trusted");
LowMaps[packetID].Encoded = (tokens[4] == "Zerocoded");
LowMaps[packetID].Blocks = new List<MapBlock>();
currentPacket = LowMaps[packetID];
}
else if (tokens[1] == "Low")
{
LowMaps[packetID] = new MapPacket();
LowMaps[packetID].ID = (ushort)packetID;
LowMaps[packetID].Frequency = PacketFrequency.Low;
LowMaps[packetID].Name = tokens[0];
LowMaps[packetID].Trusted = (tokens[2] == "Trusted");
LowMaps[packetID].Encoded = (tokens[3] == "Zerocoded");
LowMaps[packetID].Blocks = new List<MapBlock>();
currentPacket = LowMaps[packetID];
}
else if (tokens[1] == "Medium")
{
MediumMaps[packetID] = new MapPacket();
MediumMaps[packetID].ID = (ushort)packetID;
MediumMaps[packetID].Frequency = PacketFrequency.Medium;
MediumMaps[packetID].Name = tokens[0];
MediumMaps[packetID].Trusted = (tokens[2] == "Trusted");
MediumMaps[packetID].Encoded = (tokens[3] == "Zerocoded");
MediumMaps[packetID].Blocks = new List<MapBlock>();
currentPacket = MediumMaps[packetID];
}
else if (tokens[1] == "High")
{
HighMaps[packetID] = new MapPacket();
HighMaps[packetID].ID = (ushort)packetID;
HighMaps[packetID].Frequency = PacketFrequency.High;
HighMaps[packetID].Name = tokens[0];
HighMaps[packetID].Trusted = (tokens[2] == "Trusted");
HighMaps[packetID].Encoded = (tokens[3] == "Zerocoded");
HighMaps[packetID].Blocks = new List<MapBlock>();
currentPacket = HighMaps[packetID];
}
else
{
//Client.Log("Unknown packet frequency", Helpers.LogLevel.Error);
throw new Exception("Unknown packet frequency");
}
}
#endregion
}
}
else
{
if (trimmedline.Length > 0 && trimmedline.Substring(0, 1) == "{")
{
// A field
#region ParseField
MapField field = new MapField();
// Splice the string in to tokens
string[] tokens = trimmedline.Split(new char[] {' ', '\t'});
field.Name = tokens[1];
field.KeywordPosition = KeywordPosition(field.Name);
field.Type = (FieldType)Enum.Parse(typeof(FieldType), tokens[2], true);
if (tokens[3] != "}")
{
field.Count = Int32.Parse(tokens[3]);
}
else
{
field.Count = 1;
}
// Save this field to the current block
currentBlock.Fields.Add(field);
#endregion
}
else if (trimmedline == "}")
{
// currentBlock.Fields.Sort();
inBlock = false;
}
else if (trimmedline.Length != 0 && trimmedline.Substring(0, 2) != "//")
{
// The block header
#region ParseBlockHeader
currentBlock = new MapBlock();
// Splice the string in to tokens
string[] tokens = trimmedline.Split(new char[] {' ', '\t'});
currentBlock.Name = tokens[0];
currentBlock.KeywordPosition = KeywordPosition(currentBlock.Name);
currentBlock.Fields = new List<MapField>();
currentPacket.Blocks.Add(currentBlock);
if (tokens[1] == "Single")
{
currentBlock.Count = 1;
}
else if (tokens[1] == "Multiple")
{
currentBlock.Count = Int32.Parse(tokens[2]);
}
else if (tokens[1] == "Variable")
{
currentBlock.Count = -1;
}
else
{
//Client.Log("Unknown block frequency", Helpers.LogLevel.Error);
throw new Exception("Unknown block frequency");
}
#endregion
}
}
}
#endregion
}
r.Close();
map.Close();
}
catch (Exception e)
{
throw e;
}
}
private int KeywordPosition(string keyword)
{
if (KeywordPositions.ContainsKey(keyword))
{
return KeywordPositions[keyword];
}
int hash = 0;
for (int i = 1; i < keyword.Length; i++)
{
hash = (hash + (int)(keyword[i])) * 2;
}
hash *= 2;
hash &= 0x1FFF;
int startHash = hash;
while (KeywordPositions.ContainsValue(hash))
{
hash++;
hash &= 0x1FFF;
if (hash == startHash)
{
//Give up looking, went through all values and they were all taken.
throw new Exception("All hash values are taken. Failed to add keyword: " + keyword);
}
}
KeywordPositions[keyword] = hash;
return hash;
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Orleans.Runtime;
using Orleans.Streams;
namespace Orleans.Providers.Streams.Common
{
internal class CacheBucket
{
// For backpressure detection we maintain a histogram of 10 buckets.
// Every buckets recors how many items are in the cache in that bucket
// and how many cursors are poinmting to an item in that bucket.
// We update the NumCurrentItems when we add and remove cache item (potentially opening or removing a bucket)
// We update NumCurrentCursors every time we move a cursor
// If the first (most outdated bucket) has at least one cursor pointing to it, we say we are under back pressure (in a full cache).
internal int NumCurrentItems { get; private set; }
internal int NumCurrentCursors { get; private set; }
internal void UpdateNumItems(int val)
{
NumCurrentItems = NumCurrentItems + val;
}
internal void UpdateNumCursors(int val)
{
NumCurrentCursors = NumCurrentCursors + val;
}
}
internal struct SimpleQueueCacheItem
{
internal IBatchContainer Batch;
internal StreamSequenceToken SequenceToken;
internal CacheBucket CacheBucket;
}
public class SimpleQueueCache : IQueueCache
{
private readonly LinkedList<SimpleQueueCacheItem> cachedMessages;
private StreamSequenceToken lastSequenceTokenAddedToCache;
private readonly int maxCacheSize;
private readonly Logger logger;
private readonly List<CacheBucket> cacheCursorHistogram; // for backpressure detection
private const int NUM_CACHE_HISTOGRAM_BUCKETS = 10;
private readonly int CACHE_HISTOGRAM_MAX_BUCKET_SIZE;
public QueueId Id { get; private set; }
public int Size
{
get { return cachedMessages.Count; }
}
public int MaxAddCount
{
get { return CACHE_HISTOGRAM_MAX_BUCKET_SIZE; }
}
public SimpleQueueCache(QueueId queueId, int cacheSize, Logger logger)
{
Id = queueId;
cachedMessages = new LinkedList<SimpleQueueCacheItem>();
maxCacheSize = cacheSize;
this.logger = logger;
cacheCursorHistogram = new List<CacheBucket>();
CACHE_HISTOGRAM_MAX_BUCKET_SIZE = Math.Max(cacheSize / NUM_CACHE_HISTOGRAM_BUCKETS, 1); // we have 10 buckets
}
public bool IsUnderPressure()
{
if (cachedMessages.Count == 0) return false; // empty cache
if (Size < maxCacheSize) return false; // there is still space in cache
if (cacheCursorHistogram.Count == 0) return false; // no cursors yet - zero consumers basically yet.
// cache is full. Check how many cursors we have in the oldest bucket.
int numCursorsInLastBucket = cacheCursorHistogram[0].NumCurrentCursors;
return numCursorsInLastBucket > 0;
}
public virtual void AddToCache(IList<IBatchContainer> msgs)
{
if (msgs == null) throw new ArgumentNullException("msgs");
Log(logger, "AddToCache: added {0} items to cache.", msgs.Count);
foreach (var message in msgs)
{
Add(message, message.SequenceToken);
lastSequenceTokenAddedToCache = message.SequenceToken;
}
}
public virtual IQueueCacheCursor GetCacheCursor(Guid streamGuid, string streamNamespace, StreamSequenceToken token)
{
if (token != null && !(token is EventSequenceToken))
{
// Null token can come from a stream subscriber that is just interested to start consuming from latest (the most recent event added to the cache).
throw new ArgumentOutOfRangeException("token", "token must be of type EventSequenceToken");
}
var cursor = new SimpleQueueCacheCursor(this, streamGuid, streamNamespace, logger);
InitializeCursor(cursor, token);
return cursor;
}
private void InitializeCursor(SimpleQueueCacheCursor cursor, StreamSequenceToken sequenceToken)
{
Log(logger, "InitializeCursor: {0} to sequenceToken {1}", cursor, sequenceToken);
if (cachedMessages.Count == 0) // nothing in cache
{
StreamSequenceToken tokenToReset = sequenceToken ?? (lastSequenceTokenAddedToCache != null ? ((EventSequenceToken)lastSequenceTokenAddedToCache).NextSequenceNumber() : null);
ResetCursor(cursor, tokenToReset);
return;
}
// if offset is not set, iterate from newest (first) message in cache, but not including the irst message itself
if (sequenceToken == null)
{
StreamSequenceToken tokenToReset = lastSequenceTokenAddedToCache != null ? ((EventSequenceToken)lastSequenceTokenAddedToCache).NextSequenceNumber() : null;
ResetCursor(cursor, tokenToReset);
return;
}
if (sequenceToken.Newer(cachedMessages.First.Value.SequenceToken)) // sequenceId is too new to be in cache
{
ResetCursor(cursor, sequenceToken);
return;
}
LinkedListNode<SimpleQueueCacheItem> lastMessage = cachedMessages.Last;
// Check to see if offset is too old to be in cache
if (sequenceToken.Older(lastMessage.Value.SequenceToken))
{
// throw cache miss exception
throw new QueueCacheMissException(sequenceToken, cachedMessages.Last.Value.SequenceToken, cachedMessages.First.Value.SequenceToken);
}
// Now the requested sequenceToken is set and is also within the limits of the cache.
// Find first message at or below offset
// Events are ordered from newest to oldest, so iterate from start of list until we hit a node at a previous offset, or the end.
LinkedListNode<SimpleQueueCacheItem> node = cachedMessages.First;
while (node != null && node.Value.SequenceToken.Newer(sequenceToken))
{
// did we get to the end?
if (node.Next == null) // node is the last message
break;
// if sequenceId is between the two, take the higher
if (node.Next.Value.SequenceToken.Older(sequenceToken))
break;
node = node.Next;
}
// return cursor from start.
SetCursor(cursor, node);
}
/// <summary>
/// Aquires the next message in the cache at the provided cursor
/// </summary>
/// <param name="cursor"></param>
/// <param name="batch"></param>
/// <returns></returns>
internal bool TryGetNextMessage(SimpleQueueCacheCursor cursor, out IBatchContainer batch)
{
Log(logger, "TryGetNextMessage: {0}", cursor);
batch = null;
if (cursor == null) throw new ArgumentNullException("cursor");
//if not set, try to set and then get next
if (!cursor.IsSet)
{
InitializeCursor(cursor, cursor.SequenceToken);
return cursor.IsSet && TryGetNextMessage(cursor, out batch);
}
// has this message been purged
if (cursor.SequenceToken.Older(cachedMessages.Last.Value.SequenceToken))
{
throw new QueueCacheMissException(cursor.SequenceToken, cachedMessages.Last.Value.SequenceToken, cachedMessages.First.Value.SequenceToken);
}
// Cursor now points to a valid message in the cache. Get it!
// Capture the current element and advance to the next one.
batch = cursor.Element.Value.Batch;
// Advance to next:
if (cursor.Element == cachedMessages.First)
{
// If we are at the end of the cache unset cursor and move offset one forward
ResetCursor(cursor, ((EventSequenceToken)cursor.SequenceToken).NextSequenceNumber());
}
else // move to next
{
UpdateCursor(cursor, cursor.Element.Previous);
}
return true;
}
private void UpdateCursor(SimpleQueueCacheCursor cursor, LinkedListNode<SimpleQueueCacheItem> item)
{
Log(logger, "UpdateCursor: {0} to item {1}", cursor, item.Value.Batch);
cursor.Element.Value.CacheBucket.UpdateNumCursors(-1); // remove from prev bucket
cursor.Set(item);
cursor.Element.Value.CacheBucket.UpdateNumCursors(1); // add to next bucket
}
internal void SetCursor(SimpleQueueCacheCursor cursor, LinkedListNode<SimpleQueueCacheItem> item)
{
Log(logger, "SetCursor: {0} to item {1}", cursor, item.Value.Batch);
cursor.Set(item);
cursor.Element.Value.CacheBucket.UpdateNumCursors(1); // add to next bucket
}
internal void ResetCursor(SimpleQueueCacheCursor cursor, StreamSequenceToken token)
{
Log(logger, "ResetCursor: {0} to token {1}", cursor, token);
if (cursor.IsSet)
{
cursor.Element.Value.CacheBucket.UpdateNumCursors(-1);
}
cursor.Reset(token);
}
private void Add(IBatchContainer batch, StreamSequenceToken sequenceToken)
{
if (batch == null) throw new ArgumentNullException("batch");
CacheBucket cacheBucket = null;
if (cacheCursorHistogram.Count == 0)
{
cacheBucket = new CacheBucket();
cacheCursorHistogram.Add(cacheBucket);
}
else
{
cacheBucket = cacheCursorHistogram[cacheCursorHistogram.Count - 1]; // last one
}
if (cacheBucket.NumCurrentItems == CACHE_HISTOGRAM_MAX_BUCKET_SIZE) // last bucket is full, open a new one
{
cacheBucket = new CacheBucket();
cacheCursorHistogram.Add(cacheBucket);
}
cacheBucket.UpdateNumItems(1);
// Add message to linked list
var item = new SimpleQueueCacheItem
{
Batch = batch,
SequenceToken = sequenceToken,
CacheBucket = cacheBucket
};
cachedMessages.AddFirst(new LinkedListNode<SimpleQueueCacheItem>(item));
if (Size > maxCacheSize)
{
//var last = cachedMessages.Last;
cachedMessages.RemoveLast();
var bucket = cacheCursorHistogram[0]; // same as: var bucket = last.Value.CacheBucket;
bucket.UpdateNumItems(-1);
if (bucket.NumCurrentItems == 0)
{
cacheCursorHistogram.RemoveAt(0);
}
}
}
internal static void Log(Logger logger, string format, params object[] args)
{
if (logger.IsVerbose) logger.Verbose(format, args);
//if(logger.IsInfo) logger.Info(format, args);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Numerics.Tests
{
public class ComparisonTest
{
private const int NumberOfRandomIterations = 1;
[Fact]
public static void ComparisonTests()
{
int seed = 100;
RunTests(seed);
}
private static void RunTests(int seed)
{
Random random = new Random(seed);
RunPositiveTests(random);
RunNegativeTests(random);
}
private static void RunPositiveTests(Random random)
{
BigInteger bigInteger1, bigInteger2;
int expectedResult;
byte[] byteArray;
bool isNegative;
//1 Inputs from BigInteger Properties
// BigInteger.MinusOne, BigInteger.MinusOne
VerifyComparison(BigInteger.MinusOne, BigInteger.MinusOne, 0);
// BigInteger.MinusOne, BigInteger.Zero
VerifyComparison(BigInteger.MinusOne, BigInteger.Zero, -1);
// BigInteger.MinusOne, BigInteger.One
VerifyComparison(BigInteger.MinusOne, BigInteger.One, -1);
// BigInteger.MinusOne, Large Negative
VerifyComparison(BigInteger.MinusOne, -1L * ((BigInteger)long.MaxValue), 1);
// BigInteger.MinusOne, Small Negative
VerifyComparison(BigInteger.MinusOne, -1L * ((BigInteger)short.MaxValue), 1);
// BigInteger.MinusOne, Large Number
VerifyComparison(BigInteger.MinusOne, (BigInteger)int.MaxValue + 1, -1);
// BigInteger.MinusOne, Small Number
VerifyComparison(BigInteger.MinusOne, (BigInteger)int.MaxValue - 1, -1);
// BigInteger.MinusOne, One Less
VerifyComparison(BigInteger.MinusOne, BigInteger.MinusOne - 1, 1);
// BigInteger.Zero, BigInteger.Zero
VerifyComparison(BigInteger.Zero, BigInteger.Zero, 0);
// BigInteger.Zero, Large Negative
VerifyComparison(BigInteger.Zero, -1L * ((BigInteger)int.MaxValue + 1), 1);
// BigInteger.Zero, Small Negative
VerifyComparison(BigInteger.Zero, -1L * ((BigInteger)int.MaxValue - 1), 1);
// BigInteger.Zero, Large Number
VerifyComparison(BigInteger.Zero, (BigInteger)int.MaxValue + 1, -1);
// BigInteger.Zero, Small Number
VerifyComparison(BigInteger.Zero, (BigInteger)int.MaxValue - 1, -1);
// BigInteger.One, BigInteger.One
VerifyComparison(BigInteger.One, BigInteger.One, 0);
// BigInteger.One, BigInteger.MinusOne
VerifyComparison(BigInteger.One, BigInteger.MinusOne, 1);
// BigInteger.One, BigInteger.Zero
VerifyComparison(BigInteger.One, BigInteger.Zero, 1);
// BigInteger.One, Large Negative
VerifyComparison(BigInteger.One, -1 * ((BigInteger)int.MaxValue + 1), 1);
// BigInteger.One, Small Negative
VerifyComparison(BigInteger.One, -1 * ((BigInteger)int.MaxValue - 1), 1);
// BigInteger.One, Large Number
VerifyComparison(BigInteger.One, (BigInteger)int.MaxValue + 1, -1);
// BigInteger.One, Small Number
VerifyComparison(BigInteger.One, (BigInteger)int.MaxValue - 1, -1);
//Basic Checks
// BigInteger.MinusOne, (Int32) -1
VerifyComparison(BigInteger.MinusOne, (int)(-1), 0);
// BigInteger.Zero, (Int32) 0
VerifyComparison(BigInteger.Zero, (int)(0), 0);
// BigInteger.One, 1
VerifyComparison(BigInteger.One, (int)(1), 0);
//1 Inputs Around the boundary of UInt32
// -1 * UInt32.MaxValue, -1 * UInt32.MaxValue
VerifyComparison(-1L * (BigInteger)uint.MaxValue - 1, -1L * (BigInteger)uint.MaxValue - 1, 0);
// -1 * UInt32.MaxValue, -1 * UInt32.MaxValue -1
VerifyComparison(-1L * (BigInteger)uint.MaxValue, (-1L * (BigInteger)uint.MaxValue) - 1L, 1);
// UInt32.MaxValue, -1 * UInt32.MaxValue
VerifyComparison((BigInteger)uint.MaxValue, -1L * (BigInteger)uint.MaxValue, 1);
// UInt32.MaxValue, UInt32.MaxValue
VerifyComparison((BigInteger)uint.MaxValue, (BigInteger)uint.MaxValue, 0);
// UInt32.MaxValue, UInt32.MaxValue + 1
VerifyComparison((BigInteger)uint.MaxValue, (BigInteger)uint.MaxValue + 1, -1);
// UInt64.MaxValue, UInt64.MaxValue
VerifyComparison((BigInteger)ulong.MaxValue, (BigInteger)ulong.MaxValue, 0);
// UInt64.MaxValue + 1, UInt64.MaxValue
VerifyComparison((BigInteger)ulong.MaxValue + 1, ulong.MaxValue, 1);
//Other cases
// -1 * Large Bigint, -1 * Large BigInt
VerifyComparison(-1L * ((BigInteger)int.MaxValue + 1), -1L * ((BigInteger)int.MaxValue + 1), 0);
// Large Bigint, Large Negative BigInt
VerifyComparison((BigInteger)int.MaxValue + 1, -1L * ((BigInteger)int.MaxValue + 1), 1);
// Large Bigint, UInt32.MaxValue
VerifyComparison((BigInteger)long.MaxValue + 1, (BigInteger)uint.MaxValue, 1);
// Large Bigint, One More
VerifyComparison((BigInteger)int.MaxValue + 1, ((BigInteger)int.MaxValue) + 2, -1);
// -1 * Small Bigint, -1 * Small BigInt
VerifyComparison(-1L * ((BigInteger)int.MaxValue - 1), -1L * ((BigInteger)int.MaxValue - 1), 0);
// Small Bigint, Small Negative BigInt
VerifyComparison((BigInteger)int.MaxValue - 1, -1L * ((BigInteger)int.MaxValue - 1), 1);
// Small Bigint, UInt32.MaxValue
VerifyComparison((BigInteger)int.MaxValue - 1, (BigInteger)uint.MaxValue - 1, -1);
// Small Bigint, One More
VerifyComparison((BigInteger)int.MaxValue - 2, ((BigInteger)int.MaxValue) - 1, -1);
//BigInteger vs. Int32
// One Larger (BigInteger), Int32.MaxValue
VerifyComparison((BigInteger)int.MaxValue + 1, int.MaxValue, 1);
// Larger BigInteger, Int32.MaxValue
VerifyComparison((BigInteger)ulong.MaxValue + 1, int.MaxValue, 1);
// Smaller BigInteger, Int32.MaxValue
VerifyComparison((BigInteger)short.MinValue - 1, int.MaxValue, -1);
// One Smaller (BigInteger), Int32.MaxValue
VerifyComparison((BigInteger)int.MaxValue - 1, int.MaxValue, -1);
// (BigInteger) Int32.MaxValue, Int32.MaxValue
VerifyComparison((BigInteger)int.MaxValue, int.MaxValue, 0);
//BigInteger vs. UInt32
// One Larger (BigInteger), UInt32.MaxValue
VerifyComparison((BigInteger)uint.MaxValue + 1, uint.MaxValue, 1);
// Larger BigInteger, UInt32.MaxValue
VerifyComparison((BigInteger)long.MaxValue + 1, uint.MaxValue, 1);
// Smaller BigInteger, UInt32.MaxValue
VerifyComparison((BigInteger)short.MinValue - 1, uint.MaxValue, -1);
// One Smaller (BigInteger), UInt32.MaxValue
VerifyComparison((BigInteger)uint.MaxValue - 1, uint.MaxValue, -1);
// (BigInteger UInt32.MaxValue, UInt32.MaxValue
VerifyComparison((BigInteger)uint.MaxValue, uint.MaxValue, 0);
//BigInteger vs. UInt64
// One Larger (BigInteger), UInt64.MaxValue
VerifyComparison((BigInteger)ulong.MaxValue + 1, ulong.MaxValue, 1);
// Larger BigInteger, UInt64.MaxValue
VerifyComparison((BigInteger)ulong.MaxValue + 100, ulong.MaxValue, 1);
// Smaller BigInteger, UInt64.MaxValue
VerifyComparison((BigInteger)short.MinValue - 1, ulong.MaxValue, -1);
VerifyComparison((BigInteger)short.MaxValue - 1, ulong.MaxValue, -1);
VerifyComparison((BigInteger)int.MaxValue + 1, ulong.MaxValue, -1);
// One Smaller (BigInteger), UInt64.MaxValue
VerifyComparison((BigInteger)ulong.MaxValue - 1, ulong.MaxValue, -1);
// (BigInteger UInt64.MaxValue, UInt64.MaxValue
VerifyComparison((BigInteger)ulong.MaxValue, ulong.MaxValue, 0);
//BigInteger vs. Int64
// One Smaller (BigInteger), Int64.MaxValue
VerifyComparison((BigInteger)long.MaxValue - 1, long.MaxValue, -1);
// Larger BigInteger, Int64.MaxValue
VerifyComparison((BigInteger)ulong.MaxValue + 100, long.MaxValue, 1);
// Smaller BigInteger, Int32.MaxValue
VerifyComparison((BigInteger)short.MinValue - 1, long.MaxValue, -1);
// (BigInteger Int64.MaxValue, Int64.MaxValue
VerifyComparison((BigInteger)long.MaxValue, long.MaxValue, 0);
// One Larger (BigInteger), Int64.MaxValue
VerifyComparison((BigInteger)long.MaxValue + 1, long.MaxValue, 1);
//1 Random Inputs
// Random BigInteger only differs by sign
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
do
{
byteArray = GetRandomByteArray(random);
}
while (MyBigIntImp.IsZero(byteArray));
BigInteger b2 = new BigInteger(byteArray);
if (b2 > (BigInteger)0)
{
VerifyComparison(b2, -1L * b2, 1);
}
else
{
VerifyComparison(b2, -1L * b2, -1);
}
}
// Random BigInteger, Random BigInteger
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
expectedResult = GetRandomInputForComparison(random, out bigInteger1, out bigInteger2);
VerifyComparison(bigInteger1, bigInteger2, expectedResult);
}
// Random BigInteger
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(new BigInteger(byteArray), isNegative, new BigInteger(byteArray), isNegative, 0);
}
//1 Identical values constructed multiple ways
// BigInteger.Zero, BigInteger constructed with a byte[] isNegative=true
VerifyComparison(BigInteger.Zero, false, new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }), true, 0);
// BigInteger.Zero, BigInteger constructed with a byte[] isNegative=false
VerifyComparison(BigInteger.Zero, false, new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }), false, 0);
// BigInteger.Zero, BigInteger constructed from an Int64
VerifyComparison(BigInteger.Zero, 0L, 0);
// BigInteger.Zero, BigInteger constructed from a Double
VerifyComparison(BigInteger.Zero, (BigInteger)0d, 0);
// BigInteger.Zero, BigInteger constructed from a Decimal
VerifyComparison(BigInteger.Zero, (BigInteger)0, 0);
// BigInteger.Zero, BigInteger constructed with Addition
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, new BigInteger(byteArray) + (-1 * new BigInteger(byteArray)), isNegative, 0);
// BigInteger.Zero, BigInteger constructed with Subtraction
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, new BigInteger(byteArray) - new BigInteger(byteArray), isNegative, 0);
// BigInteger.Zero, BigInteger constructed with Multiplication
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, 0 * new BigInteger(byteArray), isNegative, 0);
// BigInteger.Zero, BigInteger constructed with Division
do
{
byteArray = GetRandomByteArray(random);
}
while (MyBigIntImp.IsZero(byteArray));
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, 0 / new BigInteger(byteArray), isNegative, 0);
// BigInteger.One, BigInteger constructed with a byte[]
VerifyComparison(BigInteger.One, false, new BigInteger(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0 }), false, 0);
// BigInteger.One, BigInteger constructed from an Int64
VerifyComparison(BigInteger.One, 1L, 0);
// BigInteger.One, BigInteger constructed from a Double
VerifyComparison(BigInteger.One, (BigInteger)1d, 0);
// BigInteger.One, BigInteger constructed from a Decimal
VerifyComparison(BigInteger.One, (BigInteger)1, 0);
// BigInteger.One, BigInteger constructed with Addition
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.One, false, (((BigInteger)(-1)) * new BigInteger(byteArray)) + (new BigInteger(byteArray)) + 1, false, 0);
// BigInteger.One, BigInteger constructed with Subtraction
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
BigInteger b = new BigInteger(byteArray);
if (b > (BigInteger)0)
{
VerifyComparison(BigInteger.One, false, (b + 1) - (b), false, 0);
}
else
{
b = -1L * b;
VerifyComparison(BigInteger.One, false, (b + 1) - (b), false, 0);
b = -1L * b;
}
// BigInteger.One, BigInteger constructed with Multiplication
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.One, (BigInteger)1 * (BigInteger)1, 0);
// BigInteger.One, BigInteger constructed with Division
do
{
byteArray = GetRandomByteArray(random);
}
while (MyBigIntImp.IsZero(byteArray));
BigInteger b1 = new BigInteger(byteArray);
VerifyComparison(BigInteger.One, false, b1 / b1, false, 0);
}
private static void RunNegativeTests(Random random)
{
// BigInteger.Zero, 0
Assert.Equal(false, BigInteger.Zero.Equals((object)0));
// BigInteger.Zero, null
Assert.Equal(false, BigInteger.Zero.Equals((object)null));
// BigInteger.Zero, string
Assert.Equal(false, BigInteger.Zero.Equals((object)"0"));
}
private static void IComparable_Invalid(string paramName)
{
IComparable comparable = new BigInteger();
Assert.Equal(1, comparable.CompareTo(null));
AssertExtensions.Throws<ArgumentException>(paramName, () => comparable.CompareTo(0)); // Obj is not a BigInteger
}
[Fact]
public static void IComparable_Invalid_netcore()
{
IComparable_Invalid("obj");
}
private static void VerifyComparison(BigInteger x, BigInteger y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
Assert.Equal(expectedEquals, y.Equals(x));
Assert.Equal(expectedEquals, x.Equals((object)y));
Assert.Equal(expectedEquals, y.Equals((object)x));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
VerifyCompareResult(-expectedResult, y.CompareTo(x), "y.CompareTo(x)");
IComparable comparableX = x;
IComparable comparableY = y;
VerifyCompareResult(expectedResult, comparableX.CompareTo(y), "comparableX.CompareTo(y)");
VerifyCompareResult(-expectedResult, comparableY.CompareTo(x), "comparableY.CompareTo(x)");
VerifyCompareResult(expectedResult, BigInteger.Compare(x, y), "Compare(x,y)");
VerifyCompareResult(-expectedResult, BigInteger.Compare(y, x), "Compare(y,x)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), y.GetHashCode());
Assert.Equal(x.ToString(), y.ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(y.GetHashCode(), y.GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, int y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, uint y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, long y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, ulong y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
else
{
Assert.NotEqual(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.NotEqual(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, bool IsXNegative, BigInteger y, bool IsYNegative, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
if (IsXNegative == true)
{
x = x * -1;
}
if (IsYNegative == true)
{
y = y * -1;
}
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
Assert.Equal(expectedEquals, y.Equals(x));
Assert.Equal(expectedEquals, x.Equals((object)y));
Assert.Equal(expectedEquals, y.Equals((object)x));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
VerifyCompareResult(-expectedResult, y.CompareTo(x), "y.CompareTo(x)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), y.GetHashCode());
Assert.Equal(x.ToString(), y.ToString());
}
else
{
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
Assert.NotEqual(x.ToString(), y.ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(y.GetHashCode(), y.GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyCompareResult(int expected, int actual, string message)
{
if (0 == expected)
{
Assert.Equal(expected, actual);
}
else if (0 > expected)
{
Assert.InRange(actual, int.MinValue, -1);
}
else if (0 < expected)
{
Assert.InRange(actual, 1, int.MaxValue);
}
}
private static int GetRandomInputForComparison(Random random, out BigInteger bigInteger1, out BigInteger bigInteger2)
{
byte[] byteArray1, byteArray2;
bool sameSize = 0 == random.Next(0, 2);
if (sameSize)
{
int size = random.Next(0, 1024);
byteArray1 = GetRandomByteArray(random, size);
byteArray2 = GetRandomByteArray(random, size);
}
else
{
byteArray1 = GetRandomByteArray(random);
byteArray2 = GetRandomByteArray(random);
}
bigInteger1 = new BigInteger(byteArray1);
bigInteger2 = new BigInteger(byteArray2);
if (bigInteger1 > 0 && bigInteger2 > 0)
{
if (byteArray1.Length < byteArray2.Length)
{
for (int i = byteArray2.Length - 1; byteArray1.Length <= i; --i)
{
if (0 != byteArray2[i])
{
return -1;
}
}
}
else if (byteArray1.Length > byteArray2.Length)
{
for (int i = byteArray1.Length - 1; byteArray2.Length <= i; --i)
{
if (0 != byteArray1[i])
{
return 1;
}
}
}
}
else if ((bigInteger1 < 0 && bigInteger2 > 0) || (bigInteger1 == 0 && bigInteger2 > 0) || (bigInteger1 < 0 && bigInteger2 == 0))
{
return -1;
}
else if ((bigInteger1 > 0 && bigInteger2 < 0) || (bigInteger1 == 0 && bigInteger2 < 0) || (bigInteger1 > 0 && bigInteger2 == 0))
{
return 1;
}
else if (bigInteger1 != 0 && bigInteger2 != 0)
{
if (byteArray1.Length < byteArray2.Length)
{
for (int i = byteArray2.Length - 1; byteArray1.Length <= i; --i)
{
if (0xFF != byteArray2[i])
{
return 1;
}
}
}
else if (byteArray1.Length > byteArray2.Length)
{
for (int i = byteArray1.Length - 1; byteArray2.Length <= i; --i)
{
if (0xFF != byteArray1[i])
{
return -1;
}
}
}
}
for (int i = Math.Min(byteArray1.Length, byteArray2.Length) - 1; 0 <= i; --i)
{
if (byteArray1[i] > byteArray2[i])
{
return 1;
}
else if (byteArray1[i] < byteArray2[i])
{
return -1;
}
}
return 0;
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 1024));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
}
}
| |
// *********************************
// Message from Original Author:
//
// 2008 Jose Menendez Poo
// Please give me credit if you use this code. It's all I ask.
// Contact me for more info: menendezpoo@gmail.com
// *********************************
//
// Original project from http://ribbon.codeplex.com/
// Continue to support and maintain by http://officeribbon.codeplex.com/
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel;
namespace System.Windows.Forms
{
//[Designer("System.Windows.Forms.RibbonQuickAccessToolbarDesigner")]
[Designer(typeof(RibbonItemGroupDesigner))]
public class RibbonItemGroup : RibbonItem,
IContainsSelectableRibbonItems, IContainsRibbonComponents
{
#region Fields
private RibbonItemGroupItemCollection _items;
private bool _drawBackground;
#endregion
#region Ctor
public RibbonItemGroup()
{
_items = new RibbonItemGroupItemCollection(this);
_drawBackground = true;
}
public RibbonItemGroup(IEnumerable<RibbonItem> items)
: this()
{
_items.AddRange(items);
}
protected override void Dispose(bool disposing)
{
if (disposing && RibbonDesigner.Current == null)
{
foreach (RibbonItem ri in _items)
ri.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Props
/// <summary>
/// This property is not relevant for this class
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override bool Checked
{
get
{
return base.Checked;
}
set
{
base.Checked = value;
}
}
/// <summary>
/// Gets or sets a value indicating if the group should
/// </summary>
[DefaultValue(true)]
[Description("Background drawing should be avoided when group contains only TextBoxes and ComboBoxes")]
public bool DrawBackground
{
get { return _drawBackground; }
set { _drawBackground = value; }
}
/// <summary>
/// Gets the first item of the group
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public RibbonItem FirstItem
{
get
{
if (Items.Count > 0)
{
return Items[0];
}
return null;
}
}
/// <summary>
/// Gets the last item of the group
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public RibbonItem LastItem
{
get
{
if (Items.Count > 0)
{
return Items[Items.Count - 1];
}
return null;
}
}
/// <summary>
/// Gets the collection of items of this group
/// </summary>
[DesignerSerializationVisibility( DesignerSerializationVisibility.Content)]
public RibbonItemGroupItemCollection Items
{
get
{
return _items;
}
}
#endregion
#region Methods
protected override bool ClosesDropDownAt(Point p)
{
return false;
}
public override void SetBounds(Rectangle bounds)
{
base.SetBounds(bounds);
int curLeft = bounds.Left;
foreach (RibbonItem item in Items)
{
item.SetBounds(new Rectangle(new Point(curLeft, bounds.Top), item.LastMeasuredSize));
curLeft = item.Bounds.Right + 1;
}
}
public override void OnPaint(object sender, RibbonElementPaintEventArgs e)
{
if (DrawBackground)
{
Owner.Renderer.OnRenderRibbonItem(new RibbonItemRenderEventArgs(Owner, e.Graphics, e.Clip, this));
}
foreach (RibbonItem item in Items)
{
item.OnPaint(this, new RibbonElementPaintEventArgs(item.Bounds, e.Graphics, RibbonElementSizeMode.Compact));
}
if (DrawBackground)
{
Owner.Renderer.OnRenderRibbonItemBorder(new RibbonItemRenderEventArgs(Owner, e.Graphics, e.Clip, this));
}
}
public override Size MeasureSize(object sender, RibbonElementMeasureSizeEventArgs e)
{
if (!Visible && !Owner.IsDesignMode())
{
SetLastMeasuredSize(new Size(0, 0));
return LastMeasuredSize;
}
///For RibbonItemGroup, size is always compact, and it's designed to be on an horizontal flow
///tab panel.
///
int minWidth = 16;
int widthSum = 0;
int maxHeight = 16;
foreach (RibbonItem item in Items)
{
Size s = item.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(e.Graphics, RibbonElementSizeMode.Compact));
widthSum += s.Width + 1;
maxHeight = Math.Max(maxHeight, s.Height);
}
widthSum -= 1;
widthSum = Math.Max(widthSum, minWidth);
if (Site != null && Site.DesignMode)
{
widthSum += 10;
}
Size result = new Size(widthSum, maxHeight);
SetLastMeasuredSize(result);
return result;
}
/// <param name="ownerPanel">RibbonPanel where this item is located</param>
internal override void SetOwnerPanel(System.Windows.Forms.RibbonPanel ownerPanel)
{
base.SetOwnerPanel(ownerPanel);
Items.SetOwnerPanel(ownerPanel);
}
/// <param name="owner">Ribbon that owns this item</param>
internal override void SetOwner(System.Windows.Forms.Ribbon owner)
{
base.SetOwner(owner);
Items.SetOwner(owner);
}
/// <param name="ownerTab">RibbonTab where this item is located</param>
internal override void SetOwnerTab(System.Windows.Forms.RibbonTab ownerTab)
{
base.SetOwnerTab(ownerTab);
Items.SetOwnerTab(ownerTab);
}
internal override void SetSizeMode(RibbonElementSizeMode sizeMode)
{
base.SetSizeMode(sizeMode);
foreach (RibbonItem item in Items)
{
item.SetSizeMode(RibbonElementSizeMode.Compact);
}
}
public override string ToString()
{
return "Group: " + Items.Count + " item(s)";
}
#endregion
#region IContainsRibbonItems Members
public IEnumerable<RibbonItem> GetItems()
{
return Items;
}
public Rectangle GetContentBounds()
{
return Rectangle.FromLTRB(Bounds.Left + 1, Bounds.Top + 1, Bounds.Right - 1, Bounds.Bottom);
}
#endregion
#region IContainsRibbonComponents Members
public IEnumerable<Component> GetAllChildComponents()
{
return Items.ToArray();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudioTools;
using PowerShellTools.Common.Logging;
using PowerShellTools.LanguageService;
using Tasks = System.Threading.Tasks;
namespace PowerShellTools.Classification
{
internal class PowerShellTokenizationService : IPowerShellTokenizationService
{
private static readonly ILog Log = LogManager.GetLogger(typeof(PowerShellTokenizationService));
private readonly object _tokenizationLock = new object();
private static readonly IEnumerable<string> TaskIdentifiers = new [] {"#TODO", "#HACK", "#BUG"};
public event EventHandler<Ast> TokenizationComplete;
private readonly ClassifierService _classifierService;
private readonly ErrorTagSpanService _errorTagService;
private readonly RegionAndBraceMatchingService _regionAndBraceMatchingService;
private ITextBuffer _textBuffer;
private ITextSnapshot _lastSnapshot;
private static bool _isBufferTokenizing;
private static TodoWindowTaskProvider taskProvider;
private static ErrorListProvider errorListProvider;
private static void CreateProvider()
{
if (taskProvider == null)
{
taskProvider = new TodoWindowTaskProvider(PowerShellToolsPackage.Instance);
taskProvider.ProviderName = "To Do";
}
if (errorListProvider == null)
{
errorListProvider = new ErrorListProvider(PowerShellToolsPackage.Instance);
}
}
public PowerShellTokenizationService(ITextBuffer textBuffer)
{
_textBuffer = textBuffer;
_classifierService = new ClassifierService();
_errorTagService = new ErrorTagSpanService();
_regionAndBraceMatchingService = new RegionAndBraceMatchingService();
_isBufferTokenizing = true;
_lastSnapshot = _textBuffer.CurrentSnapshot;
UpdateTokenization();
}
public void StartTokenization()
{
lock (_tokenizationLock)
{
if (_lastSnapshot == null ||
(_lastSnapshot.Version.VersionNumber != _textBuffer.CurrentSnapshot.Version.VersionNumber &&
_textBuffer.CurrentSnapshot.Length > 0))
{
if (!_isBufferTokenizing)
{
_isBufferTokenizing = true;
Tasks.Task.Factory.StartNew(() =>
{
UpdateTokenization();
});
}
}
}
}
private void UpdateTokenization()
{
while (true)
{
var currentSnapshot = _textBuffer.CurrentSnapshot;
try
{
string scriptToTokenize = currentSnapshot.GetText();
Ast genereatedAst;
Token[] generatedTokens;
List<ClassificationInfo> tokenSpans;
List<TagInformation<ErrorTag>> errorTags;
Dictionary<int, int> startBraces;
Dictionary<int, int> endBraces;
List<TagInformation<IOutliningRegionTag>> regions;
Tokenize(currentSnapshot, scriptToTokenize, 0, out genereatedAst, out generatedTokens, out tokenSpans, out errorTags, out startBraces, out endBraces, out regions);
lock (_tokenizationLock)
{
if (_textBuffer.CurrentSnapshot.Version.VersionNumber == currentSnapshot.Version.VersionNumber)
{
Tasks.Task.Factory.StartNew(() =>
{
try
{
UpdateErrorList(errorTags, currentSnapshot);
UpdateTaskList(generatedTokens, currentSnapshot);
}
catch (Exception ex)
{
Log.Warn("Failed to update task list!", ex);
}
});
SetTokenizationProperties(genereatedAst, generatedTokens, tokenSpans, errorTags, startBraces, endBraces, regions);
RemoveCachedTokenizationProperties();
_isBufferTokenizing = false;
_lastSnapshot = currentSnapshot;
OnTokenizationComplete(genereatedAst);
NotifyOnTagsChanged(BufferProperties.Classifier, currentSnapshot);
NotifyOnTagsChanged(BufferProperties.ErrorTagger, currentSnapshot);
NotifyOnTagsChanged(typeof(PowerShellOutliningTagger).Name, currentSnapshot);
NotifyBufferUpdated();
break;
}
}
}
catch (Exception ex)
{
Log.Debug("Failed to tokenize the new snapshot.", ex);
}
}
}
private static void UpdateErrorList(IEnumerable<TagInformation<ErrorTag>> errorTags, ITextSnapshot currentSnapshot)
{
CreateProvider();
errorListProvider.Tasks.Clear();
foreach (var error in errorTags)
{
var errorTask = new ErrorTask();
errorTask.Text = error.Tag.ToolTipContent.ToString();
errorTask.ErrorCategory = TaskErrorCategory.Error;
errorTask.Line = error.Start;
errorTask.Document = currentSnapshot.TextBuffer.GetFilePath();
errorTask.Priority = TaskPriority.High;
errorListProvider.Tasks.Add(errorTask);
errorTask.Navigate += (sender, args) =>
{
var dte = PowerShellToolsPackage.Instance.GetService(typeof(DTE)) as DTE;
var document = dte.Documents.Open(currentSnapshot.TextBuffer.GetFilePath());
document.Activate();
var ts = dte.ActiveDocument.Selection as TextSelection;
ts.GotoLine(error.Start, true);
};
}
}
private static void UpdateTaskList(IEnumerable<Token> generatedTokens, ITextSnapshot currentSnapshot)
{
CreateProvider();
taskProvider.Tasks.Clear();
foreach (
var token in
generatedTokens.Where(
m => m.Kind == TokenKind.Comment && TaskIdentifiers.Any(x => m.Text.StartsWith(x, StringComparison.OrdinalIgnoreCase))))
{
var errorTask = new Task();
errorTask.CanDelete = false;
errorTask.Category = TaskCategory.Comments;
errorTask.Document = currentSnapshot.TextBuffer.GetFilePath();
errorTask.Line = token.Extent.StartLineNumber;
errorTask.Column = token.Extent.StartColumnNumber;
errorTask.Navigate += (sender, args) =>
{
var dte = PowerShellToolsPackage.Instance.GetService(typeof (DTE)) as DTE;
var document = dte.Documents.Open(currentSnapshot.TextBuffer.GetFilePath());
document.Activate();
var ts = dte.ActiveDocument.Selection as TextSelection;
ts.GotoLine(token.Extent.StartLineNumber, true);
};
errorTask.Text = token.Text.Substring(1);
errorTask.Priority = TaskPriority.Normal;
errorTask.IsPriorityEditable = true;
taskProvider.Tasks.Add(errorTask);
}
var taskList = PowerShellToolsPackage.Instance.GetService(typeof (SVsTaskList)) as IVsTaskList2;
if (taskList == null)
{
return;
}
var guidProvider = typeof (TodoWindowTaskProvider).GUID;
taskList.SetActiveProvider(ref guidProvider);
}
private void NotifyOnTagsChanged(string name, ITextSnapshot currentSnapshot)
{
INotifyTagsChanged classifier;
if (_textBuffer.Properties.TryGetProperty<INotifyTagsChanged>(name, out classifier))
{
classifier.OnTagsChanged(new SnapshotSpan(currentSnapshot, new Span(0, currentSnapshot.Length)));
}
}
private void NotifyBufferUpdated()
{
INotifyBufferUpdated tagger;
if (_textBuffer.Properties.TryGetProperty<INotifyBufferUpdated>(typeof(PowerShellBraceMatchingTagger).Name, out tagger) && tagger != null)
{
tagger.OnBufferUpdated(_textBuffer);
}
}
private void SetBufferProperty(object key, object propertyValue)
{
if (_textBuffer.Properties.ContainsProperty(key))
{
_textBuffer.Properties.RemoveProperty(key);
}
_textBuffer.Properties.AddProperty(key, propertyValue);
}
private void OnTokenizationComplete(Ast generatedAst)
{
if (TokenizationComplete != null)
{
TokenizationComplete(this, generatedAst);
}
}
private void Tokenize(ITextSnapshot currentSnapshot,
string spanText,
int startPosition,
out Ast generatedAst,
out Token[] generatedTokens,
out List<ClassificationInfo> tokenSpans,
out List<TagInformation<ErrorTag>> errorTags,
out Dictionary<int, int> startBraces,
out Dictionary<int, int> endBraces,
out List<TagInformation<IOutliningRegionTag>> regions)
{
Log.Debug("Parsing input.");
ParseError[] errors;
generatedAst = Parser.ParseInput(spanText, out generatedTokens, out errors);
Log.Debug("Classifying tokens.");
tokenSpans = _classifierService.ClassifyTokens(generatedTokens, startPosition).ToList();
Log.Debug("Tagging error spans.");
// Trigger the out-proc error parsing only when there are errors from the in-proc parser
if (errors.Length != 0)
{
var errorsParsedFromOutProc = PowerShellToolsPackage.IntelliSenseService.GetParseErrors(spanText);
errorTags = _errorTagService.TagErrorSpans(currentSnapshot, startPosition, errorsParsedFromOutProc).ToList();
}
else
{
errorTags = _errorTagService.TagErrorSpans(currentSnapshot, startPosition, errors).ToList();
}
Log.Debug("Matching braces and regions.");
_regionAndBraceMatchingService.GetRegionsAndBraceMatchingInformation(spanText, startPosition, generatedTokens, out startBraces, out endBraces, out regions);
}
private void SetTokenizationProperties(Ast generatedAst,
Token[] generatedTokens,
List<ClassificationInfo> tokenSpans,
List<TagInformation<ErrorTag>> errorTags,
Dictionary<int, int> startBraces,
Dictionary<int, int> endBraces,
List<TagInformation<IOutliningRegionTag>> regions)
{
SetBufferProperty(BufferProperties.Ast, generatedAst);
SetBufferProperty(BufferProperties.Tokens, generatedTokens);
SetBufferProperty(BufferProperties.TokenSpans, tokenSpans);
SetBufferProperty(BufferProperties.TokenErrorTags, errorTags);
SetBufferProperty(BufferProperties.StartBraces, startBraces);
SetBufferProperty(BufferProperties.EndBraces, endBraces);
SetBufferProperty(BufferProperties.Regions, regions);
}
private void RemoveCachedTokenizationProperties()
{
if (_textBuffer.Properties.ContainsProperty(BufferProperties.RegionTags))
{
_textBuffer.Properties.RemoveProperty(BufferProperties.RegionTags);
}
}
}
internal struct BraceInformation
{
internal char Character;
internal int Position;
internal BraceInformation(char character, int position)
{
Character = character;
Position = position;
}
}
internal struct ClassificationInfo
{
private readonly IClassificationType _classificationType;
private readonly int _length;
private readonly int _start;
internal ClassificationInfo(int start, int length, IClassificationType classificationType)
{
_classificationType = classificationType;
_start = start;
_length = length;
}
internal int Length
{
get { return _length; }
}
internal int Start
{
get { return _start; }
}
internal IClassificationType ClassificationType
{
get { return _classificationType; }
}
}
internal struct TagInformation<T> where T : ITag
{
internal readonly int Length;
internal readonly int Start;
internal readonly T Tag;
internal TagInformation(int start, int length, T tag)
{
Tag = tag;
Start = start;
Length = length;
}
internal TagSpan<T> GetTagSpan(ITextSnapshot snapshot)
{
return snapshot.Length >= Start + Length ?
new TagSpan<T>(new SnapshotSpan(snapshot, Start, Length), Tag) : null;
}
}
public static class BufferProperties
{
public const string Ast = "PSAst";
public const string Tokens = "PSTokens";
public const string TokenErrorTags = "PSTokenErrorTags";
public const string EndBraces = "PSEndBrace";
public const string StartBraces = "PSStartBrace";
public const string TokenSpans = "PSTokenSpans";
public const string Regions = "PSRegions";
public const string RegionTags = "PSRegionTags";
public const string Classifier = "Classifier";
public const string ErrorTagger = "PowerShellErrorTagger";
public const string FromRepl = "PowerShellREPL";
public const string LastWordReplacementSpan = "LastWordReplacementSpan";
public const string LineUpToReplacementSpan = "LineUpToReplacementSpan";
public const string SessionOriginIntellisense = "SessionOrigin_Intellisense";
public const string SessionCompletionFullyMatchedStatus = "SessionCompletionFullyMatchedStatus";
public const string PowerShellTokenizer = "PowerShellTokenizer";
}
public interface INotifyTagsChanged
{
void OnTagsChanged(SnapshotSpan span);
}
public interface INotifyBufferUpdated
{
void OnBufferUpdated(ITextBuffer textBuffer);
}
}
| |
// Copyright (c) 2016 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using Windows.Devices.Enumeration;
using Windows.Devices.WiFiDirect;
using Windows.Networking.Sockets;
namespace xwalk
{
using JSONObject = Dictionary<String, Object>;
public class XWalkExtensionInstance {
// Tags:
const String TAG_CMD = "cmd";
const String TAG_CONNECTED = "connected";
const String TAG_DATA = "data";
const String TAG_ENABLED = "enabled";
const String TAG_ERROR = "error";
const String TAG_ERROR_CODE = "errorCode";
const String TAG_EVENT_NAME = "eventName";
const String TAG_FALSE = "false";
const String TAG_GROUP_FORMED = "groupFormed";
const String TAG_IS_SERVER = "isServer";
const String TAG_MAC = "MAC";
const String TAG_MESSAGE = "message";
const String TAG_NAME = "name";
const String TAG_SERVER_IP = "serverIP";
const String TAG_CLIENT_IP = "clientIP";
const String TAG_STATUS = "status";
const String TAG_TRUE = "true";
const String TAG_TYPE = "type";
// Commands:
const String CMD_CANCEL_CONNECT = "cancelConnect";
const String CMD_CONNECT = "connect";
const String CMD_DISCONNECT = "disconnect";
const String CMD_DISCOVER_PEERS = "discoverPeers";
const String CMD_GET_CONNECTION_INFO = "getConnectionInfo";
const String CMD_GET_PEERS = "getPeers";
const String CMD_INIT = "init";
// Events:
const String EVENT_CONNECTION_CHANGED = "connectionchanged";
const String EVENT_DISCOVERY_STOPPED = "discoverystoppedevent";
const String EVENT_PEERS_CHANGED = "peerschanged";
const String EVENT_WIFI_STATE_CHANGED = "wifistatechanged";
// States:
const String STATE_AVAILABLE = "available";
const String STATE_CONNECTED = "connected";
const String STATE_UNAVAILABLE = "unavailable";
// Error messages:
const String ERROR_INVALID_CALL_NO_DATA_MSG = "Error: Invalid connect API call - data === null";
const String ERROR_INVALID_CALL_DEVICE_NOT_AVAILABLE = "Error: Invalid connect API call - device not available: ";
const String ERROR_INVALID_CALL_CMD = "Error: Invalid connect API command - cmd:";
WiFiDirectAdvertisementPublisher mAdvertiser;
WiFiDirectConnectionListener mConnectionListener;
DeviceWatcher mDeviceWatcher;
Collection<DeviceInformation> mDiscovered = new Collection<DeviceInformation>();
Dictionary<string, WiFiDirectDevice> mConnected = new Dictionary<string, WiFiDirectDevice>();
bool mGroupOwner = false;
public XWalkExtensionInstance(dynamic native) {
native_ = native;
}
public void HandleMessage(String message) {
JSONObject jsonInput = new JavaScriptSerializer().Deserialize<Dictionary<String, Object>>(message);
String cmd = jsonInput.ContainsKey(TAG_CMD) ? (String)jsonInput[TAG_CMD] : "";
JSONObject jsonOutput = jsonInput;
if (cmd.Equals(CMD_DISCOVER_PEERS)) {
discoverPeers(jsonOutput);
} else if (cmd.Equals(CMD_GET_PEERS)) {
getPeers(jsonOutput);
} else if (cmd.Equals(CMD_INIT)) {
jsonOutput[TAG_DATA] = TAG_TRUE;
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(jsonOutput));
} else if (cmd.Equals(CMD_GET_CONNECTION_INFO)) {
getConnectionInfo(jsonOutput);
} else if (cmd.Equals(CMD_CONNECT)) {
connect(jsonOutput);
} else if (cmd.Equals(CMD_CANCEL_CONNECT)) {
removeConnected(jsonOutput);
} else if (cmd.Equals(CMD_DISCONNECT)) {
removeConnected(jsonOutput);
} else {
setError(jsonOutput, ERROR_INVALID_CALL_CMD + cmd, 0);
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(jsonOutput));
}
}
public void HandleSyncMessage(String message) {
native_.SendSyncReply(message);
}
DeviceInformation findDiscoveredById(string id) {
foreach (DeviceInformation deviceInfo in mDiscovered) {
if (deviceInfo.Id == id) {
return deviceInfo;
}
}
return null;
}
// Used for lookup into mConnected as a deviceId returned from different
// APIs could differ.
private String extractMAC(String deviceId) {
if (deviceId.EndsWith("_PendingRequest"))
deviceId = deviceId.Substring(0, deviceId.Length - 15);
if (deviceId.StartsWith("WiFiDirect#"))
deviceId = deviceId.Substring(11);
return deviceId.ToLower();
}
Dictionary<String, object> convertDeviceToJSON(DeviceInformation peer) {
Dictionary<String, object> ob = new Dictionary<string, object>();
ob[TAG_NAME] = peer.Name;
ob[TAG_MAC] = peer.Id;
String mac = extractMAC(peer.Id);
WiFiDirectDevice device;
mConnected.TryGetValue(mac, out device);
if (device != null && device.ConnectionStatus == WiFiDirectConnectionStatus.Connected) {
ob[TAG_STATUS] = STATE_CONNECTED;
} else {
ob[TAG_STATUS] = peer.Pairing.CanPair ? STATE_AVAILABLE : STATE_UNAVAILABLE;
}
if (peer.Properties != null) {
foreach (String key in peer.Properties.Keys) {
var value = peer.Properties[key];
if (value != null)
ob[key] = value.ToString();
}
}
return ob;
}
List<object> convertListToJSON(ICollection<DeviceInformation> deviceList) {
List<object> arr = new List<object>();
foreach (DeviceInformation peer in deviceList)
arr.Add(convertDeviceToJSON(peer));
return arr;
}
void setError(JSONObject output, String errorMessage, int reasonCode) {
JSONObject data = new JSONObject();
JSONObject error = new JSONObject();
output[TAG_DATA] = data;
error[TAG_MESSAGE] = errorMessage;
error[TAG_ERROR_CODE] = reasonCode;
data[TAG_ERROR] = error;
Debug.WriteLine("setError : " + errorMessage);
}
JSONObject createEventData(String eventName) {
JSONObject eventData = new JSONObject();
eventData[TAG_EVENT_NAME] = eventName;
eventData[TAG_DATA] = new JSONObject();
return eventData;
}
void getConnectionInfo(JSONObject jsonOutput) {
JSONObject data = new JSONObject();
jsonOutput[TAG_DATA] = data;
IEnumerator<WiFiDirectDevice> it = mConnected.Values.GetEnumerator();
if (it.MoveNext()) {
var wfdDevice = it.Current;
var endpointPairs = wfdDevice.GetConnectionEndpointPairs();
if (wfdDevice.ConnectionStatus == WiFiDirectConnectionStatus.Connected) {
if (mGroupOwner) {
data[TAG_GROUP_FORMED] = TAG_TRUE;
data[TAG_IS_SERVER] = TAG_TRUE;
data[TAG_SERVER_IP] = endpointPairs[0].LocalHostName;
data[TAG_CLIENT_IP] = endpointPairs[0].RemoteHostName;
} else {
data[TAG_GROUP_FORMED] = TAG_TRUE;
data[TAG_IS_SERVER] = TAG_FALSE;
data[TAG_SERVER_IP] = endpointPairs[0].RemoteHostName;
data[TAG_CLIENT_IP] = endpointPairs[0].LocalHostName;
}
}
}
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(jsonOutput));
}
void removeConnected(JSONObject jsonOutput) {
IEnumerator<WiFiDirectDevice> it = mConnected.Values.GetEnumerator();
string result = TAG_FALSE;
while (it.MoveNext()) {
var wfdDevice = it.Current;
wfdDevice.Dispose();
result = TAG_TRUE;
}
jsonOutput[TAG_DATA] = result;
mConnected.Clear();
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(jsonOutput));
}
void discoverPeers(Dictionary<String, Object> jsonOutput) {
try {
advertise();
mDiscovered.Clear();
mDeviceWatcher = DeviceInformation.CreateWatcher(
WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.AssociationEndpoint),
new string[] { "System.Devices.WiFiDirect.InformationElements" });
mDeviceWatcher.Added += OnDeviceAdded;
mDeviceWatcher.Removed += OnDeviceRemoved;
mDeviceWatcher.Updated += OnDeviceUpdated;
mDeviceWatcher.Stopped += OnStopped;
mDeviceWatcher.Start();
jsonOutput[TAG_DATA] = TAG_TRUE;
} catch (Exception ex) {
setError(jsonOutput, ex.ToString(), ex.HResult);
}
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(jsonOutput));
}
void getPeers(JSONObject response) {
response[TAG_DATA] = convertListToJSON(mDiscovered);
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(response));
}
void OnStatusChanged(WiFiDirectAdvertisementPublisher sender, WiFiDirectAdvertisementPublisherStatusChangedEventArgs statusEventArgs) {
Debug.WriteLine("Advertisement: Status: " + statusEventArgs.Status.ToString() + " Error: " + statusEventArgs.Error.ToString());
}
#region DeviceWatcherEvents
void OnDeviceAdded(DeviceWatcher deviceWatcher, DeviceInformation deviceInfo) {
mDiscovered.Add(deviceInfo);
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(createEventData(EVENT_PEERS_CHANGED)));
}
void OnDeviceRemoved(DeviceWatcher deviceWatcher, DeviceInformationUpdate deviceInfoUpdate) {
foreach (DeviceInformation deviceInfo in mDiscovered) {
if (deviceInfo.Id == deviceInfoUpdate.Id) {
mDiscovered.Remove(deviceInfo);
break;
}
}
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(createEventData(EVENT_PEERS_CHANGED)));
}
void OnDeviceUpdated(DeviceWatcher deviceWatcher, DeviceInformationUpdate deviceInfoUpdate) {
DeviceInformation deviceInfo = findDiscoveredById(deviceInfoUpdate.Id);
if (deviceInfo != null) {
deviceInfo.Update(deviceInfoUpdate);
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(createEventData(EVENT_PEERS_CHANGED)));
}
}
void OnStopped(DeviceWatcher deviceWatcher, object o) {
mDeviceWatcher.Added -= OnDeviceAdded;
mDeviceWatcher.Removed -= OnDeviceRemoved;
mDeviceWatcher.Updated -= OnDeviceUpdated;
mDeviceWatcher.Stopped -= OnStopped;
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(createEventData(EVENT_DISCOVERY_STOPPED)));
}
#endregion DeviceWatcherEvents
#region Inviting
void connect(JSONObject response) {
WiFiDirectDevice wfdDevice = null;
try {
JSONObject device = (JSONObject)response[TAG_DATA];
if (device == null) {
setError(response, ERROR_INVALID_CALL_NO_DATA_MSG, 0);
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(response));
return;
}
DeviceInformation deviceInfo = findDiscoveredById((string)device[TAG_MAC]);
if (deviceInfo == null) {
setError(response, ERROR_INVALID_CALL_DEVICE_NOT_AVAILABLE + device[TAG_MAC], 0);
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(response));
return;
}
wfdDevice = WiFiDirectDevice.FromIdAsync(deviceInfo.Id).AsTask().Result;
wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;
var endpointPairs = wfdDevice.GetConnectionEndpointPairs();
mConnected[extractMAC(wfdDevice.DeviceId)] = wfdDevice;
response[TAG_DATA] = TAG_TRUE;
response[TAG_SERVER_IP] = endpointPairs[0].RemoteHostName;
mGroupOwner = false;
} catch (Exception ex) {
setError(response, ex.ToString(), ex.HResult);
wfdDevice = null;
}
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(response));
if (wfdDevice != null)
OnConnectionStatusChanged(wfdDevice, null);
}
void OnConnectionStatusChanged(WiFiDirectDevice sender, object arg) {
JSONObject eventData = createEventData(EVENT_CONNECTION_CHANGED);
((JSONObject)eventData[TAG_DATA])[TAG_CONNECTED] = (sender.ConnectionStatus == WiFiDirectConnectionStatus.Connected) ? TAG_TRUE : TAG_FALSE;
if (sender.ConnectionStatus == WiFiDirectConnectionStatus.Disconnected)
mConnected.Remove(extractMAC(sender.DeviceId));
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(createEventData(EVENT_PEERS_CHANGED)));
native_.PostMessageToJS(new JavaScriptSerializer().Serialize(eventData));
}
#endregion Inviting
#region GettingInvited
void advertise() {
if (mAdvertiser == null) {
mAdvertiser = new WiFiDirectAdvertisementPublisher();
}
if (mConnectionListener == null) {
mConnectionListener = new WiFiDirectConnectionListener();
}
mConnectionListener.ConnectionRequested += OnConnectionRequested;
mAdvertiser.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;
mAdvertiser.StatusChanged += OnStatusChanged;
mAdvertiser.Start();
}
void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs connectionEventArgs) {
WiFiDirectDevice wfdDevice;
try {
var connectionRequest = connectionEventArgs.GetConnectionRequest();
WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
connectionParams.GroupOwnerIntent = 15;
wfdDevice = WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id, connectionParams).AsTask().Result;
// Register for the ConnectionStatusChanged event handler
wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;
mConnected[extractMAC(wfdDevice.DeviceId)] = wfdDevice;
mGroupOwner = true;
} catch (Exception ex) {
Debug.WriteLine("Connect operation threw an exception: " + ex.Message);
wfdDevice = null;
}
if (wfdDevice != null) {
OnConnectionStatusChanged(wfdDevice, null);
}
}
#endregion GettingInvited
dynamic native_;
}
}
| |
namespace RRLab.PhysiologyWorkbench.GUI
{
partial class TestPulsePanel
{
/// <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();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TestPulsePanel));
this.LeftSidebar = new System.Windows.Forms.Panel();
this.testPulseSidebar1 = new RRLab.PhysiologyWorkbench.TestPulseSidebar();
this.ProgramBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.AutoStartTestPulseCheckBox = new System.Windows.Forms.CheckBox();
this.ProtocolExecutionControl = new RRLab.PhysiologyWorkbench.GUI.ProtocolExecutionControl();
this.SaveInBathTestPulseDataButton = new RRLab.PhysiologyWorkbench.GUI.SaveInBathTestPulseDataButton();
this.TestPulseBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.SaveCellAttachedTestPulseData = new RRLab.PhysiologyWorkbench.GUI.SaveCellAttachedTestPulseData();
this.saveWholeCellTestPulseDataButton1 = new RRLab.PhysiologyWorkbench.GUI.SaveWholeCellTestPulseDataButton();
this.SaveButton = new System.Windows.Forms.Button();
this.RecordingDataGraphControl = new RRLab.PhysiologyData.GUI.NIRecordingDataGraphControl();
this.LeftSidebar.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ProgramBindingSource)).BeginInit();
this.flowLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.TestPulseBindingSource)).BeginInit();
this.SuspendLayout();
//
// LeftSidebar
//
this.LeftSidebar.Controls.Add(this.testPulseSidebar1);
this.LeftSidebar.Controls.Add(this.flowLayoutPanel1);
this.LeftSidebar.Dock = System.Windows.Forms.DockStyle.Left;
this.LeftSidebar.Location = new System.Drawing.Point(0, 0);
this.LeftSidebar.Name = "LeftSidebar";
this.LeftSidebar.Size = new System.Drawing.Size(233, 557);
this.LeftSidebar.TabIndex = 0;
//
// testPulseSidebar1
//
this.testPulseSidebar1.DataBindings.Add(new System.Windows.Forms.Binding("Protocol", this.ProgramBindingSource, "TestPulseProtocol", true));
this.testPulseSidebar1.Dock = System.Windows.Forms.DockStyle.Fill;
this.testPulseSidebar1.Location = new System.Drawing.Point(0, 0);
this.testPulseSidebar1.Name = "testPulseSidebar1";
this.testPulseSidebar1.Protocol = null;
this.testPulseSidebar1.Size = new System.Drawing.Size(233, 447);
this.testPulseSidebar1.TabIndex = 2;
//
// ProgramBindingSource
//
this.ProgramBindingSource.DataSource = typeof(RRLab.PhysiologyWorkbench.PhysiologyWorkbenchProgram);
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.AutoSize = true;
this.flowLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.flowLayoutPanel1.Controls.Add(this.AutoStartTestPulseCheckBox);
this.flowLayoutPanel1.Controls.Add(this.ProtocolExecutionControl);
this.flowLayoutPanel1.Controls.Add(this.SaveInBathTestPulseDataButton);
this.flowLayoutPanel1.Controls.Add(this.SaveCellAttachedTestPulseData);
this.flowLayoutPanel1.Controls.Add(this.saveWholeCellTestPulseDataButton1);
this.flowLayoutPanel1.Controls.Add(this.SaveButton);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 447);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(233, 110);
this.flowLayoutPanel1.TabIndex = 1;
//
// AutoStartTestPulseCheckBox
//
this.AutoStartTestPulseCheckBox.AutoSize = true;
this.flowLayoutPanel1.SetFlowBreak(this.AutoStartTestPulseCheckBox, true);
this.AutoStartTestPulseCheckBox.Location = new System.Drawing.Point(3, 3);
this.AutoStartTestPulseCheckBox.Name = "AutoStartTestPulseCheckBox";
this.AutoStartTestPulseCheckBox.Size = new System.Drawing.Size(166, 17);
this.AutoStartTestPulseCheckBox.TabIndex = 6;
this.AutoStartTestPulseCheckBox.Text = "Automatically Start Test Pulse";
this.AutoStartTestPulseCheckBox.UseVisualStyleBackColor = true;
this.AutoStartTestPulseCheckBox.CheckedChanged += new System.EventHandler(this.OnAutoStartTestPulseChecked);
//
// ProtocolExecutionControl
//
this.ProtocolExecutionControl.AutoSize = true;
this.ProtocolExecutionControl.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.ProtocolExecutionControl.DataBindings.Add(new System.Windows.Forms.Binding("DataManager", this.ProgramBindingSource, "DataManager", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.ProtocolExecutionControl.DataBindings.Add(new System.Windows.Forms.Binding("Protocol", this.ProgramBindingSource, "TestPulseProtocol", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.ProtocolExecutionControl.DataManager = null;
this.ProtocolExecutionControl.Dock = System.Windows.Forms.DockStyle.Top;
this.ProtocolExecutionControl.Enabled = false;
this.flowLayoutPanel1.SetFlowBreak(this.ProtocolExecutionControl, true);
this.ProtocolExecutionControl.Location = new System.Drawing.Point(3, 26);
this.ProtocolExecutionControl.Name = "ProtocolExecutionControl";
this.ProtocolExecutionControl.Protocol = null;
this.ProtocolExecutionControl.RunningColor = System.Drawing.Color.Empty;
this.ProtocolExecutionControl.Size = new System.Drawing.Size(228, 29);
this.ProtocolExecutionControl.StoppedColor = System.Drawing.Color.LawnGreen;
this.ProtocolExecutionControl.TabIndex = 2;
//
// SaveInBathTestPulseDataButton
//
this.SaveInBathTestPulseDataButton.AlertColor = System.Drawing.Color.Gold;
this.SaveInBathTestPulseDataButton.Cell = null;
this.SaveInBathTestPulseDataButton.DataBindings.Add(new System.Windows.Forms.Binding("TestPulseProtocol", this.ProgramBindingSource, "TestPulseProtocol", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.SaveInBathTestPulseDataButton.DataSet = null;
this.SaveInBathTestPulseDataButton.Location = new System.Drawing.Point(0, 58);
this.SaveInBathTestPulseDataButton.Margin = new System.Windows.Forms.Padding(0);
this.SaveInBathTestPulseDataButton.Name = "SaveInBathTestPulseDataButton";
this.SaveInBathTestPulseDataButton.NormalColor = System.Drawing.SystemColors.Control;
this.SaveInBathTestPulseDataButton.Recording = null;
this.SaveInBathTestPulseDataButton.Size = new System.Drawing.Size(57, 50);
this.SaveInBathTestPulseDataButton.TabIndex = 11;
this.SaveInBathTestPulseDataButton.TestPulseProtocol = null;
//
// TestPulseBindingSource
//
this.TestPulseBindingSource.DataSource = typeof(RRLab.PhysiologyWorkbench.Daq.TestPulseProtocol);
//
// SaveCellAttachedTestPulseData
//
this.SaveCellAttachedTestPulseData.AlertColor = System.Drawing.Color.Gold;
this.SaveCellAttachedTestPulseData.Cell = null;
this.SaveCellAttachedTestPulseData.DataBindings.Add(new System.Windows.Forms.Binding("TestPulseProtocol", this.ProgramBindingSource, "TestPulseProtocol", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.SaveCellAttachedTestPulseData.DataSet = null;
this.SaveCellAttachedTestPulseData.Location = new System.Drawing.Point(58, 59);
this.SaveCellAttachedTestPulseData.Margin = new System.Windows.Forms.Padding(1);
this.SaveCellAttachedTestPulseData.Name = "SaveCellAttachedTestPulseData";
this.SaveCellAttachedTestPulseData.NormalColor = System.Drawing.SystemColors.Control;
this.SaveCellAttachedTestPulseData.Recording = null;
this.SaveCellAttachedTestPulseData.Size = new System.Drawing.Size(74, 50);
this.SaveCellAttachedTestPulseData.TabIndex = 9;
this.SaveCellAttachedTestPulseData.TestPulseProtocol = null;
//
// saveWholeCellTestPulseDataButton1
//
this.saveWholeCellTestPulseDataButton1.AlertColor = System.Drawing.Color.Gold;
this.saveWholeCellTestPulseDataButton1.Cell = null;
this.saveWholeCellTestPulseDataButton1.DataBindings.Add(new System.Windows.Forms.Binding("TestPulseProtocol", this.ProgramBindingSource, "TestPulseProtocol", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.saveWholeCellTestPulseDataButton1.DataSet = null;
this.saveWholeCellTestPulseDataButton1.Location = new System.Drawing.Point(134, 59);
this.saveWholeCellTestPulseDataButton1.Margin = new System.Windows.Forms.Padding(1);
this.saveWholeCellTestPulseDataButton1.Name = "saveWholeCellTestPulseDataButton1";
this.saveWholeCellTestPulseDataButton1.NormalColor = System.Drawing.SystemColors.Control;
this.saveWholeCellTestPulseDataButton1.Recording = null;
this.saveWholeCellTestPulseDataButton1.Size = new System.Drawing.Size(64, 50);
this.saveWholeCellTestPulseDataButton1.TabIndex = 10;
this.saveWholeCellTestPulseDataButton1.TestPulseProtocol = null;
//
// SaveButton
//
this.SaveButton.Image = ((System.Drawing.Image)(resources.GetObject("SaveButton.Image")));
this.SaveButton.Location = new System.Drawing.Point(200, 59);
this.SaveButton.Margin = new System.Windows.Forms.Padding(1);
this.SaveButton.Name = "SaveButton";
this.SaveButton.Size = new System.Drawing.Size(26, 50);
this.SaveButton.TabIndex = 7;
this.SaveButton.UseVisualStyleBackColor = true;
this.SaveButton.Click += new System.EventHandler(this.OnSaveButtonClicked);
//
// RecordingDataGraphControl
//
this.RecordingDataGraphControl.DataSet = null;
this.RecordingDataGraphControl.DefaultAxisLocation = RRLab.PhysiologyData.GUI.NIRecordingDataGraphControl.AxisLocation.Left;
this.RecordingDataGraphControl.DefaultAxisMode = RRLab.PhysiologyData.GUI.NIRecordingDataGraphControl.AxisMode.DynamicRange;
this.RecordingDataGraphControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.RecordingDataGraphControl.GraphBackColor = System.Drawing.Color.LightGoldenrodYellow;
this.RecordingDataGraphControl.IsAutoUpdateDisabled = true;
this.RecordingDataGraphControl.IsLegendVisible = global::RRLab.PhysiologyWorkbench.Properties.Settings.Default.TestPulseLegendVisible;
this.RecordingDataGraphControl.IsSidebarVisible = global::RRLab.PhysiologyWorkbench.Properties.Settings.Default.TestPulseSidebarVisible;
this.RecordingDataGraphControl.Location = new System.Drawing.Point(233, 0);
this.RecordingDataGraphControl.Name = "RecordingDataGraphControl";
this.RecordingDataGraphControl.Recording = null;
this.RecordingDataGraphControl.Size = new System.Drawing.Size(506, 557);
this.RecordingDataGraphControl.TabIndex = 1;
//
// TestPulsePanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.RecordingDataGraphControl);
this.Controls.Add(this.LeftSidebar);
this.Name = "TestPulsePanel";
this.Size = new System.Drawing.Size(739, 557);
this.VisibleChanged += new System.EventHandler(this.OnVisibleChanged);
this.LeftSidebar.ResumeLayout(false);
this.LeftSidebar.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.ProgramBindingSource)).EndInit();
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.TestPulseBindingSource)).EndInit();
this.ResumeLayout(false);
}
#endregion
private RRLab.PhysiologyWorkbench.TestPulseSidebar testPulseSidebar1;
private System.Windows.Forms.Panel LeftSidebar;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private RRLab.PhysiologyWorkbench.GUI.ProtocolExecutionControl ProtocolExecutionControl;
private System.Windows.Forms.CheckBox AutoStartTestPulseCheckBox;
private System.Windows.Forms.BindingSource TestPulseBindingSource;
private System.Windows.Forms.BindingSource ProgramBindingSource;
private System.Windows.Forms.Button SaveButton;
private RRLab.PhysiologyData.GUI.RecordingDataGraphControl RecordingGraphControl;
private RRLab.PhysiologyWorkbench.GUI.SaveCellAttachedTestPulseData SaveCellAttachedTestPulseData;
private RRLab.PhysiologyWorkbench.GUI.SaveWholeCellTestPulseDataButton saveWholeCellTestPulseDataButton1;
private SaveInBathTestPulseDataButton SaveInBathTestPulseDataButton;
private RRLab.PhysiologyData.GUI.NIRecordingDataGraphControl RecordingDataGraphControl;
}
}
| |
//! \file ArcWAG.cs
//! \date Tue Aug 11 08:28:28 2015
//! \brief Xuse/Eternal resource archive.
//
// Copyright (C) 2015-2016 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using GameRes.Utility;
namespace GameRes.Formats.Xuse
{
internal class WagArchive : ArcFile
{
public readonly byte[] Key;
public WagArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, byte[] key)
: base (arc, impl, dir)
{
Key = key;
}
}
[Export(typeof(ArchiveFormat))]
public class WagOpener : ArchiveFormat
{
public override string Tag { get { return "WAG"; } }
public override string Description { get { return "Xuse/Eternal resource archive"; } }
public override uint Signature { get { return 0x40474157; } } // 'WAG@'
public override bool IsHierarchic { get { return true; } }
public override bool CanCreate { get { return false; } }
public WagOpener ()
{
Extensions = new string[] { "wag", "4ag" };
Signatures = new uint[] { 0x40474157, 0x34464147 }; // 'GAF4'
}
public override ArcFile TryOpen (ArcView file)
{
if (0x0300 != file.View.ReadUInt16 (4))
return null;
int count = file.View.ReadInt32 (0x46);
if (!IsSaneCount (count))
return null;
byte[] title = new byte[0x40];
if (0x40 != file.View.Read (6, title, 0, 0x40))
return null;
int title_length = Array.IndexOf<byte> (title, 0);
if (-1 == title_length)
title_length = title.Length;
string arc_filename = Path.GetFileName (file.Name).ToLowerInvariant();
byte[] bin_filename = Encodings.cp932.GetBytes (arc_filename);
byte[] name_key = GenerateKey (bin_filename);
uint key_sum = (uint)name_key.Select (x => (int)x).Sum();
uint index_offset = 0x200 + key_sum;
for (int i = 0; i < name_key.Length; ++i)
{
index_offset ^= name_key[i];
index_offset = Binary.RotR (index_offset, 1);
}
for (int i = 0; i < name_key.Length; ++i)
{
index_offset ^= name_key[i];
index_offset = Binary.RotR (index_offset, 1);
}
index_offset %= 0x401;
index_offset += 0x4A;
byte[] index = file.View.ReadBytes (index_offset, (uint)(4*count));
if (index.Length != 4*count)
return null;
byte[] index_key = new byte[index.Length];
for (int i = 0; i < index_key.Length; ++i)
{
int v = name_key[(i+1) % name_key.Length] ^ (name_key[i % name_key.Length] + (i & 0xFF));
index_key[i] = (byte)(count + v);
}
Decrypt (index_offset, index_key, index);
var dir = new List<Entry> (count);
int current_offset = 0;
uint next_offset = LittleEndian.ToUInt32 (index, current_offset);
byte[] data_key = GenerateKey (title, title_length);
string base_filename = Path.GetFileNameWithoutExtension (arc_filename);
byte[] chunk_buf = new byte[8];
byte[] filename_buf = new byte[0x40];
for (int i = 0; i < count; ++i)
{
current_offset += 4;
uint entry_offset = next_offset;
if (entry_offset >= file.MaxOffset)
return null;
if (i + 1 == count)
next_offset = (uint)file.MaxOffset;
else
next_offset = LittleEndian.ToUInt32 (index, current_offset);
uint entry_size = next_offset - entry_offset;
if (8 != file.View.Read (entry_offset, chunk_buf, 0, 8))
return null;
Decrypt (entry_offset, data_key, chunk_buf);
if (!Binary.AsciiEqual (chunk_buf, "DSET"))
return null;
uint chunk_offset = entry_offset + 10;
int chunk_count = LittleEndian.ToInt32 (chunk_buf, 4);
string filename = null;
string type = null;
for (int chunk = 0; chunk < chunk_count; ++chunk)
{
if (8 != file.View.Read (chunk_offset, chunk_buf, 0, 8))
return null;
Decrypt (chunk_offset, data_key, chunk_buf);
int chunk_size = LittleEndian.ToInt32 (chunk_buf, 4);
if (chunk_size <= 0)
return null;
if (Binary.AsciiEqual (chunk_buf, "PICT"))
{
if (null == type)
{
type = "image";
entry_offset = chunk_offset + 0x10;
entry_size = (uint)chunk_size - 6;
}
}
else if (null == filename && Binary.AsciiEqual (chunk_buf, "FTAG"))
{
if (chunk_size > filename_buf.Length)
filename_buf = new byte[chunk_size];
if (chunk_size != file.View.Read (chunk_offset+10, filename_buf, 0, (uint)chunk_size))
return null;
Decrypt (chunk_offset+10, data_key, filename_buf, 0, chunk_size-2);
filename = Encodings.cp932.GetString (filename_buf, 0, chunk_size-2);
}
chunk_offset += 10 + (uint)chunk_size;
}
Entry entry;
if (!string.IsNullOrEmpty (filename))
{
filename = DriveRe.Replace (filename, "");
entry = FormatCatalog.Instance.Create<Entry> (filename);
}
else
{
entry = new Entry {
Name = string.Format ("{0}#{1:D4}", base_filename, i),
Type = type ?? ""
};
}
entry.Offset = entry_offset;
entry.Size = entry_size;
dir.Add (entry);
}
return new WagArchive (file, this, dir, data_key);
}
static readonly Regex DriveRe = new Regex (@"^(?:.+:)?\\+");
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var warc = arc as WagArchive;
if (null == warc)
return arc.File.CreateStream (entry.Offset, entry.Size);
var data = new byte[entry.Size];
arc.File.View.Read (entry.Offset, data, 0, entry.Size);
Decrypt ((uint)entry.Offset, warc.Key, data);
return new MemoryStream (data);
}
private byte[] GenerateKey (byte[] keyword)
{
return GenerateKey (keyword, keyword.Length);
}
private byte[] GenerateKey (byte[] keyword, int length)
{
int hash = 0;
for (int i = 0; i < length; ++i)
hash = (((sbyte)keyword[i] + i) ^ hash) + length;
int key_length = (hash & 0xFF) + 0x40;
for (int i = 0; i < length; ++i)
hash += (sbyte)keyword[i];
byte[] key = new byte[key_length--];
key[1] = (byte)(hash >> 8);
hash &= 0xF;
key[0] = (byte)hash;
key[2] = 0x46;
key[3] = 0x88;
for (int i = 4; i < key_length; ++i)
{
hash += (((sbyte)keyword[i % length] ^ hash) + i) & 0xFF;
key[i] = (byte)hash;
}
return key;
}
private void Decrypt (uint offset, byte[] key, byte[] index)
{
Decrypt (offset, key, index, 0, index.Length);
}
private void Decrypt (uint offset, byte[] key, byte[] index, int pos, int length)
{
uint key_last = (uint)key.Length-1;
for (uint i = 0; i < length; ++i)
index[pos+i] ^= key[(offset + i) % key_last];
}
}
}
| |
// MbUnit Test Framework
//
// Copyright (c) 2004 Jonathan de Halleux
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// MbUnit HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
using System;
namespace MbUnit.Core.Cons.CommandLine
{
using System;
using System.Reflection;
using System.Collections;
using System.IO;
using System.Text;
using System.Diagnostics;
/// <summary>
/// Parser for command line arguments.
/// </summary>
/// <remarks>
/// <para>
/// The parser specification is infered from the instance fields of the object
/// specified as the destination of the parse.
/// Valid argument types are: int, uint, string, bool, enums
/// Also argument types of Array of the above types are also valid.
/// </para>
/// <para>
/// Error checking options can be controlled by adding a CommandLineArgumentAttribute
/// to the instance fields of the destination object.
/// </para>
/// <para>
/// At most one field may be marked with the DefaultCommandLineArgumentAttribute
/// indicating that arguments without a '-' or '/' prefix will be parsed as that argument.
/// </para>
/// <para>
/// If not specified then the parser will infer default options for parsing each
/// instance field. The default long name of the argument is the field name. The
/// default short name is the first character of the long name. Long names and explicitly
/// specified short names must be unique. Default short names will be used provided that
/// the default short name does not conflict with a long name or an explicitly
/// specified short name.
/// </para>
/// <para>
/// Arguments which are array types are collection arguments. Collection
/// arguments can be specified multiple times.
/// </para>
/// <para>
/// Command line parsing code from Peter Halam,
/// http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e
/// </para>
/// </remarks>
public class CommandLineArgumentParser
{
/// <summary>
/// Creates a new command line argument parser.
/// </summary>
/// <param name="argumentSpecification"> The type of object to parse. </param>
/// <param name="reporter"> The destination for parse errors. </param>
public CommandLineArgumentParser(Type argumentSpecification, ErrorReporter reporter)
{
this.reporter = reporter;
this.arguments = new ArrayList();
this.argumentMap = new Hashtable();
foreach (FieldInfo field in argumentSpecification.GetFields())
{
if (!field.IsStatic && !field.IsInitOnly && !field.IsLiteral)
{
CommandLineArgumentAttribute attribute = GetAttribute(field);
if (attribute is DefaultCommandLineArgumentAttribute)
{
if (this.defaultArgument!=null)
ThrowError("More that one DefaultCommandLineArgument has been used");
this.defaultArgument = new Argument(attribute, field, reporter);
}
else
{
this.arguments.Add(new Argument(attribute, field, reporter));
}
}
}
// add explicit names to map
foreach (Argument argument in this.arguments)
{
if (argumentMap.ContainsKey(argument.LongName))
ThrowError("Argument {0} is duplicated",argument.LongName);
this.argumentMap[argument.LongName] = argument;
if (argument.ExplicitShortName && argument.ShortName != null && argument.ShortName.Length > 0)
{
if(this.argumentMap.ContainsKey(argument.ShortName))
ThrowError("Argument {0} is duplicated",argument.ShortName);
this.argumentMap[argument.ShortName] = argument;
}
}
// add implicit names which don't collide to map
foreach (Argument argument in this.arguments)
{
if (!argument.ExplicitShortName && argument.ShortName != null && argument.ShortName.Length > 0)
{
if (!argumentMap.ContainsKey(argument.ShortName))
this.argumentMap[argument.ShortName] = argument;
}
}
}
private static CommandLineArgumentAttribute GetAttribute(FieldInfo field)
{
object[] attributes = field.GetCustomAttributes(typeof(CommandLineArgumentAttribute), false);
if (attributes.Length==0)
ThrowError("No fields tagged with CommandLineArgumentAttribute");
return (CommandLineArgumentAttribute) attributes[0];
}
private void ReportUnrecognizedArgument(string argument)
{
this.reporter(string.Format("Unrecognized command line argument '{0}'", argument));
}
private static void ThrowError(string message, params Object[] args)
{
throw new InvalidOperationException(String.Format(message,args));
}
/// <summary>
/// Parses an argument list into an object
/// </summary>
/// <param name="args"></param>
/// <param name="destination"></param>
/// <returns> true if an error occurred </returns>
private bool ParseArgumentList(string[] args, object destination)
{
bool hadError = false;
if (args != null)
{
foreach (string argument in args)
{
if (argument.Length > 0)
{
switch (argument[0])
{
case '-':
case '/':
int endIndex = argument.IndexOfAny(new char[] {':', '+'}, 1);
string option = argument.Substring(1, endIndex == -1 ? argument.Length - 1 : endIndex - 1);
string optionArgument;
if (option.Length + 1 == argument.Length)
{
optionArgument = null;
}
else if (argument.Length > 1 + option.Length && argument[1 + option.Length] == ':')
{
optionArgument = argument.Substring(option.Length + 2);
}
else
{
optionArgument = argument.Substring(option.Length + 1);
}
Argument arg = (Argument) this.argumentMap[option];
if (arg == null)
{
ReportUnrecognizedArgument(argument);
hadError = true;
}
else
{
hadError |= !arg.SetValue(optionArgument, destination);
}
break;
case '@':
string[] nestedArguments;
hadError |= LexFileArguments(argument.Substring(1), out nestedArguments);
hadError |= ParseArgumentList(nestedArguments, destination);
break;
default:
if (this.defaultArgument != null)
{
hadError |= !this.defaultArgument.SetValue(argument, destination);
}
else
{
ReportUnrecognizedArgument(argument);
hadError = true;
}
break;
}
}
}
}
return hadError;
}
/// <summary>
/// Parses an argument list.
/// </summary>
/// <param name="args"> The arguments to parse. </param>
/// <param name="destination"> The destination of the parsed arguments. </param>
/// <returns> true if no parse errors were encountered. </returns>
public bool Parse(string[] args, object destination)
{
bool hadError = ParseArgumentList(args, destination);
// check for missing required arguments
foreach (Argument arg in this.arguments)
{
hadError |= arg.Finish(destination);
}
if (this.defaultArgument != null)
{
hadError |= this.defaultArgument.Finish(destination);
}
return !hadError;
}
/// <summary>
/// A user friendly usage string describing the command line argument syntax.
/// </summary>
public string Usage
{
get
{
StringBuilder builder = new StringBuilder();
int oldLength;
foreach (Argument arg in this.arguments)
{
oldLength = builder.Length;
builder.Append(" /");
builder.Append(arg.LongName);
Type valueType = arg.ValueType;
if (valueType == typeof(int))
{
builder.Append(":<int>");
}
else if (valueType == typeof(uint))
{
builder.Append(":<uint>");
}
else if (valueType == typeof(bool))
{
builder.Append("[+|-]");
}
else if (valueType == typeof(string))
{
builder.Append(":<string>");
}
else
{
Debug.Assert(valueType.IsEnum);
builder.Append(":{");
bool first = true;
foreach (FieldInfo field in valueType.GetFields())
{
if (field.IsStatic)
{
if (first)
first = false;
else
builder.Append('|');
builder.Append(field.Name);
}
}
builder.Append('}');
}
if (arg.ShortName != arg.LongName && this.argumentMap[arg.ShortName] == arg)
{
builder.Append(' ', IndentLength(builder.Length - oldLength));
builder.Append("short form /");
builder.Append(arg.ShortName);
}
if (arg.Description.Length>0)
builder.Append("\t"+arg.Description);
builder.Append(CommandLineUtility.NewLine);
}
oldLength = builder.Length;
builder.Append(" @<file>");
builder.Append(' ', IndentLength(builder.Length - oldLength));
builder.Append("Read response file for more options");
builder.Append(CommandLineUtility.NewLine);
if (this.defaultArgument != null)
{
oldLength = builder.Length;
builder.Append(" <");
builder.Append(this.defaultArgument.LongName);
builder.Append(">");
builder.Append(CommandLineUtility.NewLine);
}
return builder.ToString();
}
}
private static int IndentLength(int lineLength)
{
return Math.Max(4, 40 - lineLength);
}
private bool LexFileArguments(string fileName, out string[] arguments)
{
string args = null;
try
{
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
args = (new StreamReader(file)).ReadToEnd();
}
}
catch (Exception e)
{
this.reporter(string.Format("Error: Can't open command line argument file '{0}' : '{1}'", fileName, e.Message));
arguments = null;
return false;
}
bool hadError = false;
ArrayList argArray = new ArrayList();
StringBuilder currentArg = new StringBuilder();
bool inQuotes = false;
int index = 0;
// while (index < args.Length)
try
{
while (true)
{
// skip whitespace
while (char.IsWhiteSpace(args[index]))
{
index += 1;
}
// # - comment to end of line
if (args[index] == '#')
{
index += 1;
while (args[index] != '\n')
{
index += 1;
}
continue;
}
// do one argument
do
{
if (args[index] == '\\')
{
int cSlashes = 1;
index += 1;
while (index == args.Length && args[index] == '\\')
{
cSlashes += 1;
}
if (index == args.Length || args[index] != '"')
{
currentArg.Append('\\', cSlashes);
}
else
{
currentArg.Append('\\', (cSlashes >> 1));
if (0 != (cSlashes & 1))
{
currentArg.Append('"');
}
else
{
inQuotes = !inQuotes;
}
}
}
else if (args[index] == '"')
{
inQuotes = !inQuotes;
index += 1;
}
else
{
currentArg.Append(args[index]);
index += 1;
}
} while (!char.IsWhiteSpace(args[index]) || inQuotes);
argArray.Add(currentArg.ToString());
currentArg.Length = 0;
}
}
catch (System.IndexOutOfRangeException)
{
// got EOF
if (inQuotes)
{
this.reporter(string.Format("Error: Unbalanced '\"' in command line argument file '{0}'", fileName));
hadError = true;
}
else if (currentArg.Length > 0)
{
// valid argument can be terminated by EOF
argArray.Add(currentArg.ToString());
}
}
arguments = (string[]) argArray.ToArray(typeof (string));
return hadError;
}
private static string LongName(CommandLineArgumentAttribute attribute, FieldInfo field)
{
return (attribute == null || attribute.DefaultLongName) ? field.Name : attribute.LongName;
}
private static string ShortName(CommandLineArgumentAttribute attribute, FieldInfo field)
{
return !ExplicitShortName(attribute) ? LongName(attribute, field).Substring(0,1) : attribute.ShortName;
}
private static bool ExplicitShortName(CommandLineArgumentAttribute attribute)
{
return (attribute != null && !attribute.DefaultShortName);
}
private static Type ElementType(FieldInfo field)
{
if (IsCollectionType(field.FieldType))
return field.FieldType.GetElementType();
else
return null;
}
private static CommandLineArgumentType Flags(CommandLineArgumentAttribute attribute, FieldInfo field)
{
if (attribute != null)
return attribute.Type;
else if (IsCollectionType(field.FieldType))
return CommandLineArgumentType.MultipleUnique;
else
return CommandLineArgumentType.AtMostOnce;
}
private static bool IsCollectionType(Type type)
{
return type.IsArray;
}
private static bool IsValidElementType(Type type)
{
return type != null && (
type == typeof(int) ||
type == typeof(uint) ||
type == typeof(string) ||
type == typeof(bool) ||
type.IsEnum);
}
private class Argument
{
public Argument(CommandLineArgumentAttribute attribute, FieldInfo field, ErrorReporter reporter)
{
this.longName = CommandLineArgumentParser.LongName(attribute, field);
this.explicitShortName = CommandLineArgumentParser.ExplicitShortName(attribute);
this.shortName = CommandLineArgumentParser.ShortName(attribute, field);
this.elementType = ElementType(field);
this.flags = Flags(attribute, field);
this.field = field;
this.seenValue = false;
this.reporter = reporter;
this.isDefault = attribute != null && attribute is DefaultCommandLineArgumentAttribute;
this.description=attribute.Description;
if (IsCollection)
{
this.collectionValues = new ArrayList();
}
Debug.Assert(this.longName != null && this.longName.Length > 0);
if (IsCollection && !AllowMultiple)
ThrowError("Collection arguments must have allow multiple");
Debug.Assert(!Unique || IsCollection, "Unique only applicable to collection arguments");
Debug.Assert(IsValidElementType(Type) ||
IsCollectionType(Type));
Debug.Assert((IsCollection && IsValidElementType(elementType)) ||
(!IsCollection && elementType == null));
}
public bool Finish(object destination)
{
if (this.IsCollection)
{
this.field.SetValue(destination, this.collectionValues.ToArray(this.elementType));
}
return ReportMissingRequiredArgument();
}
private bool ReportMissingRequiredArgument()
{
if (this.IsRequired && !this.SeenValue)
{
if (this.IsDefault)
reporter(string.Format("Missing required argument '<{0}>'.", this.LongName));
else
reporter(string.Format("Missing required argument '/{0}'.", this.LongName));
return true;
}
return false;
}
private void ReportDuplicateArgumentValue(string value)
{
this.reporter(string.Format("Duplicate '{0}' argument '{1}'", this.LongName, value));
}
public bool SetValue(string value, object destination)
{
if (SeenValue && !AllowMultiple)
{
this.reporter(string.Format("Duplicate '{0}' argument", this.LongName));
return false;
}
this.seenValue = true;
object newValue;
if (!ParseValue(this.ValueType, value, out newValue))
return false;
if (this.IsCollection)
{
if (this.Unique && this.collectionValues.Contains(newValue))
{
ReportDuplicateArgumentValue(value);
return false;
}
else
{
this.collectionValues.Add(newValue);
}
}
else
{
this.field.SetValue(destination, newValue);
}
return true;
}
public Type ValueType
{
get { return this.IsCollection ? this.elementType : this.Type; }
}
private void ReportBadArgumentValue(string value)
{
this.reporter(string.Format("'{0}' is not a valid value for the '{1}' command line option", value, this.LongName));
}
private bool ParseValue(Type type, string stringData, out object value)
{
// null is only valid for bool variables
// empty string is never valid
if ((stringData != null || type == typeof(bool)) && (stringData == null || stringData.Length > 0))
{
try
{
if (type == typeof(string))
{
value = stringData;
return true;
}
else if (type == typeof(bool))
{
if (stringData == null || stringData == "+")
{
value = true;
return true;
}
else if (stringData == "-")
{
value = false;
return true;
}
}
else if (type == typeof(int))
{
value = int.Parse(stringData);
return true;
}
else if (type == typeof(uint))
{
value = int.Parse(stringData);
return true;
}
else
{
Debug.Assert(type.IsEnum);
value = Enum.Parse(type, stringData, true);
return true;
}
}
catch
{
// catch parse errors
}
}
ReportBadArgumentValue(stringData);
value = null;
return false;
}
public string LongName
{
get { return this.longName; }
}
public bool ExplicitShortName
{
get { return this.explicitShortName; }
}
public string ShortName
{
get { return this.shortName; }
}
public bool IsRequired
{
get { return 0 != (this.flags & CommandLineArgumentType.Required); }
}
public bool SeenValue
{
get { return this.seenValue; }
}
public bool AllowMultiple
{
get { return 0 != (this.flags & CommandLineArgumentType.Multiple); }
}
public bool Unique
{
get { return 0 != (this.flags & CommandLineArgumentType.Unique); }
}
public Type Type
{
get { return field.FieldType; }
}
public bool IsCollection
{
get { return IsCollectionType(Type); }
}
public bool IsDefault
{
get { return this.isDefault; }
}
public string Description
{
get
{
return this.description;
}
}
private string longName;
private string shortName;
private bool explicitShortName;
private bool seenValue;
private FieldInfo field;
private Type elementType;
private CommandLineArgumentType flags;
private ArrayList collectionValues;
private ErrorReporter reporter;
private bool isDefault;
private string description;
}
private ArrayList arguments;
private Hashtable argumentMap;
private Argument defaultArgument;
private ErrorReporter reporter;
}
}
| |
//Copyright (C) 2006 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the DefaultLinker.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Thomas Morton
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using OpenNLP.Tools.Coreference.Mention;
using OpenNLP.Tools.Coreference.Resolver;
using OpenNLP.Tools.Coreference.Similarity;
namespace OpenNLP.Tools.Coreference
{
/// <summary>
/// This class perform coreference for treebank style parses or for noun-phrase chunked data.
/// Non-constituent entites such as pre-nominal named-entities and sub entities in simple coordinated
/// noun phases will be created. This linker requires that named-entity information also be provided.
/// This information can be added to the parse using the -parse option with EnglishNameFinder.
/// </summary>
public class DefaultLinker : AbstractLinker
{
private MaximumEntropyCompatibilityModel mCompatibilityModel;
protected internal MaximumEntropyCompatibilityModel CompatibilityModel
{
get
{
return mCompatibilityModel;
}
set
{
mCompatibilityModel = value;
}
}
/// <summary>
/// Creates a new linker with the specified model directory, running in the specified mode.
/// </summary>
/// <param name="modelDirectory">
/// The directory where the models for this linker are kept.
/// </param>
/// <param name="mode">
/// The mode that this linker is running in.
/// </param>
public DefaultLinker(string modelDirectory, LinkerMode mode) : this(modelDirectory, mode, true, -1)
{
}
/// <summary>
/// Creates a new linker with the specified model directory, running in the specified mode which uses a discourse model
/// based on the specified parameter.
/// </summary>
/// <param name="modelDirectory">
/// The directory where the models for this linker are kept.
/// </param>
/// <param name="mode">
/// The mode that this linker is running in.
/// </param>
/// <param name="useDiscourseModel">
/// Whether the model should use a discourse model or not.
/// </param>
public DefaultLinker(string modelDirectory, LinkerMode mode, bool useDiscourseModel) : this(modelDirectory, mode, useDiscourseModel, -1)
{
}
/// <summary>
/// Creates a new linker with the specified model directory, running in the specified mode which uses a discourse model
/// based on the specified parameter and uses the specified fixed non-referential probability.
/// </summary>
/// <param name="modelDirectory">
/// The directory where the models for this linker are kept.
/// </param>
/// <param name="mode">
/// The mode that this linker is running in.
/// </param>
/// <param name="useDiscourseModel">
/// Whether the model should use a discourse model or not.
/// </param>
/// <param name="fixedNonReferentialProbability">
/// The probability which resolvers are required to exceed to posit a coreference relationship.
/// </param>
public DefaultLinker(string modelDirectory, LinkerMode mode, bool useDiscourseModel, double fixedNonReferentialProbability) : base(modelDirectory, mode, useDiscourseModel)
{
if (mode != LinkerMode.Sim)
{
mCompatibilityModel = new MaximumEntropyCompatibilityModel(CoreferenceProjectName);
}
InitializeHeaderFinder();
InitializeMentionFinder();
if (mode != LinkerMode.Sim)
{
InitializeResolvers(mode, fixedNonReferentialProbability);
Entities = new DiscourseEntity[Resolvers.Length];
}
}
/// <summary>
/// Initializes the resolvers used by this linker.
/// </summary>
/// <param name="mode">
/// The mode in which this linker is being used.
/// </param>
/// <param name="fixedNonReferentialProbability">
/// </param>
protected internal virtual void InitializeResolvers(LinkerMode mode, double fixedNonReferentialProbability)
{
if (mode == LinkerMode.Train)
{
MentionFinder.PrenominalNamedEntitiesCollection = false;
MentionFinder.CoordinatedNounPhrasesCollection = false;
}
SingularPronounIndex = 0;
if (LinkerMode.Test == mode || LinkerMode.Eval == mode)
{
if (fixedNonReferentialProbability < 0)
{
Resolvers = new MaximumEntropyResolver[] { new SingularPronounResolver(CoreferenceProjectName, ResolverMode.Test), new ProperNounResolver(CoreferenceProjectName, ResolverMode.Test), new DefiniteNounResolver(CoreferenceProjectName, ResolverMode.Test), new IsAResolver(CoreferenceProjectName, ResolverMode.Test), new PluralPronounResolver(CoreferenceProjectName, ResolverMode.Test), new PluralNounResolver(CoreferenceProjectName, ResolverMode.Test), new CommonNounResolver(CoreferenceProjectName, ResolverMode.Test), new SpeechPronounResolver(CoreferenceProjectName, ResolverMode.Test) };
}
else
{
INonReferentialResolver nrr = new FixedNonReferentialResolver(fixedNonReferentialProbability);
Resolvers = new MaximumEntropyResolver[] { new SingularPronounResolver(CoreferenceProjectName, ResolverMode.Test, nrr), new ProperNounResolver(CoreferenceProjectName, ResolverMode.Test, nrr), new DefiniteNounResolver(CoreferenceProjectName, ResolverMode.Test, nrr), new IsAResolver(CoreferenceProjectName, ResolverMode.Test, nrr), new PluralPronounResolver(CoreferenceProjectName, ResolverMode.Test, nrr), new PluralNounResolver(CoreferenceProjectName, ResolverMode.Test, nrr), new CommonNounResolver(CoreferenceProjectName, ResolverMode.Test, nrr), new SpeechPronounResolver(CoreferenceProjectName, ResolverMode.Test, nrr) };
}
if (LinkerMode.Eval == mode)
{
//string[] names = {"Pronoun", "Proper", "Def-NP", "Is-a", "Plural Pronoun"};
//eval = new Evaluation(names);
}
MaximumEntropyResolver.SimilarityModel = SimilarityModel.TestModel(CoreferenceProjectName + "/sim");
}
else if (LinkerMode.Train == mode)
{
Resolvers = new AbstractResolver[9];
Resolvers[0] = new SingularPronounResolver(CoreferenceProjectName, ResolverMode.Train);
Resolvers[1] = new ProperNounResolver(CoreferenceProjectName, ResolverMode.Train);
Resolvers[2] = new DefiniteNounResolver(CoreferenceProjectName, ResolverMode.Train);
Resolvers[3] = new IsAResolver(CoreferenceProjectName, ResolverMode.Train);
Resolvers[4] = new PluralPronounResolver(CoreferenceProjectName, ResolverMode.Train);
Resolvers[5] = new PluralNounResolver(CoreferenceProjectName, ResolverMode.Train);
Resolvers[6] = new CommonNounResolver(CoreferenceProjectName, ResolverMode.Train);
Resolvers[7] = new SpeechPronounResolver(CoreferenceProjectName, ResolverMode.Train);
Resolvers[8] = new PerfectResolver();
}
else
{
System.Console.Error.WriteLine("DefaultLinker: Invalid Mode");
}
}
/// <summary>
/// Initializes the head finder for this linker.
/// </summary>
protected internal virtual void InitializeHeaderFinder()
{
HeadFinder = Mention.PennTreebankHeadFinder.Instance;
}
/// <summary>
/// Initializes the mention finder for this linker.
/// This can be overridden to change the space of mentions used for coreference.
/// </summary>
protected internal virtual void InitializeMentionFinder()
{
MentionFinder = ShallowParseMentionFinder.GetInstance(HeadFinder);
}
protected internal override Gender ComputeGender(Mention.MentionContext mention)
{
return mCompatibilityModel.ComputeGender(mention);
}
protected internal override Number ComputeNumber(Mention.MentionContext mention)
{
return mCompatibilityModel.ComputeNumber(mention);
}
}
}
| |
using ClosedXML.Utils;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
[assembly: CLSCompliantAttribute(true)]
namespace ClosedXML.Excel
{
internal static class Extensions
{
// Adds the .ForEach method to all IEnumerables
private static readonly char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
public static String ToHex(this Color color)
{
byte[] bytes = new byte[4];
bytes[0] = color.A;
bytes[1] = color.R;
bytes[2] = color.G;
bytes[3] = color.B;
char[] chars = new char[bytes.Length * 2];
for (int i = 0; i < bytes.Length; i++)
{
int b = bytes[i];
chars[i * 2] = hexDigits[b >> 4];
chars[i * 2 + 1] = hexDigits[b & 0xF];
}
return new string(chars);
}
public static String RemoveSpecialCharacters(this String str)
{
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
if (Char.IsLetterOrDigit(c) || c == '.' || c == '_')
{
sb.Append(c);
}
}
return sb.ToString();
}
public static Int32 CharCount(this String instance, Char c)
{
return instance.Length - instance.Replace(c.ToString(), "").Length;
}
public static Boolean HasDuplicates<T>(this IEnumerable<T> source)
{
HashSet<T> distinctItems = new HashSet<T>();
foreach (var item in source)
{
if (!distinctItems.Add(item))
{
return true;
}
}
return false;
}
public static T CastTo<T>(this Object o)
{
return (T)Convert.ChangeType(o, typeof(T));
}
}
internal static class DictionaryExtensions
{
public static void RemoveAll<TKey, TValue>(this Dictionary<TKey, TValue> dic,
Func<TValue, bool> predicate)
{
var keys = dic.Keys.Where(k => predicate(dic[k])).ToList();
foreach (var key in keys)
{
dic.Remove(key);
}
}
}
internal static class StringExtensions
{
private static readonly Regex RegexNewLine = new Regex(@"((?<!\r)\n|\r\n)", RegexOptions.Compiled);
public static String FixNewLines(this String value)
{
return value.Contains("\n") ? RegexNewLine.Replace(value, Environment.NewLine) : value;
}
public static Boolean PreserveSpaces(this String value)
{
return value.StartsWith(" ") || value.EndsWith(" ") || value.Contains(Environment.NewLine);
}
public static String ToCamel(this String value)
{
if (value.Length == 0)
return value;
if (value.Length == 1)
return value.ToLower();
return value.Substring(0, 1).ToLower() + value.Substring(1);
}
public static String ToProper(this String value)
{
if (value.Length == 0)
return value;
if (value.Length == 1)
return value.ToUpper();
return value.Substring(0, 1).ToUpper() + value.Substring(1);
}
}
internal static class DateTimeExtensions
{
public static Double MaxOADate
{
get
{
return 2958465.99999999;
}
}
public static DateTime NextWorkday(this DateTime date, IEnumerable<DateTime> bankHolidays)
{
var nextDate = date.AddDays(1);
while (!nextDate.IsWorkDay(bankHolidays))
nextDate = nextDate.AddDays(1);
return nextDate;
}
public static DateTime PreviousWorkDay(this DateTime date, IEnumerable<DateTime> bankHolidays)
{
var previousDate = date.AddDays(-1);
while (!previousDate.IsWorkDay(bankHolidays))
previousDate = previousDate.AddDays(-1);
return previousDate;
}
public static bool IsWorkDay(this DateTime date, IEnumerable<DateTime> bankHolidays)
{
return date.DayOfWeek != DayOfWeek.Saturday
&& date.DayOfWeek != DayOfWeek.Sunday
&& !bankHolidays.Contains(date);
}
}
internal static class IntegerExtensions
{
public static String ToInvariantString(this Int32 value)
{
return value.ToString(CultureInfo.InvariantCulture.NumberFormat);
}
public static bool Between(this int val, int from, int to)
{
return val >= from && val <= to;
}
}
internal static class DecimalExtensions
{
//All numbers are stored in XL files as invarient culture this is just a easy helper
public static String ToInvariantString(this Decimal value)
{
return value.ToString(CultureInfo.InvariantCulture);
}
public static Decimal SaveRound(this Decimal value)
{
return Math.Round(value, 6);
}
}
internal static class DoubleExtensions
{
//All numbers are stored in XL files as invarient culture this is just a easy helper
public static String ToInvariantString(this Double value)
{
return value.ToString(CultureInfo.InvariantCulture);
}
public static Double SaveRound(this Double value)
{
return Math.Round(value, 6);
}
}
internal static class FontBaseExtensions
{
public static Double GetWidth(this IXLFontBase fontBase, String text, Dictionary<IXLFontBase, Font> fontCache)
{
if (String.IsNullOrWhiteSpace(text))
return 0;
var font = GetCachedFont(fontBase, fontCache);
var textWidth = GraphicsUtils.MeasureString(text, font).Width;
double width = (textWidth / 7d * 256 - 128 / 7) / 256;
width = Math.Round(width + 0.2, 2);
return width;
}
public static Double GetHeight(this IXLFontBase fontBase, Dictionary<IXLFontBase, Font> fontCache)
{
var font = GetCachedFont(fontBase, fontCache);
var textHeight = GraphicsUtils.MeasureString("X", font).Height;
return (double)textHeight * 0.85;
}
public static void CopyFont(this IXLFontBase font, IXLFontBase sourceFont)
{
font.Bold = sourceFont.Bold;
font.Italic = sourceFont.Italic;
font.Underline = sourceFont.Underline;
font.Strikethrough = sourceFont.Strikethrough;
font.VerticalAlignment = sourceFont.VerticalAlignment;
font.Shadow = sourceFont.Shadow;
font.FontSize = sourceFont.FontSize;
font.FontColor = sourceFont.FontColor;
font.FontName = sourceFont.FontName;
font.FontFamilyNumbering = sourceFont.FontFamilyNumbering;
font.FontCharSet = sourceFont.FontCharSet;
}
private static Font GetCachedFont(IXLFontBase fontBase, Dictionary<IXLFontBase, Font> fontCache)
{
if (!fontCache.TryGetValue(fontBase, out Font font))
{
font = new Font(fontBase.FontName, (float)fontBase.FontSize, GetFontStyle(fontBase));
fontCache.Add(fontBase, font);
}
return font;
}
private static FontStyle GetFontStyle(IXLFontBase font)
{
FontStyle fontStyle = FontStyle.Regular;
if (font.Bold) fontStyle |= FontStyle.Bold;
if (font.Italic) fontStyle |= FontStyle.Italic;
if (font.Strikethrough) fontStyle |= FontStyle.Strikeout;
if (font.Underline != XLFontUnderlineValues.None) fontStyle |= FontStyle.Underline;
return fontStyle;
}
}
internal static class XDocumentExtensions
{
public static XDocument Load(Stream stream)
{
using (XmlReader reader = XmlReader.Create(stream))
{
return XDocument.Load(reader);
}
}
}
internal static class EnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (T item in source)
action(item);
}
public static Type GetItemType<T>(this IEnumerable<T> source)
{
return typeof(T);
}
}
internal static class ListExtensions
{
public static void RemoveAll<T>(this IList<T> list, Func<T, bool> predicate)
{
var indices = list.Where(item => predicate(item)).Select((item, i) => i).OrderByDescending(i => i).ToList();
foreach (var i in indices)
{
list.RemoveAt(i);
}
}
}
internal static class DoubleValueExtensions
{
public static DoubleValue SaveRound(this DoubleValue value)
{
return value.HasValue ? new DoubleValue(Math.Round(value, 6)) : value;
}
}
internal static class TypeExtensions
{
public static bool IsNumber(this Type type)
{
return type == typeof(sbyte)
|| type == typeof(byte)
|| type == typeof(short)
|| type == typeof(ushort)
|| type == typeof(int)
|| type == typeof(uint)
|| type == typeof(long)
|| type == typeof(ulong)
|| type == typeof(float)
|| type == typeof(double)
|| type == typeof(decimal);
}
}
internal static class ObjectExtensions
{
public static bool IsNumber(this object value)
{
return value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is int
|| value is uint
|| value is long
|| value is ulong
|| value is float
|| value is double
|| value is decimal;
}
public static string ToInvariantString(this object value)
{
switch (value)
{
case sbyte v:
return v.ToString(CultureInfo.InvariantCulture);
case byte v:
return v.ToString(CultureInfo.InvariantCulture);
case short v:
return v.ToString(CultureInfo.InvariantCulture);
case ushort v:
return v.ToString(CultureInfo.InvariantCulture);
case int v:
return v.ToString(CultureInfo.InvariantCulture);
case uint v:
return v.ToString(CultureInfo.InvariantCulture);
case long v:
return v.ToString(CultureInfo.InvariantCulture);
case ulong v:
return v.ToString(CultureInfo.InvariantCulture);
case float v:
return v.ToString(CultureInfo.InvariantCulture);
case double v:
return v.ToString(CultureInfo.InvariantCulture);
case decimal v:
return v.ToString(CultureInfo.InvariantCulture);
default:
return value.ToString();
}
}
}
}
| |
using EpisodeInformer.Core.Rss;
using EpisodeInformer.Core.Threading;
using EpisodeInformer.Data;
using EpisodeInformer.LocalClasses;
using EpisodeInformer.Properties;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace EpisodeInformer.FeedManagerUI
{
public partial class EDITFeed : UserControl
{
private RssFeed currentFeed;
private RssFeed newFeed;
public FeedAEDAction ActionTook { get; private set; }
public event EventHandler ValidatingEnded;
public event EventHandler ValidatingStarted;
public event EventHandler ActionTaken;
public EDITFeed(string URL)
{
this.InitializeComponent();
ThreadingHelper.SetUIDispatcher();
this.currentFeed = RssDBQuery.GetFeedByURL(URL);
this.newFeed = RssDBQuery.GetFeedByURL(URL);
this.newFeed.HeaderReadFinished += new delFeedHeaderRead(this.newFeed_HeaderReadFinished);
this.txtURL.Text = this.currentFeed.URL;
this.txtTitle.Text = this.currentFeed.Title;
this.txtDescription.Text = this.currentFeed.Description;
this.txtVersion.Text = this.currentFeed.Version;
this.chkSelected.Checked = this.currentFeed.Selected;
this.ActionTook = FeedAEDAction.UNTOUCHED;
}
private void newFeed_HeaderReadFinished(object sender, RssHeaderStatus status)
{
this.LockControlForValidation(false);
if (status == RssHeaderStatus.DONE)
{
this.EnableDisableControls(true);
this.txtTitle.Text = this.newFeed.Title;
this.txtDescription.Text = this.newFeed.Description;
this.txtVersion.Text = this.newFeed.Version;
this.chkSelected.Checked = this.newFeed.Selected;
}
else if (status == RssHeaderStatus.INVALID)
{
this.EnableDisableControls(false);
this.txtURL.Text = "";
this.txtTitle.Text = "";
this.txtDescription.Text = "";
this.txtVersion.Text = "";
this.chkSelected.Checked = false;
int num = (int)MessageBox.Show("This feed is not compatible with current version, Sorry!!!", "Compatibility issue", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else if (status == RssHeaderStatus.ERROR)
{
this.EnableDisableControls(false);
this.txtTitle.Text = "";
this.txtDescription.Text = "";
this.txtVersion.Text = "";
this.chkSelected.Checked = false;
int num = (int)MessageBox.Show("It seem there was an error tyring to read the feed, You should check the feed's URL and your internet connection and try again.\n\nIf you keep getting this message over and over again then there must be someting wrong with the URL, or the RSS feed server must be offline for the moment.", "Feed Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
if (this.ValidatingEnded == null)
return;
this.ValidatingEnded((object)this, EventArgs.Empty);
}
private void btnSave_Click(object sender, EventArgs e)
{
if (!this.isFieldsFilled())
return;
if (this.txtURL.Text.Trim() != this.currentFeed.URL)
{
this.newFeed.Title = this.txtTitle.Text;
this.newFeed.Description = this.txtDescription.Text;
RssDBAction.UpdateFeed(this.currentFeed.URL, this.newFeed);
this.ActionTook = FeedAEDAction.EDITED;
if (this.ActionTaken != null)
this.ActionTaken((object)this, EventArgs.Empty);
int num = (int)MessageBox.Show("Your Rss feed Updated.", "Feed Updated", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
this.ResetImportantsAfterUpdate();
}
else
{
this.newFeed.Title = this.txtTitle.Text;
this.newFeed.Description = this.txtDescription.Text;
this.newFeed.Selected = this.chkSelected.Checked;
RssDBAction.UpdateFeed(this.newFeed);
this.ActionTook = FeedAEDAction.EDITED;
if (this.ActionTaken != null)
this.ActionTaken((object)this, EventArgs.Empty);
int num = (int)MessageBox.Show("Your Rss feed Updated.", "Feed Updated", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
this.ResetImportantsAfterUpdate();
}
}
private void txtURL_TextChanged(object sender, EventArgs e)
{
if (this.txtURL.Text != this.currentFeed.URL)
{
this.lblReset.Visible = true;
this.EnableDisableControls(false);
}
else
{
this.lblReset.Visible = false;
this.EnableDisableControls(true);
this.txtTitle.Text = this.currentFeed.Title;
this.txtDescription.Text = this.currentFeed.Description;
this.txtVersion.Text = this.currentFeed.Version;
}
}
private void lblValidate_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (this.txtURL.Text.Trim().Length > 0)
{
if (!RssDBQuery.Exsist(this.txtURL.Text.Trim()))
{
this.newFeed.URL = this.txtURL.Text.Trim();
this.newFeed.ReadFeedHeaderAsync();
this.LockControlForValidation(true);
if (this.ValidatingStarted == null)
return;
this.ValidatingStarted((object)this, EventArgs.Empty);
}
else if (MessageBox.Show("You've already validated and added this Rss feed. Do you want to re-run the validation?", "Feed Exist", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
this.newFeed.URL = this.txtURL.Text;
this.newFeed.ReadFeedHeaderAsync();
this.LockControlForValidation(true);
if (this.ValidatingStarted != null)
this.ValidatingStarted((object)this, EventArgs.Empty);
}
else
{
this.txtDescription.Text = this.currentFeed.Description;
this.txtTitle.Text = this.currentFeed.Title;
this.txtVersion.Text = this.currentFeed.Version;
}
}
else
{
int num = (int)MessageBox.Show("Where is the url?", "Missing Url", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
this.txtURL.Focus();
}
}
private void lblReset_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.txtURL.Text = this.currentFeed.URL;
this.txtTitle.Text = this.currentFeed.Title;
this.txtDescription.Text = this.currentFeed.Description;
this.txtVersion.Text = this.currentFeed.Version;
this.ActionTook = FeedAEDAction.UNTOUCHED;
}
private bool isFieldsFilled()
{
bool flag = true;
if (this.txtURL.Text.Trim().Length == 0)
{
int num = (int)MessageBox.Show("You forgot to enter the URL.", "Missing URL", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
flag = false;
}
else if (this.txtTitle.Text.Trim().Length == 0)
{
int num = (int)MessageBox.Show("You forgot to enter the Title.", "Missing Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
flag = false;
}
else if (this.txtDescription.Text.Trim().Length == 0)
{
int num = (int)MessageBox.Show("You forgot to enter the Description", "Missing Description", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
flag = false;
}
return flag;
}
private void ResetImportantsAfterUpdate()
{
this.currentFeed = RssDBQuery.GetFeedByURL(this.txtURL.Text.Trim());
this.newFeed.URL = this.currentFeed.URL;
this.newFeed.Title = this.currentFeed.Title;
this.newFeed.Description = this.currentFeed.Description;
this.newFeed.Version = this.currentFeed.Version;
this.EnableDisableControls(true);
}
private void LockControlForValidation(bool lockC)
{
if (lockC)
{
this.txtURL.ReadOnly = true;
this.txtTitle.ReadOnly = true;
this.txtDescription.ReadOnly = true;
}
else
{
this.txtURL.ReadOnly = false;
this.txtTitle.ReadOnly = false;
this.txtDescription.ReadOnly = false;
}
}
private void EnableDisableControls(bool validated)
{
if (validated)
{
this.txtTitle.Enabled = true;
this.txtDescription.Enabled = true;
}
else
{
this.txtTitle.Enabled = false;
this.txtDescription.Enabled = false;
this.txtTitle.Text = "";
this.txtDescription.Text = "";
this.txtVersion.Text = "";
}
}
private void InitializeComponent()
{
this.lblReset = new System.Windows.Forms.LinkLabel();
this.lblValidate = new System.Windows.Forms.LinkLabel();
this.txtURL = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.btnSave = new System.Windows.Forms.Button();
this.txtVersion = new System.Windows.Forms.TextBox();
this.txtDescription = new System.Windows.Forms.TextBox();
this.txtTitle = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.panel3 = new System.Windows.Forms.Panel();
this.chkSelected = new System.Windows.Forms.CheckBox();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.panel3.SuspendLayout();
this.SuspendLayout();
//
// lblReset
//
this.lblReset.AutoSize = true;
this.lblReset.BackColor = System.Drawing.Color.Transparent;
this.lblReset.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblReset.Location = new System.Drawing.Point(227, 45);
this.lblReset.Name = "lblReset";
this.lblReset.Size = new System.Drawing.Size(35, 15);
this.lblReset.TabIndex = 3;
this.lblReset.TabStop = true;
this.lblReset.Text = "Reset";
this.lblReset.Visible = false;
this.lblReset.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lblReset_LinkClicked);
//
// lblValidate
//
this.lblValidate.AutoSize = true;
this.lblValidate.BackColor = System.Drawing.Color.Transparent;
this.lblValidate.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblValidate.Location = new System.Drawing.Point(268, 45);
this.lblValidate.Name = "lblValidate";
this.lblValidate.Size = new System.Drawing.Size(49, 15);
this.lblValidate.TabIndex = 2;
this.lblValidate.TabStop = true;
this.lblValidate.Text = "Validate";
this.lblValidate.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lblValidate_LinkClicked);
//
// txtURL
//
this.txtURL.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtURL.Location = new System.Drawing.Point(50, 14);
this.txtURL.Name = "txtURL";
this.txtURL.Size = new System.Drawing.Size(267, 23);
this.txtURL.TabIndex = 1;
this.txtURL.TextChanged += new System.EventHandler(this.txtURL_TextChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(16, 18);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(28, 15);
this.label1.TabIndex = 0;
this.label1.Text = "URL";
//
// btnSave
//
this.btnSave.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnSave.Location = new System.Drawing.Point(255, 9);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(75, 23);
this.btnSave.TabIndex = 0;
this.btnSave.Text = "&Save";
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// txtVersion
//
this.txtVersion.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtVersion.Location = new System.Drawing.Point(86, 68);
this.txtVersion.Name = "txtVersion";
this.txtVersion.ReadOnly = true;
this.txtVersion.Size = new System.Drawing.Size(100, 23);
this.txtVersion.TabIndex = 5;
this.txtVersion.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// txtDescription
//
this.txtDescription.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtDescription.Location = new System.Drawing.Point(86, 37);
this.txtDescription.Name = "txtDescription";
this.txtDescription.Size = new System.Drawing.Size(222, 23);
this.txtDescription.TabIndex = 4;
//
// txtTitle
//
this.txtTitle.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtTitle.Location = new System.Drawing.Point(86, 7);
this.txtTitle.Name = "txtTitle";
this.txtTitle.Size = new System.Drawing.Size(222, 23);
this.txtTitle.TabIndex = 3;
//
// label4
//
this.label4.AutoSize = true;
this.label4.BackColor = System.Drawing.Color.Transparent;
this.label4.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(14, 71);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(46, 15);
this.label4.TabIndex = 2;
this.label4.Text = "Version";
//
// label3
//
this.label3.AutoSize = true;
this.label3.BackColor = System.Drawing.Color.Transparent;
this.label3.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(14, 40);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(67, 15);
this.label3.TabIndex = 1;
this.label3.Text = "Description";
//
// label2
//
this.label2.AutoSize = true;
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(14, 10);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(30, 15);
this.label2.TabIndex = 0;
this.label2.Text = "Title";
//
// panel1
//
this.panel1.BackgroundImage = global::EpisodeInformer.Properties.Resources.fmup;
this.panel1.Controls.Add(this.lblReset);
this.panel1.Controls.Add(this.txtURL);
this.panel1.Controls.Add(this.lblValidate);
this.panel1.Controls.Add(this.label1);
this.panel1.Location = new System.Drawing.Point(13, 12);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(347, 66);
this.panel1.TabIndex = 3;
//
// panel2
//
this.panel2.BackgroundImage = global::EpisodeInformer.Properties.Resources.fmmiddle;
this.panel2.Controls.Add(this.chkSelected);
this.panel2.Controls.Add(this.txtVersion);
this.panel2.Controls.Add(this.label3);
this.panel2.Controls.Add(this.txtDescription);
this.panel2.Controls.Add(this.label2);
this.panel2.Controls.Add(this.txtTitle);
this.panel2.Controls.Add(this.label4);
this.panel2.Location = new System.Drawing.Point(14, 98);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(344, 104);
this.panel2.TabIndex = 4;
//
// panel3
//
this.panel3.BackgroundImage = global::EpisodeInformer.Properties.Resources.fmdown;
this.panel3.Controls.Add(this.btnSave);
this.panel3.Location = new System.Drawing.Point(16, 217);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(343, 41);
this.panel3.TabIndex = 5;
//
// chkSelected
//
this.chkSelected.AutoSize = true;
this.chkSelected.Location = new System.Drawing.Point(197, 71);
this.chkSelected.Name = "chkSelected";
this.chkSelected.Size = new System.Drawing.Size(111, 17);
this.chkSelected.TabIndex = 7;
this.chkSelected.Text = "Use for Download";
this.chkSelected.UseVisualStyleBackColor = true;
//
// EDITFeed
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = global::EpisodeInformer.Properties.Resources.back;
this.Controls.Add(this.panel3);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Name = "EDITFeed";
this.Size = new System.Drawing.Size(372, 280);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.panel3.ResumeLayout(false);
this.ResumeLayout(false);
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.EC2.Model
{
/// <summary>
/// Revokes permissions from a security group.
/// </summary>
/// <remarks>
/// The permissions used to revoke must be specified using the same values
/// used to grant the permissions.
///
/// Permissions are specified by IP protocol (TCP, UDP, or ICMP), the source
/// of the request (by IP range or an Amazon EC2 user-group pair), the
/// source and destination port ranges (for TCP and UDP), and the ICMP codes
/// and types (for ICMP).
///
/// Permission changes are quickly propagated to instances within the
/// security group. However, depending on the number of instances in the group,
/// a small delay is might occur.
/// </remarks>
[XmlRootAttribute(IsNullable = false)]
public class RevokeSecurityGroupIngressRequest : EC2Request
{
private string userIdField;
private string groupIdField;
private string groupNameField;
private string sourceSecurityGroupNameField;
private string sourceSecurityGroupOwnerIdField;
private string ipProtocolField;
private Decimal? fromPortField;
private Decimal? toPortField;
private string cidrIpField;
private List<IpPermissionSpecification> ipPermissionsField;
/// <summary>
/// AWS Access Key ID.
/// </summary>
[XmlElementAttribute(ElementName = "UserId")]
public string UserId
{
get { return this.userIdField; }
set { this.userIdField = value; }
}
/// <summary>
/// Sets the AWS Access Key ID.
/// </summary>
/// <param name="userId">AWS Access Key ID.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RevokeSecurityGroupIngressRequest WithUserId(string userId)
{
this.userIdField = userId;
return this;
}
/// <summary>
/// Checks if UserId property is set
/// </summary>
/// <returns>true if UserId property is set</returns>
public bool IsSetUserId()
{
return this.userIdField != null;
}
/// <summary>
/// Id of the standard (EC2) or VPC security group to modify.
/// The group must belong to your account.
/// </summary>
[XmlElementAttribute(ElementName = "GroupId")]
public string GroupId
{
get { return this.groupIdField; }
set { this.groupIdField = value; }
}
/// <summary>
/// Sets the id of the standard (EC2) or VPC security group to modify.
/// </summary>
/// <param name="groupId">Id of the standard (EC2) or VPC security group to modify. Conditional
/// The group must belong to your account.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RevokeSecurityGroupIngressRequest WithGroupId(string groupId)
{
this.groupIdField = groupId;
return this;
}
/// <summary>
/// Checks if GroupId property is set
/// </summary>
/// <returns>true if GroupId property is set</returns>
public bool IsSetGroupId()
{
return this.groupIdField != null;
}
/// <summary>
/// Name of the group to modify.
/// </summary>
[XmlElementAttribute(ElementName = "GroupName")]
public string GroupName
{
get { return this.groupNameField; }
set { this.groupNameField = value; }
}
/// <summary>
/// Sets the name of the group to modify.
/// </summary>
/// <param name="groupName">Name of the group to modify.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RevokeSecurityGroupIngressRequest WithGroupName(string groupName)
{
this.groupNameField = groupName;
return this;
}
/// <summary>
/// Checks if GroupName property is set
/// </summary>
/// <returns>true if GroupName property is set</returns>
public bool IsSetGroupName()
{
return this.groupNameField != null;
}
/// <summary>
/// Name of the security group.
/// Cannot be used when specifying a CIDR IP address.
/// </summary>
[XmlElementAttribute(ElementName = "SourceSecurityGroupName")]
public string SourceSecurityGroupName
{
get { return this.sourceSecurityGroupNameField; }
set { this.sourceSecurityGroupNameField = value; }
}
/// <summary>
/// Sets the name of the security group.
/// </summary>
/// <param name="sourceSecurityGroupName">Name of the security group. Cannot be used
/// when specifying a CIDR IP address.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RevokeSecurityGroupIngressRequest WithSourceSecurityGroupName(string sourceSecurityGroupName)
{
this.sourceSecurityGroupNameField = sourceSecurityGroupName;
return this;
}
/// <summary>
/// Checks if SourceSecurityGroupName property is set
/// </summary>
/// <returns>true if SourceSecurityGroupName property is set</returns>
public bool IsSetSourceSecurityGroupName()
{
return this.sourceSecurityGroupNameField != null;
}
/// <summary>
/// AWS User ID of an account.
/// Cannot be used when specifying a CIDR IP address.
/// </summary>
[XmlElementAttribute(ElementName = "SourceSecurityGroupOwnerId")]
public string SourceSecurityGroupOwnerId
{
get { return this.sourceSecurityGroupOwnerIdField; }
set { this.sourceSecurityGroupOwnerIdField = value; }
}
/// <summary>
/// Sets the AWS User ID of an account.
/// </summary>
/// <param name="sourceSecurityGroupOwnerId">AWS User ID of an account. Cannot be used when
/// specifying a CIDR IP address.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RevokeSecurityGroupIngressRequest WithSourceSecurityGroupOwnerId(string sourceSecurityGroupOwnerId)
{
this.sourceSecurityGroupOwnerIdField = sourceSecurityGroupOwnerId;
return this;
}
/// <summary>
/// Checks if SourceSecurityGroupOwnerId property is set
/// </summary>
/// <returns>true if SourceSecurityGroupOwnerId property is set</returns>
public bool IsSetSourceSecurityGroupOwnerId()
{
return this.sourceSecurityGroupOwnerIdField != null;
}
/// <summary>
/// IP protocol.
/// Valid Values: tcp | udp | icmp
/// </summary>
[XmlElementAttribute(ElementName = "IpProtocol")]
public string IpProtocol
{
get { return this.ipProtocolField; }
set { this.ipProtocolField = value; }
}
/// <summary>
/// Sets the IP protocol.
/// </summary>
/// <param name="ipProtocol">IP protocol. Valid Values: tcp | udp | icmp</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RevokeSecurityGroupIngressRequest WithIpProtocol(string ipProtocol)
{
this.ipProtocolField = ipProtocol;
return this;
}
/// <summary>
/// Checks if IpProtocol property is set
/// </summary>
/// <returns>true if IpProtocol property is set</returns>
public bool IsSetIpProtocol()
{
return this.ipProtocolField != null;
}
/// <summary>
/// Start of port range for the TCP and UDP protocols, or an ICMP type
/// number. An ICMP type number of -1 indicates a wildcard (i.e.,
/// any ICMP type number).
/// </summary>
[XmlElementAttribute(ElementName = "FromPort")]
public Decimal FromPort
{
get { return this.fromPortField.GetValueOrDefault(); }
set { this.fromPortField = value; }
}
/// <summary>
/// Sets the start of port range for the TCP and UDP protocols, or an ICMP type
/// number.
/// </summary>
/// <param name="fromPort">Start of port range for the TCP and UDP
/// protocols, or an ICMP type
/// number. An ICMP type number of -1
/// indicates a wildcard (i.e.,
/// any ICMP type number).</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RevokeSecurityGroupIngressRequest WithFromPort(Decimal fromPort)
{
this.fromPortField = fromPort;
return this;
}
/// <summary>
/// Checks if FromPort property is set
/// </summary>
/// <returns>true if FromPort property is set</returns>
public bool IsSetFromPort()
{
return this.fromPortField.HasValue;
}
/// <summary>
/// End of port range for the TCP and UDP protocols, or an ICMP code.
/// An ICMP code of -1 indicates a wildcard (i.e., any ICMP code).
/// </summary>
[XmlElementAttribute(ElementName = "ToPort")]
public Decimal ToPort
{
get { return this.toPortField.GetValueOrDefault(); }
set { this.toPortField = value; }
}
/// <summary>
/// Sets the end of port range for the TCP and UDP protocols, or an ICMP code.
/// </summary>
/// <param name="toPort">End of port range for the TCP and UDP
/// protocols, or an ICMP code.
/// An ICMP code of -1 indicates a
/// wildcard (i.e., any ICMP code).</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RevokeSecurityGroupIngressRequest WithToPort(Decimal toPort)
{
this.toPortField = toPort;
return this;
}
/// <summary>
/// Checks if ToPort property is set
/// </summary>
/// <returns>true if ToPort property is set</returns>
public bool IsSetToPort()
{
return this.toPortField.HasValue;
}
/// <summary>
/// CIDR range.
/// </summary>
[XmlElementAttribute(ElementName = "CidrIp")]
public string CidrIp
{
get { return this.cidrIpField; }
set { this.cidrIpField = value; }
}
/// <summary>
/// Sets the CIDR range.
/// </summary>
/// <param name="cidrIp">CIDR range.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RevokeSecurityGroupIngressRequest WithCidrIp(string cidrIp)
{
this.cidrIpField = cidrIp;
return this;
}
/// <summary>
/// Checks if CidrIp property is set
/// </summary>
/// <returns>true if CidrIp property is set</returns>
public bool IsSetCidrIp()
{
return this.cidrIpField != null;
}
/// <summary>
/// Set of IP permissions associated with the security group.
/// </summary>
[XmlElementAttribute(ElementName = "IpPermissions")]
public List<IpPermissionSpecification> IpPermissions
{
get
{
if (this.ipPermissionsField == null)
{
this.ipPermissionsField = new List<IpPermissionSpecification>();
}
return this.ipPermissionsField;
}
set { this.ipPermissionsField = value; }
}
/// <summary>
/// Sets the IP permissions associated with the security group.
/// </summary>
/// <param name="list">Set of IP permissions associated with the
/// security group.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RevokeSecurityGroupIngressRequest WithIpPermissions(params IpPermissionSpecification[] list)
{
foreach (IpPermissionSpecification item in list)
{
IpPermissions.Add(item);
}
return this;
}
/// <summary>
/// Checks if IpPermissions property is set
/// </summary>
/// <returns>true if IpPermissions property is set</returns>
public bool IsSetIpPermissions()
{
return (IpPermissions.Count > 0);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ToolStripPanel.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Diagnostics;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
using System.ComponentModel.Design;
[
ComVisible(true),
ClassInterface(ClassInterfaceType.AutoDispatch),
Designer("System.Windows.Forms.Design.ToolStripContentPanelDesigner, " + AssemblyRef.SystemDesign),
DefaultEvent("Load"),
Docking(DockingBehavior.Never),
InitializationEvent("Load"),
ToolboxItem(false)
]
public class ToolStripContentPanel : Panel {
private ToolStripRendererSwitcher rendererSwitcher = null;
private BitVector32 state = new BitVector32();
private static readonly int stateLastDoubleBuffer = BitVector32.CreateMask();
private static readonly object EventRendererChanged = new object();
private static readonly object EventLoad = new object();
public ToolStripContentPanel() {
// Consider: OptimizedDoubleBuffer
SetStyle(ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor, true);
}
/// <devdoc>
/// Allows the control to optionally shrink when AutoSize is true.
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false),
Localizable(false)
]
public override AutoSizeMode AutoSizeMode {
get {
return AutoSizeMode.GrowOnly;
}
set {
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public override AnchorStyles Anchor {
get {
return base.Anchor;
}
set {
base.Anchor = value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public override bool AutoScroll {
get { return base.AutoScroll; }
set { base.AutoScroll = value; }
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new Size AutoScrollMargin {
get { return base.AutoScrollMargin; }
set { base.AutoScrollMargin = value; }
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new Size AutoScrollMinSize {
get { return base.AutoScrollMinSize; }
set { base.AutoScrollMinSize = value; }
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public override bool AutoSize {
get { return base.AutoSize; }
set { base.AutoSize = value; }
}
public override Color BackColor {
get {
return base.BackColor;
}
set {
// To support transparency on ToolStripContainer, we need this check
// to ensure that background color of the container reflects the
// ContentPanel
if (this.ParentInternal is ToolStripContainer && value == Color.Transparent) {
this.ParentInternal.BackColor = Color.Transparent;
}
base.BackColor = value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new event EventHandler AutoSizeChanged{
add {
base.AutoSizeChanged += value;
}
remove {
base.AutoSizeChanged -= value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new bool CausesValidation {
get { return base.CausesValidation; }
set { base.CausesValidation = value; }
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler CausesValidationChanged {
add {
base.CausesValidationChanged += value;
}
remove {
base.CausesValidationChanged -= value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public override DockStyle Dock {
get {
return base.Dock;
}
set {
base.Dock=value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new event EventHandler DockChanged {
add {
base.DockChanged += value;
}
remove {
base.DockChanged -= value;
}
}
[SRCategory(SR.CatBehavior), SRDescription(SR.ToolStripContentPanelOnLoadDescr)]
public event EventHandler Load {
add {
Events.AddHandler(EventLoad, value);
}
remove {
Events.RemoveHandler(EventLoad, value);
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new Point Location {
get { return base.Location; }
set { base.Location = value; }
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new event EventHandler LocationChanged {
add {
base.LocationChanged += value;
}
remove {
base.LocationChanged -= value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public override Size MinimumSize {
get { return base.MinimumSize; }
set { base.MinimumSize = value; }
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public override Size MaximumSize {
get { return base.MaximumSize; }
set { base.MaximumSize = value; }
}
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new string Name {
get {
return base.Name;
}
set {
base.Name = value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new int TabIndex {
get {
return base.TabIndex;
}
set {
base.TabIndex = value;
}
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler TabIndexChanged {
add {
base.TabIndexChanged += value;
}
remove {
base.TabIndexChanged -= value;
}
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public new bool TabStop {
get {
return base.TabStop;
}
set {
base.TabStop = value;
}
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler TabStopChanged {
add {
base.TabStopChanged += value;
}
remove {
base.TabStopChanged -= value;
}
}
private ToolStripRendererSwitcher RendererSwitcher {
get {
if (rendererSwitcher == null) {
rendererSwitcher = new ToolStripRendererSwitcher(this, ToolStripRenderMode.System);
HandleRendererChanged(this, EventArgs.Empty);
rendererSwitcher.RendererChanged += new EventHandler(HandleRendererChanged);
}
return rendererSwitcher;
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public ToolStripRenderer Renderer {
get {
return RendererSwitcher.Renderer;
}
set {
RendererSwitcher.Renderer = value;
}
}
/// <include file='doc\ToolStrip.uex' path='docs/doc[@for="ToolStrip.DrawMode"]/*' />
[
SRDescription(SR.ToolStripRenderModeDescr),
SRCategory(SR.CatAppearance),
]
public ToolStripRenderMode RenderMode {
get {
return RendererSwitcher.RenderMode;
}
set {
RendererSwitcher.RenderMode = value;
}
}
[SRCategory(SR.CatAppearance), SRDescription(SR.ToolStripRendererChanged)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public event EventHandler RendererChanged {
add {
Events.AddHandler(EventRendererChanged, value);
}
remove {
Events.RemoveHandler(EventRendererChanged, value);
}
}
private void HandleRendererChanged(object sender, EventArgs e) {
OnRendererChanged(e);
}
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
if (!RecreatingHandle) {
OnLoad(EventArgs.Empty);
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnLoad(EventArgs e) {
// There is no good way to explain this event except to say
// that it's just another name for OnControlCreated.
EventHandler handler = (EventHandler)Events[EventLoad];
if (handler != null) handler(this,e);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnPaintBackground(PaintEventArgs e) {
ToolStripContentPanelRenderEventArgs rea = new ToolStripContentPanelRenderEventArgs(e.Graphics, this);
Renderer.DrawToolStripContentPanelBackground(rea);
if (!rea.Handled) {
base.OnPaintBackground(e);
}
}
/// <include file='doc\ToolStrip.uex' path='docs/doc[@for="ToolStrip.OnDefaultRendererChanged"]/*' />
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
protected virtual void OnRendererChanged(EventArgs e) {
// we dont want to be greedy.... if we're using TSProfessionalRenderer go DBuf, else dont.
if (Renderer is ToolStripProfessionalRenderer) {
state[stateLastDoubleBuffer] = this.DoubleBuffered;
//this.DoubleBuffered = true;
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}
else {
// restore DBuf
this.DoubleBuffered = state[stateLastDoubleBuffer];
}
Renderer.InitializeContentPanel(this);
this.Invalidate();
EventHandler handler = (EventHandler)Events[EventRendererChanged];
if (handler != null) handler(this,e);
}
private void ResetRenderMode() {
this.RendererSwitcher.ResetRenderMode();
}
private bool ShouldSerializeRenderMode() {
return this.RendererSwitcher.ShouldSerializeRenderMode();
}
}
}
| |
namespace BulletSharpTest
{
static class TorusMesh
{
public static readonly float[] Vertices = new[]
{
2.5f, 0f, 0f,
2.405f, 0.294f, 0f,
2.155f, 0.476f, 0f,
1.845f, 0.476f, 0f,
1.595f, 0.294f, 0f,
1.5f, 0f, 0f,
1.595f, -0.294f, 0f,
1.845f, -0.476f, 0f,
2.155f, -0.476f, 0f,
2.405f, -0.294f, 0f,
2.445f, 0f, 0.52f,
2.352f, 0.294f, 0.5f,
2.107f, 0.476f, 0.448f,
1.805f, 0.476f, 0.384f,
1.561f, 0.294f, 0.332f,
1.467f, 0f, 0.312f,
1.561f, -0.294f, 0.332f,
1.805f, -0.476f, 0.384f,
2.107f, -0.476f, 0.448f,
2.352f, -0.294f, 0.5f,
2.284f, 0f, 1.017f,
2.197f, 0.294f, 0.978f,
1.968f, 0.476f, 0.876f,
1.686f, 0.476f, 0.751f,
1.458f, 0.294f, 0.649f,
1.37f, 0f, 0.61f,
1.458f, -0.294f, 0.649f,
1.686f, -0.476f, 0.751f,
1.968f, -0.476f, 0.876f,
2.197f, -0.294f, 0.978f,
2.023f, 0f, 1.469f,
1.945f, 0.294f, 1.413f,
1.743f, 0.476f, 1.266f,
1.493f, 0.476f, 1.085f,
1.291f, 0.294f, 0.938f,
1.214f, 0f, 0.882f,
1.291f, -0.294f, 0.938f,
1.493f, -0.476f, 1.085f,
1.743f, -0.476f, 1.266f,
1.945f, -0.294f, 1.413f,
1.673f, 0f, 1.858f,
1.609f, 0.294f, 1.787f,
1.442f, 0.476f, 1.601f,
1.235f, 0.476f, 1.371f,
1.068f, 0.294f, 1.186f,
1.004f, 0f, 1.115f,
1.068f, -0.294f, 1.186f,
1.235f, -0.476f, 1.371f,
1.442f, -0.476f, 1.601f,
1.609f, -0.294f, 1.787f,
1.25f, 0f, 2.165f,
1.202f, 0.294f, 2.082f,
1.077f, 0.476f, 1.866f,
0.923f, 0.476f, 1.598f,
0.798f, 0.294f, 1.382f,
0.75f, 0f, 1.299f,
0.798f, -0.294f, 1.382f,
0.923f, -0.476f, 1.598f,
1.077f, -0.476f, 1.866f,
1.202f, -0.294f, 2.082f,
0.773f, 0f, 2.378f,
0.743f, 0.294f, 2.287f,
0.666f, 0.476f, 2.049f,
0.57f, 0.476f, 1.755f,
0.493f, 0.294f, 1.517f,
0.464f, 0f, 1.427f,
0.493f, -0.294f, 1.517f,
0.57f, -0.476f, 1.755f,
0.666f, -0.476f, 2.049f,
0.743f, -0.294f, 2.287f,
0.261f, 0f, 2.486f,
0.251f, 0.294f, 2.391f,
0.225f, 0.476f, 2.143f,
0.193f, 0.476f, 1.835f,
0.167f, 0.294f, 1.587f,
0.157f, 0f, 1.492f,
0.167f, -0.294f, 1.587f,
0.193f, -0.476f, 1.835f,
0.225f, -0.476f, 2.143f,
0.251f, -0.294f, 2.391f,
-0.261f, 0f, 2.486f,
-0.251f, 0.294f, 2.391f,
-0.225f, 0.476f, 2.143f,
-0.193f, 0.476f, 1.835f,
-0.167f, 0.294f, 1.587f,
-0.157f, 0f, 1.492f,
-0.167f, -0.294f, 1.587f,
-0.193f, -0.476f, 1.835f,
-0.225f, -0.476f, 2.143f,
-0.251f, -0.294f, 2.391f,
-0.773f, 0f, 2.378f,
-0.743f, 0.294f, 2.287f,
-0.666f, 0.476f, 2.049f,
-0.57f, 0.476f, 1.755f,
-0.493f, 0.294f, 1.517f,
-0.464f, 0f, 1.427f,
-0.493f, -0.294f, 1.517f,
-0.57f, -0.476f, 1.755f,
-0.666f, -0.476f, 2.049f,
-0.743f, -0.294f, 2.287f,
-1.25f, 0f, 2.165f,
-1.202f, 0.294f, 2.082f,
-1.077f, 0.476f, 1.866f,
-0.923f, 0.476f, 1.598f,
-0.798f, 0.294f, 1.382f,
-0.75f, 0f, 1.299f,
-0.798f, -0.294f, 1.382f,
-0.923f, -0.476f, 1.598f,
-1.077f, -0.476f, 1.866f,
-1.202f, -0.294f, 2.082f,
-1.673f, 0f, 1.858f,
-1.609f, 0.294f, 1.787f,
-1.442f, 0.476f, 1.601f,
-1.235f, 0.476f, 1.371f,
-1.068f, 0.294f, 1.186f,
-1.004f, 0f, 1.115f,
-1.068f, -0.294f, 1.186f,
-1.235f, -0.476f, 1.371f,
-1.442f, -0.476f, 1.601f,
-1.609f, -0.294f, 1.787f,
-2.023f, 0f, 1.469f,
-1.945f, 0.294f, 1.413f,
-1.743f, 0.476f, 1.266f,
-1.493f, 0.476f, 1.085f,
-1.291f, 0.294f, 0.938f,
-1.214f, 0f, 0.882f,
-1.291f, -0.294f, 0.938f,
-1.493f, -0.476f, 1.085f,
-1.743f, -0.476f, 1.266f,
-1.945f, -0.294f, 1.413f,
-2.284f, 0f, 1.017f,
-2.197f, 0.294f, 0.978f,
-1.968f, 0.476f, 0.876f,
-1.686f, 0.476f, 0.751f,
-1.458f, 0.294f, 0.649f,
-1.37f, 0f, 0.61f,
-1.458f, -0.294f, 0.649f,
-1.686f, -0.476f, 0.751f,
-1.968f, -0.476f, 0.876f,
-2.197f, -0.294f, 0.978f,
-2.445f, 0f, 0.52f,
-2.352f, 0.294f, 0.5f,
-2.107f, 0.476f, 0.448f,
-1.805f, 0.476f, 0.384f,
-1.561f, 0.294f, 0.332f,
-1.467f, 0f, 0.312f,
-1.561f, -0.294f, 0.332f,
-1.805f, -0.476f, 0.384f,
-2.107f, -0.476f, 0.448f,
-2.352f, -0.294f, 0.5f,
-2.5f, 0f, 0f,
-2.405f, 0.294f, 0f,
-2.155f, 0.476f, 0f,
-1.845f, 0.476f, 0f,
-1.595f, 0.294f, 0f,
-1.5f, 0f, 0f,
-1.595f, -0.294f, 0f,
-1.845f, -0.476f, 0f,
-2.155f, -0.476f, 0f,
-2.405f, -0.294f, 0f,
-2.445f, 0f, -0.52f,
-2.352f, 0.294f, -0.5f,
-2.107f, 0.476f, -0.448f,
-1.805f, 0.476f, -0.384f,
-1.561f, 0.294f, -0.332f,
-1.467f, 0f, -0.312f,
-1.561f, -0.294f, -0.332f,
-1.805f, -0.476f, -0.384f,
-2.107f, -0.476f, -0.448f,
-2.352f, -0.294f, -0.5f,
-2.284f, 0f, -1.017f,
-2.197f, 0.294f, -0.978f,
-1.968f, 0.476f, -0.876f,
-1.686f, 0.476f, -0.751f,
-1.458f, 0.294f, -0.649f,
-1.37f, 0f, -0.61f,
-1.458f, -0.294f, -0.649f,
-1.686f, -0.476f, -0.751f,
-1.968f, -0.476f, -0.876f,
-2.197f, -0.294f, -0.978f,
-2.023f, 0f, -1.469f,
-1.945f, 0.294f, -1.413f,
-1.743f, 0.476f, -1.266f,
-1.493f, 0.476f, -1.085f,
-1.291f, 0.294f, -0.938f,
-1.214f, 0f, -0.882f,
-1.291f, -0.294f, -0.938f,
-1.493f, -0.476f, -1.085f,
-1.743f, -0.476f, -1.266f,
-1.945f, -0.294f, -1.413f,
-1.673f, 0f, -1.858f,
-1.609f, 0.294f, -1.787f,
-1.442f, 0.476f, -1.601f,
-1.235f, 0.476f, -1.371f,
-1.068f, 0.294f, -1.186f,
-1.004f, 0f, -1.115f,
-1.068f, -0.294f, -1.186f,
-1.235f, -0.476f, -1.371f,
-1.442f, -0.476f, -1.601f,
-1.609f, -0.294f, -1.787f,
-1.25f, 0f, -2.165f,
-1.202f, 0.294f, -2.082f,
-1.077f, 0.476f, -1.866f,
-0.923f, 0.476f, -1.598f,
-0.798f, 0.294f, -1.382f,
-0.75f, 0f, -1.299f,
-0.798f, -0.294f, -1.382f,
-0.923f, -0.476f, -1.598f,
-1.077f, -0.476f, -1.866f,
-1.202f, -0.294f, -2.082f,
-0.773f, 0f, -2.378f,
-0.743f, 0.294f, -2.287f,
-0.666f, 0.476f, -2.049f,
-0.57f, 0.476f, -1.755f,
-0.493f, 0.294f, -1.517f,
-0.464f, 0f, -1.427f,
-0.493f, -0.294f, -1.517f,
-0.57f, -0.476f, -1.755f,
-0.666f, -0.476f, -2.049f,
-0.743f, -0.294f, -2.287f,
-0.261f, 0f, -2.486f,
-0.251f, 0.294f, -2.391f,
-0.225f, 0.476f, -2.143f,
-0.193f, 0.476f, -1.835f,
-0.167f, 0.294f, -1.587f,
-0.157f, 0f, -1.492f,
-0.167f, -0.294f, -1.587f,
-0.193f, -0.476f, -1.835f,
-0.225f, -0.476f, -2.143f,
-0.251f, -0.294f, -2.391f,
0.261f, 0f, -2.486f,
0.251f, 0.294f, -2.391f,
0.225f, 0.476f, -2.143f,
0.193f, 0.476f, -1.835f,
0.167f, 0.294f, -1.587f,
0.157f, 0f, -1.492f,
0.167f, -0.294f, -1.587f,
0.193f, -0.476f, -1.835f,
0.225f, -0.476f, -2.143f,
0.251f, -0.294f, -2.391f,
0.773f, 0f, -2.378f,
0.743f, 0.294f, -2.287f,
0.666f, 0.476f, -2.049f,
0.57f, 0.476f, -1.755f,
0.493f, 0.294f, -1.517f,
0.464f, 0f, -1.427f,
0.493f, -0.294f, -1.517f,
0.57f, -0.476f, -1.755f,
0.666f, -0.476f, -2.049f,
0.743f, -0.294f, -2.287f,
1.25f, 0f, -2.165f,
1.202f, 0.294f, -2.082f,
1.077f, 0.476f, -1.866f,
0.923f, 0.476f, -1.598f,
0.798f, 0.294f, -1.382f,
0.75f, 0f, -1.299f,
0.798f, -0.294f, -1.382f,
0.923f, -0.476f, -1.598f,
1.077f, -0.476f, -1.866f,
1.202f, -0.294f, -2.082f,
1.673f, 0f, -1.858f,
1.609f, 0.294f, -1.787f,
1.442f, 0.476f, -1.601f,
1.235f, 0.476f, -1.371f,
1.068f, 0.294f, -1.186f,
1.004f, 0f, -1.115f,
1.068f, -0.294f, -1.186f,
1.235f, -0.476f, -1.371f,
1.442f, -0.476f, -1.601f,
1.609f, -0.294f, -1.787f,
2.023f, 0f, -1.469f,
1.945f, 0.294f, -1.413f,
1.743f, 0.476f, -1.266f,
1.493f, 0.476f, -1.085f,
1.291f, 0.294f, -0.938f,
1.214f, 0f, -0.882f,
1.291f, -0.294f, -0.938f,
1.493f, -0.476f, -1.085f,
1.743f, -0.476f, -1.266f,
1.945f, -0.294f, -1.413f,
2.284f, 0f, -1.017f,
2.197f, 0.294f, -0.978f,
1.968f, 0.476f, -0.876f,
1.686f, 0.476f, -0.751f,
1.458f, 0.294f, -0.649f,
1.37f, 0f, -0.61f,
1.458f, -0.294f, -0.649f,
1.686f, -0.476f, -0.751f,
1.968f, -0.476f, -0.876f,
2.197f, -0.294f, -0.978f,
2.445f, 0f, -0.52f,
2.352f, 0.294f, -0.5f,
2.107f, 0.476f, -0.448f,
1.805f, 0.476f, -0.384f,
1.561f, 0.294f, -0.332f,
1.467f, 0f, -0.312f,
1.561f, -0.294f, -0.332f,
1.805f, -0.476f, -0.384f,
2.107f, -0.476f, -0.448f,
2.352f, -0.294f, -0.5f
};
public static readonly int[] Indices = new[]
{
0, 1, 11,
1, 2, 12,
2, 3, 13,
3, 4, 14,
4, 5, 15,
5, 6, 16,
6, 7, 17,
7, 8, 18,
8, 9, 19,
9, 0, 10,
10, 11, 21,
11, 12, 22,
12, 13, 23,
13, 14, 24,
14, 15, 25,
15, 16, 26,
16, 17, 27,
17, 18, 28,
18, 19, 29,
19, 10, 20,
20, 21, 31,
21, 22, 32,
22, 23, 33,
23, 24, 34,
24, 25, 35,
25, 26, 36,
26, 27, 37,
27, 28, 38,
28, 29, 39,
29, 20, 30,
30, 31, 41,
31, 32, 42,
32, 33, 43,
33, 34, 44,
34, 35, 45,
35, 36, 46,
36, 37, 47,
37, 38, 48,
38, 39, 49,
39, 30, 40,
40, 41, 51,
41, 42, 52,
42, 43, 53,
43, 44, 54,
44, 45, 55,
45, 46, 56,
46, 47, 57,
47, 48, 58,
48, 49, 59,
49, 40, 50,
50, 51, 61,
51, 52, 62,
52, 53, 63,
53, 54, 64,
54, 55, 65,
55, 56, 66,
56, 57, 67,
57, 58, 68,
58, 59, 69,
59, 50, 60,
60, 61, 71,
61, 62, 72,
62, 63, 73,
63, 64, 74,
64, 65, 75,
65, 66, 76,
66, 67, 77,
67, 68, 78,
68, 69, 79,
69, 60, 70,
70, 71, 81,
71, 72, 82,
72, 73, 83,
73, 74, 84,
74, 75, 85,
75, 76, 86,
76, 77, 87,
77, 78, 88,
78, 79, 89,
79, 70, 80,
80, 81, 91,
81, 82, 92,
82, 83, 93,
83, 84, 94,
84, 85, 95,
85, 86, 96,
86, 87, 97,
87, 88, 98,
88, 89, 99,
89, 80, 90,
90, 91, 101,
91, 92, 102,
92, 93, 103,
93, 94, 104,
94, 95, 105,
95, 96, 106,
96, 97, 107,
97, 98, 108,
98, 99, 109,
99, 90, 100,
100, 101, 111,
101, 102, 112,
102, 103, 113,
103, 104, 114,
104, 105, 115,
105, 106, 116,
106, 107, 117,
107, 108, 118,
108, 109, 119,
109, 100, 110,
110, 111, 121,
111, 112, 122,
112, 113, 123,
113, 114, 124,
114, 115, 125,
115, 116, 126,
116, 117, 127,
117, 118, 128,
118, 119, 129,
119, 110, 120,
120, 121, 131,
121, 122, 132,
122, 123, 133,
123, 124, 134,
124, 125, 135,
125, 126, 136,
126, 127, 137,
127, 128, 138,
128, 129, 139,
129, 120, 130,
130, 131, 141,
131, 132, 142,
132, 133, 143,
133, 134, 144,
134, 135, 145,
135, 136, 146,
136, 137, 147,
137, 138, 148,
138, 139, 149,
139, 130, 140,
140, 141, 151,
141, 142, 152,
142, 143, 153,
143, 144, 154,
144, 145, 155,
145, 146, 156,
146, 147, 157,
147, 148, 158,
148, 149, 159,
149, 140, 150,
150, 151, 161,
151, 152, 162,
152, 153, 163,
153, 154, 164,
154, 155, 165,
155, 156, 166,
156, 157, 167,
157, 158, 168,
158, 159, 169,
159, 150, 160,
160, 161, 171,
161, 162, 172,
162, 163, 173,
163, 164, 174,
164, 165, 175,
165, 166, 176,
166, 167, 177,
167, 168, 178,
168, 169, 179,
169, 160, 170,
170, 171, 181,
171, 172, 182,
172, 173, 183,
173, 174, 184,
174, 175, 185,
175, 176, 186,
176, 177, 187,
177, 178, 188,
178, 179, 189,
179, 170, 180,
180, 181, 191,
181, 182, 192,
182, 183, 193,
183, 184, 194,
184, 185, 195,
185, 186, 196,
186, 187, 197,
187, 188, 198,
188, 189, 199,
189, 180, 190,
190, 191, 201,
191, 192, 202,
192, 193, 203,
193, 194, 204,
194, 195, 205,
195, 196, 206,
196, 197, 207,
197, 198, 208,
198, 199, 209,
199, 190, 200,
200, 201, 211,
201, 202, 212,
202, 203, 213,
203, 204, 214,
204, 205, 215,
205, 206, 216,
206, 207, 217,
207, 208, 218,
208, 209, 219,
209, 200, 210,
210, 211, 221,
211, 212, 222,
212, 213, 223,
213, 214, 224,
214, 215, 225,
215, 216, 226,
216, 217, 227,
217, 218, 228,
218, 219, 229,
219, 210, 220,
220, 221, 231,
221, 222, 232,
222, 223, 233,
223, 224, 234,
224, 225, 235,
225, 226, 236,
226, 227, 237,
227, 228, 238,
228, 229, 239,
229, 220, 230,
230, 231, 241,
231, 232, 242,
232, 233, 243,
233, 234, 244,
234, 235, 245,
235, 236, 246,
236, 237, 247,
237, 238, 248,
238, 239, 249,
239, 230, 240,
240, 241, 251,
241, 242, 252,
242, 243, 253,
243, 244, 254,
244, 245, 255,
245, 246, 256,
246, 247, 257,
247, 248, 258,
248, 249, 259,
249, 240, 250,
250, 251, 261,
251, 252, 262,
252, 253, 263,
253, 254, 264,
254, 255, 265,
255, 256, 266,
256, 257, 267,
257, 258, 268,
258, 259, 269,
259, 250, 260,
260, 261, 271,
261, 262, 272,
262, 263, 273,
263, 264, 274,
264, 265, 275,
265, 266, 276,
266, 267, 277,
267, 268, 278,
268, 269, 279,
269, 260, 270,
270, 271, 281,
271, 272, 282,
272, 273, 283,
273, 274, 284,
274, 275, 285,
275, 276, 286,
276, 277, 287,
277, 278, 288,
278, 279, 289,
279, 270, 280,
280, 281, 291,
281, 282, 292,
282, 283, 293,
283, 284, 294,
284, 285, 295,
285, 286, 296,
286, 287, 297,
287, 288, 298,
288, 289, 299,
289, 280, 290,
290, 291, 1,
291, 292, 2,
292, 293, 3,
293, 294, 4,
294, 295, 5,
295, 296, 6,
296, 297, 7,
297, 298, 8,
298, 299, 9,
299, 290, 0,
0, 11, 10,
1, 12, 11,
2, 13, 12,
3, 14, 13,
4, 15, 14,
5, 16, 15,
6, 17, 16,
7, 18, 17,
8, 19, 18,
9, 10, 19,
10, 21, 20,
11, 22, 21,
12, 23, 22,
13, 24, 23,
14, 25, 24,
15, 26, 25,
16, 27, 26,
17, 28, 27,
18, 29, 28,
19, 20, 29,
20, 31, 30,
21, 32, 31,
22, 33, 32,
23, 34, 33,
24, 35, 34,
25, 36, 35,
26, 37, 36,
27, 38, 37,
28, 39, 38,
29, 30, 39,
30, 41, 40,
31, 42, 41,
32, 43, 42,
33, 44, 43,
34, 45, 44,
35, 46, 45,
36, 47, 46,
37, 48, 47,
38, 49, 48,
39, 40, 49,
40, 51, 50,
41, 52, 51,
42, 53, 52,
43, 54, 53,
44, 55, 54,
45, 56, 55,
46, 57, 56,
47, 58, 57,
48, 59, 58,
49, 50, 59,
50, 61, 60,
51, 62, 61,
52, 63, 62,
53, 64, 63,
54, 65, 64,
55, 66, 65,
56, 67, 66,
57, 68, 67,
58, 69, 68,
59, 60, 69,
60, 71, 70,
61, 72, 71,
62, 73, 72,
63, 74, 73,
64, 75, 74,
65, 76, 75,
66, 77, 76,
67, 78, 77,
68, 79, 78,
69, 70, 79,
70, 81, 80,
71, 82, 81,
72, 83, 82,
73, 84, 83,
74, 85, 84,
75, 86, 85,
76, 87, 86,
77, 88, 87,
78, 89, 88,
79, 80, 89,
80, 91, 90,
81, 92, 91,
82, 93, 92,
83, 94, 93,
84, 95, 94,
85, 96, 95,
86, 97, 96,
87, 98, 97,
88, 99, 98,
89, 90, 99,
90, 101, 100,
91, 102, 101,
92, 103, 102,
93, 104, 103,
94, 105, 104,
95, 106, 105,
96, 107, 106,
97, 108, 107,
98, 109, 108,
99, 100, 109,
100, 111, 110,
101, 112, 111,
102, 113, 112,
103, 114, 113,
104, 115, 114,
105, 116, 115,
106, 117, 116,
107, 118, 117,
108, 119, 118,
109, 110, 119,
110, 121, 120,
111, 122, 121,
112, 123, 122,
113, 124, 123,
114, 125, 124,
115, 126, 125,
116, 127, 126,
117, 128, 127,
118, 129, 128,
119, 120, 129,
120, 131, 130,
121, 132, 131,
122, 133, 132,
123, 134, 133,
124, 135, 134,
125, 136, 135,
126, 137, 136,
127, 138, 137,
128, 139, 138,
129, 130, 139,
130, 141, 140,
131, 142, 141,
132, 143, 142,
133, 144, 143,
134, 145, 144,
135, 146, 145,
136, 147, 146,
137, 148, 147,
138, 149, 148,
139, 140, 149,
140, 151, 150,
141, 152, 151,
142, 153, 152,
143, 154, 153,
144, 155, 154,
145, 156, 155,
146, 157, 156,
147, 158, 157,
148, 159, 158,
149, 150, 159,
150, 161, 160,
151, 162, 161,
152, 163, 162,
153, 164, 163,
154, 165, 164,
155, 166, 165,
156, 167, 166,
157, 168, 167,
158, 169, 168,
159, 160, 169,
160, 171, 170,
161, 172, 171,
162, 173, 172,
163, 174, 173,
164, 175, 174,
165, 176, 175,
166, 177, 176,
167, 178, 177,
168, 179, 178,
169, 170, 179,
170, 181, 180,
171, 182, 181,
172, 183, 182,
173, 184, 183,
174, 185, 184,
175, 186, 185,
176, 187, 186,
177, 188, 187,
178, 189, 188,
179, 180, 189,
180, 191, 190,
181, 192, 191,
182, 193, 192,
183, 194, 193,
184, 195, 194,
185, 196, 195,
186, 197, 196,
187, 198, 197,
188, 199, 198,
189, 190, 199,
190, 201, 200,
191, 202, 201,
192, 203, 202,
193, 204, 203,
194, 205, 204,
195, 206, 205,
196, 207, 206,
197, 208, 207,
198, 209, 208,
199, 200, 209,
200, 211, 210,
201, 212, 211,
202, 213, 212,
203, 214, 213,
204, 215, 214,
205, 216, 215,
206, 217, 216,
207, 218, 217,
208, 219, 218,
209, 210, 219,
210, 221, 220,
211, 222, 221,
212, 223, 222,
213, 224, 223,
214, 225, 224,
215, 226, 225,
216, 227, 226,
217, 228, 227,
218, 229, 228,
219, 220, 229,
220, 231, 230,
221, 232, 231,
222, 233, 232,
223, 234, 233,
224, 235, 234,
225, 236, 235,
226, 237, 236,
227, 238, 237,
228, 239, 238,
229, 230, 239,
230, 241, 240,
231, 242, 241,
232, 243, 242,
233, 244, 243,
234, 245, 244,
235, 246, 245,
236, 247, 246,
237, 248, 247,
238, 249, 248,
239, 240, 249,
240, 251, 250,
241, 252, 251,
242, 253, 252,
243, 254, 253,
244, 255, 254,
245, 256, 255,
246, 257, 256,
247, 258, 257,
248, 259, 258,
249, 250, 259,
250, 261, 260,
251, 262, 261,
252, 263, 262,
253, 264, 263,
254, 265, 264,
255, 266, 265,
256, 267, 266,
257, 268, 267,
258, 269, 268,
259, 260, 269,
260, 271, 270,
261, 272, 271,
262, 273, 272,
263, 274, 273,
264, 275, 274,
265, 276, 275,
266, 277, 276,
267, 278, 277,
268, 279, 278,
269, 270, 279,
270, 281, 280,
271, 282, 281,
272, 283, 282,
273, 284, 283,
274, 285, 284,
275, 286, 285,
276, 287, 286,
277, 288, 287,
278, 289, 288,
279, 280, 289,
280, 291, 290,
281, 292, 291,
282, 293, 292,
283, 294, 293,
284, 295, 294,
285, 296, 295,
286, 297, 296,
287, 298, 297,
288, 299, 298,
289, 290, 299,
290, 1, 0,
291, 2, 1,
292, 3, 2,
293, 4, 3,
294, 5, 4,
295, 6, 5,
296, 7, 6,
297, 8, 7,
298, 9, 8,
299, 0, 9
};
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using Xunit;
using Microsoft.Rest;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Rest.Azure.OData;
namespace ResourceGroups.Tests
{
public class InMemoryDeploymentTests
{
public ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler)
{
var subscriptionId = Guid.NewGuid().ToString();
var token = new TokenCredentials(subscriptionId, "abc123");
handler.IsPassThrough = false;
var client = new ResourceManagementClient(token, handler);
client.SubscriptionId = subscriptionId;
return client;
}
[Fact]
public void DeploymentTestsCreateValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent(@"{
'id': 'foo',
'name':'myrealease-3.14',
'properties':{
'provisioningState':'Succeeded',
'timestamp':'2014-01-05T12:30:43.00Z',
'mode':'Incremental',
'template': { 'api-version' : '123' },
'templateLink': {
'uri': 'http://wa/template.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parametersLink': { /* use either one of parameters or parametersLink */
'uri': 'http://wa/parameters.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parameters': {
'key' : {
'type':'string',
'value':'user'
}
},
'outputs': {
'key' : {
'type':'string',
'value':'user'
}
}
}
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.Created };
var client = GetResourceManagementClient(handler);
var dictionary = new Dictionary<string, object> {
{"param1", "value1"},
{"param2", true},
{"param3", new Dictionary<string, object>() {
{"param3_1", 123},
{"param3_2", "value3_2"},
}}
};
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = JObject.Parse("{'api-version':'123'}"),
TemplateLink = new TemplateLink
{
Uri = "http://abc/def/template.json",
ContentVersion = "1.0.0.0"
},
Parameters = dictionary,
ParametersLink = new ParametersLink
{
Uri = "http://abc/def/template.json",
ContentVersion = "1.0.0.0"
},
Mode = DeploymentMode.Incremental
}
};
var result = client.Deployments.CreateOrUpdate("foo", "myrealease-3.14", parameters);
JObject json = JObject.Parse(handler.Request);
// Validate headers
Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First());
Assert.Equal(HttpMethod.Put, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate payload
Assert.Equal("Incremental", json["properties"]["mode"].Value<string>());
Assert.Equal("http://abc/def/template.json", json["properties"]["templateLink"]["uri"].Value<string>());
Assert.Equal("1.0.0.0", json["properties"]["templateLink"]["contentVersion"].Value<string>());
Assert.Equal("1.0.0.0", json["properties"]["parametersLink"]["contentVersion"].Value<string>());
Assert.Equal("value1", json["properties"]["parameters"]["param1"].Value<string>());
Assert.Equal(true, json["properties"]["parameters"]["param2"].Value<bool>());
Assert.Equal(123, json["properties"]["parameters"]["param3"]["param3_1"].Value<int>());
Assert.Equal("value3_2", json["properties"]["parameters"]["param3"]["param3_2"].Value<string>());
Assert.Equal(123, json["properties"]["template"]["api-version"].Value<int>());
// Validate result
Assert.Equal("foo", result.Id);
Assert.Equal("myrealease-3.14", result.Name);
Assert.Equal("Succeeded", result.Properties.ProvisioningState);
Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.Properties.Timestamp);
Assert.Equal(DeploymentMode.Incremental, result.Properties.Mode);
Assert.Equal("http://wa/template.json", result.Properties.TemplateLink.Uri);
Assert.Equal("1.0.0.0", result.Properties.TemplateLink.ContentVersion);
Assert.True(result.Properties.Parameters.ToString().Contains("\"type\": \"string\""));
Assert.True(result.Properties.Outputs.ToString().Contains("\"type\": \"string\""));
}
[Fact]
public void DeploymentTestsTemplateAsJsonString()
{
var responseBody = @"{
'id': 'foo',
'name': 'test-release-3',
'properties': {
'parameters': {
'storageAccountName': {
'type': 'String',
'value': 'tianotest04'
}
},
'mode': 'Incremental',
'provisioningState': 'Succeeded',
'timestamp': '2016-07-12T17:36:39.2398177Z',
'duration': 'PT0.5966357S',
'correlationId': 'c0d728d5-5b97-41b9-b79a-abcd9eb5fe4a'
}
}";
var templateString = @"{
'$schema': 'http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#',
'contentVersion': '1.0.0.0',
'parameters': {
'storageAccountName': {
'type': 'string'
}
},
'resources': [
],
'outputs': { }
}";
var parametersStringFull = @"{
'$schema': 'http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#',
'contentVersion': '1.0.0.0',
'parameters': {
'storageAccountName': {
'value': 'tianotest04'
}
}
}";
var parametersStringsShort = @"{
'storageAccountName': {
'value': 'tianotest04'
}
}";
for (int i = 0; i < 2; i++)
{
var response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent(responseBody)
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.Created };
var client = GetResourceManagementClient(handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = templateString,
Parameters = i == 0 ? parametersStringFull: parametersStringsShort,
Mode = DeploymentMode.Incremental
}
};
var result = client.Deployments.CreateOrUpdate("foo", "myrealease-3.14", parameters);
JObject json = JObject.Parse(handler.Request);
// Validate headers
Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First());
Assert.Equal(HttpMethod.Put, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate payload
Assert.Equal("Incremental", json["properties"]["mode"].Value<string>());
Assert.Equal("tianotest04", json["properties"]["parameters"]["storageAccountName"]["value"].Value<string>());
Assert.Equal("1.0.0.0", json["properties"]["template"]["contentVersion"].Value<string>());
// Validate result
Assert.Equal("foo", result.Id);
Assert.Equal("test-release-3", result.Name);
Assert.Equal("Succeeded", result.Properties.ProvisioningState);
Assert.Equal(DeploymentMode.Incremental, result.Properties.Mode);
Assert.True(result.Properties.Parameters.ToString().Contains("\"value\": \"tianotest04\""));
}
}
[Fact]
public void ListDeploymentOperationsReturnsMultipleObjects()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [
{
'subscriptionId':'mysubid',
'resourceGroup': 'foo',
'deploymentName':'test-release-3',
'operationId': 'AEF2398',
'properties':{
'targetResource':{
'id': '/subscriptions/123abc/resourcegroups/foo/providers/ResourceProviderTestHost/TestResourceType/resource1',
'resourceName':'mySite1',
'resourceType': 'Microsoft.Web',
},
'provisioningState':'Succeeded',
'timestamp': '2014-02-25T23:08:21.8183932Z',
'correlationId': 'afb170c6-fe57-4b38-a43b-900fe09be4ca',
'statusCode': 'InternalServerError',
'statusMessage': 'InternalServerError',
}
}
],
'nextLink': 'https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw'
}
")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.DeploymentOperations.List("foo", "bar", null);
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate response
Assert.Equal(1, result.Count());
Assert.Equal("AEF2398", result.First().OperationId);
Assert.Equal("/subscriptions/123abc/resourcegroups/foo/providers/ResourceProviderTestHost/TestResourceType/resource1", result.First().Properties.TargetResource.Id);
Assert.Equal("mySite1", result.First().Properties.TargetResource.ResourceName);
Assert.Equal("Microsoft.Web", result.First().Properties.TargetResource.ResourceType);
Assert.Equal("Succeeded", result.First().Properties.ProvisioningState);
Assert.Equal("InternalServerError", result.First().Properties.StatusCode);
Assert.Equal("InternalServerError", result.First().Properties.StatusMessage);
Assert.Equal("https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw", result.NextPageLink);
}
[Fact]
public void ListDeploymentOperationsReturnsEmptyArray()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [],
'nextLink': 'https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw'
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.DeploymentOperations.List("foo", "bar", null);
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate response
Assert.Equal(0, result.Count());
}
[Fact]
public void ListDeploymentOperationsWithRealPayloadReadsJsonInStatusMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [
{
'id': '/subscriptions/abcd1234/resourcegroups/foo/deployments/testdeploy/operations/334558C2218CAEB0',
'subscriptionId': 'abcd1234',
'resourceGroup': 'foo',
'deploymentName': 'testdeploy',
'operationId': '334558C2218CAEB0',
'properties': {
'provisioningState': 'Failed',
'timestamp': '2014-03-14T23:43:31.8688746Z',
'trackingId': '4f258f91-edd5-4d71-87c2-fac9a4b5cbbd',
'statusCode': 'Conflict',
'statusMessage': {
'Code': 'Conflict',
'Message': 'Website with given name ilygreTest4 already exists.',
'Target': null,
'Details': [
{
'Message': 'Website with given name ilygreTest4 already exists.'
},
{
'Code': 'Conflict'
},
{
'ErrorEntity': {
'Code': 'Conflict',
'Message': 'Website with given name ilygreTest4 already exists.',
'ExtendedCode': '54001',
'MessageTemplate': 'Website with given name {0} already exists.',
'Parameters': [
'ilygreTest4'
],
'InnerErrors': null
}
}
],
'Innererror': null
},
'targetResource': {
'id':
'/subscriptions/abcd1234/resourcegroups/foo/providers/Microsoft.Web/Sites/ilygreTest4',
'subscriptionId': 'abcd1234',
'resourceGroup': 'foo',
'resourceType': 'Microsoft.Web/Sites',
'resourceName': 'ilygreTest4'
}
}
},
{
'id':
'/subscriptions/abcd1234/resourcegroups/foo/deployments/testdeploy/operations/6B9A5A38C94E6
F14',
'subscriptionId': 'abcd1234',
'resourceGroup': 'foo',
'deploymentName': 'testdeploy',
'operationId': '6B9A5A38C94E6F14',
'properties': {
'provisioningState': 'Succeeded',
'timestamp': '2014-03-14T23:43:25.2101422Z',
'trackingId': '2ff7a8ad-abf3-47f6-8ce0-e4aae8c26065',
'statusCode': 'OK',
'statusMessage': null,
'targetResource': {
'id':
'/subscriptions/abcd1234/resourcegroups/foo/providers/Microsoft.Web/serverFarms/ilygreTest4
Host',
'subscriptionId': 'abcd1234',
'resourceGroup': 'foo',
'resourceType': 'Microsoft.Web/serverFarms',
'resourceName': 'ilygreTest4Host'
}
}
}
]
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.DeploymentOperations.List("foo", "bar", null);
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
Assert.True(JObject.Parse(result.First().Properties.StatusMessage.ToString()).HasValues);
}
[Fact]
public void ListDeploymentOperationsWorksWithNextLink()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [
{
'subscriptionId':'mysubid',
'resourceGroup': 'foo',
'deploymentName':'test-release-3',
'operationId': 'AEF2398',
'properties':{
'targetResource':{
'subscriptionId':'mysubid',
'resourceGroup': 'TestRG',
'resourceName':'mySite1',
'resourceType': 'Microsoft.Web',
},
'provisioningState':'Succeeded',
'timestamp': '2014-02-25T23:08:21.8183932Z',
'correlationId': 'afb170c6-fe57-4b38-a43b-900fe09be4ca',
'statusCode': 'InternalServerError',
'statusMessage': 'InternalServerError',
}
}
],
'nextLink': 'https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw'
}
")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.DeploymentOperations.List("foo", "bar", null);
response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': []
}")
};
handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
client = GetResourceManagementClient(handler);
result = client.DeploymentOperations.ListNext(result.NextPageLink);
// Validate body
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
Assert.Equal("https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw", handler.Uri.ToString());
// Validate response
Assert.Equal(0, result.Count());
Assert.Equal(null, result.NextPageLink);
}
[Fact]
public void GetDeploymentOperationsReturnsValue()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'subscriptionId':'mysubid',
'resourceGroup': 'foo',
'deploymentName':'test-release-3',
'operationId': 'AEF2398',
'properties':{
'targetResource':{
'id':'/subscriptions/123abc/resourcegroups/foo/providers/ResourceProviderTestHost/TestResourceType/resource1',
'resourceName':'mySite1',
'resourceType': 'Microsoft.Web',
},
'provisioningState':'Succeeded',
'timestamp': '2014-02-25T23:08:21.8183932Z',
'correlationId': 'afb170c6-fe57-4b38-a43b-900fe09be4ca',
'statusCode': 'OK',
'statusMessage': 'OK',
}
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.DeploymentOperations.Get("foo", "bar", "123");
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate response
Assert.Equal("AEF2398", result.OperationId);
Assert.Equal("mySite1", result.Properties.TargetResource.ResourceName);
Assert.Equal("/subscriptions/123abc/resourcegroups/foo/providers/ResourceProviderTestHost/TestResourceType/resource1", result.Properties.TargetResource.Id);
Assert.Equal("Microsoft.Web", result.Properties.TargetResource.ResourceType);
Assert.Equal("Succeeded", result.Properties.ProvisioningState);
Assert.Equal("OK", result.Properties.StatusCode);
Assert.Equal("OK", result.Properties.StatusMessage);
}
[Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")]
public void DeploymentTestsCreateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetResourceManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.Deployments.CreateOrUpdate(null, "bar", new Deployment()));
Assert.Throws<ArgumentNullException>(() => client.Deployments.CreateOrUpdate("foo", null, new Deployment()));
Assert.Throws<ArgumentNullException>(() => client.Deployments.CreateOrUpdate("foo", "bar", null));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Deployments.CreateOrUpdate("~`123", "bar", new Deployment()));
}
[Fact]
public void DeploymentTestsValidateCheckPayload()
{
var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent(@"{
'error': {
'code': 'InvalidTemplate',
'message': 'Deployment template validation failed.'
}
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.BadRequest };
var client = GetResourceManagementClient(handler);
var dictionary = new Dictionary<string, object> {
{"param1", "value1"},
{"param2", true},
{"param3", new Dictionary<string, object>() {
{"param3_1", 123},
{"param3_2", "value3_2"},
}}
};
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = "http://abc/def/template.json",
ContentVersion = "1.0.0.0",
},
Parameters = dictionary,
Mode = DeploymentMode.Incremental
}
};
var result = client.Deployments.Validate("foo", "bar", parameters);
JObject json = JObject.Parse(handler.Request);
// Validate headers
Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First());
Assert.Equal(HttpMethod.Post, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate payload
Assert.Equal("Incremental", json["properties"]["mode"].Value<string>());
Assert.Equal("http://abc/def/template.json", json["properties"]["templateLink"]["uri"].Value<string>());
Assert.Equal("1.0.0.0", json["properties"]["templateLink"]["contentVersion"].Value<string>());
Assert.Equal("value1", json["properties"]["parameters"]["param1"].Value<string>());
Assert.Equal(true, json["properties"]["parameters"]["param2"].Value<bool>());
Assert.Equal(123, json["properties"]["parameters"]["param3"]["param3_1"].Value<int>());
Assert.Equal("value3_2", json["properties"]["parameters"]["param3"]["param3_2"].Value<string>());
}
[Fact]
public void DeploymentTestsValidateSimpleFailure()
{
var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent(@"{
'error': {
'code': 'InvalidTemplate',
'message': 'Deployment template validation failed: The template parameters hostingPlanName, siteMode, computeMode are not valid; they are not present.'
}
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.BadRequest };
var client = GetResourceManagementClient(handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = "http://abc/def/template.json",
ContentVersion = "1.0.0.0",
},
Mode = DeploymentMode.Incremental
}
};
var result = client.Deployments.Validate("foo", "bar", parameters);
// Validate result
Assert.Equal("InvalidTemplate", result.Error.Code);
Assert.Equal("Deployment template validation failed: The template parameters hostingPlanName, siteMode, computeMode are not valid; they are not present.", result.Error.Message);
Assert.Null(result.Error.Target);
Assert.Null(result.Error.Details);
}
[Fact]
public void DeploymentTestsValidateComplexFailure()
{
var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent(@"{
'error': {
'code': 'InvalidTemplate',
'target': '',
'message': 'Deployment template validation failed: The template parameters hostingPlanName, siteMode, computeMode are not valid; they are not present.',
'details': [
{
'code': 'Error1',
'message': 'Deployment template validation failed.'
},
{
'code': 'Error2',
'message': 'Deployment template validation failed.'
}
]
}
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.BadRequest };
var client = GetResourceManagementClient(handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = "http://abc/def/template.json",
ContentVersion = "1.0.0.0",
},
Mode = DeploymentMode.Incremental
}
};
var result = client.Deployments.Validate("foo", "bar", parameters);
JObject json = JObject.Parse(handler.Request);
// Validate result
Assert.Equal("InvalidTemplate", result.Error.Code);
Assert.Equal("Deployment template validation failed: The template parameters hostingPlanName, siteMode, computeMode are not valid; they are not present.", result.Error.Message);
Assert.Equal("", result.Error.Target);
Assert.Equal(2, result.Error.Details.Count);
Assert.Equal("Error1", result.Error.Details[0].Code);
Assert.Equal("Error2", result.Error.Details[1].Code);
}
[Fact]
public void DeploymentTestsValidateSuccess()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = "http://abc/def/template.json",
ContentVersion = "1.0.0.0",
},
Mode = DeploymentMode.Incremental
}
};
var result = client.Deployments.Validate("foo", "bar", parameters);
JObject json = JObject.Parse(handler.Request);
// Validate headers
Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First());
Assert.Equal(HttpMethod.Post, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate result
Assert.Null(result);
}
[Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")]
public void DeploymentTestsValidateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetResourceManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.Deployments.Validate(null, "bar", new Deployment()));
Assert.Throws<ArgumentNullException>(() => client.Deployments.Validate("foo", "bar", null));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Deployments.Validate("~`123", "bar", new Deployment()));
}
[Fact]
public void DeploymentTestsCancelValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.NoContent) { Content = new StringContent("") };
var handler = new RecordedDelegatingHandler(response)
{
StatusCodeToReturn = HttpStatusCode.NoContent,
};
var client = GetResourceManagementClient(handler);
client.Deployments.Cancel("foo", "bar");
}
[Fact]
public void DeploymentTestsCancelThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetResourceManagementClient(handler);
Assert.Throws<Microsoft.Rest.ValidationException>(() => client.Deployments.Cancel(null, "bar"));
Assert.Throws<Microsoft.Rest.ValidationException>(() => client.Deployments.Cancel("foo", null));
}
[Fact]
public void DeploymentTestsGetValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'resourceGroup': 'foo',
'name':'myrealease-3.14',
'properties':{
'provisioningState':'Succeeded',
'timestamp':'2014-01-05T12:30:43.00Z',
'mode':'Incremental',
'correlationId':'12345',
'templateLink': {
'uri': 'http://wa/template.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parametersLink': { /* use either one of parameters or parametersLink */
'uri': 'http://wa/parameters.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parameters': {
'key' : {
'type':'string',
'value':'user'
}
},
'outputs': {
'key' : {
'type':'string',
'value':'user'
}
}
}
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.Deployments.Get("foo", "bar");
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate result
Assert.Equal("myrealease-3.14", result.Name);
Assert.Equal("Succeeded", result.Properties.ProvisioningState);
Assert.Equal("12345", result.Properties.CorrelationId);
Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.Properties.Timestamp);
Assert.Equal(DeploymentMode.Incremental, result.Properties.Mode);
Assert.Equal("http://wa/template.json", result.Properties.TemplateLink.Uri.ToString());
Assert.Equal("1.0.0.0", result.Properties.TemplateLink.ContentVersion);
Assert.True(result.Properties.Parameters.ToString().Contains("\"type\": \"string\""));
Assert.True(result.Properties.Outputs.ToString().Contains("\"type\": \"string\""));
}
[Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")]
public void DeploymentGetValidateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetResourceManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.Deployments.Get(null, "bar"));
Assert.Throws<ArgumentNullException>(() => client.Deployments.Get("foo", null));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Deployments.Get("~`123", "bar"));
}
[Fact]
public void DeploymentTestsListAllValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value' : [
{
'resourceGroup': 'foo',
'name':'myrealease-3.14',
'properties':{
'provisioningState':'Succeeded',
'timestamp':'2014-01-05T12:30:43.00Z',
'mode':'Incremental',
'templateLink': {
'uri': 'http://wa/template.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parametersLink': { /* use either one of parameters or parametersLink */
'uri': 'http://wa/parameters.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parameters': {
'key' : {
'type':'string',
'value':'user'
}
},
'outputs': {
'key' : {
'type':'string',
'value':'user'
}
}
}
},
{
'resourceGroup': 'bar',
'name':'myrealease-3.14',
'properties':{
'provisioningState':'Succeeded',
'timestamp':'2014-01-05T12:30:43.00Z',
'mode':'Incremental',
'templateLink': {
'uri': 'http://wa/template.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parametersLink': { /* use either one of parameters or parametersLink */
'uri': 'http://wa/parameters.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parameters': {
'key' : {
'type':'string',
'value':'user'
}
},
'outputs': {
'key' : {
'type':'string',
'value':'user'
}
}
}
}
],
'nextLink': 'https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw'
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.Deployments.List("foo");
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate result
Assert.Equal("myrealease-3.14", result.First().Name);
Assert.Equal("Succeeded", result.First().Properties.ProvisioningState);
Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.First().Properties.Timestamp);
Assert.Equal(DeploymentMode.Incremental, result.First().Properties.Mode);
Assert.Equal("http://wa/template.json", result.First().Properties.TemplateLink.Uri.ToString());
Assert.Equal("1.0.0.0", result.First().Properties.TemplateLink.ContentVersion);
Assert.True(result.First().Properties.Parameters.ToString().Contains("\"type\": \"string\""));
Assert.True(result.First().Properties.Outputs.ToString().Contains("\"type\": \"string\""));
Assert.Equal("https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw", result.NextPageLink);
}
[Fact]
public void DeploymentTestsListValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value' : [
{
'resourceGroup': 'foo',
'name':'myrealease-3.14',
'properties':{
'provisioningState':'Succeeded',
'timestamp':'2014-01-05T12:30:43.00Z',
'mode':'Incremental',
'templateLink': {
'uri': 'http://wa/template.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parametersLink': { /* use either one of parameters or parametersLink */
'uri': 'http://wa/parameters.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parameters': {
'key' : {
'type':'string',
'value':'user'
}
},
'outputs': {
'key' : {
'type':'string',
'value':'user'
}
}
}
},
{
'resourceGroup': 'bar',
'name':'myrealease-3.14',
'properties':{
'provisioningState':'Succeeded',
'timestamp':'2014-01-05T12:30:43.00Z',
'mode':'Incremental',
'templateLink': {
'uri': 'http://wa/template.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parametersLink': { /* use either one of parameters or parametersLink */
'uri': 'http://wa/parameters.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parameters': {
'key' : {
'type':'string',
'value':'user'
}
},
'outputs': {
'key' : {
'type':'string',
'value':'user'
}
}
}
}
],
'nextLink': 'https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw'
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.Deployments.List("foo", new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Succeeded") { Top = 10 });
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
Assert.True(handler.Uri.ToString().Contains("$top=10"));
Assert.True(handler.Uri.ToString().Contains("$filter=provisioningState eq 'Succeeded'"));
// Validate result
Assert.Equal("myrealease-3.14", result.First().Name);
Assert.Equal("Succeeded", result.First().Properties.ProvisioningState);
Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.First().Properties.Timestamp);
Assert.Equal(DeploymentMode.Incremental, result.First().Properties.Mode);
Assert.Equal("http://wa/template.json", result.First().Properties.TemplateLink.Uri.ToString());
Assert.Equal("1.0.0.0", result.First().Properties.TemplateLink.ContentVersion);
Assert.True(result.First().Properties.Parameters.ToString().Contains("\"type\": \"string\""));
Assert.True(result.First().Properties.Outputs.ToString().Contains("\"type\": \"string\""));
Assert.Equal("https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw", result.NextPageLink);
}
// TODO: Fix
[Fact]
public void DeploymentTestsListForGroupValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value' : [
{
'resourceGroup': 'foo',
'name':'myrealease-3.14',
'properties':{
'provisioningState':'Succeeded',
'timestamp':'2014-01-05T12:30:43.00Z',
'mode':'Incremental',
'templateLink': {
'uri': 'http://wa/template.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parametersLink': { /* use either one of parameters or parametersLink */
'uri': 'http://wa/parameters.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parameters': {
'key' : {
'type':'string',
'value':'user'
}
},
'outputs': {
'key' : {
'type':'string',
'value':'user'
}
}
}
},
{
'resourceGroup': 'bar',
'name':'myrealease-3.14',
'properties':{
'provisioningState':'Succeeded',
'timestamp':'2014-01-05T12:30:43.00Z',
'mode':'Incremental',
'templateLink': {
'uri': 'http://wa/template.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parametersLink': { /* use either one of parameters or parametersLink */
'uri': 'http://wa/parameters.json',
'contentVersion': '1.0.0.0',
'contentHash': {
'algorithm': 'sha256',
'value': 'yyz7xhhshfasf',
}
},
'parameters': {
'key' : {
'type':'string',
'value':'user'
}
},
'outputs': {
'key' : {
'type':'string',
'value':'user'
}
}
}
}
],
'nextLink': 'https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw'
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.Deployments.List("foo", new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Succeeded") { Top = 10 });
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
Assert.True(handler.Uri.ToString().Contains("$top=10"));
Assert.True(handler.Uri.ToString().Contains("$filter=provisioningState eq 'Succeeded'"));
Assert.True(handler.Uri.ToString().Contains("resourcegroups/foo/providers/Microsoft.Resources/deployments"));
// Validate result
Assert.Equal("myrealease-3.14", result.First().Name);
Assert.Equal("Succeeded", result.First().Properties.ProvisioningState);
Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.First().Properties.Timestamp);
Assert.Equal(DeploymentMode.Incremental, result.First().Properties.Mode);
Assert.Equal("http://wa/template.json", result.First().Properties.TemplateLink.Uri.ToString());
Assert.Equal("1.0.0.0", result.First().Properties.TemplateLink.ContentVersion);
Assert.True(result.First().Properties.Parameters.ToString().Contains("\"type\": \"string\""));
Assert.True(result.First().Properties.Outputs.ToString().Contains("\"type\": \"string\""));
Assert.Equal("https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw", result.NextPageLink);
}
[Fact]
public void DeploymentTestListDoesNotThrowExceptions()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("{'value' : []}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.Deployments.List("foo");
Assert.Empty(result);
}
}
}
| |
using Microsoft.Xna.Framework;
namespace GlueTestProject.Entities
{
public enum TopDownDirection
{
Right = 0,
UpRight = 1,
Up = 2,
UpLeft = 3,
Left = 4,
DownLeft = 5,
Down = 6,
DownRight = 7
}
public static class TopDownDirectionExtensions
{
public static TopDownDirection FromDirection(Microsoft.Xna.Framework.Vector2 direction, PossibleDirections possibleDirections)
{
return FromDirection(direction.X, direction.Y, possibleDirections);
}
public static TopDownDirection FromDirection(Microsoft.Xna.Framework.Vector3 direction, PossibleDirections possibleDirections)
{
return FromDirection(direction.X, direction.Y, possibleDirections);
}
public static Microsoft.Xna.Framework.Vector3 ToVector(this TopDownDirection direction)
{
float diagonalLength = (float)System.Math.Cos( MathHelper.PiOver4 );
switch(direction)
{
case TopDownDirection.Left: return Vector3.Left;
case TopDownDirection.UpLeft: return new Vector3(-diagonalLength, diagonalLength, 0);
case TopDownDirection.Up: return Vector3.Up;
case TopDownDirection.UpRight: return new Vector3(diagonalLength, diagonalLength, 0);
case TopDownDirection.Right: return Vector3.Right;
case TopDownDirection.DownRight: return new Vector3(diagonalLength, -diagonalLength, 0);
case TopDownDirection.Down: return Vector3.Down;
case TopDownDirection.DownLeft: return new Vector3(-diagonalLength, -diagonalLength, 0);
}
return Vector3.Right;
}
public static TopDownDirection FlipX(this TopDownDirection directionToFlip)
{
switch(directionToFlip)
{
case TopDownDirection.Left: return TopDownDirection.Right;
case TopDownDirection.UpLeft: return TopDownDirection.UpRight;
case TopDownDirection.Up: return TopDownDirection.Up;
case TopDownDirection.UpRight: return TopDownDirection.UpLeft;
case TopDownDirection.Right: return TopDownDirection.Left;
case TopDownDirection.DownRight: return TopDownDirection.DownLeft;
case TopDownDirection.Down: return TopDownDirection.Down;
case TopDownDirection.DownLeft: return TopDownDirection.DownRight;
}
throw new System.Exception();
}
public static TopDownDirection FlipY(this TopDownDirection directionToFlip)
{
switch (directionToFlip)
{
case TopDownDirection.Left: return TopDownDirection.Left;
case TopDownDirection.UpLeft: return TopDownDirection.DownLeft;
case TopDownDirection.Up: return TopDownDirection.Down;
case TopDownDirection.UpRight: return TopDownDirection.DownRight;
case TopDownDirection.Right: return TopDownDirection.Right;
case TopDownDirection.DownRight: return TopDownDirection.UpRight;
case TopDownDirection.Down: return TopDownDirection.Up;
case TopDownDirection.DownLeft: return TopDownDirection.UpLeft;
}
throw new System.Exception();
}
public static TopDownDirection Mirror(this TopDownDirection directionToFlip)
{
switch (directionToFlip)
{
case TopDownDirection.Left: return TopDownDirection.Right;
case TopDownDirection.UpLeft: return TopDownDirection.DownRight;
case TopDownDirection.Up: return TopDownDirection.Down;
case TopDownDirection.UpRight: return TopDownDirection.DownLeft;
case TopDownDirection.Right: return TopDownDirection.Left;
case TopDownDirection.DownRight: return TopDownDirection.UpLeft;
case TopDownDirection.Down: return TopDownDirection.Up;
case TopDownDirection.DownLeft: return TopDownDirection.UpRight;
}
throw new System.Exception();
}
public static TopDownDirection FromDirection(float x, float y, PossibleDirections possibleDirections)
{
if(x == 0 && y == 0)
{
throw new System.Exception("Can't convert 0,0 to a direction");
}
switch (possibleDirections)
{
case PossibleDirections.LeftRight:
if (x > 0)
{
return TopDownDirection.Right;
}
else if (x < 0)
{
return TopDownDirection.Left;
}
break;
case PossibleDirections.FourWay:
var absXVelocity = System.Math.Abs(x);
var absYVelocity = System.Math.Abs(y);
if (absXVelocity > absYVelocity)
{
if (x > 0)
{
return TopDownDirection.Right;
}
else if (x < 0)
{
return TopDownDirection.Left;
}
}
else if (absYVelocity > absXVelocity)
{
if (y > 0)
{
return TopDownDirection.Up;
}
else if (y < 0)
{
return TopDownDirection.Down;
}
}
else // absx and absy are equal:
{
if(x > 0)
{
return TopDownDirection.Right;
}
else
{
return TopDownDirection.Left;
}
}
break;
case PossibleDirections.EightWay:
if (x != 0 || y != 0)
{
var angle = FlatRedBall.Math.MathFunctions.RegulateAngle(
(float)System.Math.Atan2(y, x));
var ratioOfCircle = angle / Microsoft.Xna.Framework.MathHelper.TwoPi;
var eights = FlatRedBall.Math.MathFunctions.RoundToInt(ratioOfCircle * 8) % 8;
return (TopDownDirection)eights;
}
break;
}
throw new System.Exception();
}
public static string ToFriendlyString(this TopDownDirection direction)
{
switch(direction)
{
case TopDownDirection.Down:
return nameof(TopDownDirection.Down);
case TopDownDirection.DownLeft:
return nameof(TopDownDirection.DownLeft);
case TopDownDirection.DownRight:
return nameof(TopDownDirection.DownRight);
case TopDownDirection.Left:
return nameof(TopDownDirection.Left);
case TopDownDirection.Right:
return nameof(TopDownDirection.Right);
case TopDownDirection.Up:
return nameof(TopDownDirection.Up);
case TopDownDirection.UpLeft:
return nameof(TopDownDirection.UpLeft);
case TopDownDirection.UpRight:
return nameof(TopDownDirection.UpRight);
}
return nameof(TopDownDirection.Down);
}
}
public enum PossibleDirections
{
LeftRight,
FourWay,
EightWay
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a single manifest resource file either embedded into the .NET assembly, or put into a separate file.
/// In this case, it contains also a reference to the file the resource is located in.
/// </summary>
public class ManifestResource :
MetadataMember,
INameProvider,
IHasCustomAttribute,
IOwnedCollectionElement<ModuleDefinition>
{
private readonly LazyVariable<Utf8String?> _name;
private readonly LazyVariable<IImplementation?> _implementation;
private readonly LazyVariable<ISegment?> _embeddedData;
private IList<CustomAttribute>? _customAttributes;
/// <summary>
/// Initializes the <see cref="ManifestResource"/> with a metadata token.
/// </summary>
/// <param name="token">The metadata token.</param>
protected ManifestResource(MetadataToken token)
: base(token)
{
_name = new LazyVariable<Utf8String?>(GetName);
_implementation = new LazyVariable<IImplementation?>(GetImplementation);
_embeddedData = new LazyVariable<ISegment?>(GetEmbeddedDataSegment);
}
/// <summary>
/// Creates a new external manifest resource.
/// </summary>
/// <param name="name">The name of the resource</param>
/// <param name="attributes">The attributes of the resource.</param>
/// <param name="implementation">The location of the resource data.</param>
/// <param name="offset">The offset within the file referenced by <paramref name="implementation"/> where the data starts.</param>
public ManifestResource(string? name, ManifestResourceAttributes attributes, IImplementation? implementation, uint offset)
: this(new MetadataToken(TableIndex.ManifestResource, 0))
{
Name = name;
Attributes = attributes;
Implementation = implementation;
Offset = offset;
}
/// <summary>
/// Creates a new embedded manifest resource.
/// </summary>
/// <param name="name">The name of the repository.</param>
/// <param name="attributes">The attributes of the resource.</param>
/// <param name="data">The embedded resource data.</param>
public ManifestResource(string? name, ManifestResourceAttributes attributes, ISegment? data)
: this(new MetadataToken(TableIndex.ManifestResource, 0))
{
Name = name;
Attributes = attributes;
EmbeddedDataSegment = data;
}
/// <summary>
/// Depending on the value of <see cref="Implementation"/>, gets or sets the (relative) offset the resource data
/// starts at.
/// </summary>
public uint Offset
{
get;
set;
}
/// <summary>
/// Gets or sets the attributes associated with this resource.
/// </summary>
public ManifestResourceAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether the resource is public and exported by the .NET module.
/// </summary>
public bool IsPublic
{
get => Attributes == ManifestResourceAttributes.Public;
set => Attributes = value ? ManifestResourceAttributes.Public : ManifestResourceAttributes.Private;
}
/// <summary>
/// Gets or sets a value indicating whether the resource is private to the .NET module.
/// </summary>
public bool IsPrivate
{
get => Attributes == ManifestResourceAttributes.Private;
set => Attributes = value ? ManifestResourceAttributes.Private : ManifestResourceAttributes.Public;
}
/// <summary>
/// Gets or sets the name of the manifest resource.
/// </summary>
/// <remarks>
/// This property corresponds to the Name column in the manifest resource table.
/// </remarks>
public Utf8String? Name
{
get => _name.Value;
set => _name.Value = value;
}
string? INameProvider.Name => Name;
/// <summary>
/// Gets or sets the implementation indicating the file containing the resource data.
/// </summary>
public IImplementation? Implementation
{
get => _implementation.Value;
set => _implementation.Value = value;
}
/// <summary>
/// Gets a value indicating whether the resource is embedded into the current module.
/// </summary>
public bool IsEmbedded => Implementation is null;
/// <summary>
/// When this resource is embedded into the current module, gets or sets the embedded resource data.
/// </summary>
public ISegment? EmbeddedDataSegment
{
get => _embeddedData.Value;
set => _embeddedData.Value = value;
}
/// <summary>
/// Gets the module that this manifest resource reference is stored in.
/// </summary>
public ModuleDefinition? Module
{
get;
private set;
}
/// <inheritdoc />
ModuleDefinition? IOwnedCollectionElement<ModuleDefinition>.Owner
{
get => Module;
set => Module = value;
}
/// <inheritdoc />
public IList<CustomAttribute> CustomAttributes
{
get
{
if (_customAttributes is null)
Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
return _customAttributes;
}
}
/// <summary>
/// Gets the data stored in the manifest resource.
/// </summary>
/// <returns>The data, or <c>null</c> if no data was stored or if the external resource was not found.</returns>
public byte[]? GetData()
{
// TODO: resolve external resources.
return EmbeddedDataSegment is IReadableSegment readableSegment
? readableSegment.ToArray()
: null;
}
/// <summary>
/// Gets the reader of stored data in the manifest resource.
/// </summary>
/// <returns>The reader, or <c>null</c> if no data was stored or if the external resource was not found.</returns>
[Obsolete("Use TryGetReader instead.")]
public BinaryStreamReader? GetReader()
{
// TODO: resolve external resources.
return EmbeddedDataSegment is IReadableSegment readableSegment
? readableSegment.CreateReader()
: null;
}
/// <summary>
/// Gets the reader of stored data in the manifest resource.
/// </summary>
public bool TryGetReader(out BinaryStreamReader reader)
{
// TODO: resolve external resources.
if (EmbeddedDataSegment is IReadableSegment readableSegment)
{
reader = readableSegment.CreateReader();
return true;
}
reader = default;
return false;
}
/// <summary>
/// Obtains the name of the manifest resource.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual Utf8String? GetName() => null;
/// <summary>
/// Obtains the implementation of this resource.
/// </summary>
/// <returns>The implementation.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Implementation"/> property.
/// </remarks>
protected virtual IImplementation? GetImplementation() => null;
/// <summary>
/// When the resource is embedded, obtains the contents of the manifest resource.
/// </summary>
/// <returns>The data, or <c>null</c> if the resource is not embedded.</returns>
protected virtual ISegment? GetEmbeddedDataSegment() => null;
/// <summary>
/// Obtains the list of custom attributes assigned to the member.
/// </summary>
/// <returns>The attributes</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="CustomAttributes"/> property.
/// </remarks>
protected virtual IList<CustomAttribute> GetCustomAttributes() =>
new OwnedCollection<IHasCustomAttribute, CustomAttribute>(this);
/// <inheritdoc />
public override string ToString() => Name ?? NullName;
}
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trinity.Utilities.IO
{
enum DataFieldType
{
Double, Float, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, String
}
struct DataCellUnion
{
public double[][] DoubleCells;
public float[][] FloatCells;
public byte[][] ByteCells;
public sbyte[][] SByteCells;
public Int16[][] Int16Cells;
public UInt16[][] UInt16Cells;
public Int32[][] Int32Cells;
public UInt32[][] UInt32Cells;
public Int64[][] Int64Cells;
public UInt64[][] UInt64Cells;
public string[][] StringCells;
}
internal class DataTable
{
string[][] Cells;
string[] Header;
string DataFile;
bool WithHeader;
bool IsLargeFile;
char[] Separators;
int[] SkipColumns;
int StartLine = 0;
public int FieldCount = 0;
public int RecordCount = 0;
public DataTable(string file, char[] separators, int[] skipColumns = null, bool withHeader = false, bool isLargeFile = false)
{
DataFile = file;
WithHeader = withHeader;
IsLargeFile = isLargeFile;
Separators = separators;
SkipColumns = skipColumns;
}
public void Load()
{
if (!IsLargeFile)
{
StartLine = 0;
string[] lines = File.ReadAllLines(DataFile);
if (lines.Length == 0)
{
Console.Error.WriteLine("No data is found in {0}.", DataFile);
return;
}
if (WithHeader)
{
StartLine = 1;
Header = lines[0].Split(Separators);
}
if (lines.Length <= StartLine)
{
Console.Error.WriteLine("No data is found in {0}.", DataFile);
return;
}
string probe_line = lines[StartLine];
string[] probe_fields = probe_line.Split(Separators);
if (WithHeader && Header.Length != probe_fields.Length)
{
Console.Error.WriteLine("Header and data do not match: header has {0} fields, data has {1} fields.", Header.Length, probe_fields.Length);
}
int AllFieldCount = probe_fields.Length;
FieldCount = AllFieldCount - SkipColumns.Length;
RecordCount = lines.Length - StartLine;
int[] columnIndexes = new int[FieldCount];
int p = 0;
Console.WriteLine("Selected columns:");
for (int j = 0; j < AllFieldCount; j++)
{
if (SkipColumns == null || (!SkipColumns.Contains(j)))
{
columnIndexes[p++] = j;
Console.Write("{0} ", j);
}
}
Console.WriteLine();
Cells = new string[RecordCount][];
for (int i = 0; i < RecordCount; i++)
{
string[] temp = lines[StartLine + i].Split(Separators);
Cells[i] = new string[FieldCount];
p = 0;
foreach (int j in columnIndexes)
{
if (temp.Length != AllFieldCount)
{
Console.Error.WriteLine("Data file line {0} does not match the detected data format.", i);
}
else
{
Cells[i][p++] = temp[j];
}
}
}
Console.WriteLine("Loaded {0} lines from {1}.", RecordCount, DataFile);
}
else
{
throw new NotImplementedException();
}
}
public DataCellUnion Convert(DataFieldType dataType)
{
DataCellUnion dataUnion = new DataCellUnion();
switch (dataType)
{
case DataFieldType.Double:
dataUnion.DoubleCells = new double[RecordCount][];
for (int i = 0; i < RecordCount; i++)
{
dataUnion.DoubleCells[i] = new double[FieldCount];
for (int j = 0; j < FieldCount; j++)
{
double value = 0.0d;
if (!double.TryParse(Cells[i][j], out value))
{
Console.Error.WriteLine("Warning: cannot parse data cell {0}({1}, {2}), set its value = 0.0", Cells[i][j], i, j);
}
dataUnion.DoubleCells[i][j] = value;
}
}
Console.WriteLine("Convert the loaded {0} cells to double values.", RecordCount * FieldCount);
break;
case DataFieldType.Float:
dataUnion.FloatCells = new float[RecordCount][];
for (int i = 0; i < RecordCount; i++)
{
dataUnion.FloatCells[i] = new float[FieldCount];
for (int j = 0; j < FieldCount; j++)
{
float value = 0.0f;
if (!float.TryParse(Cells[i][j], out value))
{
Console.Error.WriteLine("Warning: cannot parse data cell {0}({1}, {2}), set its value = 0.0", Cells[i][j], i, j);
}
dataUnion.FloatCells[i][j] = value;
}
}
Console.WriteLine("Convert the loaded {0} cells to float values.", RecordCount * FieldCount);
break;
case DataFieldType.Byte:
dataUnion.ByteCells = new byte[RecordCount][];
for (int i = 0; i < RecordCount; i++)
{
dataUnion.ByteCells[i] = new byte[FieldCount];
for (int j = 0; j < FieldCount; j++)
{
byte value = 0;
if (!byte.TryParse(Cells[i][j], out value))
{
Console.Error.WriteLine("Warning: cannot parse data cell {0}({1}, {2}), set its value = 0.0", Cells[i][j], i, j);
}
dataUnion.ByteCells[i][j] = value;
}
}
Console.WriteLine("Convert the loaded {0} cells to byte values.", RecordCount * FieldCount);
break;
case DataFieldType.SByte:
dataUnion.SByteCells = new sbyte[RecordCount][];
for (int i = 0; i < RecordCount; i++)
{
dataUnion.SByteCells[i] = new sbyte[FieldCount];
for (int j = 0; j < FieldCount; j++)
{
sbyte value = 0;
if (!sbyte.TryParse(Cells[i][j], out value))
{
Console.Error.WriteLine("Warning: cannot parse data cell {0}({1}, {2}), set its value = 0.0", Cells[i][j], i, j);
}
dataUnion.SByteCells[i][j] = value;
}
}
Console.WriteLine("Convert the loaded {0} cells to signed byte values.", RecordCount * FieldCount);
break;
case DataFieldType.Int16:
dataUnion.Int16Cells = new Int16[RecordCount][];
for (int i = 0; i < RecordCount; i++)
{
dataUnion.Int16Cells[i] = new Int16[FieldCount];
for (int j = 0; j < FieldCount; j++)
{
Int16 value = 0;
if (!Int16.TryParse(Cells[i][j], out value))
{
Console.Error.WriteLine("Warning: cannot parse data cell {0}({1}, {2}), set its value = 0.0", Cells[i][j], i, j);
}
dataUnion.Int16Cells[i][j] = value;
}
}
Console.WriteLine("Convert the loaded {0} cells to Int16 values.", RecordCount * FieldCount);
break;
case DataFieldType.UInt16:
dataUnion.UInt16Cells = new UInt16[RecordCount][];
for (int i = 0; i < RecordCount; i++)
{
dataUnion.UInt16Cells[i] = new UInt16[FieldCount];
for (int j = 0; j < FieldCount; j++)
{
UInt16 value = 0;
if (!UInt16.TryParse(Cells[i][j], out value))
{
Console.Error.WriteLine("Warning: cannot parse data cell {0}({1}, {2}), set its value = 0.0", Cells[i][j], i, j);
}
dataUnion.UInt16Cells[i][j] = value;
}
}
Console.WriteLine("Convert the loaded {0} cells to UInt16 values.", RecordCount * FieldCount);
break;
case DataFieldType.Int32:
dataUnion.Int32Cells = new Int32[RecordCount][];
for (int i = 0; i < RecordCount; i++)
{
dataUnion.Int32Cells[i] = new Int32[FieldCount];
for (int j = 0; j < FieldCount; j++)
{
Int32 value = 0;
if (!Int32.TryParse(Cells[i][j], out value))
{
Console.Error.WriteLine("Warning: cannot parse data cell {0}({1}, {2}), set its value = 0.0", Cells[i][j], i, j);
}
dataUnion.Int32Cells[i][j] = value;
}
}
Console.WriteLine("Convert the loaded {0} cells to Int32 values.", RecordCount * FieldCount);
break;
case DataFieldType.UInt32:
dataUnion.UInt32Cells = new UInt32[RecordCount][];
for (int i = 0; i < RecordCount; i++)
{
dataUnion.UInt32Cells[i] = new UInt32[FieldCount];
for (int j = 0; j < FieldCount; j++)
{
UInt32 value = 0;
if (!UInt32.TryParse(Cells[i][j], out value))
{
Console.Error.WriteLine("Warning: cannot parse data cell {0}({1}, {2}), set its value = 0.0", Cells[i][j], i, j);
}
dataUnion.UInt32Cells[i][j] = value;
}
}
Console.WriteLine("Convert the loaded {0} cells to UInt32 values.", RecordCount * FieldCount);
break;
case DataFieldType.Int64:
dataUnion.Int64Cells = new Int64[RecordCount][];
for (int i = 0; i < RecordCount; i++)
{
dataUnion.Int64Cells[i] = new Int64[FieldCount];
for (int j = 0; j < FieldCount; j++)
{
Int64 value = 0;
if (!Int64.TryParse(Cells[i][j], out value))
{
Console.Error.WriteLine("Warning: cannot parse data cell {0}({1}, {2}), set its value = 0.0", Cells[i][j], i, j);
}
dataUnion.Int64Cells[i][j] = value;
}
}
Console.WriteLine("Convert the loaded {0} cells to Int64 values.", RecordCount * FieldCount);
break;
case DataFieldType.UInt64:
dataUnion.UInt64Cells = new UInt64[RecordCount][];
for (int i = 0; i < RecordCount; i++)
{
dataUnion.UInt64Cells[i] = new UInt64[FieldCount];
for (int j = 0; j < FieldCount; j++)
{
UInt64 value = 0;
if (!UInt64.TryParse(Cells[i][j], out value))
{
Console.Error.WriteLine("Warning: cannot parse data cell {0}({1}, {2}), set its value = 0.0", Cells[i][j], i, j);
}
dataUnion.UInt64Cells[i][j] = value;
}
}
Console.WriteLine("Convert the loaded {0} cells to UInt64 values.", RecordCount * FieldCount);
break;
default:
dataUnion.StringCells = Cells;
Console.WriteLine("Convert the loaded {0} cells to string values.", RecordCount * FieldCount);
break;
}
return dataUnion;
}
public void Peek(int maxRow)
{
for (int i = 0; i < maxRow; i++)
{
for (int j = 0; j < FieldCount; j++)
{
Console.Write("{0}\t", Cells[i][j]);
}
Console.WriteLine();
}
}
}
}
| |
using XenAdmin.Controls.DataGridViewEx;
namespace XenAdmin.Wizards.PatchingWizard
{
partial class PatchingWizard_SelectPatchPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PatchingWizard_SelectPatchPage));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle7 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.labelWithoutAutomatedUpdates = new System.Windows.Forms.Label();
this.labelWithAutomatedUpdates = new System.Windows.Forms.Label();
this.AutomatedUpdatesRadioButton = new System.Windows.Forms.RadioButton();
this.automatedUpdatesOptionLabel = new System.Windows.Forms.Label();
this.downloadUpdateRadioButton = new System.Windows.Forms.RadioButton();
this.RefreshListButton = new System.Windows.Forms.Button();
this.RestoreDismUpdatesButton = new System.Windows.Forms.Button();
this.selectFromDiskRadioButton = new System.Windows.Forms.RadioButton();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.label2 = new System.Windows.Forms.Label();
this.fileNameTextBox = new System.Windows.Forms.TextBox();
this.BrowseButton = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.tableLayoutPanelSpinner = new System.Windows.Forms.TableLayoutPanel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.label1 = new System.Windows.Forms.Label();
this.dataGridViewPatches = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx();
this.ColumnUpdate = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnDescription = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnDate = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.webPageColumn = new System.Windows.Forms.DataGridViewLinkColumn();
this._backgroundWorker = new System.ComponentModel.BackgroundWorker();
this.tableLayoutPanel1.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.panel1.SuspendLayout();
this.tableLayoutPanelSpinner.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewPatches)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.labelWithoutAutomatedUpdates, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.labelWithAutomatedUpdates, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.AutomatedUpdatesRadioButton, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.automatedUpdatesOptionLabel, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.downloadUpdateRadioButton, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.RefreshListButton, 1, 6);
this.tableLayoutPanel1.Controls.Add(this.RestoreDismUpdatesButton, 2, 6);
this.tableLayoutPanel1.Controls.Add(this.selectFromDiskRadioButton, 0, 7);
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 1, 8);
this.tableLayoutPanel1.Controls.Add(this.panel1, 1, 5);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// labelWithoutAutomatedUpdates
//
resources.ApplyResources(this.labelWithoutAutomatedUpdates, "labelWithoutAutomatedUpdates");
this.tableLayoutPanel1.SetColumnSpan(this.labelWithoutAutomatedUpdates, 3);
this.labelWithoutAutomatedUpdates.Name = "labelWithoutAutomatedUpdates";
//
// labelWithAutomatedUpdates
//
resources.ApplyResources(this.labelWithAutomatedUpdates, "labelWithAutomatedUpdates");
this.tableLayoutPanel1.SetColumnSpan(this.labelWithAutomatedUpdates, 3);
this.labelWithAutomatedUpdates.Name = "labelWithAutomatedUpdates";
//
// AutomatedUpdatesRadioButton
//
resources.ApplyResources(this.AutomatedUpdatesRadioButton, "AutomatedUpdatesRadioButton");
this.AutomatedUpdatesRadioButton.Checked = true;
this.tableLayoutPanel1.SetColumnSpan(this.AutomatedUpdatesRadioButton, 3);
this.AutomatedUpdatesRadioButton.Name = "AutomatedUpdatesRadioButton";
this.AutomatedUpdatesRadioButton.TabStop = true;
this.AutomatedUpdatesRadioButton.UseVisualStyleBackColor = true;
this.AutomatedUpdatesRadioButton.CheckedChanged += new System.EventHandler(this.AutomaticRadioButton_CheckedChanged);
this.AutomatedUpdatesRadioButton.TabStopChanged += new System.EventHandler(this.AutomaticRadioButton_TabStopChanged);
//
// automatedUpdatesOptionLabel
//
resources.ApplyResources(this.automatedUpdatesOptionLabel, "automatedUpdatesOptionLabel");
this.tableLayoutPanel1.SetColumnSpan(this.automatedUpdatesOptionLabel, 2);
this.automatedUpdatesOptionLabel.Name = "automatedUpdatesOptionLabel";
//
// downloadUpdateRadioButton
//
resources.ApplyResources(this.downloadUpdateRadioButton, "downloadUpdateRadioButton");
this.tableLayoutPanel1.SetColumnSpan(this.downloadUpdateRadioButton, 3);
this.downloadUpdateRadioButton.Name = "downloadUpdateRadioButton";
this.downloadUpdateRadioButton.UseVisualStyleBackColor = true;
this.downloadUpdateRadioButton.CheckedChanged += new System.EventHandler(this.downloadUpdateRadioButton_CheckedChanged);
this.downloadUpdateRadioButton.TabStopChanged += new System.EventHandler(this.downloadUpdateRadioButton_TabStopChanged);
//
// RefreshListButton
//
resources.ApplyResources(this.RefreshListButton, "RefreshListButton");
this.RefreshListButton.Name = "RefreshListButton";
this.RefreshListButton.UseVisualStyleBackColor = true;
this.RefreshListButton.Click += new System.EventHandler(this.RefreshListButton_Click);
//
// RestoreDismUpdatesButton
//
resources.ApplyResources(this.RestoreDismUpdatesButton, "RestoreDismUpdatesButton");
this.RestoreDismUpdatesButton.Name = "RestoreDismUpdatesButton";
this.RestoreDismUpdatesButton.UseVisualStyleBackColor = true;
this.RestoreDismUpdatesButton.Click += new System.EventHandler(this.RestoreDismUpdatesButton_Click);
//
// selectFromDiskRadioButton
//
resources.ApplyResources(this.selectFromDiskRadioButton, "selectFromDiskRadioButton");
this.tableLayoutPanel1.SetColumnSpan(this.selectFromDiskRadioButton, 3);
this.selectFromDiskRadioButton.Name = "selectFromDiskRadioButton";
this.selectFromDiskRadioButton.UseVisualStyleBackColor = true;
this.selectFromDiskRadioButton.CheckedChanged += new System.EventHandler(this.selectFromDiskRadioButton_CheckedChanged);
this.selectFromDiskRadioButton.TabStopChanged += new System.EventHandler(this.selectFromDiskRadioButton_TabStopChanged);
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel1.SetColumnSpan(this.tableLayoutPanel2, 2);
this.tableLayoutPanel2.Controls.Add(this.label2, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.fileNameTextBox, 1, 0);
this.tableLayoutPanel2.Controls.Add(this.BrowseButton, 2, 0);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// fileNameTextBox
//
resources.ApplyResources(this.fileNameTextBox, "fileNameTextBox");
this.fileNameTextBox.Name = "fileNameTextBox";
this.fileNameTextBox.TextChanged += new System.EventHandler(this.fileNameTextBox_TextChanged);
this.fileNameTextBox.Enter += new System.EventHandler(this.fileNameTextBox_Enter);
//
// BrowseButton
//
resources.ApplyResources(this.BrowseButton, "BrowseButton");
this.BrowseButton.Name = "BrowseButton";
this.BrowseButton.UseVisualStyleBackColor = true;
this.BrowseButton.Click += new System.EventHandler(this.BrowseButton_Click);
//
// panel1
//
this.tableLayoutPanel1.SetColumnSpan(this.panel1, 2);
this.panel1.Controls.Add(this.tableLayoutPanelSpinner);
this.panel1.Controls.Add(this.dataGridViewPatches);
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Name = "panel1";
//
// tableLayoutPanelSpinner
//
resources.ApplyResources(this.tableLayoutPanelSpinner, "tableLayoutPanelSpinner");
this.tableLayoutPanelSpinner.BackColor = System.Drawing.SystemColors.Window;
this.tableLayoutPanelSpinner.Controls.Add(this.pictureBox1, 0, 0);
this.tableLayoutPanelSpinner.Controls.Add(this.label1, 1, 0);
this.tableLayoutPanelSpinner.Name = "tableLayoutPanelSpinner";
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.SystemColors.Window;
this.pictureBox1.Image = global::XenAdmin.Properties.Resources.ajax_loader;
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.BackColor = System.Drawing.SystemColors.Window;
this.label1.Name = "label1";
//
// dataGridViewPatches
//
this.dataGridViewPatches.AllowUserToResizeColumns = false;
this.dataGridViewPatches.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
this.dataGridViewPatches.BackgroundColor = System.Drawing.SystemColors.Window;
this.dataGridViewPatches.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.dataGridViewPatches.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.dataGridViewPatches.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnUpdate,
this.ColumnDescription,
this.ColumnDate,
this.webPageColumn});
dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle5.BackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle5.ForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle5.SelectionBackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle5.SelectionForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle5.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dataGridViewPatches.DefaultCellStyle = dataGridViewCellStyle5;
resources.ApplyResources(this.dataGridViewPatches, "dataGridViewPatches");
this.dataGridViewPatches.HideSelection = true;
this.dataGridViewPatches.Name = "dataGridViewPatches";
this.dataGridViewPatches.ReadOnly = true;
dataGridViewCellStyle6.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle6.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle6.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle6.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle6.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle6.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dataGridViewPatches.RowHeadersDefaultCellStyle = dataGridViewCellStyle6;
dataGridViewCellStyle7.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridViewPatches.RowsDefaultCellStyle = dataGridViewCellStyle7;
this.dataGridViewPatches.RowTemplate.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridViewPatches.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridViewPatches_CellContentClick);
this.dataGridViewPatches.SelectionChanged += new System.EventHandler(this.dataGridViewPatches_SelectionChanged);
this.dataGridViewPatches.SortCompare += new System.Windows.Forms.DataGridViewSortCompareEventHandler(this.dataGridViewPatches_SortCompare);
this.dataGridViewPatches.Enter += new System.EventHandler(this.dataGridViewPatches_Enter);
//
// ColumnUpdate
//
this.ColumnUpdate.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.ColumnUpdate.DefaultCellStyle = dataGridViewCellStyle1;
this.ColumnUpdate.FillWeight = 76.67365F;
resources.ApplyResources(this.ColumnUpdate, "ColumnUpdate");
this.ColumnUpdate.Name = "ColumnUpdate";
this.ColumnUpdate.ReadOnly = true;
//
// ColumnDescription
//
this.ColumnDescription.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft;
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.ColumnDescription.DefaultCellStyle = dataGridViewCellStyle2;
this.ColumnDescription.FillWeight = 172.4619F;
resources.ApplyResources(this.ColumnDescription, "ColumnDescription");
this.ColumnDescription.Name = "ColumnDescription";
this.ColumnDescription.ReadOnly = true;
//
// ColumnDate
//
this.ColumnDate.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft;
dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.ColumnDate.DefaultCellStyle = dataGridViewCellStyle3;
this.ColumnDate.FillWeight = 80F;
resources.ApplyResources(this.ColumnDate, "ColumnDate");
this.ColumnDate.Name = "ColumnDate";
this.ColumnDate.ReadOnly = true;
//
// webPageColumn
//
this.webPageColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft;
dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.webPageColumn.DefaultCellStyle = dataGridViewCellStyle4;
this.webPageColumn.FillWeight = 60F;
resources.ApplyResources(this.webPageColumn, "webPageColumn");
this.webPageColumn.Name = "webPageColumn";
this.webPageColumn.ReadOnly = true;
this.webPageColumn.Resizable = System.Windows.Forms.DataGridViewTriState.True;
//
// _backgroundWorker
//
this._backgroundWorker.WorkerSupportsCancellation = true;
this._backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this._backgroundWorker_DoWork);
this._backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this._backgroundWorker_RunWorkerCompleted);
//
// PatchingWizard_SelectPatchPage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "PatchingWizard_SelectPatchPage";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.tableLayoutPanelSpinner.ResumeLayout(false);
this.tableLayoutPanelSpinner.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewPatches)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button BrowseButton;
private DataGridViewEx dataGridViewPatches;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox fileNameTextBox;
private System.Windows.Forms.RadioButton selectFromDiskRadioButton;
private System.Windows.Forms.Button RefreshListButton;
private System.Windows.Forms.RadioButton downloadUpdateRadioButton;
private System.Windows.Forms.Label labelWithAutomatedUpdates;
private System.Windows.Forms.Button RestoreDismUpdatesButton;
private System.Windows.Forms.Label automatedUpdatesOptionLabel;
private System.Windows.Forms.RadioButton AutomatedUpdatesRadioButton;
private System.Windows.Forms.Label labelWithoutAutomatedUpdates;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelSpinner;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnUpdate;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDescription;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDate;
private System.Windows.Forms.DataGridViewLinkColumn webPageColumn;
private System.ComponentModel.BackgroundWorker _backgroundWorker;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using BeWellApi.Data;
using BeWellApi.Models;
using BeWellApi.Models.ActivityViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
namespace BeWellApi.Controllers
{
[Authorize]
[Produces("application/json")]
[EnableCors("AllowDevelopmentEnvironment")]
public class ActivityController : Controller
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
public ActivityController(UserManager<ApplicationUser> userManager, ApplicationDbContext context)
{
_userManager = userManager;
_context = context;
}
private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
[HttpGet]
[Route("Activities/{IsMeditation}")]
//If meditations are wanted then IsMeditation should be 1. If other activities are wanted then IsMeditation should be 0. This is for users to see all of the meditations and other activities on the menu.
public async Task<IActionResult> GetActivities(int IsMeditation)
{
if (IsMeditation == 1)
{
var meditations = _context.Activity.Where(a => a.IsMeditation == true).ToList();
return Json(meditations);
}
else if (IsMeditation == 0)
{
var user = await GetCurrentUserAsync();
var activities = _context.Activity.Where(a => a.IsMeditation == false && (a.User == user || a.User == null)).ToList();
return Json(activities);
}
else
{
return BadRequest();
}
}
[HttpGet("{id}")]
[Route("Activity/{id}")]
//This will be utilized when an activity is needed as part of the three suggested activities
public async Task<IActionResult> GetActivity([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Activity activity = await _context.Activity.SingleOrDefaultAsync(m => m.ActivityId == id);
if (activity == null)
{
return NotFound();
}
return Json(activity);
}
[HttpPost]
[Route("AddActivity")]
public async Task<IActionResult> PostActivity([FromBody] NewActivityViewModel activity)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = await GetCurrentUserAsync();
Activity UserActivity = new Activity
{
Name = activity.Name,
Description = activity.Description,
PointValue = activity.PointValue,
UserAdded = true,
IsMeditation = false,
PhysicalMax = 2,
PhysicalMin = -2,
User = user
};
_context.Activity.Add(UserActivity);
try
{
await _context.SaveChangesAsync();
foreach (int e in activity.Emotions)
{
EmotionActivity emotion = new EmotionActivity
{
ActivityId = _context.Activity.Single(a => a.ActivityId == UserActivity.ActivityId).ActivityId,
EmotionId = _context.Emotion.Single(s => s.EmotionId == e).EmotionId
};
_context.EmotionActivity.Add(emotion);
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
throw;
}
}
catch (DbUpdateException)
{
if (ActivityExists(UserActivity.ActivityId))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtAction("GetActivity", new { id = UserActivity.ActivityId }, activity);
}
// NEED TO IMPLEMENT
[HttpPut("{id}")]
[Route("EditActivity/{id}")]
public async Task<IActionResult> PutActivity([FromRoute] int id, [FromBody]NewActivityViewModel activity)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != activity.ActivityId)
{
return BadRequest();
}
_context.Entry(activity).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ActivityExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
[HttpDelete("{id}")]
[Route("DeleteActivity/{id}")]
public async Task<IActionResult> DeleteActivity([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Activity activity = await _context.Activity.SingleOrDefaultAsync(m => m.ActivityId == id);
var EmotionActivities = await _context.EmotionActivity.Where(e => e.ActivityId == id).ToListAsync();
if (activity == null)
{
return NotFound();
}
_context.Activity.Remove(activity);
await _context.SaveChangesAsync();
if (EmotionActivities.Count() != 0)
{
foreach (var e in EmotionActivities)
{
_context.EmotionActivity.Remove(e);
}
}
await _context.SaveChangesAsync();
return Ok(activity);
}
[HttpPost]
[Route("SaveActivity/{id}")]
public async Task<IActionResult> SaveActivity([FromRoute] int id)
{
var activity = _context.Activity.Single(a => a.ActivityId == id);
if (activity == null)
{
return BadRequest();
}
var user = await GetCurrentUserAsync();
SavedActivity savedActivity = new SavedActivity
{
User = user,
ActivityId = id
};
_context.SavedActivity.Add(savedActivity);
await _context.SaveChangesAsync();
return Ok(savedActivity);
}
private bool ActivityExists(int id)
{
return _context.Activity.Any(e => e.ActivityId == id);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ClusterClientSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Akka.Actor;
using Akka.Cluster.TestKit;
using Akka.Cluster.Tools.Client;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Cluster.Tools.PublishSubscribe.Internal;
using Akka.Configuration;
using Akka.Remote.TestKit;
using Akka.Remote.Transport;
using Akka.Util.Internal;
using FluentAssertions;
namespace Akka.Cluster.Tools.Tests.MultiNode.Client
{
public class ClusterClientSpecConfig : MultiNodeConfig
{
public RoleName Client { get; }
public RoleName First { get; }
public RoleName Second { get; }
public RoleName Third { get; }
public RoleName Fourth { get; }
public ClusterClientSpecConfig()
{
Client = Role("client");
First = Role("first");
Second = Role("second");
Third = Role("third");
Fourth = Role("fourth");
CommonConfig = ConfigurationFactory.ParseString(@"
akka.loglevel = DEBUG
akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
akka.remote.log-remote-lifecycle-events = off
akka.cluster.auto-down-unreachable-after = 0s
akka.cluster.client.heartbeat-interval = 1s
akka.cluster.client.acceptable-heartbeat-pause = 3s
akka.cluster.client.refresh-contacts-interval = 1s
# number-of-contacts must be >= 4 because we shutdown all but one in the end
akka.cluster.client.receptionist.number-of-contacts = 4
akka.cluster.client.receptionist.heartbeat-interval = 10s
akka.cluster.client.receptionist.acceptable-heartbeat-pause = 10s
akka.cluster.client.receptionist.failure-detection-interval = 1s
akka.test.filter-leeway = 10s
")
.WithFallback(ClusterClientReceptionist.DefaultConfig())
.WithFallback(DistributedPubSub.DefaultConfig());
TestTransport = true;
}
#region Helpers
public class Reply
{
public Reply(object msg, Address node)
{
Msg = msg;
Node = node;
}
public object Msg { get; }
public Address Node { get; }
}
public class TestService : ReceiveActor
{
public TestService(IActorRef testActorRef)
{
Receive<string>(cmd => cmd.Equals("shutdown"), msg =>
{
Context.System.Terminate();
});
ReceiveAny(msg =>
{
testActorRef.Forward(msg);
Sender.Tell(new Reply(msg.ToString() + "-ack", Cluster.Get(Context.System).SelfAddress));
});
}
}
public class Service : ReceiveActor
{
public Service()
{
ReceiveAny(msg => Sender.Tell(msg));
}
}
public class TestClientListener : ReceiveActor
{
#region TestClientListener messages
public sealed class GetLatestContactPoints
{
public static readonly GetLatestContactPoints Instance = new GetLatestContactPoints();
private GetLatestContactPoints() { }
}
public sealed class LatestContactPoints : INoSerializationVerificationNeeded
{
public LatestContactPoints(ImmutableHashSet<ActorPath> contactPoints)
{
ContactPoints = contactPoints;
}
public ImmutableHashSet<ActorPath> ContactPoints { get; }
}
#endregion
private readonly IActorRef _targetClient;
private ImmutableHashSet<ActorPath> _contactPoints;
public TestClientListener(IActorRef targetClient)
{
_targetClient = targetClient;
_contactPoints = ImmutableHashSet<ActorPath>.Empty;
Receive<GetLatestContactPoints>(_ =>
{
Sender.Tell(new LatestContactPoints(_contactPoints));
});
Receive<ContactPoints>(cps =>
{
// Now do something with the up-to-date "cps"
_contactPoints = cps.ContactPointsList;
});
Receive<ContactPointAdded>(cp =>
{
// Now do something with an up-to-date "contactPoints + cp"
_contactPoints = _contactPoints.Add(cp.ContactPoint);
});
Receive<ContactPointRemoved>(cp =>
{
// Now do something with an up-to-date "contactPoints - cp"
_contactPoints = _contactPoints.Remove(cp.ContactPoint);
});
}
protected override void PreStart()
{
_targetClient.Tell(SubscribeContactPoints.Instance);
}
}
public class TestReceptionistListener : ReceiveActor
{
#region TestReceptionistListener messages
public sealed class GetLatestClusterClients
{
public static readonly GetLatestClusterClients Instance = new GetLatestClusterClients();
private GetLatestClusterClients() { }
}
public sealed class LatestClusterClients : INoSerializationVerificationNeeded
{
public LatestClusterClients(ImmutableHashSet<IActorRef> clusterClients)
{
ClusterClients = clusterClients;
}
public ImmutableHashSet<IActorRef> ClusterClients { get; }
}
#endregion
private readonly IActorRef _targetReceptionist;
private ImmutableHashSet<IActorRef> _clusterClients;
public TestReceptionistListener(IActorRef targetReceptionist)
{
_targetReceptionist = targetReceptionist;
_clusterClients = ImmutableHashSet<IActorRef>.Empty;
Receive<GetLatestClusterClients>(_ =>
{
Sender.Tell(new LatestClusterClients(_clusterClients));
});
Receive<ClusterClients>(cs =>
{
// Now do something with the up-to-date "c"
_clusterClients = cs.ClusterClientsList;
});
Receive<ClusterClientUp>(c =>
{
// Now do something with an up-to-date "clusterClients + c"
_clusterClients = _clusterClients.Add(c.ClusterClient);
});
Receive<ClusterClientUnreachable>(c =>
{
// Now do something with an up-to-date "clusterClients - c"
_clusterClients = _clusterClients.Remove(c.ClusterClient);
});
}
protected override void PreStart()
{
_targetReceptionist.Tell(SubscribeClusterClients.Instance);
}
}
#endregion
}
public class ClusterClientMultiNode1 : ClusterClientSpec { }
public class ClusterClientMultiNode2 : ClusterClientSpec { }
public class ClusterClientMultiNode3 : ClusterClientSpec { }
public class ClusterClientMultiNode4 : ClusterClientSpec { }
public class ClusterClientMultiNode5 : ClusterClientSpec { }
public abstract class ClusterClientSpec : MultiNodeClusterSpec
{
private readonly ClusterClientSpecConfig _config;
protected ClusterClientSpec() : this(new ClusterClientSpecConfig())
{
}
protected ClusterClientSpec(ClusterClientSpecConfig config) : base(config)
{
_config = config;
_remainingServerRoleNames = ImmutableHashSet.Create(_config.First, _config.Second, _config.Third, _config.Fourth);
}
protected override int InitialParticipantsValueFactory
{
get { return Roles.Count; }
}
private void Join(RoleName from, RoleName to)
{
RunOn(() =>
{
Cluster.Join(Node(to).Address);
CreateReceptionist();
}, from);
EnterBarrier(from.Name + "-joined");
}
private void CreateReceptionist()
{
ClusterClientReceptionist.Get(Sys);
}
private void AwaitCount(int expected)
{
AwaitAssert(() =>
{
DistributedPubSub.Get(Sys).Mediator.Tell(Count.Instance);
ExpectMsg<int>().Should().Be(expected);
});
}
private RoleName GetRoleName(Address address)
{
return _remainingServerRoleNames.FirstOrDefault(r => Node(r).Address.Equals(address));
}
private ImmutableHashSet<RoleName> _remainingServerRoleNames;
private ImmutableHashSet<ActorPath> InitialContacts
{
get
{
return _remainingServerRoleNames.Remove(_config.First).Remove(_config.Fourth).Select(r => Node(r) / "system" / "receptionist").ToImmutableHashSet();
}
}
[MultiNodeFact]
public void ClusterClientSpecs()
{
ClusterClient_must_startup_cluster();
ClusterClient_must_communicate_to_any_node_in_cluster();
ClusterClient_must_demonstrate_usage();
ClusterClient_must_report_events();
ClusterClient_must_reestablish_connection_to_another_receptionist_when_server_is_shutdown();
ClusterClient_must_reestablish_connection_to_receptionist_after_partition();
//ClusterClient_must_reestablish_connection_to_receptionist_after_server_restart();
}
public void ClusterClient_must_startup_cluster()
{
Within(30.Seconds(), () =>
{
Join(_config.First, _config.First);
Join(_config.Second, _config.First);
Join(_config.Third, _config.First);
Join(_config.Fourth, _config.First);
RunOn(() =>
{
var service = Sys.ActorOf(Props.Create(() => new ClusterClientSpecConfig.TestService(TestActor)), "testService");
ClusterClientReceptionist.Get(Sys).RegisterService(service);
}, _config.Fourth);
RunOn(() =>
{
AwaitCount(1);
}, _config.First, _config.Second, _config.Third, _config.Fourth);
EnterBarrier("after-1");
});
}
public void ClusterClient_must_communicate_to_any_node_in_cluster()
{
Within(10.Seconds(), () =>
{
RunOn(() =>
{
var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client1");
c.Tell(new ClusterClient.Send("/user/testService", "hello", localAffinity: true));
ExpectMsg<ClusterClientSpecConfig.Reply>().Msg.Should().Be("hello-ack");
Sys.Stop(c);
}, _config.Client);
RunOn(() =>
{
ExpectMsg("hello");
}, _config.Fourth);
EnterBarrier("after-2");
});
}
public void ClusterClient_must_demonstrate_usage()
{
var host1 = _config.First;
var host2 = _config.Second;
var host3 = _config.Third;
Within(15.Seconds(), () =>
{
//#server
RunOn(() =>
{
var serviceA = Sys.ActorOf(Props.Create<ClusterClientSpecConfig.Service>(), "serviceA");
ClusterClientReceptionist.Get(Sys).RegisterService(serviceA);
}, host1);
RunOn(() =>
{
var serviceB = Sys.ActorOf(Props.Create<ClusterClientSpecConfig.Service>(), "serviceB");
ClusterClientReceptionist.Get(Sys).RegisterService(serviceB);
}, host2, host3);
//#server
RunOn(() =>
{
AwaitCount(4);
}, host1, host2, host3, _config.Fourth);
EnterBarrier("services-replicated");
//#client
RunOn(() =>
{
var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client");
c.Tell(new ClusterClient.Send("/user/serviceA", "hello", localAffinity: true));
c.Tell(new ClusterClient.SendToAll("/user/serviceB", "hi"));
}, _config.Client);
//#client
RunOn(() =>
{
// note that "hi" was sent to 2 "serviceB"
var received = ReceiveN(3);
received.ToImmutableHashSet().Should().BeEquivalentTo(ImmutableHashSet.Create("hello", "hi"));
}, _config.Client);
// strange, barriers fail without this sleep
Thread.Sleep(1000);
EnterBarrier("after-3");
});
}
public void ClusterClient_must_report_events()
{
Within(15.Seconds(), () =>
{
RunOn(() =>
{
var c = Sys.ActorSelection("/user/client").ResolveOne(Dilated(1.Seconds())).Result;
var l = Sys.ActorOf(
Props.Create(() => new ClusterClientSpecConfig.TestClientListener(c)),
"reporter-client-listener");
var expectedContacts = ImmutableHashSet.Create(_config.First, _config.Second, _config.Third, _config.Fourth)
.Select(_ => Node(_) / "system" / "receptionist");
Within(10.Seconds(), () =>
{
AwaitAssert(() =>
{
var probe = CreateTestProbe();
l.Tell(ClusterClientSpecConfig.TestClientListener.GetLatestContactPoints.Instance, probe.Ref);
probe.ExpectMsg<ClusterClientSpecConfig.TestClientListener.LatestContactPoints>()
.ContactPoints.Should()
.BeEquivalentTo(expectedContacts);
});
});
}, _config.Client);
EnterBarrier("reporter-client-listener-tested");
RunOn(() =>
{
// Only run this test on a node that knows about our client. It could be that no node knows
// but there isn't a means of expressing that at least one of the nodes needs to pass the test.
var r = ClusterClientReceptionist.Get(Sys).Underlying;
r.Tell(GetClusterClients.Instance);
var cps = ExpectMsg<ClusterClients>();
if (cps.ClusterClientsList.Any(c => c.Path.Name.Equals("client")))
{
Log.Info("Testing that the receptionist has just one client");
var l = Sys.ActorOf(
Props.Create(() => new ClusterClientSpecConfig.TestReceptionistListener(r)),
"reporter-receptionist-listener");
var c = Sys
.ActorSelection(Node(_config.Client) / "user" / "client")
.ResolveOne(Dilated(2.Seconds())).Result;
var expectedClients = ImmutableHashSet.Create(c);
Within(10.Seconds(), () =>
{
AwaitAssert(() =>
{
var probe = CreateTestProbe();
l.Tell(ClusterClientSpecConfig.TestReceptionistListener.GetLatestClusterClients.Instance, probe.Ref);
probe.ExpectMsg<ClusterClientSpecConfig.TestReceptionistListener.LatestClusterClients>()
.ClusterClients.Should()
.BeEquivalentTo(expectedClients);
});
});
}
}, _config.First, _config.Second, _config.Third);
EnterBarrier("after-6");
});
}
public void ClusterClient_must_reestablish_connection_to_another_receptionist_when_server_is_shutdown()
{
Within(30.Seconds(), () =>
{
RunOn(() =>
{
var service2 = Sys.ActorOf(Props.Create(() => new ClusterClientSpecConfig.TestService(TestActor)), "service2");
ClusterClientReceptionist.Get(Sys).RegisterService(service2);
AwaitCount(8);
}, _config.First, _config.Second, _config.Third, _config.Fourth);
EnterBarrier("service2-replicated");
RunOn(() =>
{
var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client2");
c.Tell(new ClusterClient.Send("/user/service2", "bonjour", localAffinity: true));
var reply = ExpectMsg<ClusterClientSpecConfig.Reply>();
reply.Msg.Should().Be("bonjour-ack");
RoleName receptionistRoleName = GetRoleName(reply.Node);
if (receptionistRoleName == null)
{
throw new Exception("Unexpected missing role name: " + reply.Node);
}
TestConductor.Exit(receptionistRoleName, 0).Wait();
_remainingServerRoleNames = _remainingServerRoleNames.Remove(receptionistRoleName);
Within(Remaining - 3.Seconds(), () =>
{
AwaitAssert(() =>
{
c.Tell(new ClusterClient.Send("/user/service2", "hi again", localAffinity: true));
ExpectMsg<ClusterClientSpecConfig.Reply>(1.Seconds()).Msg.Should().Be("hi again-ack");
});
});
Sys.Stop(c);
}, _config.Client);
EnterBarrier("verified-3");
ReceiveWhile(2.Seconds(), msg =>
{
if (msg.Equals("hi again")) return msg;
else throw new Exception("Unexpected message: " + msg);
});
RunOn(() =>
{
// Locate the test listener from a previous test and see that it agrees
// with what the client is telling it about what receptionists are alive
var l = Sys.ActorSelection("/user/reporter-client-listener");
var expectedContacts = _remainingServerRoleNames.Select(c => Node(c) / "system" / "receptionist");
Within(10.Seconds(), () =>
{
AwaitAssert(() =>
{
var probe = CreateTestProbe();
l.Tell(ClusterClientSpecConfig.TestClientListener.GetLatestContactPoints.Instance, probe.Ref);
probe.ExpectMsg<ClusterClientSpecConfig.TestClientListener.LatestContactPoints>()
.ContactPoints.Should()
.BeEquivalentTo(expectedContacts);
});
});
}, _config.Client);
EnterBarrier("after-4");
});
}
public void ClusterClient_must_reestablish_connection_to_receptionist_after_partition()
{
Within(30.Seconds(), () =>
{
RunOn(() =>
{
var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client3");
c.Tell(new ClusterClient.Send("/user/service2", "bonjour2", localAffinity: true));
var reply = ExpectMsg<ClusterClientSpecConfig.Reply>();
reply.Msg.Should().Be("bonjour2-ack");
RoleName receptionistRoleName = GetRoleName(reply.Node);
if (receptionistRoleName == null)
{
throw new Exception("Unexpected missing role name: " + reply.Node);
}
// shutdown all but the one that the client is connected to
_remainingServerRoleNames.Where(r => !r.Equals(receptionistRoleName)).ForEach(r =>
{
TestConductor.Exit(r, 0).Wait();
});
_remainingServerRoleNames = ImmutableHashSet.Create(receptionistRoleName);
// network partition between client and server
TestConductor.Blackhole(_config.Client, receptionistRoleName, ThrottleTransportAdapter.Direction.Both).Wait();
c.Tell(new ClusterClient.Send("/user/service2", "ping", localAffinity: true));
// if we would use remote watch the failure detector would trigger and
// connection quarantined
ExpectNoMsg(5.Seconds());
TestConductor.PassThrough(_config.Client, receptionistRoleName, ThrottleTransportAdapter.Direction.Both).Wait();
var expectedAddress = GetAddress(receptionistRoleName);
AwaitAssert(() =>
{
var probe = CreateTestProbe();
c.Tell(new ClusterClient.Send("/user/service2", "bonjour3", localAffinity: true), probe.Ref);
var reply2 = probe.ExpectMsg<ClusterClientSpecConfig.Reply>(1.Seconds());
reply2.Msg.Should().Be("bonjour3-ack");
reply2.Node.Should().Be(expectedAddress);
});
Sys.Stop(c);
}, _config.Client);
EnterBarrier("after-5");
});
}
public void ClusterClient_must_reestablish_connection_to_receptionist_after_server_restart()
{
Within(30.Seconds(), () =>
{
RunOn(() =>
{
_remainingServerRoleNames.Count.Should().Be(1);
var remainingContacts = _remainingServerRoleNames.Select(r => Node(r) / "system" / "receptionist").ToList();
var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(remainingContacts)), "client4");
c.Tell(new ClusterClient.Send("/user/service2", "bonjour4", localAffinity: true));
var reply = ExpectMsg<ClusterClientSpecConfig.Reply>(10.Seconds());
reply.Msg.Should().Be("bonjour4-ack");
reply.Node.Should().Be(remainingContacts.First().Address);
var logSource = $"{(Sys as ExtendedActorSystem).Provider.DefaultAddress}/user/client4";
EventFilter.Info(start: "Connected to", source: logSource).ExpectOne(() =>
{
EventFilter.Info(start: "Lost contact", source: logSource).ExpectOne(() =>
{
// shutdown server
TestConductor.Shutdown(_remainingServerRoleNames.First()).Wait();
});
});
c.Tell(new ClusterClient.Send("/user/service2", "shutdown", localAffinity: true));
Thread.Sleep(2000); // to ensure that it is sent out before shutting down system
}, _config.Client);
RunOn(() =>
{
Sys.WhenTerminated.Wait(20.Seconds());
// start new system on same port
var sys2 = ActorSystem.Create(
Sys.Name,
ConfigurationFactory.ParseString("akka.remote.helios.tcp.port=" + Cluster.Get(Sys).SelfAddress.Port).WithFallback(Sys.Settings.Config));
Cluster.Get(sys2).Join(Cluster.Get(sys2).SelfAddress);
var service2 = sys2.ActorOf(Props.Create(() => new ClusterClientSpecConfig.TestService(TestActor)), "service2");
ClusterClientReceptionist.Get(sys2).RegisterService(service2);
sys2.WhenTerminated.Wait(20.Seconds());
}, _remainingServerRoleNames.ToArray());
});
}
}
}
| |
/*
* 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 ParquetSharp.Schema
{
using System;
using System.Collections.Generic;
using System.Reflection;
/**
* This class provides fluent builders that produce Parquet schema Types.
* <p>
* The most basic use is to build primitive types:
* <pre>
* Types.required(INT64).named("id");
* Types.optional(INT32).named("number");
* </pre>
* <p>
* The {@link #required(PrimitiveTypeName)} factory method produces a primitive
* type builder, and the {@link PrimitiveBuilder#named(String)} builds the
* {@link PrimitiveType}. Between {@code required} and {@code named}, other
* builder methods can be used to add type annotations or other type metadata:
* <pre>
* Types.required(BINARY).as(UTF8).named("username");
* Types.optional(FIXED_LEN_BYTE_ARRAY).length(20).named("sha1");
* </pre>
* <p>
* Optional types are built using {@link #optional(PrimitiveTypeName)} to get
* the builder.
* <p>
* Groups are built similarly, using {@code requiredGroup()} (or the optional
* version) to return a group builder. Group builders provide {@code required}
* and {@code optional} to add primitive types, which return primitive builders
* like the versions above.
* <pre>
* // This produces:
* // required group User {
* // required int64 id;
* // optional binary email (UTF8);
* // }
* Types.requiredGroup()
* .required(INT64).named("id")
* .required(BINARY).as(UTF8).named("email")
* .named("User")
* </pre>
* <p>
* When {@code required} is called on a group builder, the builder it returns
* will add the type to the parent group when it is built and {@code named} will
* return its parent group builder (instead of the type) so more fields can be
* added.
* <p>
* Sub-groups can be created using {@code requiredGroup()} to get a group
* builder that will create the group type, add it to the parent builder, and
* return the parent builder for more fields.
* <pre>
* // required group User {
* // required int64 id;
* // optional binary email (UTF8);
* // optional group address {
* // required binary street (UTF8);
* // required int32 zipcode;
* // }
* // }
* Types.requiredGroup()
* .required(INT64).named("id")
* .required(BINARY).as(UTF8).named("email")
* .optionalGroup()
* .required(BINARY).as(UTF8).named("street")
* .required(INT32).named("zipcode")
* .named("address")
* .named("User")
* </pre>
* <p>
* Maps are built similarly, using {@code requiredMap()} (or the optionalMap()
* version) to return a map builder. Map builders provide {@code key} to add
* a primitive as key or a {@code groupKey} to add a group as key. {@code key()}
* returns a MapKey builder, which : a primitive builder. On the other hand,
* {@code groupKey()} returns a MapGroupKey builder, which : a group builder.
* A key in a map is always required.
* <p>
* Once a key is built, a primitive map value can be built using {@code requiredValue()}
* (or the optionalValue() version) that returns MapValue builder. A group map value
* can be built using {@code requiredGroupValue()} (or the optionalGroupValue()
* version) that returns MapGroupValue builder.
*
* // required group zipMap (MAP) {
* // repeated group map (MAP_KEY_VALUE) {
* // required float key
* // optional int32 value
* // }
* // }
* Types.requiredMap()
* .key(FLOAT)
* .optionalValue(INT32)
* .named("zipMap")
*
*
* // required group zipMap (MAP) {
* // repeated group map (MAP_KEY_VALUE) {
* // required group key {
* // optional int64 first;
* // required group second {
* // required float inner_id_1;
* // optional int32 inner_id_2;
* // }
* // }
* // optional group value {
* // optional group localGeoInfo {
* // required float inner_value_1;
* // optional int32 inner_value_2;
* // }
* // optional int32 zipcode;
* // }
* // }
* // }
* Types.requiredMap()
* .groupKey()
* .optional(INT64).named("id")
* .requiredGroup()
* .required(FLOAT).named("inner_id_1")
* .required(FLOAT).named("inner_id_2")
* .named("second")
* .optionalGroup()
* .optionalGroup()
* .required(FLOAT).named("inner_value_1")
* .optional(INT32).named("inner_value_2")
* .named("localGeoInfo")
* .optional(INT32).named("zipcode")
* .named("zipMap")
* </pre>
* <p>
* Message types are built using {@link #buildMessage()} and function just like
* group builders.
* <pre>
* // message User {
* // required int64 id;
* // optional binary email (UTF8);
* // optional group address {
* // required binary street (UTF8);
* // required int32 zipcode;
* // }
* // }
* Types.buildMessage()
* .required(INT64).named("id")
* .required(BINARY).as(UTF8).named("email")
* .optionalGroup()
* .required(BINARY).as(UTF8).named("street")
* .required(INT32).named("zipcode")
* .named("address")
* .named("User")
* </pre>
* <p>
* These builders enforce consistency checks based on the specifications in
* the parquet-format documentation. For example, if DECIMAL is used to annotate
* a FIXED_LEN_BYTE_ARRAY that is not long enough for its maximum precision,
* these builders will throw an IllegalArgumentException:
* <pre>
* // throws IllegalArgumentException with message:
* // "FIXED(4) is not long enough to store 10 digits"
* Types.required(FIXED_LEN_BYTE_ARRAY).length(4)
* .as(DECIMAL).precision(10)
* .named("badDecimal");
* </pre>
*/
public class Types
{
private const int NOT_SET = 0;
/**
* A base builder for {@link Type} objects.
*
* @param <P> The type that this builder will return from
* {@link #named(String)} when the type is built.
*/
public abstract class Builder<THIS, P>
{
protected P parent;
protected System.Type returnClass;
protected Type.Repetition? _repetition = null;
protected OriginalType? originalType = null;
protected Type.ID _id = null;
private bool repetitionAlreadySet = false;
/**
* Construct a type builder that returns a "parent" object when the builder
* is finished. The {@code parent} will be returned by
* {@link #named(String)} so that builders can be chained.
*
* @param parent a non-null object to return from {@link #named(String)}
*/
protected Builder(P parent)
{
this.parent = parent;
this.returnClass = null;
}
/**
* Construct a type builder that returns the {@link Type} that was built
* when the builder is finished. The {@code returnClass} must be the
* expected {@code Type} class.
*
* @param returnClass a {@code Type} to return from {@link #named(String)}
*/
protected Builder(System.Type returnClass)
{
Preconditions.checkArgument(typeof(Type).IsAssignableFrom(returnClass),
"The requested return class must extend Type");
this.returnClass = returnClass;
this.parent = default(P);
}
protected abstract THIS self();
internal THIS repetition(Type.Repetition repetition)
{
Preconditions.checkArgument(!repetitionAlreadySet,
"Repetition has already been set");
Preconditions.checkNotNull(repetition, "Repetition cannot be null");
this._repetition = repetition;
this.repetitionAlreadySet = true;
return self();
}
/**
* Adds a type annotation ({@link OriginalType}) to the type being built.
* <p>
* Type annotations are used to extend the types that parquet can store, by
* specifying how the primitive types should be interpreted. This keeps the
* set of primitive types to a minimum and reuses parquet's efficient
* encodings. For example, strings are stored as byte arrays (binary) with
* a UTF8 annotation.
*
* @param type an {@code OriginalType}
* @return this builder for method chaining
*/
public THIS @as(OriginalType type)
{
this.originalType = type;
return self();
}
/**
* adds an id annotation to the type being built.
* <p>
* ids are used to capture the original id when converting from models using ids (thrift, protobufs)
*
* @param id the id of the field
* @return this builder for method chaining
*/
public THIS id(int id)
{
this._id = new Type.ID(id);
return self();
}
abstract protected Type build(string name);
/**
* Builds a {@link Type} and returns the parent builder, if given, or the
* {@code Type} that was built. If returning a parent object that is a
* GroupBuilder, the constructed type will be added to it as a field.
* <p>
* <em>Note:</em> Any configuration for this type builder should be done
* before calling this method.
*
* @param name a name for the constructed type
* @return the parent {@code GroupBuilder} or the constructed {@code Type}
*/
public virtual P named(string name)
{
Preconditions.checkNotNull(name, "Name is required");
Preconditions.checkNotNull(_repetition, "Repetition is required");
Type type = build(name);
if (parent != null)
{
// if the parent is a BaseGroupBuilder, add type to it
if (parent is IAddable)
{
((IAddable)parent).addField(type);
}
return parent;
}
else if (returnClass != null)
{
return (P)(object)type;
}
else
{
throw new InvalidOperationException(
"[BUG] Parent and return type are null: must override named");
}
}
}
public abstract class BasePrimitiveBuilder<P, THIS> : Builder<THIS, P>
where THIS : BasePrimitiveBuilder<P, THIS>
{
private static long MAX_PRECISION_INT32 = maxPrecision(4);
private static long MAX_PRECISION_INT64 = maxPrecision(8);
private PrimitiveType.PrimitiveTypeName primitiveType;
private int _length = NOT_SET;
private int _precision = NOT_SET;
private int _scale = NOT_SET;
protected BasePrimitiveBuilder(P parent, PrimitiveType.PrimitiveTypeName type)
: base(parent)
{
this.primitiveType = type;
}
protected BasePrimitiveBuilder(System.Type returnType, PrimitiveType.PrimitiveTypeName type)
: base(returnType)
{
this.primitiveType = type;
}
protected override abstract THIS self();
/**
* Adds the length for a FIXED_LEN_BYTE_ARRAY.
*
* @param length an int length
* @return this builder for method chaining
*/
public BasePrimitiveBuilder<P, THIS> length(int length)
{
this._length = length;
return this;
}
/**
* Adds the precision for a DECIMAL.
* <p>
* This value is required for decimals and must be less than or equal to
* the maximum number of base-10 digits in the underlying type. A 4-byte
* fixed, for example, can store up to 9 base-10 digits.
*
* @param precision an int precision value for the DECIMAL
* @return this builder for method chaining
*/
public BasePrimitiveBuilder<P, THIS> precision(int precision)
{
this._precision = precision;
return this;
}
/**
* Adds the scale for a DECIMAL.
* <p>
* This value must be less than the maximum precision of the type and must
* be a positive number. If not set, the default scale is 0.
* <p>
* The scale specifies the number of digits of the underlying unscaled
* that are to the right of the decimal point. The decimal interpretation
* of values in this column is: {@code value*10^(-scale)}.
*
* @param scale an int scale value for the DECIMAL
* @return this builder for method chaining
*/
public BasePrimitiveBuilder<P, THIS> scale(int scale)
{
this._scale = scale;
return this;
}
protected override Type build(string name)
{
if (PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY == primitiveType)
{
Preconditions.checkArgument(_length > 0,
"Invalid FIXED_LEN_BYTE_ARRAY length: " + _length);
}
DecimalMetadata meta = decimalMetadata();
// validate type annotations and required metadata
if (originalType != null)
{
switch (originalType)
{
case OriginalType.UTF8:
case OriginalType.JSON:
case OriginalType.BSON:
Preconditions.checkState(
primitiveType == PrimitiveType.PrimitiveTypeName.BINARY,
originalType.ToString() + " can only annotate binary fields");
break;
case OriginalType.DECIMAL:
Preconditions.checkState(
(primitiveType == PrimitiveType.PrimitiveTypeName.INT32) ||
(primitiveType == PrimitiveType.PrimitiveTypeName.INT64) ||
(primitiveType == PrimitiveType.PrimitiveTypeName.BINARY) ||
(primitiveType == PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY),
"DECIMAL can only annotate INT32, INT64, BINARY, and FIXED"
);
if (primitiveType == PrimitiveType.PrimitiveTypeName.INT32)
{
Preconditions.checkState(
meta.getPrecision() <= MAX_PRECISION_INT32,
"INT32 cannot store " + meta.getPrecision() + " digits " +
"(max " + MAX_PRECISION_INT32 + ")");
}
else if (primitiveType == PrimitiveType.PrimitiveTypeName.INT64)
{
Preconditions.checkState(
meta.getPrecision() <= MAX_PRECISION_INT64,
"INT64 cannot store " + meta.getPrecision() + " digits " +
"(max " + MAX_PRECISION_INT64 + ")");
}
else if (primitiveType == PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY)
{
Preconditions.checkState(
meta.getPrecision() <= maxPrecision(_length),
"FIXED(" + _length + ") cannot store " + meta.getPrecision() +
" digits (max " + maxPrecision(_length) + ")");
}
break;
case OriginalType.DATE:
case OriginalType.TIME_MILLIS:
case OriginalType.UINT_8:
case OriginalType.UINT_16:
case OriginalType.UINT_32:
case OriginalType.INT_8:
case OriginalType.INT_16:
case OriginalType.INT_32:
Preconditions.checkState(primitiveType == PrimitiveType.PrimitiveTypeName.INT32,
originalType.ToString() + " can only annotate INT32");
break;
case OriginalType.TIMESTAMP_MILLIS:
case OriginalType.UINT_64:
case OriginalType.INT_64:
Preconditions.checkState(primitiveType == PrimitiveType.PrimitiveTypeName.INT64,
originalType.ToString() + " can only annotate INT64");
break;
case OriginalType.INTERVAL:
Preconditions.checkState(
(primitiveType == PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY) &&
(_length == 12),
"INTERVAL can only annotate FIXED_LEN_BYTE_ARRAY(12)");
break;
case OriginalType.ENUM:
Preconditions.checkState(
primitiveType == PrimitiveType.PrimitiveTypeName.BINARY,
"ENUM can only annotate binary fields");
break;
default:
throw new InvalidOperationException(originalType + " can not be applied to a primitive type");
}
}
return new PrimitiveType(_repetition.Value, primitiveType, _length, name, originalType, meta, _id);
}
private static long maxPrecision(int numBytes)
{
return (long)Math.Round( // convert double to long
Math.Floor(Math.Log10( // number of base-10 digits
Math.Pow(2, 8 * numBytes - 1) - 1) // max value stored in numBytes
)
);
}
protected DecimalMetadata decimalMetadata()
{
DecimalMetadata meta = null;
if (OriginalType.DECIMAL == originalType)
{
Preconditions.checkArgument(_precision > 0,
"Invalid DECIMAL precision: " + _precision);
Preconditions.checkArgument(_scale >= 0,
"Invalid DECIMAL scale: " + _scale);
Preconditions.checkArgument(_scale <= _precision,
"Invalid DECIMAL scale: cannot be greater than precision");
meta = new DecimalMetadata(_precision, _scale);
}
return meta;
}
}
/**
* A builder for {@link PrimitiveType} objects.
*
* @param <P> The type that this builder will return from
* {@link #named(String)} when the type is built.
*/
public class PrimitiveBuilder<P> : BasePrimitiveBuilder<P, PrimitiveBuilder<P>>
{
internal PrimitiveBuilder(P parent, PrimitiveType.PrimitiveTypeName type)
: base(parent, type)
{
}
internal PrimitiveBuilder(System.Type returnType, PrimitiveType.PrimitiveTypeName type)
: base(returnType, type)
{
}
protected override PrimitiveBuilder<P> self()
{
return this;
}
}
interface IAddable
{
void addField(Type type);
}
public abstract class BaseGroupBuilder<P, THIS> : Builder<THIS, P>, IAddable
where THIS : BaseGroupBuilder<P, THIS>
{
protected List<Type> fields;
protected BaseGroupBuilder(P parent)
: base(parent)
{
this.fields = new List<Type>();
}
protected BaseGroupBuilder(System.Type returnType)
: base(returnType)
{
this.fields = new List<Type>();
}
protected override abstract THIS self();
public PrimitiveBuilder<THIS> primitive(
PrimitiveType.PrimitiveTypeName type, Type.Repetition repetition)
{
return new PrimitiveBuilder<THIS>(self(), type)
.repetition(repetition);
}
/**
* Returns a {@link PrimitiveBuilder} for the required primitive type
* {@code type}.
*
* @param type a {@link PrimitiveTypeName}
* @return a primitive builder for {@code type} that will return this
* builder for additional fields.
*/
public PrimitiveBuilder<THIS> required(
PrimitiveType.PrimitiveTypeName type)
{
return new PrimitiveBuilder<THIS>(self(), type)
.repetition(Type.Repetition.REQUIRED);
}
/**
* Returns a {@link PrimitiveBuilder} for the optional primitive type
* {@code type}.
*
* @param type a {@link PrimitiveTypeName}
* @return a primitive builder for {@code type} that will return this
* builder for additional fields.
*/
public PrimitiveBuilder<THIS> optional(
PrimitiveType.PrimitiveTypeName type)
{
return new PrimitiveBuilder<THIS>(self(), type)
.repetition(Type.Repetition.OPTIONAL);
}
/**
* Returns a {@link PrimitiveBuilder} for the repeated primitive type
* {@code type}.
*
* @param type a {@link PrimitiveTypeName}
* @return a primitive builder for {@code type} that will return this
* builder for additional fields.
*/
public PrimitiveBuilder<THIS> repeated(
PrimitiveType.PrimitiveTypeName type)
{
return new PrimitiveBuilder<THIS>(self(), type)
.repetition(Type.Repetition.REPEATED);
}
public GroupBuilder<THIS> group(Type.Repetition repetition)
{
return new GroupBuilder<THIS>(self())
.repetition(repetition);
}
/**
* Returns a {@link GroupBuilder} to build a required sub-group.
*
* @return a group builder that will return this builder for additional
* fields.
*/
public GroupBuilder<THIS> requiredGroup()
{
return new GroupBuilder<THIS>(self())
.repetition(Type.Repetition.REQUIRED);
}
/**
* Returns a {@link GroupBuilder} to build an optional sub-group.
*
* @return a group builder that will return this builder for additional
* fields.
*/
public GroupBuilder<THIS> optionalGroup()
{
return new GroupBuilder<THIS>(self())
.repetition(Type.Repetition.OPTIONAL);
}
/**
* Returns a {@link GroupBuilder} to build a repeated sub-group.
*
* @return a group builder that will return this builder for additional
* fields.
*/
public GroupBuilder<THIS> repeatedGroup()
{
return new GroupBuilder<THIS>(self())
.repetition(Type.Repetition.REPEATED);
}
/**
* Adds {@code type} as a sub-field to the group configured by this builder.
*
* @return this builder for additional fields.
*/
public THIS addField(Type type)
{
fields.Add(type);
return self();
}
void IAddable.addField(Type type)
{
addField(type);
}
/**
* Adds {@code types} as sub-fields of the group configured by this builder.
*
* @return this builder for additional fields.
*/
public THIS addFields(params Type[] types)
{
fields.AddRange(types);
return self();
}
protected override Type build(string name)
{
return new GroupType(_repetition.Value, name, originalType, fields, _id);
}
public MapBuilder<THIS> map(
Type.Repetition repetition)
{
return new MapBuilder<THIS>(self()).repetition(repetition);
}
public MapBuilder<THIS> requiredMap()
{
return new MapBuilder<THIS>(self())
.repetition(Type.Repetition.REQUIRED);
}
public MapBuilder<THIS> optionalMap()
{
return new MapBuilder<THIS>(self())
.repetition(Type.Repetition.OPTIONAL);
}
public ListBuilder<THIS> list(Type.Repetition repetition)
{
return new ListBuilder<THIS>(self()).repetition(repetition);
}
public ListBuilder<THIS> requiredList()
{
return list(Type.Repetition.REQUIRED);
}
public ListBuilder<THIS> optionalList()
{
return list(Type.Repetition.OPTIONAL);
}
}
/**
* A builder for {@link GroupType} objects.
*
* @param <P> The type that this builder will return from
* {@link #named(String)} when the type is built.
*/
public class GroupBuilder<P> : BaseGroupBuilder<P, GroupBuilder<P>>
{
internal GroupBuilder(P parent)
: base(parent)
{
}
internal GroupBuilder(System.Type returnType)
: base(returnType)
{
}
protected override GroupBuilder<P> self()
{
return this;
}
}
public abstract class BaseMapBuilder<P, THIS> : Builder<THIS, P>
where THIS : BaseMapBuilder<P, THIS>
{
private static readonly Type STRING_KEY = Types
.required(PrimitiveType.PrimitiveTypeName.BINARY).@as(OriginalType.UTF8).named("key");
public class KeyBuilder<MP, M> : BasePrimitiveBuilder<MP, KeyBuilder<MP, M>>
where M : BaseMapBuilder<MP, M>
{
private readonly M mapBuilder;
public KeyBuilder(M mapBuilder, PrimitiveType.PrimitiveTypeName type)
: base(mapBuilder.parent, type)
{
this.mapBuilder = mapBuilder;
repetition(Type.Repetition.REQUIRED);
}
public ValueBuilder<MP, M> value(PrimitiveType.PrimitiveTypeName type,
Type.Repetition repetition)
{
mapBuilder.setKeyType(build("key"));
return new ValueBuilder<MP, M>(mapBuilder, type).repetition(repetition);
}
public ValueBuilder<MP, M> requiredValue(PrimitiveType.PrimitiveTypeName type)
{
return value(type, Type.Repetition.REQUIRED);
}
public ValueBuilder<MP, M> optionalValue(PrimitiveType.PrimitiveTypeName type)
{
return value(type, Type.Repetition.OPTIONAL);
}
public GroupValueBuilder<MP, M> groupValue(Type.Repetition repetition)
{
mapBuilder.setKeyType(build("key"));
return new GroupValueBuilder<MP, M>(mapBuilder).repetition(repetition);
}
public GroupValueBuilder<MP, M> requiredGroupValue()
{
return groupValue(Type.Repetition.REQUIRED);
}
public GroupValueBuilder<MP, M> optionalGroupValue()
{
return groupValue(Type.Repetition.OPTIONAL);
}
public MapValueBuilder<MP, M> mapValue(Type.Repetition repetition)
{
mapBuilder.setKeyType(build("key"));
return new MapValueBuilder<MP, M>(mapBuilder).repetition(repetition);
}
public MapValueBuilder<MP, M> requiredMapValue()
{
return mapValue(Type.Repetition.REQUIRED);
}
public MapValueBuilder<MP, M> optionalMapValue()
{
return mapValue(Type.Repetition.OPTIONAL);
}
public ListValueBuilder<MP, M> listValue(Type.Repetition repetition)
{
mapBuilder.setKeyType(build("key"));
return new ListValueBuilder<MP, M>(mapBuilder).repetition(repetition);
}
public ListValueBuilder<MP, M> requiredListValue()
{
return listValue(Type.Repetition.REQUIRED);
}
public ListValueBuilder<MP, M> optionalListValue()
{
return listValue(Type.Repetition.OPTIONAL);
}
public M value(Type type)
{
mapBuilder.setKeyType(build("key"));
mapBuilder.setValueType(type);
return this.mapBuilder;
}
public override MP named(string name)
{
mapBuilder.setKeyType(build("key"));
return mapBuilder.named(name);
}
protected override KeyBuilder<MP, M> self()
{
return this;
}
}
public class ValueBuilder<MP, M> : BasePrimitiveBuilder<MP, ValueBuilder<MP, M>>
where M : BaseMapBuilder<MP, M>
{
private readonly M mapBuilder;
public ValueBuilder(M mapBuilder, PrimitiveType.PrimitiveTypeName type)
: base(mapBuilder.parent, type)
{
this.mapBuilder = mapBuilder;
}
public override MP named(string name)
{
mapBuilder.setValueType(build("value"));
return mapBuilder.named(name);
}
protected override ValueBuilder<MP, M> self()
{
return this;
}
}
public class GroupKeyBuilder<MP, M> : BaseGroupBuilder<MP, GroupKeyBuilder<MP, M>>
where M : BaseMapBuilder<MP, M>
{
private M mapBuilder;
public GroupKeyBuilder(M mapBuilder)
: base(mapBuilder.parent)
{
this.mapBuilder = mapBuilder;
repetition(Type.Repetition.REQUIRED);
}
protected override GroupKeyBuilder<MP, M> self()
{
return this;
}
public ValueBuilder<MP, M> value(PrimitiveType.PrimitiveTypeName type,
Type.Repetition repetition)
{
mapBuilder.setKeyType(build("key"));
return new ValueBuilder<MP, M>(mapBuilder, type).repetition(repetition);
}
public ValueBuilder<MP, M> requiredValue(PrimitiveType.PrimitiveTypeName type)
{
return value(type, Type.Repetition.REQUIRED);
}
public ValueBuilder<MP, M> optionalValue(PrimitiveType.PrimitiveTypeName type)
{
return value(type, Type.Repetition.OPTIONAL);
}
public GroupValueBuilder<MP, M> groupValue(Type.Repetition repetition)
{
mapBuilder.setKeyType(build("key"));
return new GroupValueBuilder<MP, M>(mapBuilder).repetition(repetition);
}
public GroupValueBuilder<MP, M> requiredGroupValue()
{
return groupValue(Type.Repetition.REQUIRED);
}
public GroupValueBuilder<MP, M> optionalGroupValue()
{
return groupValue(Type.Repetition.OPTIONAL);
}
public MapValueBuilder<MP, M> mapValue(Type.Repetition repetition)
{
mapBuilder.setKeyType(build("key"));
return new MapValueBuilder<MP, M>(mapBuilder).repetition(repetition);
}
public MapValueBuilder<MP, M> requiredMapValue()
{
return mapValue(Type.Repetition.REQUIRED);
}
public MapValueBuilder<MP, M> optionalMapValue()
{
return mapValue(Type.Repetition.OPTIONAL);
}
public ListValueBuilder<MP, M> listValue(Type.Repetition repetition)
{
mapBuilder.setKeyType(build("key"));
return new ListValueBuilder<MP, M>(mapBuilder).repetition(repetition);
}
public ListValueBuilder<MP, M> requiredListValue()
{
return listValue(Type.Repetition.REQUIRED);
}
public ListValueBuilder<MP, M> optionalListValue()
{
return listValue(Type.Repetition.OPTIONAL);
}
public M value(Type type)
{
mapBuilder.setKeyType(build("key"));
mapBuilder.setValueType(type);
return this.mapBuilder;
}
public override MP named(string name)
{
mapBuilder.setKeyType(build("key"));
return mapBuilder.named(name);
}
}
public class GroupValueBuilder<MP, M> : BaseGroupBuilder<MP, GroupValueBuilder<MP, M>>
where M : BaseMapBuilder<MP, M>
{
private M mapBuilder;
public GroupValueBuilder(M mapBuilder)
: base(mapBuilder.parent)
{
this.mapBuilder = mapBuilder;
}
public override MP named(string name)
{
mapBuilder.setValueType(build("value"));
return mapBuilder.named(name);
}
protected override GroupValueBuilder<MP, M> self()
{
return this;
}
}
public class MapValueBuilder<MP, M> : BaseMapBuilder<MP, MapValueBuilder<MP, M>>
where M : BaseMapBuilder<MP, M>
{
private M mapBuilder;
public MapValueBuilder(M mapBuilder)
: base(mapBuilder.parent)
{
this.mapBuilder = mapBuilder;
}
public override MP named(string name)
{
mapBuilder.setValueType(build("value"));
return mapBuilder.named(name);
}
protected override BaseMapBuilder<P, THIS>.MapValueBuilder<MP, M> self()
{
return this;
}
}
public class ListValueBuilder<MP, M> : BaseListBuilder<MP, ListValueBuilder<MP, M>>
where M : BaseMapBuilder<MP, M>
{
private readonly M mapBuilder;
public ListValueBuilder(M mapBuilder)
: base(mapBuilder.parent)
{
this.mapBuilder = mapBuilder;
}
public override MP named(string name)
{
mapBuilder.setValueType(build("value"));
return mapBuilder.named(name);
}
protected override ListValueBuilder<MP, M> self()
{
return this;
}
}
protected void setKeyType(Type keyType)
{
Preconditions.checkState(this.keyType == null,
"Only one key type can be built with a MapBuilder");
this.keyType = keyType;
}
protected void setValueType(Type valueType)
{
Preconditions.checkState(this.valueType == null,
"Only one key type can be built with a ValueBuilder");
this.valueType = valueType;
}
private Type keyType = null;
private Type valueType = null;
public BaseMapBuilder(P parent)
: base(parent)
{
}
protected BaseMapBuilder(System.Type returnType)
: base(returnType)
{
}
protected override abstract THIS self();
public KeyBuilder<P, THIS> key(PrimitiveType.PrimitiveTypeName type)
{
return new KeyBuilder<P, THIS>(self(), type);
}
public THIS key(Type type)
{
setKeyType(type);
return self();
}
public GroupKeyBuilder<P, THIS> groupKey()
{
return new GroupKeyBuilder<P, THIS>(self());
}
public ValueBuilder<P, THIS> value(PrimitiveType.PrimitiveTypeName type,
Type.Repetition repetition)
{
return new ValueBuilder<P, THIS>(self(), type).repetition(repetition);
}
public ValueBuilder<P, THIS> requiredValue(PrimitiveType.PrimitiveTypeName type)
{
return value(type, Type.Repetition.REQUIRED);
}
public ValueBuilder<P, THIS> optionalValue(PrimitiveType.PrimitiveTypeName type)
{
return value(type, Type.Repetition.OPTIONAL);
}
public GroupValueBuilder<P, THIS> groupValue(Type.Repetition repetition)
{
return new GroupValueBuilder<P, THIS>(self()).repetition(repetition);
}
public GroupValueBuilder<P, THIS> requiredGroupValue()
{
return groupValue(Type.Repetition.REQUIRED);
}
public GroupValueBuilder<P, THIS> optionalGroupValue()
{
return groupValue(Type.Repetition.OPTIONAL);
}
public MapValueBuilder<P, THIS> mapValue(Type.Repetition repetition)
{
return new MapValueBuilder<P, THIS>(self()).repetition(repetition);
}
public MapValueBuilder<P, THIS> requiredMapValue()
{
return mapValue(Type.Repetition.REQUIRED);
}
public MapValueBuilder<P, THIS> optionalMapValue()
{
return mapValue(Type.Repetition.OPTIONAL);
}
public ListValueBuilder<P, THIS> listValue(Type.Repetition repetition)
{
return new ListValueBuilder<P, THIS>(self()).repetition(repetition);
}
public ListValueBuilder<P, THIS> requiredListValue()
{
return listValue(Type.Repetition.REQUIRED);
}
public ListValueBuilder<P, THIS> optionalListValue()
{
return listValue(Type.Repetition.OPTIONAL);
}
public THIS value(Type type)
{
setValueType(type);
return self();
}
protected override Type build(string name)
{
Preconditions.checkState(originalType == null,
"MAP is already a logical type and can't be changed.");
if (keyType == null)
{
keyType = STRING_KEY;
}
if (valueType != null)
{
return buildGroup(_repetition.Value).@as(OriginalType.MAP)
.repeatedGroup().addFields(keyType, valueType).named("map")
.named(name);
}
else
{
return buildGroup(_repetition.Value).@as(OriginalType.MAP)
.repeatedGroup().addFields(keyType).named("map")
.named(name);
}
}
}
public class MapBuilder<P> : BaseMapBuilder<P, MapBuilder<P>>
{
public MapBuilder(P parent)
: base(parent)
{
}
internal MapBuilder(System.Type returnType)
: base(returnType)
{
}
protected override MapBuilder<P> self()
{
return this;
}
}
public abstract class BaseListBuilder<P, THIS> : Builder<THIS, P>
where THIS : BaseListBuilder<P, THIS>
{
private Type elementType = null;
private new P parent;
public BaseListBuilder(P parent)
: base(parent)
{
this.parent = parent;
}
public BaseListBuilder(System.Type returnType)
: base(returnType)
{
}
public void setElementType(Type elementType)
{
Preconditions.checkState(this.elementType == null,
"Only one element can be built with a ListBuilder");
this.elementType = elementType;
}
public class ElementBuilder<LP, L> : BasePrimitiveBuilder<LP, ElementBuilder<LP, L>>
where L : BaseListBuilder<LP, L>
{
private readonly BaseListBuilder<LP, L> listBuilder;
public ElementBuilder(L listBuilder, PrimitiveType.PrimitiveTypeName type)
: base(((BaseListBuilder<LP, L>)listBuilder).parent, type)
{
this.listBuilder = listBuilder;
}
public override LP named(string name)
{
listBuilder.setElementType(build("element"));
return listBuilder.named(name);
}
protected override ElementBuilder<LP, L> self()
{
return this;
}
}
public class GroupElementBuilder<LP, L> : BaseGroupBuilder<LP, GroupElementBuilder<LP, L>>
where L : BaseListBuilder<LP, L>
{
private readonly L listBuilder;
public GroupElementBuilder(L listBuilder)
: base(((BaseListBuilder<LP, L>)listBuilder).parent)
{
this.listBuilder = listBuilder;
}
public override LP named(string name)
{
listBuilder.setElementType(build("element"));
return listBuilder.named(name);
}
protected override GroupElementBuilder<LP, L> self()
{
return this;
}
}
public class MapElementBuilder<LP, L> : BaseMapBuilder<LP, MapElementBuilder<LP, L>>
where L : BaseListBuilder<LP, L>
{
private readonly L listBuilder;
public MapElementBuilder(L listBuilder)
: base(((BaseListBuilder<LP, L>)listBuilder).parent)
{
this.listBuilder = listBuilder;
}
protected override MapElementBuilder<LP, L> self()
{
return this;
}
public override LP named(string name)
{
listBuilder.setElementType(build("element"));
return listBuilder.named(name);
}
}
public class ListElementBuilder<LP, L> : BaseListBuilder<LP, ListElementBuilder<LP, L>>
where L : BaseListBuilder<LP, L>
{
private readonly L listBuilder;
public ListElementBuilder(L listBuilder)
: base(((BaseListBuilder<LP, L>)listBuilder).parent)
{
this.listBuilder = listBuilder;
}
protected override BaseListBuilder<P, THIS>.ListElementBuilder<LP, L> self()
{
return this;
}
public override LP named(string name)
{
listBuilder.setElementType(build("element"));
return listBuilder.named(name);
}
}
protected override abstract THIS self();
protected override Type build(string name)
{
Preconditions.checkState(originalType == null,
"LIST is already the logical type and can't be changed");
Preconditions.checkNotNull(elementType, "List element type");
return buildGroup(_repetition.Value).@as(OriginalType.LIST)
.repeatedGroup().addFields(elementType).named("list")
.named(name);
}
public ElementBuilder<P, THIS> element(PrimitiveType.PrimitiveTypeName type,
Type.Repetition repetition)
{
return new ElementBuilder<P, THIS>(self(), type).repetition(repetition);
}
public ElementBuilder<P, THIS> requiredElement(PrimitiveType.PrimitiveTypeName type)
{
return element(type, Type.Repetition.REQUIRED);
}
public ElementBuilder<P, THIS> optionalElement(PrimitiveType.PrimitiveTypeName type)
{
return element(type, Type.Repetition.OPTIONAL);
}
public GroupElementBuilder<P, THIS> groupElement(Type.Repetition repetition)
{
return new GroupElementBuilder<P, THIS>(self()).repetition(repetition);
}
public GroupElementBuilder<P, THIS> requiredGroupElement()
{
return groupElement(Type.Repetition.REQUIRED);
}
public GroupElementBuilder<P, THIS> optionalGroupElement()
{
return groupElement(Type.Repetition.OPTIONAL);
}
public MapElementBuilder<P, THIS> mapElement(Type.Repetition repetition)
{
return new MapElementBuilder<P, THIS>(self()).repetition(repetition);
}
public MapElementBuilder<P, THIS> requiredMapElement()
{
return mapElement(Type.Repetition.REQUIRED);
}
public MapElementBuilder<P, THIS> optionalMapElement()
{
return mapElement(Type.Repetition.OPTIONAL);
}
public ListElementBuilder<P, THIS> listElement(Type.Repetition repetition)
{
return new ListElementBuilder<P, THIS>(self()).repetition(repetition);
}
public ListElementBuilder<P, THIS> requiredListElement()
{
return listElement(Type.Repetition.REQUIRED);
}
public ListElementBuilder<P, THIS> optionalListElement()
{
return listElement(Type.Repetition.OPTIONAL);
}
public BaseListBuilder<P, THIS> element(Type type)
{
setElementType(type);
return self();
}
}
public class ListBuilder<P> : BaseListBuilder<P, ListBuilder<P>>
{
public ListBuilder(P parent)
: base(parent)
{
}
public ListBuilder(System.Type returnType)
: base(returnType)
{
}
protected override ListBuilder<P> self()
{
return this;
}
}
public class MessageTypeBuilder : GroupBuilder<MessageType>
{
internal MessageTypeBuilder()
: base(typeof(MessageType))
{
repetition(Type.Repetition.REQUIRED);
}
/**
* Builds and returns the {@link MessageType} configured by this builder.
* <p>
* <em>Note:</em> All primitive types and sub-groups should be added before
* calling this method.
*
* @param name a name for the constructed type
* @return the final {@code MessageType} configured by this builder.
*/
public override MessageType named(string name)
{
Preconditions.checkNotNull(name, "Name is required");
return new MessageType(name, fields);
}
}
/**
* Returns a builder to construct a {@link MessageType}.
*
* @return a {@link MessageTypeBuilder}
*/
public static MessageTypeBuilder buildMessage()
{
return new MessageTypeBuilder();
}
public static PrimitiveBuilder<PrimitiveType> primitive(PrimitiveType.PrimitiveTypeName type,
Type.Repetition repetition)
{
return new PrimitiveBuilder<PrimitiveType>(typeof(PrimitiveType), type)
.repetition(repetition);
}
/**
* Returns a builder to construct a required {@link PrimitiveType}.
*
* @param type a {@link PrimitiveTypeName} for the constructed type
* @return a {@link PrimitiveBuilder}
*/
public static PrimitiveBuilder<PrimitiveType> required(PrimitiveType.PrimitiveTypeName type)
{
return new PrimitiveBuilder<PrimitiveType>(typeof(PrimitiveType), type)
.repetition(Type.Repetition.REQUIRED);
}
/**
* Returns a builder to construct an optional {@link PrimitiveType}.
*
* @param type a {@link PrimitiveTypeName} for the constructed type
* @return a {@link PrimitiveBuilder}
*/
public static PrimitiveBuilder<PrimitiveType> optional(PrimitiveType.PrimitiveTypeName type)
{
return new PrimitiveBuilder<PrimitiveType>(typeof(PrimitiveType), type)
.repetition(Type.Repetition.OPTIONAL);
}
/**
* Returns a builder to construct a repeated {@link PrimitiveType}.
*
* @param type a {@link PrimitiveTypeName} for the constructed type
* @return a {@link PrimitiveBuilder}
*/
public static PrimitiveBuilder<PrimitiveType> repeated(PrimitiveType.PrimitiveTypeName type)
{
return new PrimitiveBuilder<PrimitiveType>(typeof(PrimitiveType), type)
.repetition(Type.Repetition.REPEATED);
}
public static GroupBuilder<GroupType> buildGroup(
Type.Repetition repetition)
{
return new GroupBuilder<GroupType>(typeof(GroupType)).repetition(repetition);
}
/**
* Returns a builder to construct a required {@link GroupType}.
*
* @return a {@link GroupBuilder}
*/
public static GroupBuilder<GroupType> requiredGroup()
{
return new GroupBuilder<GroupType>(typeof(GroupType))
.repetition(Type.Repetition.REQUIRED);
}
/**
* Returns a builder to construct an optional {@link GroupType}.
*
* @return a {@link GroupBuilder}
*/
public static GroupBuilder<GroupType> optionalGroup()
{
return new GroupBuilder<GroupType>(typeof(GroupType))
.repetition(Type.Repetition.OPTIONAL);
}
/**
* Returns a builder to construct a repeated {@link GroupType}.
*
* @return a {@link GroupBuilder}
*/
public static GroupBuilder<GroupType> repeatedGroup()
{
return new GroupBuilder<GroupType>(typeof(GroupType))
.repetition(Type.Repetition.REPEATED);
}
public static MapBuilder<GroupType> map(Type.Repetition repetition)
{
return new MapBuilder<GroupType>(typeof(GroupType)).repetition(repetition);
}
public static MapBuilder<GroupType> requiredMap()
{
return map(Type.Repetition.REQUIRED);
}
public static MapBuilder<GroupType> optionalMap()
{
return map(Type.Repetition.OPTIONAL);
}
public static ListBuilder<GroupType> list(Type.Repetition repetition)
{
return new ListBuilder<GroupType>(typeof(GroupType)).repetition(repetition);
}
public static ListBuilder<GroupType> requiredList()
{
return list(Type.Repetition.REQUIRED);
}
public static ListBuilder<GroupType> optionalList()
{
return list(Type.Repetition.OPTIONAL);
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
namespace FileSystemTest
{
public class Exists : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// Add your functionality here.
try
{
IOTests.IntializeVolume();
Directory.CreateDirectory(TestDir);
}
catch (Exception ex)
{
Log.Comment("Skipping: Unable to initialize file system" + ex.Message);
return InitializeResult.Skip;
}
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
#region local vars
private const string TestDir = "ExistsDirectory";
#endregion local vars
#region Helper functions
private bool TestExists(string path, bool exists)
{
Log.Comment("Checking for " + path);
if (Directory.Exists(path) != exists)
{
Log.Exception("Expeceted " + exists + " but got " + !exists);
return false;
}
return true;
}
#endregion Helper functions
#region Test Cases
[TestMethod]
public MFTestResults InvalidArguments()
{
bool dir;
MFTestResults result = MFTestResults.Pass;
try
{
try
{
Log.Comment("Null");
dir = Directory.Exists(null);
Log.Exception( "Expected ArgumentNullException, but got " + dir );
return MFTestResults.Fail;
}
catch (ArgumentNullException ane)
{ /* pass case */
Log.Comment( "Got correct exception: " + ane.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("String.Empty");
dir = Directory.Exists(String.Empty);
Log.Exception( "Expected ArgumentException, but got " + dir );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{ /* pass case */
Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("White Space");
dir = Directory.Exists(" ");
Log.Exception( "Expected ArgumentException, but got " + dir );
return MFTestResults.Fail;
}
catch (ArgumentException ae1)
{ /* pass case */
Log.Comment( "Got correct exception: " + ae1.Message );
result = MFTestResults.Pass;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults CurrentDirectory()
{
MFTestResults result = MFTestResults.Pass;
try
{
if (!TestExists(".", true))
return MFTestResults.Fail;
if (!TestExists("..", true))
return MFTestResults.Fail;
if (!TestExists(Directory.GetCurrentDirectory(), true))
return MFTestResults.Fail;
Log.Comment("Set relative Directory");
Directory.SetCurrentDirectory(TestDir);
if (!TestExists(".", true))
return MFTestResults.Fail;
if (!TestExists(Directory.GetCurrentDirectory(), true))
return MFTestResults.Fail;
if (!TestExists("..", true))
return MFTestResults.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults NonExistentDirs()
{
MFTestResults result = MFTestResults.Pass;
try
{
if (!TestExists("unknown directory", false))
return MFTestResults.Fail;
if (!TestExists(IOTests.Volume.RootDirectory + @"\Dir1\dir2", false))
result = MFTestResults.Fail;
if (!TestExists(@"BAR\", false))
return MFTestResults.Fail;
try
{
bool test = TestExists("XX:\\", false);
Log.Comment("Expected ArgumentException, got " + test);
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{ /* pass case */
Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults PathTooLong()
{
MFTestResults result = MFTestResults.Pass;
try
{
string path = new string('x', 500);
bool exists = Directory.Exists(path);
Log.Exception("Expected IOException, got " + exists);
return MFTestResults.Fail;
}
catch (IOException ioe)
{
/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message );
result = MFTestResults.Pass;
} // PathTooLong
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults CaseInsensitive()
{
MFTestResults result = MFTestResults.Pass;
try
{
Directory.CreateDirectory(TestDir);
if (!TestExists(TestDir.ToLower(), true))
return MFTestResults.Fail;
if (!TestExists(TestDir.ToUpper(), true))
return MFTestResults.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults MultiSpaceExists()
{
MFTestResults result = MFTestResults.Pass;
try
{
string dir = Directory.GetCurrentDirectory() + @"\Microsoft Visual Studio .NET\Frame work\V1.0.0.0000";
Directory.CreateDirectory(dir);
if (!TestExists(dir, true))
return MFTestResults.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
#endregion Test Cases
public MFTestMethod[] Tests
{
get
{
return new MFTestMethod[]
{
new MFTestMethod( InvalidArguments, "InvalidArguments" ),
new MFTestMethod( CurrentDirectory, "CurrentDirectory" ),
new MFTestMethod( NonExistentDirs, "NonExistentDirs" ),
new MFTestMethod( PathTooLong, "PathTooLong" ),
new MFTestMethod( CaseInsensitive, "CaseInsensitive" ),
new MFTestMethod( MultiSpaceExists, "MultiSpaceExists" ),
};
}
}
}
}
| |
/* ====================================================================
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 TestCases.HSSF.Record.CF
{
using System;
using NUnit.Framework;
using NPOI.HSSF.Record.CF;
using NPOI.HSSF.Util;
using NPOI.SS.Util;
/**
* Tests CellRange operations.
*/
[TestFixture]
public class TestCellRange
{
private static CellRangeAddress biggest = CreateCR( 0, -1, 0,-1);
private static CellRangeAddress tenthColumn = CreateCR( 0, -1,10,10);
private static CellRangeAddress tenthRow = CreateCR(10, 10, 0,-1);
private static CellRangeAddress box10x10 = CreateCR( 0, 10, 0,10);
private static CellRangeAddress box9x9 = CreateCR( 0, 9, 0, 9);
private static CellRangeAddress box10to20c = CreateCR( 0, 10,10,20);
private static CellRangeAddress oneCell = CreateCR(10, 10,10,10);
private static CellRangeAddress[] sampleRanges = {
biggest, tenthColumn, tenthRow, box10x10, box9x9, box10to20c, oneCell,
};
/** cross-reference of <c>contains()</c> operations for sampleRanges against itself */
private static bool[,] containsExpectedResults =
{
// biggest, tenthColumn, tenthRow, box10x10, box9x9, box10to20c, oneCell
/*biggest */ {true, true , true , true , true , true , true},
/*tenthColumn*/ {false, true , false, false, false, false, true},
/*tenthRow */ {false, false, true , false, false, false, true},
/*box10x10 */ {false, false, false, true , true , false, true},
/*box9x9 */ {false, false, false, false, true , false, false},
/*box10to20c */ {false, false, false, false, false, true , true},
/*oneCell */ {false, false, false, false, false, false, true},
};
/**
* @param lastRow pass -1 for max row index
* @param lastCol pass -1 for max col index
*/
private static CellRangeAddress CreateCR(int firstRow, int lastRow, int firstCol, int lastCol) {
// max row & max col limit as per BIFF8
return new CellRangeAddress(
firstRow,
lastRow == -1 ? 0xFFFF : lastRow,
firstCol,
lastCol == -1 ? 0x00FF : lastCol);
}
[Test]
public void TestContainsMethod()
{
CellRangeAddress[] ranges = sampleRanges;
for(int i = 0; i != ranges.Length; i++)
{
for(int j = 0; j != ranges.Length; j++)
{
bool expectedResult = containsExpectedResults[i,j];
Assert.AreEqual(expectedResult, CellRangeUtil.Contains(ranges[i], ranges[j]), "("+i+","+j+"): ");
}
}
}
private static CellRangeAddress col1 = CreateCR( 0, -1, 1,1);
private static CellRangeAddress col2 = CreateCR( 0, -1, 2,2);
private static CellRangeAddress row1 = CreateCR( 1, 1, 0,-1);
private static CellRangeAddress row2 = CreateCR( 2, 2, 0,-1);
private static CellRangeAddress box0 = CreateCR( 0, 2, 0,2);
private static CellRangeAddress box1 = CreateCR( 0, 1, 0,1);
private static CellRangeAddress box2 = CreateCR( 0, 1, 2,3);
private static CellRangeAddress box3 = CreateCR( 2, 3, 0,1);
private static CellRangeAddress box4 = CreateCR( 2, 3, 2,3);
private static CellRangeAddress box5 = CreateCR( 1, 3, 1,3);
[Test]
public void TestHasSharedBorderMethod()
{
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(col1, col1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(col2, col2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(col1, col2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(col2, col1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(row1, row1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(row2, row2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(row1, row2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(row2, row1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(row1, col1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(row1, col2));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(col1, row1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(col2, row1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(row2, col1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(row2, col2));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(col1, row2));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(col2, row2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(col2, col1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box1, box1));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box1, box2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box1, box3));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box1, box4));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box2, box1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box2, box2));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box2, box3));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box2, box4));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box3, box1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box3, box2));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box3, box3));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box3, box4));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box4, box1));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box4, box2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box4, box3));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box4, box4));
}
[Test]
public void TestIntersectMethod()
{
Assert.AreEqual(CellRangeUtil.OVERLAP, CellRangeUtil.Intersect(box0, box5));
Assert.AreEqual(CellRangeUtil.OVERLAP, CellRangeUtil.Intersect(box5, box0));
Assert.AreEqual(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.Intersect(box1, box4));
Assert.AreEqual(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.Intersect(box4, box1));
Assert.AreEqual(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.Intersect(box2, box3));
Assert.AreEqual(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.Intersect(box3, box2));
Assert.AreEqual(CellRangeUtil.INSIDE, CellRangeUtil.Intersect(box0, box1));
Assert.AreEqual(CellRangeUtil.INSIDE, CellRangeUtil.Intersect(box0, box0));
Assert.AreEqual(CellRangeUtil.ENCLOSES, CellRangeUtil.Intersect(box1, box0));
Assert.AreEqual(CellRangeUtil.INSIDE, CellRangeUtil.Intersect(tenthColumn, oneCell));
Assert.AreEqual(CellRangeUtil.ENCLOSES, CellRangeUtil.Intersect(oneCell, tenthColumn));
Assert.AreEqual(CellRangeUtil.OVERLAP, CellRangeUtil.Intersect(tenthColumn, tenthRow));
Assert.AreEqual(CellRangeUtil.OVERLAP, CellRangeUtil.Intersect(tenthRow, tenthColumn));
Assert.AreEqual(CellRangeUtil.INSIDE, CellRangeUtil.Intersect(tenthColumn, tenthColumn));
Assert.AreEqual(CellRangeUtil.INSIDE, CellRangeUtil.Intersect(tenthRow, tenthRow));
}
/**
* Cell ranges like the following are valid
* =$C:$IV,$B$1:$B$8,$B$10:$B$65536,$A:$A
*/
[Test]
public void TestCreate() {
CellRangeAddress cr;
cr = CreateCR(0, -1, 2, 255); // $C:$IV
ConfirmRange(cr, false, true);
cr = CreateCR(0, 7, 1, 1); // $B$1:$B$8
try {
cr = CreateCR(9, -1, 1, 1); // $B$65536
} catch (ArgumentException e) {
if(e.Message.StartsWith("invalid cell range")) {
throw new AssertionException("Identified bug 44739");
}
throw e;
}
cr = CreateCR(0, -1, 0, 0); // $A:$A
}
private static void ConfirmRange(CellRangeAddress cr, bool isFullRow, bool isFullColumn) {
Assert.AreEqual(isFullRow, cr.IsFullRowRange, "isFullRowRange");
Assert.AreEqual(isFullColumn, cr.IsFullColumnRange, "isFullColumnRange");
}
[Test]
public void TestNumberOfCells()
{
Assert.AreEqual(1, oneCell.NumberOfCells);
Assert.AreEqual(100, box9x9.NumberOfCells);
Assert.AreEqual(121, box10to20c.NumberOfCells);
}
[Test]
public void TestMergeCellRanges()
{
CellRangeAddress cr1 = CellRangeAddress.ValueOf("A1:B1");
CellRangeAddress cr2 = CellRangeAddress.ValueOf("A2:B2");
CellRangeAddress[] cr3 = CellRangeUtil.MergeCellRanges(new CellRangeAddress[] { cr1, cr2 });
Assert.AreEqual(1, cr3.Length);
Assert.AreEqual("A1:B2", cr3[0].FormatAsString());
}
[Test]
public void TestValueOf()
{
CellRangeAddress cr1 = CellRangeAddress.ValueOf("A1:B1");
Assert.AreEqual(0, cr1.FirstColumn);
Assert.AreEqual(0, cr1.FirstRow);
Assert.AreEqual(1, cr1.LastColumn);
Assert.AreEqual(0, cr1.LastRow);
CellRangeAddress cr2 = CellRangeAddress.ValueOf("B1");
Assert.AreEqual(1, cr2.FirstColumn);
Assert.AreEqual(0, cr2.FirstRow);
Assert.AreEqual(1, cr2.LastColumn);
Assert.AreEqual(0, cr2.LastRow);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// SubscriptionInCredentialsOperations operations.
/// </summary>
internal partial class SubscriptionInCredentialsOperations : Microsoft.Rest.IServiceOperations<AutoRestAzureSpecialParametersTestClient>, ISubscriptionInCredentialsOperations
{
/// <summary>
/// Initializes a new instance of the SubscriptionInCredentialsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SubscriptionInCredentialsOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// POST method with subscriptionId modeled in credentials. Set the
/// credential subscriptionId to '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostMethodGlobalValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostMethodGlobalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/global/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
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;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in credentials. Set the
/// credential subscriptionId to null, and client-side validation should
/// prevent you from making this call
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostMethodGlobalNullWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostMethodGlobalNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/global/null/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
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;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in credentials. Set the
/// credential subscriptionId to '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostMethodGlobalNotProvidedValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostMethodGlobalNotProvidedValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/globalNotProvided/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
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;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in credentials. Set the
/// credential subscriptionId to '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostPathGlobalValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostPathGlobalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/path/string/none/path/global/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
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;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in credentials. Set the
/// credential subscriptionId to '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostSwaggerGlobalValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostSwaggerGlobalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/swagger/string/none/path/global/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
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;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Globalization;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Tests.Common.Builders.Extensions;
using Umbraco.Cms.Tests.Common.Builders.Interfaces;
using Umbraco.Cms.Tests.Common.Extensions;
using Constants = Umbraco.Cms.Core.Constants;
namespace Umbraco.Cms.Tests.Common.Builders
{
public class ContentBuilder
: BuilderBase<Content>,
IBuildContentTypes,
IBuildContentCultureInfosCollection,
IWithIdBuilder,
IWithKeyBuilder,
IWithParentIdBuilder,
IWithCreatorIdBuilder,
IWithCreateDateBuilder,
IWithUpdateDateBuilder,
IWithNameBuilder,
IWithTrashedBuilder,
IWithLevelBuilder,
IWithPathBuilder,
IWithSortOrderBuilder,
IWithCultureInfoBuilder,
IWithPropertyValues
{
private ContentTypeBuilder _contentTypeBuilder;
private ContentCultureInfosCollectionBuilder _contentCultureInfosCollectionBuilder;
private GenericDictionaryBuilder<ContentBuilder, string, object> _propertyDataBuilder;
private int? _id;
private int? _versionId;
private Guid? _key;
private DateTime? _createDate;
private DateTime? _updateDate;
private int? _parentId;
private IContent _parent;
private string _name;
private int? _creatorId;
private int? _level;
private string _path;
private int? _sortOrder;
private bool? _trashed;
private CultureInfo _cultureInfo;
private IContentType _contentType;
private ContentCultureInfosCollection _contentCultureInfosCollection;
private readonly IDictionary<string, string> _cultureNames = new Dictionary<string, string>();
private object _propertyValues;
private string _propertyValuesCulture;
private string _propertyValuesSegment;
public ContentBuilder WithVersionId(int versionId)
{
_versionId = versionId;
return this;
}
public ContentBuilder WithParent(IContent parent)
{
_parentId = null;
_parent = parent;
return this;
}
public ContentBuilder WithContentType(IContentType contentType)
{
_contentTypeBuilder = null;
_contentType = contentType;
return this;
}
public ContentBuilder WithContentCultureInfosCollection(
ContentCultureInfosCollection contentCultureInfosCollection)
{
_contentCultureInfosCollectionBuilder = null;
_contentCultureInfosCollection = contentCultureInfosCollection;
return this;
}
public ContentBuilder WithCultureName(string culture, string name = "")
{
if (string.IsNullOrWhiteSpace(name))
{
if (_cultureNames.TryGetValue(culture, out _))
{
_cultureNames.Remove(culture);
}
}
else
{
_cultureNames[culture] = name;
}
return this;
}
public ContentTypeBuilder AddContentType()
{
_contentType = null;
var builder = new ContentTypeBuilder(this);
_contentTypeBuilder = builder;
return builder;
}
public GenericDictionaryBuilder<ContentBuilder, string, object> AddPropertyData()
{
var builder = new GenericDictionaryBuilder<ContentBuilder, string, object>(this);
_propertyDataBuilder = builder;
return builder;
}
public ContentCultureInfosCollectionBuilder AddContentCultureInfosCollection()
{
_contentCultureInfosCollection = null;
var builder = new ContentCultureInfosCollectionBuilder(this);
_contentCultureInfosCollectionBuilder = builder;
return builder;
}
public override Content Build()
{
var id = _id ?? 0;
var versionId = _versionId ?? 0;
Guid key = _key ?? Guid.NewGuid();
var parentId = _parentId ?? -1;
IContent parent = _parent ?? null;
DateTime createDate = _createDate ?? DateTime.Now;
DateTime updateDate = _updateDate ?? DateTime.Now;
var name = _name ?? Guid.NewGuid().ToString();
var creatorId = _creatorId ?? 0;
var level = _level ?? 1;
var path = _path ?? $"-1,{id}";
var sortOrder = _sortOrder ?? 0;
var trashed = _trashed ?? false;
var culture = _cultureInfo?.Name ?? null;
var propertyValues = _propertyValues ?? null;
var propertyValuesCulture = _propertyValuesCulture ?? null;
var propertyValuesSegment = _propertyValuesSegment ?? null;
if (_contentTypeBuilder is null && _contentType is null)
{
throw new InvalidOperationException("A content item cannot be constructed without providing a content type. Use AddContentType() or WithContentType().");
}
IContentType contentType = _contentType ?? _contentTypeBuilder.Build();
Content content;
if (parent != null)
{
content = new Content(name, parent, contentType, culture);
}
else
{
content = new Content(name, parentId, contentType, culture);
}
content.Id = id;
content.VersionId = versionId;
content.Key = key;
content.CreateDate = createDate;
content.UpdateDate = updateDate;
content.CreatorId = creatorId;
content.Level = level;
content.Path = path;
content.SortOrder = sortOrder;
content.Trashed = trashed;
if (contentType.DefaultTemplate?.Id > 0)
{
content.TemplateId = contentType.DefaultTemplate.Id;
}
foreach (KeyValuePair<string, string> cultureName in _cultureNames)
{
content.SetCultureName(cultureName.Value, cultureName.Key);
}
if (_propertyDataBuilder != null || propertyValues != null)
{
if (_propertyDataBuilder != null)
{
IDictionary<string, object> propertyData = _propertyDataBuilder.Build();
foreach (KeyValuePair<string, object> keyValuePair in propertyData)
{
content.SetValue(keyValuePair.Key, keyValuePair.Value);
}
}
else
{
content.PropertyValues(propertyValues, propertyValuesCulture, propertyValuesSegment);
}
content.ResetDirtyProperties(false);
}
if (_contentCultureInfosCollection is not null || _contentCultureInfosCollectionBuilder is not null)
{
ContentCultureInfosCollection contentCultureInfos =
_contentCultureInfosCollection ?? _contentCultureInfosCollectionBuilder.Build();
content.PublishCultureInfos = contentCultureInfos;
}
return content;
}
public static Content CreateBasicContent(IContentType contentType, int id = 0) =>
new ContentBuilder()
.WithId(id)
.WithContentType(contentType)
.WithName("Home")
.Build();
public static Content CreateSimpleContent(IContentType contentType) =>
new ContentBuilder()
.WithContentType(contentType)
.WithName("Home")
.WithPropertyValues(new
{
title = "Welcome to our Home page",
bodyText = "This is the welcome message on the first page",
author = "John Doe"
})
.Build();
public static Content CreateSimpleContent(IContentType contentType, string name, int parentId = -1, string culture = null, string segment = null) =>
new ContentBuilder()
.WithContentType(contentType)
.WithName(name)
.WithParentId(parentId)
.WithPropertyValues(
new
{
title = "Welcome to our Home page",
bodyText = "This is the welcome message on the first page",
author = "John Doe"
},
culture,
segment)
.Build();
public static Content CreateSimpleContent(IContentType contentType, string name, IContent parent, string culture = null, string segment = null, bool setPropertyValues = true)
{
ContentBuilder builder = new ContentBuilder()
.WithContentType(contentType)
.WithName(name)
.WithParent(parent);
if (!(culture is null))
{
builder = builder.WithCultureName(culture, name);
}
if (setPropertyValues)
{
builder = builder.WithPropertyValues(
new
{
title = name + " Subpage",
bodyText = "This is a subpage",
author = "John Doe"
},
culture,
segment);
}
Content content = builder.Build();
content.ResetDirtyProperties(false);
return content;
}
public static IEnumerable<Content> CreateTextpageContent(IContentType contentType, int parentId, int amount)
{
var list = new List<Content>();
for (var i = 0; i < amount; i++)
{
var name = "Textpage No-" + i;
var content = new Content(name, parentId, contentType) { CreatorId = 0, WriterId = 0 };
object obj =
new
{
title = name + " title",
bodyText = string.Format("This is a textpage based on the {0} ContentType", contentType.Alias),
keywords = "text,page,meta",
description = "This is the meta description for a textpage"
};
content.PropertyValues(obj);
content.ResetDirtyProperties(false);
list.Add(content);
}
return list;
}
public static Content CreateTextpageContent(IContentType contentType, string name, int parentId) =>
new ContentBuilder()
.WithId(0)
.WithContentType(contentType)
.WithName(name)
.WithParentId(parentId)
.WithPropertyValues(
new
{
title = name + " textpage",
bodyText = string.Format("This is a textpage based on the {0} ContentType", contentType.Alias),
keywords = "text,page,meta",
description = "This is the meta description for a textpage"
})
.Build();
public static IEnumerable<Content> CreateMultipleTextpageContent(IContentType contentType, int parentId, int amount)
{
var list = new List<Content>();
for (var i = 0; i < amount; i++)
{
var name = "Textpage No-" + i;
Content content = new ContentBuilder()
.WithName(name)
.WithParentId(parentId)
.WithContentType(contentType)
.WithPropertyValues(new
{
title = name + " title",
bodyText = $"This is a textpage based on the {contentType.Alias} ContentType",
keywords = "text,page,meta",
description = "This is the meta description for a textpage"
})
.Build();
list.Add(content);
}
return list;
}
public static Content CreateAllTypesContent(IContentType contentType, string name, int parentId)
{
Content content = new ContentBuilder()
.WithName(name)
.WithParentId(parentId)
.WithContentType(contentType)
.Build();
content.SetValue("isTrue", true);
content.SetValue("number", 42);
content.SetValue("bodyText", "Lorem Ipsum Body Text Test");
content.SetValue("singleLineText", "Single Line Text Test");
content.SetValue("multilineText", "Multiple lines \n in one box");
content.SetValue("upload", "/media/1234/koala.jpg");
content.SetValue("label", "Non-editable label");
content.SetValue("dateTime", DateTime.Now.AddDays(-20));
content.SetValue("colorPicker", "black");
content.SetValue("ddlMultiple", "1234,1235");
content.SetValue("rbList", "random");
content.SetValue("date", DateTime.Now.AddDays(-10));
content.SetValue("ddl", "1234");
content.SetValue("chklist", "randomc");
content.SetValue("contentPicker", Udi.Create(Constants.UdiEntityType.Document, new Guid("74ECA1D4-934E-436A-A7C7-36CC16D4095C")).ToString());
content.SetValue("mediaPicker", Udi.Create(Constants.UdiEntityType.Media, new Guid("44CB39C8-01E5-45EB-9CF8-E70AAF2D1691")).ToString());
content.SetValue("memberPicker", Udi.Create(Constants.UdiEntityType.Member, new Guid("9A50A448-59C0-4D42-8F93-4F1D55B0F47D")).ToString());
content.SetValue("multiUrlPicker", "[{\"name\":\"https://test.com\",\"url\":\"https://test.com\"}]");
content.SetValue("tags", "this,is,tags");
return content;
}
int? IWithIdBuilder.Id
{
get => _id;
set => _id = value;
}
Guid? IWithKeyBuilder.Key
{
get => _key;
set => _key = value;
}
int? IWithCreatorIdBuilder.CreatorId
{
get => _creatorId;
set => _creatorId = value;
}
DateTime? IWithCreateDateBuilder.CreateDate
{
get => _createDate;
set => _createDate = value;
}
DateTime? IWithUpdateDateBuilder.UpdateDate
{
get => _updateDate;
set => _updateDate = value;
}
string IWithNameBuilder.Name
{
get => _name;
set => _name = value;
}
bool? IWithTrashedBuilder.Trashed
{
get => _trashed;
set => _trashed = value;
}
int? IWithLevelBuilder.Level
{
get => _level;
set => _level = value;
}
string IWithPathBuilder.Path
{
get => _path;
set => _path = value;
}
int? IWithSortOrderBuilder.SortOrder
{
get => _sortOrder;
set => _sortOrder = value;
}
int? IWithParentIdBuilder.ParentId
{
get => _parentId;
set => _parentId = value;
}
CultureInfo IWithCultureInfoBuilder.CultureInfo
{
get => _cultureInfo;
set => _cultureInfo = value;
}
object IWithPropertyValues.PropertyValues
{
get => _propertyValues;
set => _propertyValues = value;
}
string IWithPropertyValues.PropertyValuesCulture
{
get => _propertyValuesCulture;
set => _propertyValuesCulture = value;
}
string IWithPropertyValues.PropertyValuesSegment
{
get => _propertyValuesSegment;
set => _propertyValuesSegment = value;
}
}
}
| |
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Windows.System;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Platform.WinPhone;
namespace Xamarin.Forms
{
internal class WP8PlatformServices : IPlatformServices
{
static readonly MD5CryptoServiceProvider Checksum = new MD5CryptoServiceProvider();
public void BeginInvokeOnMainThread(Action action)
{
Deployment.Current.Dispatcher.BeginInvoke(action);
}
public Ticker CreateTicker()
{
return new WinPhoneTicker();
}
public Assembly[] GetAssemblies()
{
return AppDomain.CurrentDomain.GetAssemblies();
}
public string GetMD5Hash(string input)
{
byte[] bytes = Checksum.ComputeHash(Encoding.UTF8.GetBytes(input));
var ret = new char[32];
for (var i = 0; i < 16; i++)
{
ret[i * 2] = (char)Hex(bytes[i] >> 4);
ret[i * 2 + 1] = (char)Hex(bytes[i] & 0xf);
}
return new string(ret);
}
public double GetNamedSize(NamedSize size, Type targetElementType, bool useOldSizes)
{
switch (size)
{
case NamedSize.Default:
if (typeof(Label).IsAssignableFrom(targetElementType))
return (double)System.Windows.Application.Current.Resources["PhoneFontSizeNormal"];
return (double)System.Windows.Application.Current.Resources["PhoneFontSizeMedium"];
case NamedSize.Micro:
return (double)System.Windows.Application.Current.Resources["PhoneFontSizeSmall"] - 3;
case NamedSize.Small:
return (double)System.Windows.Application.Current.Resources["PhoneFontSizeSmall"];
case NamedSize.Medium:
if (useOldSizes)
goto case NamedSize.Default;
return (double)System.Windows.Application.Current.Resources["PhoneFontSizeMedium"];
case NamedSize.Large:
return (double)System.Windows.Application.Current.Resources["PhoneFontSizeLarge"];
default:
throw new ArgumentOutOfRangeException("size");
}
}
public Task<Stream> GetStreamAsync(Uri uri, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<Stream>();
try
{
HttpWebRequest request = WebRequest.CreateHttp(uri);
request.AllowReadStreamBuffering = true;
request.BeginGetResponse(ar =>
{
if (cancellationToken.IsCancellationRequested)
{
tcs.SetCanceled();
return;
}
try
{
Stream stream = request.EndGetResponse(ar).GetResponseStream();
tcs.TrySetResult(stream);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}, null);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
return tcs.Task;
}
public IIsolatedStorageFile GetUserStoreForApplication()
{
return new _IsolatedStorageFile(IsolatedStorageFile.GetUserStoreForApplication());
}
public bool IsInvokeRequired
{
get { return !Deployment.Current.Dispatcher.CheckAccess(); }
}
public void OpenUriAction(Uri uri)
{
Launcher.LaunchUriAsync(uri).WatchForError();
}
public void StartTimer(TimeSpan interval, Func<bool> callback)
{
var timer = new DispatcherTimer { Interval = interval };
timer.Start();
timer.Tick += (sender, args) =>
{
bool result = callback();
if (!result)
timer.Stop();
};
}
static int Hex(int v)
{
if (v < 10)
return '0' + v;
return 'a' + v - 10;
}
public class _Timer : ITimer
{
readonly Timer _timer;
public _Timer(Timer timer)
{
_timer = timer;
}
public void Change(int dueTime, int period)
{
_timer.Change(dueTime, period);
}
public void Change(long dueTime, long period)
{
_timer.Change(dueTime, period);
}
public void Change(TimeSpan dueTime, TimeSpan period)
{
_timer.Change(dueTime, period);
}
public void Change(uint dueTime, uint period)
{
_timer.Change(dueTime, period);
}
}
public class _IsolatedStorageFile : IIsolatedStorageFile
{
readonly IsolatedStorageFile _isolatedStorageFile;
public _IsolatedStorageFile(IsolatedStorageFile isolatedStorageFile)
{
_isolatedStorageFile = isolatedStorageFile;
}
public Task CreateDirectoryAsync(string path)
{
_isolatedStorageFile.CreateDirectory(path);
return Task.FromResult(true);
}
public Task<bool> GetDirectoryExistsAsync(string path)
{
return Task.FromResult(_isolatedStorageFile.DirectoryExists(path));
}
public Task<bool> GetFileExistsAsync(string path)
{
return Task.FromResult(_isolatedStorageFile.FileExists(path));
}
public Task<DateTimeOffset> GetLastWriteTimeAsync(string path)
{
return Task.FromResult(_isolatedStorageFile.GetLastWriteTime(path));
}
public Task<Stream> OpenFileAsync(string path, FileMode mode, FileAccess access)
{
Stream stream = _isolatedStorageFile.OpenFile(path, (System.IO.FileMode)mode, (System.IO.FileAccess)access);
return Task.FromResult(stream);
}
public Task<Stream> OpenFileAsync(string path, FileMode mode, FileAccess access, FileShare share)
{
Stream stream = _isolatedStorageFile.OpenFile(path, (System.IO.FileMode)mode, (System.IO.FileAccess)access, (System.IO.FileShare)share);
return Task.FromResult(stream);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Shooter;
namespace SpaceShooter
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
enum PlayerState
{
Idle,
Left,
Right
}
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
private Player player;
KeyboardState currentKeyboardState;
KeyboardState previousKeyboardState;
private Texture2D mainBackground;
float playerMoveSpeed;
private Texture2D meteorTexture;
private List<Meteor> meteors;
private TimeSpan enemySpawnTime;
private TimeSpan previousSpawnTime;
private Random random;
private Texture2D projectileTexture;
private List<Projectile> projectiles;
private TimeSpan fireTime;
private TimeSpan previousFireTime;
private bool IsShooting;
private Texture2D explosionTexture;
private List<Animation> explosions;
private Texture2D spaceShipIdle;
private Texture2D spaceShipLeft;
private Texture2D spaceShipRight;
SoundEffect laserSound;
SoundEffect explosionSound;
Song gameplayMusic;
int score;
SpriteFont font;
private PlayerState playerState;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
player = new Player();
playerMoveSpeed = 8.0f;
previousSpawnTime = TimeSpan.Zero;
enemySpawnTime = TimeSpan.FromSeconds(1.0f);
random = new Random();
meteors = new List<Meteor>();
projectiles = new List<Projectile>();
fireTime = TimeSpan.FromSeconds(0.15f);
explosions = new List<Animation>();
score = 0;
playerState = PlayerState.Idle;
IsShooting = false;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
Vector2 playerPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X, GraphicsDevice.Viewport.TitleSafeArea.Y + GraphicsDevice.Viewport.TitleSafeArea.Height / 2);
spaceShipIdle = Content.Load<Texture2D>("player");
player.Initialize(spaceShipIdle, playerPosition);
spaceShipLeft = Content.Load<Texture2D>("playerLeft");
spaceShipRight = Content.Load<Texture2D>("playerRight");
mainBackground = Content.Load<Texture2D>("mainbackground");
meteorTexture = Content.Load<Texture2D>("meteorSmall");
projectileTexture = Content.Load<Texture2D>("laserGreen");
explosionTexture = Content.Load<Texture2D>("explosion");
// Load the music
gameplayMusic = Content.Load<Song>("sound/gameMusic");
laserSound = Content.Load<SoundEffect>("sound/laserFire");
explosionSound = Content.Load<SoundEffect>("sound/explosion");
PlayMusic(gameplayMusic);
font = Content.Load<SpriteFont>("gameFont");
}
private void PlayMusic(Song song)
{
try
{
MediaPlayer.Play(song);
MediaPlayer.IsRepeating = true;
}
catch { }
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
previousKeyboardState = currentKeyboardState;
currentKeyboardState = Keyboard.GetState();
UpdateMeteors(gameTime);
UpdateCollision();
UpdateProjectiles(gameTime);
UpdateExplosion(gameTime);
UpdatePlayer(gameTime);
base.Update(gameTime);
}
private void UpdateProjectiles(GameTime gameTime)
{
for (int i = projectiles.Count - 1; i >= 0; i--)
{
projectiles[i].Update(gameTime);
if (projectiles[i].Active == false)
projectiles.RemoveAt(i);
}
}
private void UpdatePlayer(GameTime gameTime)
{
player.Update(gameTime);
if (currentKeyboardState.IsKeyDown(Keys.Left))
{
player.Position.X -= playerMoveSpeed;
playerState = PlayerState.Left;
player.Sprite = spaceShipLeft;
}
else if (currentKeyboardState.IsKeyDown(Keys.Right))
{
player.Position.X += playerMoveSpeed;
playerState = PlayerState.Right;
player.Sprite = spaceShipRight;
}
else
{
playerState = PlayerState.Idle;
player.Sprite = spaceShipIdle;
}
if (currentKeyboardState.IsKeyDown(Keys.Up))
{
player.Position.Y -= playerMoveSpeed;
}
if (currentKeyboardState.IsKeyDown(Keys.Down))
{
player.Position.Y += playerMoveSpeed;
}
if (currentKeyboardState.IsKeyDown(Keys.Space))
IsShooting = true;
else
IsShooting = false;
player.Position.X = MathHelper.Clamp(player.Position.X,
0, GraphicsDevice.Viewport.Width - player.Width);
player.Position.Y = MathHelper.Clamp(player.Position.Y,
0, GraphicsDevice.Viewport.Height - player.Height);
if (gameTime.TotalGameTime - previousFireTime > fireTime && IsShooting)
{
previousFireTime = gameTime.TotalGameTime;
AddProjectile(player.Position + new Vector2(player.Width / 2f, 0));
laserSound.Play();
}
// reset score if player health goes to zero
if (player.Health <= 0)
{
player.Health = 100;
score = 0;
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
// Start drawing
spriteBatch.Begin();
spriteBatch.Draw(mainBackground, Vector2.Zero, Color.White);
for (int i = 0; i < meteors.Count; i++)
meteors[i].Draw(spriteBatch);
for (int i = 0; i < explosions.Count; i++)
explosions[i].Draw(spriteBatch);
for (int i = 0; i < projectiles.Count; i++)
projectiles[i].Draw(spriteBatch);
spriteBatch.DrawString(font, "score: " + score, new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X, GraphicsDevice.Viewport.TitleSafeArea.Y), Color.White);
spriteBatch.DrawString(font, "health: " + player.Health, new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X, GraphicsDevice.Viewport.TitleSafeArea.Y + 30), Color.White);
player.Draw(spriteBatch);
// Stop drawing
spriteBatch.End();
base.Draw(gameTime);
}
private void AddMeteor()
{
Vector2 position = new Vector2(random.Next(100, GraphicsDevice.Viewport.Width - 100),
(float)meteorTexture.Height / 2
);
Meteor meteor = new Meteor();
meteor.Initialize(meteorTexture, position);
meteors.Add(meteor);
}
private void AddProjectile(Vector2 position)
{
Projectile projectile = new Projectile();
projectile.Initialize(GraphicsDevice.Viewport, projectileTexture, position);
projectiles.Add(projectile);
}
private void UpdateMeteors(GameTime gameTime)
{
if (gameTime.TotalGameTime - previousSpawnTime > enemySpawnTime)
{
previousSpawnTime = gameTime.TotalGameTime;
AddMeteor();
}
for (int i = meteors.Count - 1; i >= 0; i--)
{
meteors[i].Update(gameTime);
if (meteors[i].Active == false)
{
if (meteors[i].Health <= 0)
{
AddExplosion(meteors[i].Position);
explosionSound.Play();
//Add to the player's score
score += meteors[i].Value;
}
meteors.RemoveAt(i);
}
}
}
void AddExplosion(Vector2 position)
{
Animation explosion = new Animation();
explosion.Initialize(explosionTexture, position, 134, 134, 12, 45, Color.White, 1f, false);
explosions.Add(explosion);
}
void UpdateExplosion(GameTime gameTime)
{
for (int i = explosions.Count - 1; i >= 0; i--)
{
explosions[i].Update(gameTime);
if (explosions[i].Active == false)
explosions.RemoveAt(i);
}
}
void UpdateCollision()
{
Rectangle rectangle1;
Rectangle rectangle2;
rectangle1 = new Rectangle((int)player.Position.X,
(int)player.Position.Y,
player.Width,
player.Height);
for (int i = 0; i < meteors.Count; i++)
{
rectangle2 = new Rectangle(
(int)meteors[i].Position.X,
(int)meteors[i].Position.Y,
meteors[i].Width,
meteors[i].Height);
if (rectangle1.Intersects(rectangle2))
{
player.Health -= meteors[i].Damage;
meteors[i].Health = 0;
if (player.Health <= 0)
player.Active = false;
}
}
for (int i = 0; i < projectiles.Count; i++)
{
for (int j = 0; j < meteors.Count; j++)
{
// Create the rectangles we need to determine if we collided with each other
rectangle1 = new Rectangle((int)projectiles[i].Position.X -
projectiles[i].Width / 2, (int)projectiles[i].Position.Y -
projectiles[i].Height / 2, projectiles[i].Width, projectiles[i].Height);
rectangle2 = new Rectangle((int)meteors[j].Position.X - meteors[j].Width / 2,
(int)meteors[j].Position.Y - meteors[j].Height / 2,
meteors[j].Width, meteors[j].Height);
// Determine if the two objects collided with each other
if (rectangle1.Intersects(rectangle2))
{
meteors[j].Health -= projectiles[i].Damage;
projectiles[i].Active = false;
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using System.Runtime.InteropServices;
using System.Collections;
using System.IO;
using Microsoft.Win32;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using IServiceProvider = System.IServiceProvider;
using System.Diagnostics;
using System.Xml;
using System.Text;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
using Microsoft.VisualStudio.FSharp.LanguageService.Resources;
namespace Microsoft.VisualStudio.FSharp.LanguageService {
internal class DefaultFieldValue {
private string field;
private string value;
internal DefaultFieldValue(string field, string value) {
this.field = field;
this.value = value;
}
internal string Field {
get { return this.field; }
}
internal string Value {
get { return this.value; }
}
}
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public class ExpansionProvider : IDisposable, IVsExpansionClient {
IVsTextView view;
ISource source;
IVsExpansion vsExpansion;
IVsExpansionSession expansionSession;
bool expansionActive;
bool expansionPrepared;
bool completorActiveDuringPreExec;
ArrayList fieldDefaults; // CDefaultFieldValues
string titleToInsert;
string pathToInsert;
internal ExpansionProvider(ISource src) {
if (src == null){
throw new ArgumentNullException("src");
}
this.fieldDefaults = new ArrayList();
if (src == null)
throw new System.ArgumentNullException();
this.source = src;
this.vsExpansion = null; // do we need a Close() method here?
// QI for IVsExpansion
IVsTextLines buffer = src.GetTextLines();
this.vsExpansion = (IVsExpansion)buffer;
if (this.vsExpansion == null) {
throw new ArgumentNullException("(IVsExpansion)src.GetTextLines()");
}
}
~ExpansionProvider() {
#if LANGTRACE
Trace.WriteLine("~ExpansionProvider");
#endif
}
public virtual void Dispose() {
EndTemplateEditing(true);
this.source = null;
this.vsExpansion = null;
this.view = null;
GC.SuppressFinalize(this);
}
internal ISource Source {
get { return this.source; }
}
internal IVsTextView TextView {
get { return this.view; }
}
internal IVsExpansion Expansion {
get { return this.vsExpansion; }
}
internal IVsExpansionSession ExpansionSession {
get { return this.expansionSession; }
}
internal virtual bool HandleQueryStatus(ref Guid guidCmdGroup, uint nCmdId, out int hr) {
// in case there's something to conditinally support later on...
hr = 0;
return false;
}
internal virtual bool InTemplateEditingMode {
get {
return this.expansionActive;
}
}
internal virtual TextSpan GetExpansionSpan() {
if (this.expansionSession == null){
throw new System.InvalidOperationException(SR.GetString(SR.NoExpansionSession));
}
TextSpan[] pts = new TextSpan[1];
int hr = this.expansionSession.GetSnippetSpan(pts);
if (NativeMethods.Succeeded(hr)) {
return pts[0];
}
return new TextSpan();
}
internal virtual bool HandlePreExec(ref Guid guidCmdGroup, uint nCmdId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (!this.expansionActive || this.expansionSession == null) {
return false;
}
this.completorActiveDuringPreExec = this.IsCompletorActive(this.view);
if (guidCmdGroup == typeof(VsCommands2K).GUID) {
VsCommands2K cmd = (VsCommands2K)nCmdId;
#if TRACE_EXEC
Trace.WriteLine(String.Format("ExecCommand: {0}", cmd.ToString()));
#endif
switch (cmd) {
case VsCommands2K.CANCEL:
if (this.completorActiveDuringPreExec)
return false;
EndTemplateEditing(true);
return true;
case VsCommands2K.RETURN:
bool leaveCaret = false;
int line = 0, col = 0;
if (NativeMethods.Succeeded(this.view.GetCaretPos(out line, out col))) {
TextSpan span = GetExpansionSpan();
if (!TextSpanHelper.ContainsExclusive(span, line, col)) {
leaveCaret = true;
}
}
if (this.completorActiveDuringPreExec)
return false;
if (this.completorActiveDuringPreExec)
return false;
EndTemplateEditing(leaveCaret);
if (leaveCaret)
return false;
return true;
case VsCommands2K.BACKTAB:
if (this.completorActiveDuringPreExec)
return false;
this.expansionSession.GoToPreviousExpansionField();
return true;
case VsCommands2K.TAB:
if (this.completorActiveDuringPreExec)
return false;
this.expansionSession.GoToNextExpansionField(0); // fCommitIfLast=false
return true;
#if TRACE_EXEC
case VsCommands2K.TYPECHAR:
if (pvaIn != IntPtr.Zero) {
Variant v = Variant.ToVariant(pvaIn);
char ch = v.ToChar();
Trace.WriteLine(String.Format("TYPECHAR: {0}, '{1}', {2}", cmd.ToString(), ch.ToString(), (int)ch));
}
return true;
#endif
}
}
return false;
}
internal virtual bool HandlePostExec(ref Guid guidCmdGroup, uint nCmdId, uint nCmdexecopt, bool commit, IntPtr pvaIn, IntPtr pvaOut) {
if (guidCmdGroup == typeof(VsCommands2K).GUID) {
VsCommands2K cmd = (VsCommands2K)nCmdId;
switch (cmd) {
case VsCommands2K.RETURN:
if (this.completorActiveDuringPreExec && commit) {
// if the completor was active during the pre-exec we want to let it handle the command first
// so we didn't deal with this in pre-exec. If we now get the command, we want to end
// the editing of the expansion. We also return that we handled the command so auto-indenting doesn't happen
EndTemplateEditing(false);
this.completorActiveDuringPreExec = false;
return true;
}
break;
}
}
this.completorActiveDuringPreExec = false;
return false;
}
internal virtual bool DisplayExpansionBrowser(IVsTextView view, string prompt, string[] types, bool includeNullType, string[] kinds, bool includeNullKind) {
if (this.expansionActive) this.EndTemplateEditing(true);
if (this.source.IsCompletorActive) {
this.source.DismissCompletor();
}
this.view = view;
IServiceProvider site = this.source.LanguageService.Site;
IVsTextManager2 textmgr = site.GetService(typeof(SVsTextManager)) as IVsTextManager2;
if (textmgr == null) return false;
IVsExpansionManager exmgr;
textmgr.GetExpansionManager(out exmgr);
Guid languageSID = this.source.LanguageService.GetLanguageServiceGuid();
int hr = 0;
if (exmgr != null) {
hr = exmgr.InvokeInsertionUI(view, // pView
this, // pClient
languageSID, // guidLang
types, // bstrTypes
(types == null) ? 0 : types.Length, // iCountTypes
includeNullType ? 1 : 0, // fIncludeNULLType
kinds, // bstrKinds
(kinds == null) ? 0 : kinds.Length, // iCountKinds
includeNullKind ? 1 : 0, // fIncludeNULLKind
prompt, // bstrPrefixText
">" //bstrCompletionChar
);
if (NativeMethods.Succeeded(hr)) {
return true;
}
}
return false;
}
internal virtual bool InsertSpecificExpansion(IVsTextView view, XmlElement snippet, TextSpan pos, string relativePath) {
if (this.expansionActive) this.EndTemplateEditing(true);
if (this.source.IsCompletorActive) {
this.source.DismissCompletor();
}
this.view = view;
MSXML.IXMLDOMDocument doc = new MSXML.DOMDocumentClass();
if (!doc.loadXML(snippet.OuterXml)) {
throw new ArgumentException(doc.parseError.reason);
}
Guid guidLanguage = this.source.LanguageService.GetLanguageServiceGuid();
int hr = this.vsExpansion.InsertSpecificExpansion(doc, pos, this, guidLanguage, relativePath, out this.expansionSession);
if (hr != NativeMethods.S_OK || this.expansionSession == null) {
this.EndTemplateEditing(true);
} else {
this.expansionActive = true;
return true;
}
return false;
}
bool IsCompletorActive(IVsTextView view){
if (this.source.IsCompletorActive)
return true;
IVsTextViewEx viewex = view as IVsTextViewEx;
if (viewex != null) {
return viewex.IsCompletorWindowActive() == VSConstants.S_OK;
}
return false;
}
internal virtual bool InsertNamedExpansion(IVsTextView view, string title, string path, TextSpan pos, bool showDisambiguationUI) {
if (this.source.IsCompletorActive) {
this.source.DismissCompletor();
}
this.view = view;
if (this.expansionActive) this.EndTemplateEditing(true);
Guid guidLanguage = this.source.LanguageService.GetLanguageServiceGuid();
int hr = this.vsExpansion.InsertNamedExpansion(title, path, pos, this, guidLanguage, showDisambiguationUI ? 1 : 0, out this.expansionSession);
if (hr != NativeMethods.S_OK || this.expansionSession == null) {
this.EndTemplateEditing(true);
return false;
} else if (hr == NativeMethods.S_OK) {
this.expansionActive = true;
return true;
}
return false;
}
/// <summary>Returns S_OK if match found, S_FALSE if expansion UI is shown, and error otherwise</summary>
internal virtual int FindExpansionByShortcut(IVsTextView view, string shortcut, TextSpan span, bool showDisambiguationUI, out string title, out string path) {
if (this.expansionActive) this.EndTemplateEditing(true);
this.view = view;
title = path = null;
LanguageService svc = this.source.LanguageService;
IVsExpansionManager mgr = svc.Site.GetService(typeof(SVsExpansionManager)) as IVsExpansionManager;
if (mgr == null) return NativeMethods.E_FAIL ;
Guid guidLanguage = svc.GetLanguageServiceGuid();
TextSpan[] pts = new TextSpan[1];
pts[0] = span;
int hr = mgr.GetExpansionByShortcut(this, guidLanguage, shortcut, this.TextView, pts, showDisambiguationUI ? 1 : 0, out path, out title);
return hr;
}
public virtual IVsExpansionFunction GetExpansionFunction(XmlElement xmlFunctionNode, string fieldName) {
string functionName = null;
ArrayList rgFuncParams = new ArrayList();
// first off, get the function string from the node
string function = xmlFunctionNode.InnerText;
if (function == null || function.Length == 0)
return null;
bool inIdent = false;
bool inParams = false;
int token = 0;
// initialize the vars needed for our super-complex function parser :-)
for (int i = 0, n = function.Length; i < n; i++) {
char ch = function[i];
// ignore and skip whitespace
if (!Char.IsWhiteSpace(ch)) {
switch (ch) {
case ',':
if (!inIdent || !inParams)
i = n; // terminate loop
else {
// we've hit a comma, so end this param and move on...
string name = function.Substring(token, i - token);
rgFuncParams.Add(name);
inIdent = false;
}
break;
case '(':
if (!inIdent || inParams)
i = n; // terminate loop
else {
// we've hit the (, so we know the token before this is the name of the function
functionName = function.Substring(token, i - token);
inIdent = false;
inParams = true;
}
break;
case ')':
if (!inParams)
i = n; // terminate loop
else {
if (inIdent) {
// save last param and stop
string name = function.Substring(token, i - token);
rgFuncParams.Add(name);
inIdent = false;
}
i = n; // terminate loop
}
break;
default:
if (!inIdent) {
inIdent = true;
token = i;
}
break;
}
}
}
if (functionName != null && functionName.Length > 0) {
ExpansionFunction func = this.source.LanguageService.CreateExpansionFunction(this, functionName);
if (func != null) {
func.FieldName = fieldName;
func.Arguments = (string[])rgFuncParams.ToArray(typeof(string));
return func;
}
}
return null;
}
internal virtual void PrepareTemplate(string title, string path) {
if (title == null)
throw new System.ArgumentNullException("title");
// stash the title and path for when we actually insert the template
this.titleToInsert = title;
this.pathToInsert = path;
this.expansionPrepared = true;
}
void SetFieldDefault(string field, string value) {
if (!this.expansionPrepared) {
throw new System.InvalidOperationException(SR.GetString(SR.TemplateNotPrepared));
}
if (field == null) throw new System.ArgumentNullException("field");
if (value == null) throw new System.ArgumentNullException("value");
// we have an expansion "prepared" to insert, so we can now save this
// field default to set when the expansion is actually inserted
this.fieldDefaults.Add(new DefaultFieldValue(field, value));
}
internal virtual void BeginTemplateEditing(int line, int col) {
if (!this.expansionPrepared) {
throw new System.InvalidOperationException(SR.GetString(SR.TemplateNotPrepared));
}
TextSpan tsInsert = new TextSpan();
tsInsert.iStartLine = tsInsert.iEndLine = line;
tsInsert.iStartIndex = tsInsert.iEndIndex = col;
Guid languageSID = this.source.LanguageService.GetType().GUID;
int hr = this.vsExpansion.InsertNamedExpansion(this.titleToInsert,
this.pathToInsert,
tsInsert,
(IVsExpansionClient)this,
languageSID,
0, // fShowDisambiguationUI,
out this.expansionSession);
if (hr != NativeMethods.S_OK) {
this.EndTemplateEditing(true);
}
this.pathToInsert = null;
this.titleToInsert = null;
}
internal virtual void EndTemplateEditing(bool leaveCaret) {
if (!this.expansionActive || this.expansionSession == null) {
this.expansionActive = false;
return;
}
this.expansionSession.EndCurrentExpansion(leaveCaret ? 1 : 0); // fLeaveCaret=true
this.expansionSession = null;
this.expansionActive = false;
}
internal virtual bool GetFieldSpan(string field, out TextSpan pts) {
if (this.expansionSession == null) {
throw new System.InvalidOperationException(SR.GetString(SR.NoExpansionSession));
}
if (this.expansionSession != null) {
TextSpan[] apt = new TextSpan[1];
this.expansionSession.GetFieldSpan(field, apt);
pts = apt[0];
return true;
} else {
pts = new TextSpan();
return false;
}
}
internal virtual bool GetFieldValue(string field, out string value) {
if (this.expansionSession == null) {
throw new System.InvalidOperationException(SR.GetString(SR.NoExpansionSession));
}
if (this.expansionSession != null) {
this.expansionSession.GetFieldValue(field, out value);
} else {
value = null;
}
return value != null;
}
public int EndExpansion() {
this.expansionActive = false;
this.expansionSession = null;
return NativeMethods.S_OK;
}
public virtual int FormatSpan(IVsTextLines buffer, TextSpan[] ts) {
if (this.source.GetTextLines() != buffer) {
throw new System.ArgumentException(SR.GetString(SR.UnknownBuffer), "buffer");
}
int rc = NativeMethods.E_NOTIMPL;
if (ts != null) {
for (int i = 0, n = ts.Length; i < n; i++) {
if (this.source.LanguageService.Preferences.EnableFormatSelection) {
TextSpan span = ts[i];
// We should not merge edits in this case because it might clobber the
// $varname$ spans which are markers for yellow boxes.
using (EditArray edits = new EditArray(this.source, this.view, false, SR.GetString(SR.FormatSpan))) {
this.source.ReformatSpan(edits, span);
edits.ApplyEdits();
}
rc = NativeMethods.S_OK;
}
}
}
return rc;
}
public virtual int IsValidKind(IVsTextLines buffer, TextSpan[] ts, string bstrKind, out int /*BOOL*/ fIsValid)
{
fIsValid = 0;
if (this.source.GetTextLines() != buffer)
{
throw new System.ArgumentException(SR.GetString(SR.UnknownBuffer), "buffer");
}
fIsValid = 1;
return NativeMethods.S_OK;
}
public virtual int IsValidType(IVsTextLines buffer, TextSpan[] ts, string[] rgTypes, int iCountTypes, out int /*BOOL*/ fIsValid)
{
fIsValid = 0;
if (this.source.GetTextLines() != buffer) {
throw new System.ArgumentException(SR.GetString(SR.UnknownBuffer), "buffer");
}
fIsValid = 1;
return NativeMethods.S_OK;
}
public virtual int OnItemChosen(string pszTitle, string pszPath) {
TextSpan ts;
view.GetCaretPos(out ts.iStartLine, out ts.iStartIndex);
ts.iEndLine = ts.iStartLine;
ts.iEndIndex = ts.iStartIndex;
if (this.expansionSession != null) { // previous session should have been ended by now!
EndTemplateEditing(true);
}
Guid languageSID = this.source.LanguageService.GetType().GUID;
// insert the expansion
int hr = this.vsExpansion.InsertNamedExpansion(pszTitle,
pszPath,
ts,
(IVsExpansionClient)this,
languageSID,
0, // fShowDisambiguationUI, (FALSE)
out this.expansionSession);
return hr;
}
public virtual int PositionCaretForEditing(IVsTextLines pBuffer, TextSpan[] ts) {
// NOP
return NativeMethods.S_OK;
}
public virtual int OnAfterInsertion(IVsExpansionSession session) {
return NativeMethods.S_OK;
}
public virtual int OnBeforeInsertion(IVsExpansionSession session) {
if (session == null)
return NativeMethods.E_UNEXPECTED;
this.expansionPrepared = false;
this.expansionActive = true;
// stash the expansion session pointer while the expansion is active
if (this.expansionSession == null) {
this.expansionSession = session;
} else {
// these better be the same!
Debug.Assert(this.expansionSession == session);
}
// now set any field defaults that we have.
foreach (DefaultFieldValue dv in this.fieldDefaults) {
this.expansionSession.SetFieldDefault(dv.Field, dv.Value);
}
this.fieldDefaults.Clear();
return NativeMethods.S_OK;
}
public virtual int GetExpansionFunction(MSXML.IXMLDOMNode xmlFunctionNode, string fieldName, out IVsExpansionFunction func) {
XmlDocument doc = new XmlDocument();
doc.XmlResolver = null;
using(StringReader stream = new StringReader(xmlFunctionNode.xml))
using (XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings() { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }))
{
doc.Load(reader);
func = GetExpansionFunction(doc.DocumentElement, fieldName);
}
return NativeMethods.S_OK;
}
}
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class ExpansionFunction : IVsExpansionFunction {
ExpansionProvider provider;
string fieldName;
string[] args;
string[] list;
/// <summary>You must construct this object with an ExpansionProvider</summary>
private ExpansionFunction() {
}
internal ExpansionFunction(ExpansionProvider provider) {
this.provider = provider;
}
public ExpansionProvider ExpansionProvider {
get { return this.provider; }
}
public string[] Arguments {
get { return this.args; }
set { this.args = value; }
}
public string FieldName {
get { return this.fieldName; }
set { this.fieldName = value; }
}
public abstract string GetCurrentValue();
public virtual string GetDefaultValue() {
// This must call GetCurrentValue sincs during initialization of the snippet
// VS will call GetDefaultValue and not GetCurrentValue.
return GetCurrentValue();
}
/// <summary>Override this method if you want intellisense drop support on a list of possible values.</summary>
public virtual string[] GetIntellisenseList() {
return null;
}
/// <summary>
/// Gets the value of the specified argument, resolving any fields referenced in the argument.
/// In the substitution, "$$" is replaced with "$" and any floating '$' signs are left unchanged,
/// for example "$US 23.45" is returned as is. Only if the two dollar signs enclose a string of
/// letters or digits is this considered a field name (e.g. "$foo123$"). If the field is not found
/// then the unresolved string "$foo" is returned.
/// </summary>
public string GetArgument(int index) {
if (args == null || args.Length == 0 || index > args.Length) return null;
string arg = args[index];
if (arg == null) return null;
int i = arg.IndexOf('$');
if (i >= 0) {
StringBuilder sb = new StringBuilder();
int len = arg.Length;
int start = 0;
while (i >= 0 && i + 1 < len) {
sb.Append(arg.Substring(start, i - start));
start = i;
i++;
if (arg[i] == '$') {
sb.Append('$');
start = i + 1; // $$ is resolved to $.
} else {
// parse name of variable.
int j = i;
for (; j < len; j++) {
if (!Char.IsLetterOrDigit(arg[j]))
break;
}
if (j == len) {
// terminating '$' not found.
sb.Append('$');
start = i;
break;
} else if (arg[j] == '$') {
string name = arg.Substring(i, j - i);
string value;
if (GetFieldValue(name, out value)) {
sb.Append(value);
} else {
// just return the unresolved variable.
sb.Append('$');
sb.Append(name);
sb.Append('$');
}
start = j + 1;
} else {
// invalid syntax, e.g. "$US 23.45" or some such thing
sb.Append('$');
sb.Append(arg.Substring(i, j - i));
start = j;
}
}
i = arg.IndexOf('$', start);
}
if (start < len) {
sb.Append(arg.Substring(start, len - start));
}
arg = sb.ToString();
}
// remove quotes around string literals.
if (arg.Length > 2 && arg[0] == '"' && arg[arg.Length - 1] == '"') {
arg = arg.Substring(1, arg.Length - 2);
} else if (arg.Length > 2 && arg[0] == '\'' && arg[arg.Length - 1] == '\'') {
arg = arg.Substring(1, arg.Length - 2);
}
return arg;
}
public bool GetFieldValue(string name, out string value) {
value = null;
if (this.provider != null && this.provider.ExpansionSession != null) {
int hr = this.provider.ExpansionSession.GetFieldValue(name, out value);
return NativeMethods.Succeeded(hr);
}
return false;
}
public TextSpan GetSelection() {
TextSpan result = new TextSpan();
ExpansionProvider provider = this.ExpansionProvider;
if (provider != null && provider.TextView != null) {
NativeMethods.ThrowOnFailure(provider.TextView.GetSelection(out result.iStartLine,
out result.iStartIndex, out result.iEndLine, out result.iEndIndex));
}
return result;
}
public virtual int FieldChanged(string bstrField, out int fRequeryValue) {
// Returns true if we care about this field changing.
// We care if the field changes if one of the arguments refers to it.
if (this.args != null) {
string var = "$" + bstrField + "$";
foreach (string arg in this.args) {
if (arg == var) {
fRequeryValue = 1; // we care!
return NativeMethods.S_OK;
}
}
}
fRequeryValue = 0;
return NativeMethods.S_OK;
}
public int GetCurrentValue(out string bstrValue, out int hasDefaultValue) {
try {
bstrValue = this.GetCurrentValue();
} catch {
bstrValue = String.Empty;
}
hasDefaultValue = (bstrValue == null) ? 0 : 1;
return NativeMethods.S_OK;
}
public int GetDefaultValue(out string bstrValue, out int hasCurrentValue) {
try {
bstrValue = this.GetDefaultValue();
} catch {
bstrValue = String.Empty;
}
hasCurrentValue = (bstrValue == null) ? 0 : 1;
return NativeMethods.S_OK;
}
public virtual int GetFunctionType(out uint pFuncType) {
if (this.list == null) {
this.list = this.GetIntellisenseList();
}
pFuncType = (this.list == null) ? (uint)_ExpansionFunctionType.eft_Value : (uint)_ExpansionFunctionType.eft_List;
return NativeMethods.S_OK;
}
public virtual int GetListCount(out int iListCount) {
if (this.list == null) {
this.list = this.GetIntellisenseList();
}
if (this.list != null) {
iListCount = this.list.Length;
} else {
iListCount = 0;
}
return NativeMethods.S_OK;
}
public virtual int GetListText(int iIndex, out string ppszText) {
if (this.list == null) {
this.list = this.GetIntellisenseList();
}
if (this.list != null) {
ppszText = this.list[iIndex];
} else {
ppszText = null;
}
return NativeMethods.S_OK;
}
public virtual int ReleaseFunction() {
this.provider = null;
return NativeMethods.S_OK;
}
}
// todo: for some reason VsExpansionManager is wrong.
[Guid("4970C2BC-AF33-4a73-A34F-18B0584C40E4")]
internal class SVsExpansionManager {
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyNumber
{
using System.Threading.Tasks;
using Models;
/// <summary>
/// Extension methods for Number.
/// </summary>
public static partial class NumberExtensions
{
/// <summary>
/// Get null Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetNull(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetNullAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get null Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<double?> GetNullAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get invalid float Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetInvalidFloat(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetInvalidFloatAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid float Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<double?> GetInvalidFloatAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetInvalidFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get invalid double Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetInvalidDouble(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetInvalidDoubleAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid double Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<double?> GetInvalidDoubleAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetInvalidDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get invalid decimal Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static decimal? GetInvalidDecimal(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetInvalidDecimalAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid decimal Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<decimal?> GetInvalidDecimalAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetInvalidDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big float value 3.402823e+20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigFloat(this INumber operations, double numberBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).PutBigFloatAsync(numberBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big float value 3.402823e+20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutBigFloatAsync(this INumber operations, double numberBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutBigFloatWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big float value 3.402823e+20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetBigFloat(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetBigFloatAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big float value 3.402823e+20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<double?> GetBigFloatAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetBigFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big double value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigDouble(this INumber operations, double numberBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).PutBigDoubleAsync(numberBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big double value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutBigDoubleAsync(this INumber operations, double numberBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutBigDoubleWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big double value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetBigDouble(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetBigDoubleAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big double value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<double?> GetBigDoubleAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetBigDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big double value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigDoublePositiveDecimal(this INumber operations, double numberBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).PutBigDoublePositiveDecimalAsync(numberBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big double value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutBigDoublePositiveDecimalAsync(this INumber operations, double numberBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutBigDoublePositiveDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big double value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetBigDoublePositiveDecimal(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetBigDoublePositiveDecimalAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big double value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<double?> GetBigDoublePositiveDecimalAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetBigDoublePositiveDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big double value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigDoubleNegativeDecimal(this INumber operations, double numberBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).PutBigDoubleNegativeDecimalAsync(numberBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big double value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutBigDoubleNegativeDecimalAsync(this INumber operations, double numberBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutBigDoubleNegativeDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big double value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetBigDoubleNegativeDecimal(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetBigDoubleNegativeDecimalAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big double value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<double?> GetBigDoubleNegativeDecimalAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetBigDoubleNegativeDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big decimal value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigDecimal(this INumber operations, decimal numberBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).PutBigDecimalAsync(numberBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big decimal value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutBigDecimalAsync(this INumber operations, decimal numberBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutBigDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big decimal value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static decimal? GetBigDecimal(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetBigDecimalAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big decimal value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<decimal?> GetBigDecimalAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetBigDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big decimal value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigDecimalPositiveDecimal(this INumber operations, decimal numberBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).PutBigDecimalPositiveDecimalAsync(numberBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big decimal value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutBigDecimalPositiveDecimalAsync(this INumber operations, decimal numberBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutBigDecimalPositiveDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big decimal value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static decimal? GetBigDecimalPositiveDecimal(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetBigDecimalPositiveDecimalAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big decimal value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<decimal?> GetBigDecimalPositiveDecimalAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetBigDecimalPositiveDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big decimal value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigDecimalNegativeDecimal(this INumber operations, decimal numberBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).PutBigDecimalNegativeDecimalAsync(numberBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big decimal value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutBigDecimalNegativeDecimalAsync(this INumber operations, decimal numberBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutBigDecimalNegativeDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big decimal value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static decimal? GetBigDecimalNegativeDecimal(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetBigDecimalNegativeDecimalAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big decimal value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<decimal?> GetBigDecimalNegativeDecimalAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetBigDecimalNegativeDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put small float value 3.402823e-20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutSmallFloat(this INumber operations, double numberBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).PutSmallFloatAsync(numberBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put small float value 3.402823e-20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutSmallFloatAsync(this INumber operations, double numberBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutSmallFloatWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big double value 3.402823e-20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetSmallFloat(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetSmallFloatAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big double value 3.402823e-20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<double?> GetSmallFloatAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetSmallFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put small double value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutSmallDouble(this INumber operations, double numberBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).PutSmallDoubleAsync(numberBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put small double value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutSmallDoubleAsync(this INumber operations, double numberBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutSmallDoubleWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big double value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetSmallDouble(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetSmallDoubleAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big double value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<double?> GetSmallDoubleAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetSmallDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put small decimal value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutSmallDecimal(this INumber operations, decimal numberBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).PutSmallDecimalAsync(numberBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put small decimal value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutSmallDecimalAsync(this INumber operations, decimal numberBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutSmallDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get small decimal value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static decimal? GetSmallDecimal(this INumber operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INumber)s).GetSmallDecimalAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get small decimal value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<decimal?> GetSmallDecimalAsync(this INumber operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetSmallDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.ServiceManagemenet.Common.Models;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC.Publish;
using Microsoft.WindowsAzure.Storage.Auth;
using System;
using System.Management.Automation;
using Microsoft.Azure.Commands.Common.Authentication.Models;
namespace Microsoft.Azure.Commands.Compute.Extension.DSC
{
/// <summary>
/// Uploads a Desired State Configuration script to Azure blob storage, which
/// later can be applied to Azure Virtual Machines using the
/// Set-AzureRmVMDscExtension cmdlet.
/// </summary>
[Cmdlet(
VerbsData.Publish,
ProfileNouns.VirtualMachineDscConfiguration,
SupportsShouldProcess = true,
DefaultParameterSetName = UploadArchiveParameterSetName),
OutputType(
typeof(String))]
public class PublishAzureVMDscConfigurationCommand : DscExtensionPublishCmdletCommonBase
{
private const string CreateArchiveParameterSetName = "CreateArchive";
private const string UploadArchiveParameterSetName = "UploadArchive";
[Parameter(
Mandatory = true,
Position = 2,
ParameterSetName = UploadArchiveParameterSetName,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The name of the resource group that contains the storage account.")]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
/// <summary>
/// Path to a file containing one or more configurations; the file can be a
/// PowerShell script (*.ps1) or MOF interface (*.mof).
/// </summary>
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a file containing one or more configurations")]
[ValidateNotNullOrEmpty]
public string ConfigurationPath { get; set; }
/// <summary>
/// Name of the Azure Storage Container the configuration is uploaded to.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
Position = 4,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "Name of the Azure Storage Container the configuration is uploaded to")]
[ValidateNotNullOrEmpty]
public string ContainerName { get; set; }
/// <summary>
/// The Azure Storage Account name used to upload the configuration script to the container specified by ContainerName.
/// </summary>
[Parameter(
Mandatory = true,
Position = 3,
ValueFromPipelineByPropertyName = true,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "The Azure Storage Account name used to upload the configuration script to the container " +
"specified by ContainerName ")]
[ValidateNotNullOrEmpty]
public String StorageAccountName { get; set; }
/// <summary>
/// Path to a local ZIP file to write the configuration archive to.
/// When using this parameter, Publish-AzureRmVMDscConfiguration creates a
/// local ZIP archive instead of uploading it to blob storage..
/// </summary>
[Alias("ConfigurationArchivePath")]
[Parameter(
Position = 2,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CreateArchiveParameterSetName,
HelpMessage = "Path to a local ZIP file to write the configuration archive to.")]
[ValidateNotNullOrEmpty]
public string OutputArchivePath { get; set; }
/// <summary>
/// Suffix for the storage end point, e.g. core.windows.net
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "Suffix for the storage end point, e.g. core.windows.net")]
[ValidateNotNullOrEmpty]
public string StorageEndpointSuffix { get; set; }
/// <summary>
/// By default Publish-AzureRmVMDscConfiguration will not overwrite any existing blobs.
/// Use -Force to overwrite them.
/// </summary>
[Parameter(HelpMessage = "By default Publish-AzureRmVMDscConfiguration will not overwrite any existing blobs")]
public SwitchParameter Force { get; set; }
/// <summary>
/// Excludes DSC resource dependencies from the configuration archive
/// </summary>
[Parameter(HelpMessage = "Excludes DSC resource dependencies from the configuration archive")]
public SwitchParameter SkipDependencyDetection { get; set; }
/// <summary>
///Path to a .psd1 file that specifies the data for the Configuration. This
/// file must contain a hashtable with the items described in
/// http://technet.microsoft.com/en-us/library/dn249925.aspx.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration. This is added to the configuration " +
"archive and then passed to the configuration function. It gets overwritten by the configuration data path " +
"provided through the Set-AzureRmVMDscExtension cmdlet")]
[ValidateNotNullOrEmpty]
public string ConfigurationDataPath { get; set; }
/// <summary>
/// Path to a file or a directory to include in the configuration archive
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a file or a directory to include in the configuration archive. It gets downloaded to the " +
"VM along with the configuration")]
[ValidateNotNullOrEmpty]
public String[] AdditionalPath { get; set; }
//Private Variables
/// <summary>
/// Credentials used to access Azure Storage
/// </summary>
private StorageCredentials _storageCredentials;
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
try
{
ValidatePsVersion();
//validate cmdlet params
ConfigurationPath = GetUnresolvedProviderPathFromPSPath(ConfigurationPath);
ValidateConfigurationPath(ConfigurationPath, ParameterSetName);
if (ConfigurationDataPath != null)
{
ConfigurationDataPath = GetUnresolvedProviderPathFromPSPath(ConfigurationDataPath);
ValidateConfigurationDataPath(ConfigurationDataPath);
}
if (AdditionalPath != null && AdditionalPath.Length > 0)
{
for (var count = 0; count < AdditionalPath.Length; count++)
{
AdditionalPath[count] = GetUnresolvedProviderPathFromPSPath(AdditionalPath[count]);
}
}
switch (ParameterSetName)
{
case CreateArchiveParameterSetName:
OutputArchivePath = GetUnresolvedProviderPathFromPSPath(OutputArchivePath);
break;
case UploadArchiveParameterSetName:
_storageCredentials = this.GetStorageCredentials(ResourceGroupName,StorageAccountName);
if (ContainerName == null)
{
ContainerName = DscExtensionCmdletConstants.DefaultContainerName;
}
if (StorageEndpointSuffix == null)
{
StorageEndpointSuffix =
DefaultProfile.Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix);
}
break;
}
PublishConfiguration(
ConfigurationPath,
ConfigurationDataPath,
AdditionalPath,
OutputArchivePath,
StorageEndpointSuffix,
ContainerName,
ParameterSetName,
Force.IsPresent,
SkipDependencyDetection.IsPresent,
_storageCredentials);
}
finally
{
DeleteTemporaryFiles();
}
}
}
}
| |
using Lucene.Net.Attributes;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using System.IO;
using System.Text;
namespace Lucene.Net.Support.IO
{
/*
* 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.
*/
public class TestDataInputStream : LuceneTestCase
{
[Test, LuceneNetSpecific]
public void TestReadFully()
{
const string READFULLY_TEST_FILE = "ReadFully.txt";
int fileLength;
Stream @in;
// Read one time to measure the length of the file (it may be different
// on different operating systems because of line endings)
using (@in = GetType().getResourceAsStream(READFULLY_TEST_FILE))
{
using (var ms = new MemoryStream())
{
@in.CopyTo(ms);
fileLength = ms.ToArray().Length;
}
}
// Declare the buffer one byte too large
byte[] buffer = new byte[fileLength + 1];
@in = GetType().getResourceAsStream(READFULLY_TEST_FILE);
DataInputStream dis;
using (dis = new DataInputStream(@in))
{
// Read once for real (to the exact length)
dis.ReadFully(buffer, 0, fileLength);
}
// Read past the end of the stream
@in = GetType().getResourceAsStream(READFULLY_TEST_FILE);
dis = new DataInputStream(@in);
bool caughtException = false;
try
{
// Using the buffer length (that is 1 byte too many)
// should generate EndOfStreamException.
dis.ReadFully(buffer, 0, buffer.Length);
}
#pragma warning disable 168
catch (EndOfStreamException ie)
#pragma warning restore 168
{
caughtException = true;
}
finally
{
dis.Dispose();
if (!caughtException)
fail("Test failed");
}
// Ensure we get an IndexOutOfRangeException exception when length is negative
@in = GetType().getResourceAsStream(READFULLY_TEST_FILE);
dis = new DataInputStream(@in);
caughtException = false;
try
{
dis.ReadFully(buffer, 0, -20);
}
#pragma warning disable 168
catch (IndexOutOfRangeException ie)
#pragma warning restore 168
{
caughtException = true;
}
finally
{
dis.Dispose();
if (!caughtException)
fail("Test failed");
}
}
[Test, LuceneNetSpecific]
public void TestReadLinePushback()
{
using (MemoryStream pis = new MemoryStream("\r".GetBytes(Encoding.UTF8)))
{
DataInputStream dis = new DataInputStream(pis);
#pragma warning disable 612, 618
string line = dis.ReadLine();
#pragma warning restore 612, 618
if (line == null)
{
fail("Got null, should return empty line");
}
long count = pis.Length - (line.Length + 1 /*account for the newline*/);
if (count != 0)
{
fail("Test failed: available() returns "
+ count + " when the file is empty");
}
}
}
[Test, LuceneNetSpecific]
public void TestReadUTF()
{
for (int i = 0; i < TEST_ITERATIONS; i++)
{
try
{
WriteAndReadAString();
}
catch (FormatException utfdfe)
{
if (utfdfe.Message == null)
fail("vague exception thrown");
}
#pragma warning disable 168
catch (EndOfStreamException eofe)
#pragma warning restore 168
{
// These are rare and beyond the scope of the test
}
}
}
private static readonly int TEST_ITERATIONS = 1000;
private static readonly int A_NUMBER_NEAR_65535 = 60000;
private static readonly int MAX_CORRUPTIONS_PER_CYCLE = 3;
private static void WriteAndReadAString()
{
// Write out a string whose UTF-8 encoding is quite possibly
// longer than 65535 bytes
int length = Random().nextInt(A_NUMBER_NEAR_65535) + 1;
MemoryStream baos = new MemoryStream();
StringBuilder testBuffer = new StringBuilder();
for (int i = 0; i < length; i++)
testBuffer.append((char)Random().Next());
string testString = testBuffer.toString();
DataOutputStream dos = new DataOutputStream(baos);
dos.WriteUTF(testString);
// Corrupt the data to produce malformed characters
byte[] testBytes = baos.ToArray();
int dataLength = testBytes.Length;
int corruptions = Random().nextInt(MAX_CORRUPTIONS_PER_CYCLE);
for (int i = 0; i < corruptions; i++)
{
int index = Random().nextInt(dataLength);
testBytes[index] = (byte)Random().Next();
}
// Pay special attention to mangling the end to produce
// partial characters at end
testBytes[dataLength - 1] = (byte)Random().Next();
testBytes[dataLength - 2] = (byte)Random().Next();
// Attempt to decode the bytes back into a String
MemoryStream bais = new MemoryStream(testBytes);
DataInputStream dis = new DataInputStream(bais);
dis.ReadUTF();
}
[Test, LuceneNetSpecific]
public void TestSkipBytes()
{
DataInputStream dis = new DataInputStream(new MyInputStream());
dotest(dis, 0, 11, -1, 0);
dotest(dis, 0, 11, 5, 5);
Console.WriteLine("\n***CAUTION**** - may go into an infinite loop");
dotest(dis, 5, 11, 20, 6);
}
private static void dotest(DataInputStream dis, int pos, int total,
int toskip, int expected)
{
try
{
if (VERBOSE)
{
Console.WriteLine("\n\nTotal bytes in the stream = " + total);
Console.WriteLine("Currently at position = " + pos);
Console.WriteLine("Bytes to skip = " + toskip);
Console.WriteLine("Expected result = " + expected);
}
int skipped = dis.SkipBytes(toskip);
if (VERBOSE)
{
Console.WriteLine("Actual skipped = " + skipped);
}
if (skipped != expected)
{
fail("DataInputStream.skipBytes does not return expected value");
}
}
#pragma warning disable 168
catch (EndOfStreamException e)
#pragma warning restore 168
{
fail("DataInputStream.skipBytes throws unexpected EOFException");
}
#pragma warning disable 168
catch (IOException e)
#pragma warning restore 168
{
Console.WriteLine("IOException is thrown - possible result");
}
}
internal class MyInputStream : MemoryStream
{
private int readctr = 0;
public override int ReadByte()
{
if (readctr > 10)
{
return -1;
}
else
{
readctr++;
return 0;
}
}
}
}
}
| |
/*
* REST API Documentation for Schoolbus
*
* API Sample
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using SchoolBusAPI.Models;
using SchoolBusAPI.ViewModels;
using SchoolBusAPI.Mappings;
namespace SchoolBusAPI.Services.Impl
{
/// <summary>
///
/// </summary>
public class GroupService : IGroupService
{
private readonly DbAppContext _context;
/// <summary>
/// Create a service and set the database context
/// </summary>
public GroupService(DbAppContext context)
{
_context = context;
}
/// <summary>
/// returns users in a given Group
/// </summary>
/// <remarks>Used to get users in a given Group</remarks>
/// <param name="id">id of Group to fetch Users for</param>
/// <response code="200">OK</response>
public IActionResult GroupsIdUsersGetAsync(int id)
{
bool exists = _context.Groups.Any(a => a.Id == id);
if (exists)
{
var result = new List<UserViewModel>();
var data = _context.GroupMemberships
.Include("User")
.Include("Group")
.Where(x => x.Group.Id == id);
// extract the users
foreach (var item in data)
{
result.Add(item.User.ToViewModel());
}
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
/// <response code="201">Groups created</response>
public IActionResult GroupsBulkPostAsync(Group[] items)
{
if (items == null)
{
return new BadRequestResult();
}
foreach (Group item in items)
{
bool exists = _context.Groups.Any(a => a.Id == item.Id);
if (exists)
{
_context.Groups.Update(item);
}
else
{
_context.Groups.Add(item);
}
}
// Save the changes
_context.SaveChanges();
return new NoContentResult();
}
/// <summary>
///
/// </summary>
/// <remarks>Returns a collection of groups</remarks>
/// <response code="200">OK</response>
public virtual IActionResult GroupsGetAsync()
{
var result = _context.Groups.Select(x => x.ToViewModel()).ToList();
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Group to delete</param>
/// <response code="200">OK</response>
/// <response code="404">Group not found</response>
public IActionResult GroupsIdDeletePostAsync(int id)
{
var exists = _context.Groups.Any(a => a.Id == id);
if (exists)
{
var item = _context.Groups.First(a => a.Id == id);
if (item != null)
{
_context.Groups.Remove(item);
// Save the changes
_context.SaveChanges();
}
return new ObjectResult(item);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Returns a Group</remarks>
/// <param name="id">id of Group to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">Group not found</response>
public IActionResult GroupsIdGetAsync(int id)
{
var exists = _context.Groups.Any(a => a.Id == id);
if (exists)
{
var result = _context.Groups.First(a => a.Id == id);
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Group to update</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">Group not found</response>
public IActionResult GroupsIdPutAsync(int id, Group item)
{
var exists = _context.Groups.Any(a => a.Id == id);
if (exists && id == item.Id)
{
_context.Groups.Update(item);
// Save the changes
_context.SaveChanges();
return new ObjectResult(item);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <response code="201">Group created</response>
public IActionResult GroupsPostAsync(Group item)
{
var exists = _context.Groups.Any(a => a.Id == item.Id);
if (exists)
{
_context.Groups.Update(item);
}
else
{
// record not found
_context.Groups.Add(item);
}
_context.SaveChanges();
return new ObjectResult(item);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Rainbow.Framework;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Web.UI.WebControls;
using Label=System.Web.UI.WebControls.Label;
namespace Rainbow.Content.Web.Modules
{
/// <summary>
/// DatabaseTool Module
/// Based on VB code Written by Sreedhar Koganti (w3coder)
/// Modifications (lots!) and conversion for Rainbow by Jakob hansen
/// </summary>
public partial class DatabaseTool : PortalModuleControl
{
protected bool Trusted_Connection;
protected string ServerName;
protected string DatabaseName;
protected string UserID;
protected string Password;
protected string InfoFields;
protected string InfoExtendedFields;
protected bool ShowQueryBox;
protected int QueryBoxHeight;
protected bool Connected = false;
protected string ConnectionString;
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void Page_Load(object sender, EventArgs e)
{
Trusted_Connection = "True" == Settings["Trusted Connection"].ToString();
ServerName = Settings["ServerName"].ToString();
DatabaseName = Settings["DatabaseName"].ToString();
UserID = Settings["UserID"].ToString();
Password = Settings["Password"].ToString();
if (Trusted_Connection)
ConnectionString = "Server=" + ServerName + ";Trusted_Connection=true;database=" + DatabaseName;
else
ConnectionString = "Server=" + ServerName + ";database=" + DatabaseName + ";uid=" + UserID + ";pwd=" +
Password + ";";
Connected = Connect(lblRes);
panConnected.Visible = Connected;
if (Connected)
{
lblConnectedError.Visible = false;
InfoFields = Settings["InfoFields"].ToString();
InfoExtendedFields = Settings["InfoExtendedFields"].ToString();
ShowQueryBox = "True" == Settings["Show Query Box"].ToString();
QueryBoxHeight = int.Parse(Settings["Query Box Height"].ToString());
panQueryBox.Visible = ShowQueryBox;
txtQueryBox.Height = QueryBoxHeight;
if (!Page.IsPostBack)
FillObjects("U", "dbo"); // The User table is the initial selected object
}
else
{
lblConnectedError.Visible = true;
lblConnectedError.Text = "Please connect to a database... (check settings)";
}
}
/// <summary>
/// Connects the specified LBL.
/// </summary>
/// <param name="lbl">The LBL.</param>
/// <returns></returns>
protected bool Connect(Label lbl)
{
lbl.Text = string.Empty;
bool retValue;
try
{
SqlConnection SqlCon = new SqlConnection(ConnectionString);
SqlDataAdapter DA = new SqlDataAdapter("SELECT NULL", SqlCon);
SqlCon.Open();
SqlCon.Close();
SqlCon.Dispose();
retValue = true;
}
catch (Exception ex)
{
lbl.Text = "Error: " + ex.Message;
retValue = false;
}
return retValue;
}
/// <summary>
/// Fills the objects.
/// </summary>
/// <param name="xtype">The xtype.</param>
/// <param name="user">The user.</param>
protected void FillObjects(string xtype, string user)
{
lblRes.Text = string.Empty;
try
{
SqlConnection SqlCon = new SqlConnection(ConnectionString);
SqlDataAdapter DA =
new SqlDataAdapter(
"Select name,id from sysobjects where uid=USER_ID('" + user + "') AND xtype='" + xtype +
"' order by name", SqlCon);
SqlCon.Open();
DataSet DS = new DataSet();
try
{
DA.Fill(DS, "Table");
lbObjects.DataSource = DS;
lbObjects.DataTextField = "name";
lbObjects.DataValueField = "id";
lbObjects.DataBind();
lbObjects.SelectedIndex = 0;
}
finally
{
SqlCon.Close();
}
}
catch (Exception ex)
{
lblRes.Text = "Error: " + ex.Message;
}
}
/// <summary>
/// Fills the data grid.
/// </summary>
/// <param name="SQL">The SQL.</param>
protected void FillDataGrid(string SQL)
{
lblRes.Text = string.Empty;
try
{
SqlConnection SqlCon = new SqlConnection(ConnectionString);
SqlDataAdapter DA = new SqlDataAdapter(SQL, SqlCon);
SqlCon.Open();
DataSet DS = new DataSet();
try
{
DA.Fill(DS, "Table");
DataGrid1.DataSource = DS;
DataGrid1.DataBind();
}
finally
{
SqlCon.Close();
}
}
catch (Exception ex)
{
lblRes.Text = "Error: " + ex.Message;
}
}
/// <summary>
/// Gets the table field.
/// </summary>
/// <param name="selectCmd">The select CMD.</param>
/// <param name="idxField">The idx field.</param>
protected void GetTableField(string selectCmd, int idxField)
{
lblRes.Text = string.Empty;
try
{
SqlConnection SqlCon = new SqlConnection(ConnectionString);
SqlCommand SqlComm = new SqlCommand(selectCmd, SqlCon);
SqlComm.Connection.Open();
try
{
SqlDataReader dr = SqlComm.ExecuteReader(CommandBehavior.CloseConnection);
try
{
if (dr.Read())
txtQueryBox.Text = dr[idxField].ToString();
else
txtQueryBox.Text = "No data for SQL: \n" + selectCmd;
}
finally
{
dr.Close(); //by Manu, fixed bug 807858
}
}
finally
{
SqlCon.Close();
}
}
catch (Exception ex)
{
lblRes.Text = "Error: " + ex.Message;
}
}
/// <summary>
/// Handles the SelectedIndexChanged event of the ObjectSelectList control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
protected void ObjectSelectList_SelectedIndexChanged(object sender, EventArgs e)
{
// There are only data in tables or views:
if (ddObjectSelectList.SelectedItem.Value == "U" ||
ddObjectSelectList.SelectedItem.Value == "V")
btnGetObjectData.Visible = true;
else
btnGetObjectData.Visible = false;
FillObjects(ddObjectSelectList.SelectedItem.Value, tbUserName.Text);
}
/// <summary>
/// Handles the Click event of the GetObjectInfo control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
protected void GetObjectInfo_Click(object sender, EventArgs e)
{
FillDataGrid("SELECT " + InfoFields + " FROM sysobjects WHERE uid=USER_ID('" + tbUserName.Text +
"') AND id=" + lbObjects.SelectedItem.Value.ToString());
}
/// <summary>
/// Handles the Click event of the GetObjectInfoExtended control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
protected void GetObjectInfoExtended_Click(object sender, EventArgs e)
{
FillDataGrid("SELECT " + InfoExtendedFields + " FROM sysobjects WHERE uid=USER_ID('" + tbUserName.Text +
"') AND id=" + lbObjects.SelectedItem.Value.ToString());
}
/// <summary>
/// Handles the Click event of the GetObjectProps control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
protected void GetObjectProps_Click(object sender, EventArgs e)
{
string SQL = string.Empty;
if (ddObjectSelectList.SelectedItem.Value == "U" ||
ddObjectSelectList.SelectedItem.Value == "V")
{
SQL += "EXEC sp_columns";
SQL += " @table_name = '" + lbObjects.SelectedItem.Text.ToString() + "'";
SQL += ",@table_owner = '" + tbUserName.Text + "'";
FillDataGrid(SQL);
}
else
{
SQL += " SELECT c.[text] FROM sysobjects o, syscomments c";
SQL += " WHERE o.uid=USER_ID('" + tbUserName.Text + "')";
SQL += " AND o.id=c.id";
SQL += " AND o.id=" + lbObjects.SelectedItem.Value.ToString();
GetTableField(SQL, 0);
}
}
/// <summary>
/// Handles the Click event of the GetObjectData control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
protected void GetObjectData_Click(object sender, EventArgs e)
{
FillDataGrid("SELECT * FROM " + lbObjects.SelectedItem.Text.Trim());
}
/// <summary>
/// Handles the Click event of the QueryExecute control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
protected void QueryExecute_Click(object sender, EventArgs e)
{
lblRes.Text = string.Empty;
try
{
SqlConnection SqlCon = new SqlConnection(ConnectionString);
string SQL = txtQueryBox.Text.Trim();
if (SQL.Length > 6 && SQL.Substring(0, 6).ToUpper() == "SELECT")
{
SqlDataAdapter DA = new SqlDataAdapter(SQL, SqlCon);
SqlCon.Open();
DataSet DS = new DataSet();
try
{
DA.Fill(DS, "Table");
DataGrid1.DataSource = DS;
DataGrid1.DataBind();
lblRes.Text = "Successful Query...";
}
finally
{
SqlCon.Close();
}
}
else
{
SqlCommand SqlComm = new SqlCommand(SQL, SqlCon);
SqlCon.Open();
try
{
int Rowseff = SqlComm.ExecuteNonQuery();
lblRes.Text = "Effected Rows: " + Rowseff.ToString();
}
finally
{
SqlCon.Close();
}
}
}
catch (Exception ex)
{
lblRes.Text = "Error: " + ex.Message;
}
}
/// <summary>
/// Gets the GUID ID.
/// </summary>
/// <value>The GUID ID.</value>
public override Guid GuidID
{
get { return new Guid("{2502DB18-B580-4F90-8CB4-C15E6E531032}"); }
}
/// <summary>
/// Admin Module
/// </summary>
/// <value><c>true</c> if [admin module]; otherwise, <c>false</c>.</value>
public override bool AdminModule
{
get { return true; }
}
/// <summary>
/// Public constructor. Sets base settings for module.
/// </summary>
public DatabaseTool()
{
SettingItem Trusted_Connection = new SettingItem(new BooleanDataType());
Trusted_Connection.Order = 1;
//Trusted_Connection.Required = true; // hmmm... problem here! Dont set to true!"
Trusted_Connection.Value = "True";
_baseSettings.Add("Trusted Connection", Trusted_Connection);
SettingItem ServerName = new SettingItem(new StringDataType());
ServerName.Order = 2;
ServerName.Required = true;
ServerName.Value = "localhost";
_baseSettings.Add("ServerName", ServerName);
SettingItem DatabaseName = new SettingItem(new StringDataType());
DatabaseName.Order = 3;
DatabaseName.Required = true;
DatabaseName.Value = "Rainbow";
_baseSettings.Add("DatabaseName", DatabaseName);
SettingItem UserID = new SettingItem(new StringDataType());
UserID.Order = 4;
UserID.Required = false;
UserID.Value = string.Empty;
_baseSettings.Add("UserID", UserID);
SettingItem Password = new SettingItem(new StringDataType());
Password.Order = 5;
Password.Required = false;
Password.Value = string.Empty;
_baseSettings.Add("Password", Password);
SettingItem InfoFields = new SettingItem(new StringDataType());
InfoFields.Order = 6;
InfoFields.Required = true;
InfoFields.Value = "name,id,xtype,uid"; // for table sysobjects
_baseSettings.Add("InfoFields", InfoFields);
SettingItem InfoExtendedFields = new SettingItem(new StringDataType());
InfoExtendedFields.Order = 7;
InfoExtendedFields.Required = true;
InfoExtendedFields.Value = "*"; // for table sysobjects
_baseSettings.Add("InfoExtendedFields", InfoExtendedFields);
SettingItem ShowQueryBox = new SettingItem(new BooleanDataType());
ShowQueryBox.Order = 8;
//ShowQueryBox.Required = true; // hmmm... problem here! Dont set to true!"
ShowQueryBox.Value = "True";
_baseSettings.Add("Show Query Box", ShowQueryBox);
SettingItem QueryBoxHeight = new SettingItem(new IntegerDataType());
QueryBoxHeight.Order = 9;
QueryBoxHeight.Required = true;
QueryBoxHeight.Value = "150";
QueryBoxHeight.MinValue = 10;
QueryBoxHeight.MaxValue = 2000;
_baseSettings.Add("Query Box Height", QueryBoxHeight);
}
#region Web Form Designer generated code
/// <summary>
/// Raises the init event.
/// </summary>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
protected override void OnInit(EventArgs e)
{
this.ddObjectSelectList.SelectedIndexChanged += new EventHandler(this.ObjectSelectList_SelectedIndexChanged);
this.btnGetObjectInfo.Click += new EventHandler(this.GetObjectInfo_Click);
this.btnGetObjectInfoExtended.Click += new EventHandler(this.GetObjectInfoExtended_Click);
this.btnGetObjectProps.Click += new EventHandler(this.GetObjectProps_Click);
this.btnGetObjectData.Click += new EventHandler(this.GetObjectData_Click);
this.btnQueryExecute.Click += new EventHandler(this.QueryExecute_Click);
this.Load += new EventHandler(this.Page_Load);
// ModuleTitle = new DesktopModuleTitle();
// Controls.AddAt(0, ModuleTitle);
base.OnInit(e);
}
#endregion
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
// NOTE: this file was generated from 'xd.xml'
namespace System.IdentityModel
{
using System.Xml;
using System.Runtime.CompilerServices;
class IdentityModelStringsVersion1 : IdentityModelStrings
{
public const string String0 = "Algorithm";
public const string String1 = "URI";
public const string String2 = "Reference";
public const string String3 = "Id";
public const string String4 = "Transforms";
public const string String5 = "Transform";
public const string String6 = "DigestMethod";
public const string String7 = "DigestValue";
public const string String8 = "http://www.w3.org/2000/09/xmldsig#";
public const string String9 = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
public const string String10 = "KeyInfo";
public const string String11 = "Signature";
public const string String12 = "SignedInfo";
public const string String13 = "CanonicalizationMethod";
public const string String14 = "SignatureMethod";
public const string String15 = "SignatureValue";
public const string String16 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
public const string String17 = "Timestamp";
public const string String18 = "Created";
public const string String19 = "Expires";
public const string String20 = "http://www.w3.org/2001/10/xml-exc-c14n#";
public const string String21 = "PrefixList";
public const string String22 = "InclusiveNamespaces";
public const string String23 = "ec";
public const string String24 = "Access";
public const string String25 = "AccessDecision";
public const string String26 = "Action";
public const string String27 = "Advice";
public const string String28 = "Assertion";
public const string String29 = "AssertionID";
public const string String30 = "AssertionIDReference";
public const string String31 = "Attribute";
public const string String32 = "AttributeName";
public const string String33 = "AttributeNamespace";
public const string String34 = "AttributeStatement";
public const string String35 = "AttributeValue";
public const string String36 = "Audience";
public const string String37 = "AudienceRestrictionCondition";
public const string String38 = "AuthenticationInstant";
public const string String39 = "AuthenticationMethod";
public const string String40 = "AuthenticationStatement";
public const string String41 = "AuthorityBinding";
public const string String42 = "AuthorityKind";
public const string String43 = "AuthorizationDecisionStatement";
public const string String44 = "Binding";
public const string String45 = "Condition";
public const string String46 = "Conditions";
public const string String47 = "Decision";
public const string String48 = "DoNotCacheCondition";
public const string String49 = "Evidence";
public const string String50 = "IssueInstant";
public const string String51 = "Issuer";
public const string String52 = "Location";
public const string String53 = "MajorVersion";
public const string String54 = "MinorVersion";
public const string String55 = "urn:oasis:names:tc:SAML:1.0:assertion";
public const string String56 = "NameIdentifier";
public const string String57 = "Format";
public const string String58 = "NameQualifier";
public const string String59 = "Namespace";
public const string String60 = "NotBefore";
public const string String61 = "NotOnOrAfter";
public const string String62 = "saml";
public const string String63 = "Statement";
public const string String64 = "Subject";
public const string String65 = "SubjectConfirmation";
public const string String66 = "SubjectConfirmationData";
public const string String67 = "ConfirmationMethod";
public const string String68 = "urn:oasis:names:tc:SAML:1.0:cm:holder-of-key";
public const string String69 = "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches";
public const string String70 = "SubjectLocality";
public const string String71 = "DNSAddress";
public const string String72 = "IPAddress";
public const string String73 = "SubjectStatement";
public const string String74 = "urn:oasis:names:tc:SAML:1.0:am:unspecified";
public const string String75 = "xmlns";
public const string String76 = "Resource";
public const string String77 = "UserName";
public const string String78 = "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName";
public const string String79 = "EmailName";
public const string String80 = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress";
public const string String81 = "u";
public const string String82 = "KeyName";
public const string String83 = "Type";
public const string String84 = "MgmtData";
public const string String85 = "";
public const string String86 = "KeyValue";
public const string String87 = "RSAKeyValue";
public const string String88 = "Modulus";
public const string String89 = "Exponent";
public const string String90 = "X509Data";
public const string String91 = "X509IssuerSerial";
public const string String92 = "X509IssuerName";
public const string String93 = "X509SerialNumber";
public const string String94 = "X509Certificate";
public const string String95 = "http://www.w3.org/2001/04/xmlenc#aes128-cbc";
public const string String96 = "http://www.w3.org/2001/04/xmlenc#kw-aes128";
public const string String97 = "http://www.w3.org/2001/04/xmlenc#aes192-cbc";
public const string String98 = "http://www.w3.org/2001/04/xmlenc#kw-aes192";
public const string String99 = "http://www.w3.org/2001/04/xmlenc#aes256-cbc";
public const string String100 = "http://www.w3.org/2001/04/xmlenc#kw-aes256";
public const string String101 = "http://www.w3.org/2001/04/xmlenc#des-cbc";
public const string String102 = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
public const string String103 = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments";
public const string String104 = "http://www.w3.org/2000/09/xmldsig#hmac-sha1";
public const string String105 = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
public const string String106 = "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1";
public const string String107 = "http://www.w3.org/2001/04/xmlenc#ripemd160";
public const string String108 = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p";
public const string String109 = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
public const string String110 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
public const string String111 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5";
public const string String112 = "http://www.w3.org/2000/09/xmldsig#sha1";
public const string String113 = "http://www.w3.org/2001/04/xmlenc#sha256";
public const string String114 = "http://www.w3.org/2001/04/xmlenc#sha512";
public const string String115 = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc";
public const string String116 = "http://www.w3.org/2001/04/xmlenc#kw-tripledes";
public const string String117 = "http://schemas.xmlsoap.org/2005/02/trust/tlsnego#TLS_Wrap";
public const string String118 = "http://schemas.xmlsoap.org/2005/02/trust/spnego#GSS_Wrap";
public const string String119 = "o";
public const string String120 = "Nonce";
public const string String121 = "Password";
public const string String122 = "PasswordText";
public const string String123 = "Username";
public const string String124 = "UsernameToken";
public const string String125 = "BinarySecurityToken";
public const string String126 = "EncodingType";
public const string String127 = "KeyIdentifier";
public const string String128 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary";
public const string String129 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#HexBinary";
public const string String130 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Text";
public const string String131 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier";
public const string String132 = "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ";
public const string String133 = "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ1510";
public const string String134 = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID";
public const string String135 = "http://docs.oasis-open.org/wss/oasis-wss-rel-token-profile-1.0.pdf#license";
public const string String136 = "FailedAuthentication";
public const string String137 = "InvalidSecurityToken";
public const string String138 = "InvalidSecurity";
public const string String139 = "SecurityTokenReference";
public const string String140 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
public const string String141 = "Security";
public const string String142 = "ValueType";
public const string String143 = "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#Kerberosv5APREQSHA1";
public const string String144 = "k";
public const string String145 = "SignatureConfirmation";
public const string String146 = "Value";
public const string String147 = "TokenType";
public const string String148 = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1";
public const string String149 = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey";
public const string String150 = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKeySHA1";
public const string String151 = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
public const string String152 = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";
public const string String153 = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID";
public const string String154 = "EncryptedHeader";
public const string String155 = "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd";
public const string String156 = "http://www.w3.org/2001/04/xmlenc#";
public const string String157 = "DataReference";
public const string String158 = "EncryptedData";
public const string String159 = "EncryptionMethod";
public const string String160 = "CipherData";
public const string String161 = "CipherValue";
public const string String162 = "ReferenceList";
public const string String163 = "Encoding";
public const string String164 = "MimeType";
public const string String165 = "CarriedKeyName";
public const string String166 = "Recipient";
public const string String167 = "EncryptedKey";
public const string String168 = "KeyReference";
public const string String169 = "e";
public const string String170 = "http://www.w3.org/2001/04/xmlenc#Element";
public const string String171 = "http://www.w3.org/2001/04/xmlenc#Content";
public const string String172 = "http://schemas.xmlsoap.org/ws/2005/02/sc";
public const string String173 = "DerivedKeyToken";
public const string String174 = "Length";
public const string String175 = "SecurityContextToken";
public const string String176 = "Generation";
public const string String177 = "Label";
public const string String178 = "Offset";
public const string String179 = "Properties";
public const string String180 = "Identifier";
public const string String181 = "Cookie";
public const string String182 = "RenewNeeded";
public const string String183 = "BadContextToken";
public const string String184 = "c";
public const string String185 = "http://schemas.xmlsoap.org/ws/2005/02/sc/dk";
public const string String186 = "http://schemas.xmlsoap.org/ws/2005/02/sc/sct";
public const string String187 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT";
public const string String188 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT";
public const string String189 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Renew";
public const string String190 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Renew";
public const string String191 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Cancel";
public const string String192 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Cancel";
public const string String193 = "RequestSecurityTokenResponseCollection";
public const string String194 = "http://schemas.xmlsoap.org/ws/2005/02/trust";
public const string String195 = "http://schemas.xmlsoap.org/ws/2005/02/trust#BinarySecret";
public const string String196 = "AUTH-HASH";
public const string String197 = "RequestSecurityTokenResponse";
public const string String198 = "KeySize";
public const string String199 = "RequestedTokenReference";
public const string String200 = "AppliesTo";
public const string String201 = "Authenticator";
public const string String202 = "CombinedHash";
public const string String203 = "BinaryExchange";
public const string String204 = "Lifetime";
public const string String205 = "RequestedSecurityToken";
public const string String206 = "Entropy";
public const string String207 = "RequestedProofToken";
public const string String208 = "ComputedKey";
public const string String209 = "RequestSecurityToken";
public const string String210 = "RequestType";
public const string String211 = "Context";
public const string String212 = "BinarySecret";
public const string String213 = "http://schemas.microsoft.com/net/2004/07/secext/WS-SPNego";
public const string String214 = "http://schemas.microsoft.com/net/2004/07/secext/TLSNego";
public const string String215 = "t";
public const string String216 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue";
public const string String217 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue";
public const string String218 = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue";
public const string String219 = "http://schemas.xmlsoap.org/ws/2005/02/trust/SymmetricKey";
public const string String220 = "http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1";
public const string String221 = "http://schemas.xmlsoap.org/ws/2005/02/trust/Nonce";
public const string String222 = "RenewTarget";
public const string String223 = "CancelTarget";
public const string String224 = "RequestedTokenCancelled";
public const string String225 = "RequestedAttachedReference";
public const string String226 = "RequestedUnattachedReference";
public const string String227 = "IssuedTokens";
public const string String228 = "http://schemas.xmlsoap.org/ws/2005/02/trust/Renew";
public const string String229 = "http://schemas.xmlsoap.org/ws/2005/02/trust/Cancel";
public const string String230 = "KeyType";
public const string String231 = "http://schemas.xmlsoap.org/ws/2005/02/trust/PublicKey";
public const string String232 = "Claims";
public const string String233 = "InvalidRequest";
public const string String234 = "UseKey";
public const string String235 = "SignWith";
public const string String236 = "EncryptWith";
public const string String237 = "EncryptionAlgorithm";
public const string String238 = "CanonicalizationAlgorithm";
public const string String239 = "ComputedKeyAlgorithm";
public const string String240 = "http://schemas.xmlsoap.org/ws/2005/02/trust/spnego";
public const string String241 = "http://schemas.xmlsoap.org/ws/2005/02/trust/tlsnego";
public const string String242 = "trust";
public const string String243 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue";
public const string String244 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Issue";
public const string String245 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue";
public const string String246 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/AsymmetricKey";
public const string String247 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey";
public const string String248 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Nonce";
public const string String249 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/CK/PSHA1";
public const string String250 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/PublicKey";
public const string String251 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512";
public const string String252 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512#BinarySecret";
public const string String253 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTRC/IssueFinal";
public const string String254 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Renew";
public const string String255 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Renew";
public const string String256 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/RenewFinal";
public const string String257 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Cancel";
public const string String258 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Cancel";
public const string String259 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/CancelFinal";
public const string String260 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Renew";
public const string String261 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Cancel";
public const string String262 = "KeyWrapAlgorithm";
public const string String263 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer";
public const string String264 = "SecondaryParameters";
public const string String265 = "Dialect";
public const string String266 = "http://schemas.xmlsoap.org/ws/2005/05/identity";
public const string String267 = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/dk/p_sha1";
public const string String268 = "sc";
public const string String269 = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/dk";
public const string String270 = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/sct";
public const string String271 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT";
public const string String272 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT";
public const string String273 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT/Renew";
public const string String274 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT/Renew";
public const string String275 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT/Cancel";
public const string String276 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT/Cancel";
public const string String277 = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512";
public const string String278 = "Instance";
public override int Count { get { return 279; } }
public override string this[int index]
{
get
{
DiagnosticUtility.DebugAssert(index >= 0 && index < this.Count, "The index is out of range. It should be greater than or equal to 0 and less than" + this.Count.ToString());
switch (index)
{
case 0: return String0;
case 1: return String1;
case 2: return String2;
case 3: return String3;
case 4: return String4;
case 5: return String5;
case 6: return String6;
case 7: return String7;
case 8: return String8;
case 9: return String9;
case 10: return String10;
case 11: return String11;
case 12: return String12;
case 13: return String13;
case 14: return String14;
case 15: return String15;
case 16: return String16;
case 17: return String17;
case 18: return String18;
case 19: return String19;
case 20: return String20;
case 21: return String21;
case 22: return String22;
case 23: return String23;
case 24: return String24;
case 25: return String25;
case 26: return String26;
case 27: return String27;
case 28: return String28;
case 29: return String29;
case 30: return String30;
case 31: return String31;
case 32: return String32;
case 33: return String33;
case 34: return String34;
case 35: return String35;
case 36: return String36;
case 37: return String37;
case 38: return String38;
case 39: return String39;
case 40: return String40;
case 41: return String41;
case 42: return String42;
case 43: return String43;
case 44: return String44;
case 45: return String45;
case 46: return String46;
case 47: return String47;
case 48: return String48;
case 49: return String49;
case 50: return String50;
case 51: return String51;
case 52: return String52;
case 53: return String53;
case 54: return String54;
case 55: return String55;
case 56: return String56;
case 57: return String57;
case 58: return String58;
case 59: return String59;
case 60: return String60;
case 61: return String61;
case 62: return String62;
case 63: return String63;
case 64: return String64;
case 65: return String65;
case 66: return String66;
case 67: return String67;
case 68: return String68;
case 69: return String69;
case 70: return String70;
case 71: return String71;
case 72: return String72;
case 73: return String73;
case 74: return String74;
case 75: return String75;
case 76: return String76;
case 77: return String77;
case 78: return String78;
case 79: return String79;
case 80: return String80;
case 81: return String81;
case 82: return String82;
case 83: return String83;
case 84: return String84;
case 85: return String85;
case 86: return String86;
case 87: return String87;
case 88: return String88;
case 89: return String89;
case 90: return String90;
case 91: return String91;
case 92: return String92;
case 93: return String93;
case 94: return String94;
case 95: return String95;
case 96: return String96;
case 97: return String97;
case 98: return String98;
case 99: return String99;
case 100: return String100;
case 101: return String101;
case 102: return String102;
case 103: return String103;
case 104: return String104;
case 105: return String105;
case 106: return String106;
case 107: return String107;
case 108: return String108;
case 109: return String109;
case 110: return String110;
case 111: return String111;
case 112: return String112;
case 113: return String113;
case 114: return String114;
case 115: return String115;
case 116: return String116;
case 117: return String117;
case 118: return String118;
case 119: return String119;
case 120: return String120;
case 121: return String121;
case 122: return String122;
case 123: return String123;
case 124: return String124;
case 125: return String125;
case 126: return String126;
case 127: return String127;
case 128: return String128;
case 129: return String129;
case 130: return String130;
case 131: return String131;
case 132: return String132;
case 133: return String133;
case 134: return String134;
case 135: return String135;
case 136: return String136;
case 137: return String137;
case 138: return String138;
case 139: return String139;
case 140: return String140;
case 141: return String141;
case 142: return String142;
case 143: return String143;
case 144: return String144;
case 145: return String145;
case 146: return String146;
case 147: return String147;
case 148: return String148;
case 149: return String149;
case 150: return String150;
case 151: return String151;
case 152: return String152;
case 153: return String153;
case 154: return String154;
case 155: return String155;
case 156: return String156;
case 157: return String157;
case 158: return String158;
case 159: return String159;
case 160: return String160;
case 161: return String161;
case 162: return String162;
case 163: return String163;
case 164: return String164;
case 165: return String165;
case 166: return String166;
case 167: return String167;
case 168: return String168;
case 169: return String169;
case 170: return String170;
case 171: return String171;
case 172: return String172;
case 173: return String173;
case 174: return String174;
case 175: return String175;
case 176: return String176;
case 177: return String177;
case 178: return String178;
case 179: return String179;
case 180: return String180;
case 181: return String181;
case 182: return String182;
case 183: return String183;
case 184: return String184;
case 185: return String185;
case 186: return String186;
case 187: return String187;
case 188: return String188;
case 189: return String189;
case 190: return String190;
case 191: return String191;
case 192: return String192;
case 193: return String193;
case 194: return String194;
case 195: return String195;
case 196: return String196;
case 197: return String197;
case 198: return String198;
case 199: return String199;
case 200: return String200;
case 201: return String201;
case 202: return String202;
case 203: return String203;
case 204: return String204;
case 205: return String205;
case 206: return String206;
case 207: return String207;
case 208: return String208;
case 209: return String209;
case 210: return String210;
case 211: return String211;
case 212: return String212;
case 213: return String213;
case 214: return String214;
case 215: return String215;
case 216: return String216;
case 217: return String217;
case 218: return String218;
case 219: return String219;
case 220: return String220;
case 221: return String221;
case 222: return String222;
case 223: return String223;
case 224: return String224;
case 225: return String225;
case 226: return String226;
case 227: return String227;
case 228: return String228;
case 229: return String229;
case 230: return String230;
case 231: return String231;
case 232: return String232;
case 233: return String233;
case 234: return String234;
case 235: return String235;
case 236: return String236;
case 237: return String237;
case 238: return String238;
case 239: return String239;
case 240: return String240;
case 241: return String241;
case 242: return String242;
case 243: return String243;
case 244: return String244;
case 245: return String245;
case 246: return String246;
case 247: return String247;
case 248: return String248;
case 249: return String249;
case 250: return String250;
case 251: return String251;
case 252: return String252;
case 253: return String253;
case 254: return String254;
case 255: return String255;
case 256: return String256;
case 257: return String257;
case 258: return String258;
case 259: return String259;
case 260: return String260;
case 261: return String261;
case 262: return String262;
case 263: return String263;
case 264: return String264;
case 265: return String265;
case 266: return String266;
case 267: return String267;
case 268: return String268;
case 269: return String269;
case 270: return String270;
case 271: return String271;
case 272: return String272;
case 273: return String273;
case 274: return String274;
case 275: return String275;
case 276: return String276;
case 277: return String277;
case 278: return String278;
default: return null;
}
}
}
}
}
| |
/*
* MindTouch MediaWiki Converter
* Copyright (C) 2006-2008 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* http://www.gnu.org/copyleft/lesser.html
*/
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Xsl;
using MindTouch.Data;
using MindTouch.Deki;
using MindTouch.Deki.Data;
using MindTouch.Deki.Data.MySql;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Tools {
class MediaWikiConverterContext {
private XDoc _config;
private XslCompiledTransform _converterXslt;
private uint? _mergeUserId;
private string _logPath;
private string _templatePath;
private char _pageSeparator;
private Plug _converterUri;
private DataCatalog _mwCatalog;
private Site[] _mwSites;
private String _userPrefix;
internal MediaWikiConverterContext(XDoc config) {
_config = config;
}
public static MediaWikiConverterContext Current {
get {
MediaWikiConverterContext dc = CurrentOrNull;
if (dc == null) {
throw new InvalidOperationException("DekiContext.Current is not set");
}
return dc;
}
}
public static MediaWikiConverterContext CurrentOrNull {
get {
return DreamContext.Current.GetState<MediaWikiConverterContext>();
}
}
public XslCompiledTransform MWConverterXslt {
get {
if (null == _converterXslt) {
XDoc doc = Plug.New("resource://mindtouch.deki.mwconverter/MindTouch.Tools.mediawikixml2dekixml.xslt").With(DreamOutParam.TYPE, MimeType.XML.FullType).Get().ToDocument();
_converterXslt = new XslCompiledTransform();
_converterXslt.Load(new XmlNodeReader(doc.AsXmlNode), null, null);
}
return _converterXslt;
}
}
public bool Merge {
get {
return MergeUserId > 0;
}
}
public uint MergeUserId {
get {
if (null == _mergeUserId) {
try {
_mergeUserId = _config["mediawiki/merge-userid"].AsUInt;
} catch {
_mergeUserId = 0;
}
}
return _mergeUserId ?? 0;
}
}
public bool AttributeViaPageRevComment {
get {
return _config["mediawiki/attribute-via-page-rev-comment"].AsBool ?? false;
}
}
public string AttributeViaPageRevCommentPattern {
get {
string s = _config["mediawiki/attribute-via-page-rev-comment-pattern"].AsText;
return string.IsNullOrEmpty(s) ? "{0}; Edited by {1}" : PhpUtil.ConvertToFormatString(s);
}
}
public string LogPath {
get {
if (null == _logPath) {
_logPath = _config["mediawiki/log"].Contents;
}
return _logPath;
}
}
public bool LoggingEnabled {
get {
return LogPath != String.Empty;
}
}
public string MWTemplatePath {
get {
if (null == _templatePath) {
_templatePath = _config["mediawiki/template-path"].Contents;
}
return _templatePath;
}
}
public char MWPageSeparator {
get {
if (null == _converterUri) {
XDoc pageSeparatorDoc = _config["mediawiki/page.separator"];
if (!pageSeparatorDoc.IsEmpty && !String.IsNullOrEmpty(pageSeparatorDoc.Contents)) {
_pageSeparator = pageSeparatorDoc.Contents[0];
}
}
return _pageSeparator;
}
}
public Plug MWConverterUri {
get {
if (null == _converterUri) {
XDoc uriDoc = _config["mediawiki/uri.converter"];
if (!uriDoc.IsEmpty && !String.IsNullOrEmpty(uriDoc.Contents)) {
_converterUri = Plug.New(uriDoc.Contents);
}
}
return _converterUri;
}
}
public DataCatalog MWCatalog {
get {
if (null == _mwCatalog) {
_mwCatalog = new DataCatalog(new DataFactory(MySql.Data.MySqlClient.MySqlClientFactory.Instance, "?"), _config["mediawiki"]);
}
return _mwCatalog;
}
}
public DataCatalog DWCatalog {
get {
MySqlDekiDataSession session = DbUtils.CurrentSession as MySqlDekiDataSession;
// TODO (brigettek): MediaWiki conversion should not require a MySql backend
if (null == session) {
throw new Exception("MediaWiki Conversion requires a MySql backend");
}
return session.Catalog;
}
}
public Site[] MWSites {
get {
if (null == _mwSites) {
List<Site> sites = new List<Site>();
foreach (XDoc siteDoc in _config["mediawiki/sites/site"]) {
Site site = new Site();
site.DbPrefix = siteDoc["db-prefix"].Contents;
site.Language = siteDoc["language"].Contents;
site.MWRootPage = siteDoc["mwrootpage"].Contents;
site.DWRootPage = siteDoc["dwrootpage"].Contents;
site.ImageDir = siteDoc["imagedir"].Contents;
site.Name = siteDoc["name"].Contents;
sites.Add(site);
}
_mwSites = sites.ToArray();
}
return _mwSites;
}
}
public Site GetMWSite(string language) {
foreach (Site currentSite in MWSites) {
if (language == currentSite.Language) {
return currentSite;
}
}
return Site.Empty;
}
public string MWUserPrefix {
get {
if (null == _userPrefix) {
_userPrefix = _config["mediawiki/db-userprefix"].Contents;
}
return _userPrefix;
}
}
}
}
| |
using System;
using System.Buffers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BencodeNET.Exceptions;
using BencodeNET.IO;
using BencodeNET.Objects;
namespace BencodeNET.Parsing
{
/// <summary>
/// A parser for bencoded byte strings.
/// </summary>
public class BStringParser : BObjectParser<BString>
{
/// <summary>
/// The minimum stream length in bytes for a valid string ('0:').
/// </summary>
protected const int MinimumLength = 2;
/// <summary>
/// Creates an instance using <see cref="System.Text.Encoding.UTF8"/> for parsing.
/// </summary>
public BStringParser()
: this(Encoding.UTF8)
{ }
/// <summary>
/// Creates an instance using the specified encoding for parsing.
/// </summary>
/// <param name="encoding"></param>
public BStringParser(Encoding encoding)
{
_encoding = encoding ?? throw new ArgumentNullException(nameof(encoding));
}
/// <summary>
/// The encoding used when creating the <see cref="BString"/> when parsing.
/// </summary>
public override Encoding Encoding => _encoding;
private Encoding _encoding;
/// <summary>
/// Changes the encoding used for parsing.
/// </summary>
/// <param name="encoding">The new encoding to use.</param>
public void ChangeEncoding(Encoding encoding)
{
_encoding = encoding;
}
/// <summary>
/// Parses the next <see cref="BString"/> from the reader.
/// </summary>
/// <param name="reader">The reader to parse from.</param>
/// <returns>The parsed <see cref="BString"/>.</returns>
/// <exception cref="InvalidBencodeException{BString}">Invalid bencode.</exception>
/// <exception cref="UnsupportedBencodeException{BString}">The bencode is unsupported by this library.</exception>
public override BString Parse(BencodeReader reader)
{
if (reader == null) throw new ArgumentNullException(nameof(reader));
// Minimum valid bencode string is '0:' meaning an empty string
if (reader.Length < MinimumLength)
throw InvalidBencodeException<BString>.BelowMinimumLength(MinimumLength, reader.Length.Value, reader.Position);
var startPosition = reader.Position;
var buffer = ArrayPool<char>.Shared.Rent(BString.LengthMaxDigits);
try
{
var lengthString = buffer.AsSpan();
var lengthStringCount = 0;
for (var c = reader.ReadChar(); c != default && c.IsDigit(); c = reader.ReadChar())
{
EnsureLengthStringBelowMaxLength(lengthStringCount, startPosition);
lengthString[lengthStringCount++] = c;
}
EnsurePreviousCharIsColon(reader.PreviousChar, reader.Position);
var stringLength = ParseStringLength(lengthString, lengthStringCount, startPosition);
var bytes = new byte[stringLength];
var bytesRead = reader.Read(bytes);
EnsureExpectedBytesRead(bytesRead, stringLength, startPosition);
return new BString(bytes, Encoding);
}
finally
{
ArrayPool<char>.Shared.Return(buffer);
}
}
/// <summary>
/// Parses the next <see cref="BString"/> from the reader.
/// </summary>
/// <param name="reader">The reader to parse from.</param>
/// <param name="cancellationToken"></param>
/// <returns>The parsed <see cref="BString"/>.</returns>
/// <exception cref="InvalidBencodeException{BString}">Invalid bencode.</exception>
/// <exception cref="UnsupportedBencodeException{BString}">The bencode is unsupported by this library.</exception>
public override async ValueTask<BString> ParseAsync(PipeBencodeReader reader, CancellationToken cancellationToken = default)
{
if (reader == null) throw new ArgumentNullException(nameof(reader));
var startPosition = reader.Position;
using var memoryOwner = MemoryPool<char>.Shared.Rent(BString.LengthMaxDigits);
var lengthString = memoryOwner.Memory;
var lengthStringCount = 0;
for (var c = await reader.ReadCharAsync(cancellationToken).ConfigureAwait(false);
c != default && c.IsDigit();
c = await reader.ReadCharAsync(cancellationToken).ConfigureAwait(false))
{
EnsureLengthStringBelowMaxLength(lengthStringCount, startPosition);
lengthString.Span[lengthStringCount++] = c;
}
EnsurePreviousCharIsColon(reader.PreviousChar, reader.Position);
var stringLength = ParseStringLength(lengthString.Span, lengthStringCount, startPosition);
var bytes = new byte[stringLength];
var bytesRead = await reader.ReadAsync(bytes, cancellationToken).ConfigureAwait(false);
EnsureExpectedBytesRead(bytesRead, stringLength, startPosition);
return new BString(bytes, Encoding);
}
/// <summary>
/// Ensures that the length (number of digits) of the string-length part is not above <see cref="BString.LengthMaxDigits"/>
/// as that would equal 10 GB of data, which we cannot handle.
/// </summary>
private void EnsureLengthStringBelowMaxLength(int lengthStringCount, long startPosition)
{
// Because of memory limitations (~1-2 GB) we know for certain we cannot handle more than 10 digits (10GB)
if (lengthStringCount >= BString.LengthMaxDigits)
{
throw UnsupportedException(
$"Length of string is more than {BString.LengthMaxDigits} digits (>10GB) and is not supported (max is ~1-2GB).",
startPosition);
}
}
/// <summary>
/// Ensure that the previously read char is a colon (:),
/// separating the string-length part and the actual string value.
/// </summary>
private void EnsurePreviousCharIsColon(char previousChar, long position)
{
if (previousChar != ':') throw InvalidBencodeException<BString>.UnexpectedChar(':', previousChar, position - 1);
}
/// <summary>
/// Parses the string-length <see cref="string"/> into a <see cref="long"/>.
/// </summary>
private long ParseStringLength(Span<char> lengthString, int lengthStringCount, long startPosition)
{
lengthString = lengthString.Slice(0, lengthStringCount);
if (!ParseUtil.TryParseLongFast(lengthString, out var stringLength))
throw InvalidException($"Invalid length '{lengthString.AsString()}' of string.", startPosition);
// Int32.MaxValue is ~2GB and is the absolute maximum that can be handled in memory
if (stringLength > int.MaxValue)
{
throw UnsupportedException(
$"Length of string is {stringLength:N0} but maximum supported length is {int.MaxValue:N0}.",
startPosition);
}
return stringLength;
}
/// <summary>
/// Ensures that number of bytes read matches the expected number parsed from the string-length part.
/// </summary>
private void EnsureExpectedBytesRead(long bytesRead, long stringLength, long startPosition)
{
// If the two don't match we've reached the end of the stream before reading the expected number of chars
if (bytesRead == stringLength) return;
throw InvalidException(
$"Expected string to be {stringLength:N0} bytes long but could only read {bytesRead:N0} bytes.",
startPosition);
}
private static InvalidBencodeException<BString> InvalidException(string message, long startPosition)
{
return new InvalidBencodeException<BString>(
$"{message} The string starts at position {startPosition}.",
startPosition);
}
private static UnsupportedBencodeException<BString> UnsupportedException(string message, long startPosition)
{
return new UnsupportedBencodeException<BString>(
$"{message} The string starts at position {startPosition}.",
startPosition);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
** Purpose: Generic hash table implementation
**
** #DictionaryVersusHashtableThreadSafety
** Hashtable has multiple reader/single writer (MR/SW) thread safety built into
** certain methods and properties, whereas Dictionary doesn't. If you're
** converting framework code that formerly used Hashtable to Dictionary, it's
** important to consider whether callers may have taken a dependence on MR/SW
** thread safety. If a reader writer lock is available, then that may be used
** with a Dictionary to get the same thread safety guarantee.
**
** Reader writer locks don't exist in silverlight, so we do the following as a
** result of removing non-generic collections from silverlight:
** 1. If the Hashtable was fully synchronized, then we replace it with a
** Dictionary with full locks around reads/writes (same thread safety
** guarantee).
** 2. Otherwise, the Hashtable has the default MR/SW thread safety behavior,
** so we do one of the following on a case-by-case basis:
** a. If the race condition can be addressed by rearranging the code and using a temp
** variable (for example, it's only populated immediately after created)
** then we address the race condition this way and use Dictionary.
** b. If there's concern about degrading performance with the increased
** locking, we ifdef with FEATURE_NONGENERIC_COLLECTIONS so we can at
** least use Hashtable in the desktop build, but Dictionary with full
** locks in silverlight builds. Note that this is heavier locking than
** MR/SW, but this is the only option without rewriting (or adding back)
** the reader writer lock.
** c. If there's no performance concern (e.g. debug-only code) we
** consistently replace Hashtable with Dictionary plus full locks to
** reduce complexity.
** d. Most of serialization is dead code in silverlight. Instead of updating
** those Hashtable occurences in serialization, we carved out references
** to serialization such that this code doesn't need to build in
** silverlight.
===========================================================*/
namespace System.Collections.Generic
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
/// <summary>
/// Used internally to control behavior of insertion into a <see cref="Dictionary{TKey, TValue}"/>.
/// </summary>
internal enum InsertionBehavior : byte
{
/// <summary>
/// The default insertion behavior.
/// </summary>
None = 0,
/// <summary>
/// Specifies that an existing entry with the same key should be overwritten if encountered.
/// </summary>
OverwriteExisting = 1,
/// <summary>
/// Specifies that if an existing entry with the same key is encountered, an exception should be thrown.
/// </summary>
ThrowOnExisting = 2
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback
{
private struct Entry
{
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
private int[] buckets;
private Entry[] entries;
private int count;
private int version;
private int freeList;
private int freeCount;
private IEqualityComparer<TKey> comparer;
private KeyCollection keys;
private ValueCollection values;
private Object _syncRoot;
// constants for serialization
private const String VersionName = "Version";
private const String HashSizeName = "HashSize"; // Must save buckets.Length
private const String KeyValuePairsName = "KeyValuePairs";
private const String ComparerName = "Comparer";
public Dictionary() : this(0, null) { }
public Dictionary(int capacity) : this(capacity, null) { }
public Dictionary(IEqualityComparer<TKey> comparer) : this(0, comparer) { }
public Dictionary(int capacity, IEqualityComparer<TKey> comparer)
{
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
if (capacity > 0) Initialize(capacity);
this.comparer = comparer ?? EqualityComparer<TKey>.Default;
#if FEATURE_RANDOMIZED_STRING_HASHING
if (HashHelpers.s_UseRandomizedStringHashing && this.comparer == EqualityComparer<string>.Default)
{
this.comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default;
}
#endif // FEATURE_RANDOMIZED_STRING_HASHING
}
public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { }
public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) :
this(dictionary != null ? dictionary.Count : 0, comparer)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
// It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case,
// avoid the enumerator allocation and overhead by looping through the entries array directly.
// We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain
// back-compat with subclasses that may have overridden the enumerator behavior.
if (dictionary.GetType() == typeof(Dictionary<TKey, TValue>))
{
Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary;
int count = d.count;
Entry[] entries = d.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
Add(entries[i].key, entries[i].value);
}
}
return;
}
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
Add(pair.Key, pair.Value);
}
}
public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) :
this(collection, null)
{ }
public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer) :
this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
foreach (KeyValuePair<TKey, TValue> pair in collection)
{
Add(pair.Key, pair.Value);
}
}
protected Dictionary(SerializationInfo info, StreamingContext context)
{
//We can't do anything with the keys and values until the entire graph has been deserialized
//and we have a resonable estimate that GetHashCode is not going to fail. For the time being,
//we'll just cache this. The graph is not valid until OnDeserialization has been called.
HashHelpers.SerializationInfoTable.Add(this, info);
}
public IEqualityComparer<TKey> Comparer
{
get
{
return comparer;
}
}
public int Count
{
get { return count - freeCount; }
}
public KeyCollection Keys
{
get
{
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
public ValueCollection Values
{
get
{
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (values == null) values = new ValueCollection(this);
return values;
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
if (values == null) values = new ValueCollection(this);
return values;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
if (values == null) values = new ValueCollection(this);
return values;
}
}
public TValue this[TKey key]
{
get
{
int i = FindEntry(key);
if (i >= 0) return entries[i].value;
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
set
{
bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting);
Debug.Assert(modified);
}
}
public void Add(TKey key, TValue value)
{
bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting);
Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown.
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
{
Add(keyValuePair.Key, keyValuePair.Value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
int i = FindEntry(keyValuePair.Key);
if (i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value))
{
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
int i = FindEntry(keyValuePair.Key);
if (i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value))
{
Remove(keyValuePair.Key);
return true;
}
return false;
}
public void Clear()
{
if (count > 0)
{
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
Array.Clear(entries, 0, count);
freeList = -1;
count = 0;
freeCount = 0;
version++;
}
}
public bool ContainsKey(TKey key)
{
return FindEntry(key) >= 0;
}
public bool ContainsValue(TValue value)
{
if (value == null)
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0 && entries[i].value == null) return true;
}
}
else
{
EqualityComparer<TValue> c = EqualityComparer<TValue>.Default;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0 && c.Equals(entries[i].value, value)) return true;
}
}
return false;
}
private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = this.count;
Entry[] entries = this.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
}
info.AddValue(VersionName, version);
info.AddValue(ComparerName, comparer, typeof(IEqualityComparer<TKey>));
info.AddValue(HashSizeName, buckets == null ? 0 : buckets.Length); //This is the length of the bucket array.
if (buckets != null)
{
KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[Count];
CopyTo(array, 0);
info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[]));
}
}
private int FindEntry(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null)
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next)
{
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
}
}
return -1;
}
private void Initialize(int capacity)
{
int size = HashHelpers.GetPrime(capacity);
buckets = new int[size];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
entries = new Entry[size];
freeList = -1;
}
private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets == null) Initialize(0);
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int targetBucket = hashCode % buckets.Length;
#if FEATURE_RANDOMIZED_STRING_HASHING
int collisionCount = 0;
#endif
for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next)
{
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
#if FEATURE_RANDOMIZED_STRING_HASHING
collisionCount++;
#endif
}
int index;
if (freeCount > 0)
{
index = freeList;
freeList = entries[index].next;
freeCount--;
}
else
{
if (count == entries.Length)
{
Resize();
targetBucket = hashCode % buckets.Length;
}
index = count;
count++;
}
entries[index].hashCode = hashCode;
entries[index].next = buckets[targetBucket];
entries[index].key = key;
entries[index].value = value;
buckets[targetBucket] = index;
version++;
#if FEATURE_RANDOMIZED_STRING_HASHING
// In case we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
// in this case will be EqualityComparer<string>.Default.
// Note, randomized string hashing is turned on by default on coreclr so EqualityComparer<string>.Default will
// be using randomized string hashing
if (collisionCount > HashHelpers.HashCollisionThreshold && comparer == NonRandomizedStringEqualityComparer.Default)
{
comparer = (IEqualityComparer<TKey>)EqualityComparer<string>.Default;
Resize(entries.Length, true);
}
#endif
return true;
}
public virtual void OnDeserialization(Object sender)
{
SerializationInfo siInfo;
HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo);
if (siInfo == null)
{
// It might be necessary to call OnDeserialization from a container if the container object also implements
// OnDeserialization. However, remoting will call OnDeserialization again.
// We can return immediately if this function is called twice.
// Note we set remove the serialization info from the table at the end of this method.
return;
}
int realVersion = siInfo.GetInt32(VersionName);
int hashsize = siInfo.GetInt32(HashSizeName);
comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>));
if (hashsize != 0)
{
buckets = new int[hashsize];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
entries = new Entry[hashsize];
freeList = -1;
KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[])
siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[]));
if (array == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys);
}
for (int i = 0; i < array.Length; i++)
{
if (array[i].Key == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
}
Add(array[i].Key, array[i].Value);
}
}
else
{
buckets = null;
}
version = realVersion;
HashHelpers.SerializationInfoTable.Remove(this);
}
private void Resize()
{
Resize(HashHelpers.ExpandPrime(count), false);
}
private void Resize(int newSize, bool forceNewHashCodes)
{
Debug.Assert(newSize >= entries.Length);
int[] newBuckets = new int[newSize];
for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1;
Entry[] newEntries = new Entry[newSize];
Array.Copy(entries, 0, newEntries, 0, count);
if (forceNewHashCodes)
{
for (int i = 0; i < count; i++)
{
if (newEntries[i].hashCode != -1)
{
newEntries[i].hashCode = (comparer.GetHashCode(newEntries[i].key) & 0x7FFFFFFF);
}
}
}
for (int i = 0; i < count; i++)
{
if (newEntries[i].hashCode >= 0)
{
int bucket = newEntries[i].hashCode % newSize;
newEntries[i].next = newBuckets[bucket];
newBuckets[bucket] = i;
}
}
buckets = newBuckets;
entries = newEntries;
}
// The overload Remove(TKey key, out TValue value) is a copy of this method with one additional
// statement to copy the value for entry being removed into the output parameter.
// Code has been intentionally duplicated for performance reasons.
public bool Remove(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null)
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int bucket = hashCode % buckets.Length;
int last = -1;
int i = buckets[bucket];
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.hashCode == hashCode && comparer.Equals(entry.key, key))
{
if (last < 0)
{
buckets[bucket] = entry.next;
}
else
{
entries[last].next = entry.next;
}
entry.hashCode = -1;
entry.next = freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
entry.key = default(TKey);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
entry.value = default(TValue);
}
freeList = i;
freeCount++;
version++;
return true;
}
last = i;
i = entry.next;
}
}
return false;
}
// This overload is a copy of the overload Remove(TKey key) with one additional
// statement to copy the value for entry being removed into the output parameter.
// Code has been intentionally duplicated for performance reasons.
public bool Remove(TKey key, out TValue value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null)
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int bucket = hashCode % buckets.Length;
int last = -1;
int i = buckets[bucket];
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.hashCode == hashCode && comparer.Equals(entry.key, key))
{
if (last < 0)
{
buckets[bucket] = entry.next;
}
else
{
entries[last].next = entry.next;
}
value = entry.value;
entry.hashCode = -1;
entry.next = freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
entry.key = default(TKey);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
entry.value = default(TValue);
}
freeList = i;
freeCount++;
version++;
return true;
}
last = i;
i = entry.next;
}
}
value = default(TValue);
return false;
}
public bool TryGetValue(TKey key, out TValue value)
{
int i = FindEntry(key);
if (i >= 0)
{
value = entries[i].value;
return true;
}
value = default(TValue);
return false;
}
// Method similar to TryGetValue that returns the value instead of putting it in an out param.
public TValue GetValueOrDefault(TKey key) => GetValueOrDefault(key, default(TValue));
// Method similar to TryGetValue that returns the value instead of putting it in an out param. If the entry
// doesn't exist, returns the defaultValue instead.
public TValue GetValueOrDefault(TKey key, TValue defaultValue)
{
int i = FindEntry(key);
if (i >= 0)
{
return entries[i].value;
}
return defaultValue;
}
public bool TryAdd(TKey key, TValue value) => TryInsert(key, value, InsertionBehavior.None);
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
CopyTo(array, index);
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[];
if (pairs != null)
{
CopyTo(pairs, index);
}
else if (array is DictionaryEntry[])
{
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
Entry[] entries = this.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value);
}
}
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try
{
int count = this.count;
Entry[] entries = this.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
bool IDictionary.IsFixedSize
{
get { return false; }
}
bool IDictionary.IsReadOnly
{
get { return false; }
}
ICollection IDictionary.Keys
{
get { return (ICollection)Keys; }
}
ICollection IDictionary.Values
{
get { return (ICollection)Values; }
}
object IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
int i = FindEntry((TKey)key);
if (i >= 0)
{
return entries[i].value;
}
}
return null;
}
set
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try
{
TKey tempKey = (TKey)key;
try
{
this[tempKey] = (TValue)value;
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return (key is TKey);
}
void IDictionary.Add(object key, object value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try
{
TKey tempKey = (TKey)key;
try
{
Add(tempKey, (TValue)value);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
bool IDictionary.Contains(object key)
{
if (IsCompatibleKey(key))
{
return ContainsKey((TKey)key);
}
return false;
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new Enumerator(this, Enumerator.DictEntry);
}
void IDictionary.Remove(object key)
{
if (IsCompatibleKey(key))
{
Remove((TKey)key);
}
}
[Serializable]
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>,
IDictionaryEnumerator
{
private Dictionary<TKey, TValue> dictionary;
private int version;
private int index;
private KeyValuePair<TKey, TValue> current;
private int getEnumeratorRetType; // What should Enumerator.Current return?
internal const int DictEntry = 1;
internal const int KeyValuePair = 2;
internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType)
{
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
this.getEnumeratorRetType = getEnumeratorRetType;
current = new KeyValuePair<TKey, TValue>();
}
public bool MoveNext()
{
if (version != dictionary.version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue
while ((uint)index < (uint)dictionary.count)
{
ref Entry entry = ref dictionary.entries[index++];
if (entry.hashCode >= 0)
{
current = new KeyValuePair<TKey, TValue>(entry.key, entry.value);
return true;
}
}
index = dictionary.count + 1;
current = new KeyValuePair<TKey, TValue>();
return false;
}
public KeyValuePair<TKey, TValue> Current
{
get { return current; }
}
public void Dispose()
{
}
object IEnumerator.Current
{
get
{
if (index == 0 || (index == dictionary.count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
if (getEnumeratorRetType == DictEntry)
{
return new System.Collections.DictionaryEntry(current.Key, current.Value);
}
else
{
return new KeyValuePair<TKey, TValue>(current.Key, current.Value);
}
}
}
void IEnumerator.Reset()
{
if (version != dictionary.version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
current = new KeyValuePair<TKey, TValue>();
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (index == 0 || (index == dictionary.count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return new DictionaryEntry(current.Key, current.Value);
}
}
object IDictionaryEnumerator.Key
{
get
{
if (index == 0 || (index == dictionary.count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return current.Key;
}
}
object IDictionaryEnumerator.Value
{
get
{
if (index == 0 || (index == dictionary.count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return current.Value;
}
}
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private Dictionary<TKey, TValue> dictionary;
public KeyCollection(Dictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
this.dictionary = dictionary;
}
public Enumerator GetEnumerator()
{
return new Enumerator(dictionary);
}
public void CopyTo(TKey[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) array[index++] = entries[i].key;
}
}
public int Count
{
get { return dictionary.Count; }
}
bool ICollection<TKey>.IsReadOnly
{
get { return true; }
}
void ICollection<TKey>.Add(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
void ICollection<TKey>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
bool ICollection<TKey>.Contains(TKey item)
{
return dictionary.ContainsKey(item);
}
bool ICollection<TKey>.Remove(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
return false;
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
{
return new Enumerator(dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(dictionary);
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
TKey[] keys = array as TKey[];
if (keys != null)
{
CopyTo(keys, index);
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) objects[index++] = entries[i].key;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
Object ICollection.SyncRoot
{
get { return ((ICollection)dictionary).SyncRoot; }
}
[Serializable]
public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> dictionary;
private int index;
private int version;
private TKey currentKey;
internal Enumerator(Dictionary<TKey, TValue> dictionary)
{
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
currentKey = default(TKey);
}
public void Dispose()
{
}
public bool MoveNext()
{
if (version != dictionary.version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)index < (uint)dictionary.count)
{
ref Entry entry = ref dictionary.entries[index++];
if (entry.hashCode >= 0)
{
currentKey = entry.key;
return true;
}
}
index = dictionary.count + 1;
currentKey = default(TKey);
return false;
}
public TKey Current
{
get
{
return currentKey;
}
}
Object System.Collections.IEnumerator.Current
{
get
{
if (index == 0 || (index == dictionary.count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return currentKey;
}
}
void System.Collections.IEnumerator.Reset()
{
if (version != dictionary.version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
currentKey = default(TKey);
}
}
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private Dictionary<TKey, TValue> dictionary;
public ValueCollection(Dictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
this.dictionary = dictionary;
}
public Enumerator GetEnumerator()
{
return new Enumerator(dictionary);
}
public void CopyTo(TValue[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) array[index++] = entries[i].value;
}
}
public int Count
{
get { return dictionary.Count; }
}
bool ICollection<TValue>.IsReadOnly
{
get { return true; }
}
void ICollection<TValue>.Add(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Remove(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
return false;
}
void ICollection<TValue>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Contains(TValue item)
{
return dictionary.ContainsValue(item);
}
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
{
return new Enumerator(dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(dictionary);
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
TValue[] values = array as TValue[];
if (values != null)
{
CopyTo(values, index);
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) objects[index++] = entries[i].value;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
Object ICollection.SyncRoot
{
get { return ((ICollection)dictionary).SyncRoot; }
}
[Serializable]
public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> dictionary;
private int index;
private int version;
private TValue currentValue;
internal Enumerator(Dictionary<TKey, TValue> dictionary)
{
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
currentValue = default(TValue);
}
public void Dispose()
{
}
public bool MoveNext()
{
if (version != dictionary.version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)index < (uint)dictionary.count)
{
ref Entry entry = ref dictionary.entries[index++];
if (entry.hashCode >= 0)
{
currentValue = entry.value;
return true;
}
}
index = dictionary.count + 1;
currentValue = default(TValue);
return false;
}
public TValue Current
{
get
{
return currentValue;
}
}
Object System.Collections.IEnumerator.Current
{
get
{
if (index == 0 || (index == dictionary.count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return currentValue;
}
}
void System.Collections.IEnumerator.Reset()
{
if (version != dictionary.version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
currentValue = default(TValue);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Text
{
using System;
using System.Security;
using System.Globalization;
using System.Text;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
// This internal class wraps up our normalization behavior
internal class Normalization
{
//
// Flags that track whether given normalization form was initialized
//
#if !FEATURE_NORM_IDNA_ONLY
private static volatile bool NFC;
private static volatile bool NFD;
private static volatile bool NFKC;
private static volatile bool NFKD;
#endif // !FEATURE_NORM_IDNA_ONLY
private static volatile bool IDNA;
#if !FEATURE_NORM_IDNA_ONLY
private static volatile bool NFCDisallowUnassigned;
private static volatile bool NFDDisallowUnassigned;
private static volatile bool NFKCDisallowUnassigned;
private static volatile bool NFKDDisallowUnassigned;
#endif // !FEATURE_NORM_IDNA_ONLY
private static volatile bool IDNADisallowUnassigned;
private static volatile bool Other;
// These are error codes we get back from the Normalization DLL
private const int ERROR_SUCCESS = 0;
private const int ERROR_NOT_ENOUGH_MEMORY = 8;
private const int ERROR_INVALID_PARAMETER = 87;
private const int ERROR_INSUFFICIENT_BUFFER = 122;
private const int ERROR_NO_UNICODE_TRANSLATION = 1113;
[System.Security.SecurityCritical] // auto-generated
static private unsafe void InitializeForm(NormalizationForm form, String strDataFile)
{
byte* pTables = null;
// Normalization uses OS on Win8
if (!Environment.IsWindows8OrAbove)
{
if (strDataFile == null)
{
// They were supposed to have a form that we know about!
throw new ArgumentException(
Environment.GetResourceString("Argument_InvalidNormalizationForm"));
}
// Tell the DLL where to find our data
pTables = GlobalizationAssembly.GetGlobalizationResourceBytePtr(
typeof(Normalization).Assembly, strDataFile);
if (pTables == null)
{
// Unable to load the specified normalizationForm,
// tables not loaded from file
throw new ArgumentException(
Environment.GetResourceString("Argument_InvalidNormalizationForm"));
}
}
nativeNormalizationInitNormalization(form, pTables);
}
[System.Security.SecurityCritical] // auto-generated
static private void EnsureInitialized(NormalizationForm form)
{
switch ((ExtendedNormalizationForms)form)
{
#if !FEATURE_NORM_IDNA_ONLY
case ExtendedNormalizationForms.FormC:
if (NFC) return;
InitializeForm(form, "normnfc.nlp");
NFC = true;
break;
case ExtendedNormalizationForms.FormD:
if (NFD) return;
InitializeForm(form, "normnfd.nlp");
NFD = true;
break;
case ExtendedNormalizationForms.FormKC:
if (NFKC) return;
InitializeForm(form, "normnfkc.nlp");
NFKC = true;
break;
case ExtendedNormalizationForms.FormKD:
if (NFKD) return;
InitializeForm(form, "normnfkd.nlp");
NFKD = true;
break;
#endif // !FEATURE_NORM_IDNA_ONLY
case ExtendedNormalizationForms.FormIdna:
if (IDNA) return;
InitializeForm(form, "normidna.nlp");
IDNA = true;
break;
#if !FEATURE_NORM_IDNA_ONLY
case ExtendedNormalizationForms.FormCDisallowUnassigned:
if (NFCDisallowUnassigned) return;
InitializeForm(form, "normnfc.nlp");
NFCDisallowUnassigned = true;
break;
case ExtendedNormalizationForms.FormDDisallowUnassigned:
if (NFDDisallowUnassigned) return;
InitializeForm(form, "normnfd.nlp");
NFDDisallowUnassigned = true;
break;
case ExtendedNormalizationForms.FormKCDisallowUnassigned:
if (NFKCDisallowUnassigned) return;
InitializeForm(form, "normnfkc.nlp");
NFKCDisallowUnassigned = true;
break;
case ExtendedNormalizationForms.FormKDDisallowUnassigned:
if (NFKDDisallowUnassigned) return;
InitializeForm(form, "normnfkd.nlp");
NFKDDisallowUnassigned = true;
break;
#endif // !FEATURE_NORM_IDNA_ONLY
case ExtendedNormalizationForms.FormIdnaDisallowUnassigned:
if (IDNADisallowUnassigned) return;
InitializeForm(form, "normidna.nlp");
IDNADisallowUnassigned = true;
break;
default:
if (Other) return;
InitializeForm(form, null);
Other = true;
break;
}
}
[System.Security.SecurityCritical]
internal static bool IsNormalized(String strInput, NormalizationForm normForm)
{
Contract.Requires(strInput != null);
EnsureInitialized(normForm);
int iError = ERROR_SUCCESS;
bool result = nativeNormalizationIsNormalizedString(
normForm,
ref iError,
strInput,
strInput.Length);
switch(iError)
{
// Success doesn't need to do anything
case ERROR_SUCCESS:
break;
// Do appropriate stuff for the individual errors:
case ERROR_INVALID_PARAMETER:
case ERROR_NO_UNICODE_TRANSLATION:
throw new ArgumentException(
Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ),
nameof(strInput));
case ERROR_NOT_ENOUGH_MEMORY:
throw new OutOfMemoryException(
Environment.GetResourceString("Arg_OutOfMemoryException"));
default:
throw new InvalidOperationException(
Environment.GetResourceString("UnknownError_Num", iError));
}
return result;
}
[System.Security.SecurityCritical]
internal static String Normalize(String strInput, NormalizationForm normForm)
{
Contract.Requires(strInput != null);
EnsureInitialized(normForm);
int iError = ERROR_SUCCESS;
// Guess our buffer size first
int iLength = nativeNormalizationNormalizeString(normForm, ref iError, strInput, strInput.Length, null, 0);
// Could have an error (actually it'd be quite hard to have an error here)
if (iError != ERROR_SUCCESS)
{
if (iError == ERROR_INVALID_PARAMETER)
throw new ArgumentException(
Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ),
nameof(strInput));
// We shouldn't really be able to get here..., guessing length is
// a trivial math function...
// Can't really be Out of Memory, but just in case:
if (iError == ERROR_NOT_ENOUGH_MEMORY)
throw new OutOfMemoryException(
Environment.GetResourceString("Arg_OutOfMemoryException"));
// Who knows what happened? Not us!
throw new InvalidOperationException(
Environment.GetResourceString("UnknownError_Num", iError));
}
// Don't break for empty strings (only possible for D & KD and not really possible at that)
if (iLength == 0) return String.Empty;
// Someplace to stick our buffer
char[] cBuffer = null;
for (;;)
{
// (re)allocation buffer and normalize string
cBuffer = new char[iLength];
iLength = nativeNormalizationNormalizeString(
normForm,
ref iError,
strInput,
strInput.Length,
cBuffer,
cBuffer.Length);
if (iError == ERROR_SUCCESS)
break;
// Could have an error (actually it'd be quite hard to have an error here)
switch(iError)
{
// Do appropriate stuff for the individual errors:
case ERROR_INSUFFICIENT_BUFFER:
Contract.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
continue;
case ERROR_INVALID_PARAMETER:
case ERROR_NO_UNICODE_TRANSLATION:
// Illegal code point or order found. Ie: FFFE or D800 D800, etc.
throw new ArgumentException(
Environment.GetResourceString("Argument_InvalidCharSequence", iLength ),
nameof(strInput));
case ERROR_NOT_ENOUGH_MEMORY:
throw new OutOfMemoryException(
Environment.GetResourceString("Arg_OutOfMemoryException"));
default:
// We shouldn't get here...
throw new InvalidOperationException(
Environment.GetResourceString("UnknownError_Num", iError));
}
}
// Copy our buffer into our new string, which will be the appropriate size
return new String(cBuffer, 0, iLength);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe private static extern int nativeNormalizationNormalizeString(
NormalizationForm normForm, ref int iError,
String lpSrcString, int cwSrcLength,
char[] lpDstString, int cwDstLength);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe private static extern bool nativeNormalizationIsNormalizedString(
NormalizationForm normForm, ref int iError,
String lpString, int cwLength);
[System.Security.SecurityCritical] // auto-generated
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
unsafe private static extern void nativeNormalizationInitNormalization(
NormalizationForm normForm, byte* pTableData);
}
}
| |
using System;
using System.IO;
using SharpCompress.IO;
namespace SharpCompress.Common.Rar.Headers
{
internal class FileHeader : RarHeader
{
private const byte SALT_SIZE = 8;
private const byte NEWLHD_SIZE = 32;
protected override void ReadFromReader(MarkingBinaryReader reader)
{
uint lowUncompressedSize = reader.ReadUInt32();
HostOS = (HostOS)reader.ReadByte();
FileCRC = reader.ReadUInt32();
FileLastModifiedTime = Utility.DosDateToDateTime(reader.ReadInt32());
RarVersion = reader.ReadByte();
PackingMethod = reader.ReadByte();
short nameSize = reader.ReadInt16();
FileAttributes = reader.ReadInt32();
uint highCompressedSize = 0;
uint highUncompressedkSize = 0;
if (FileFlags.HasFlag(FileFlags.LARGE))
{
highCompressedSize = reader.ReadUInt32();
highUncompressedkSize = reader.ReadUInt32();
}
else
{
if (lowUncompressedSize == 0xffffffff)
{
lowUncompressedSize = 0xffffffff;
highUncompressedkSize = int.MaxValue;
}
}
CompressedSize = UInt32To64(highCompressedSize, AdditionalSize);
UncompressedSize = UInt32To64(highUncompressedkSize, lowUncompressedSize);
nameSize = nameSize > 4 * 1024 ? (short)(4 * 1024) : nameSize;
byte[] fileNameBytes = reader.ReadBytes(nameSize);
switch (HeaderType)
{
case HeaderType.FileHeader:
{
if (FileFlags.HasFlag(FileFlags.UNICODE))
{
int length = 0;
while (length < fileNameBytes.Length
&& fileNameBytes[length] != 0)
{
length++;
}
if (length != nameSize)
{
length++;
FileName = FileNameDecoder.Decode(fileNameBytes, length);
}
else
{
FileName = DecodeDefault(fileNameBytes);
}
}
else
{
FileName = DecodeDefault(fileNameBytes);
}
FileName = ConvertPath(FileName, HostOS);
}
break;
case HeaderType.NewSubHeader:
{
int datasize = HeaderSize - NEWLHD_SIZE - nameSize;
if (FileFlags.HasFlag(FileFlags.SALT))
{
datasize -= SALT_SIZE;
}
if (datasize > 0)
{
SubData = reader.ReadBytes(datasize);
}
if (NewSubHeaderType.SUBHEAD_TYPE_RR.Equals(fileNameBytes))
{
RecoverySectors = SubData[8] + (SubData[9] << 8)
+ (SubData[10] << 16) + (SubData[11] << 24);
}
}
break;
}
if (FileFlags.HasFlag(FileFlags.SALT))
{
Salt = reader.ReadBytes(SALT_SIZE);
}
if (FileFlags.HasFlag(FileFlags.EXTTIME))
{
// verify that the end of the header hasn't been reached before reading the Extended Time.
// some tools incorrectly omit Extended Time despite specifying FileFlags.EXTTIME, which most parsers tolerate.
if (ReadBytes + reader.CurrentReadByteCount <= HeaderSize - 2)
{
ushort extendedFlags = reader.ReadUInt16();
FileLastModifiedTime = ProcessExtendedTime(extendedFlags, FileLastModifiedTime, reader, 0);
FileCreatedTime = ProcessExtendedTime(extendedFlags, null, reader, 1);
FileLastAccessedTime = ProcessExtendedTime(extendedFlags, null, reader, 2);
FileArchivedTime = ProcessExtendedTime(extendedFlags, null, reader, 3);
}
}
}
//only the full .net framework will do other code pages than unicode/utf8
private string DecodeDefault(byte[] bytes)
{
return ArchiveEncoding.Default.GetString(bytes, 0, bytes.Length);
}
private long UInt32To64(uint x, uint y)
{
long l = x;
l <<= 32;
return l + y;
}
private static DateTime? ProcessExtendedTime(ushort extendedFlags, DateTime? time, MarkingBinaryReader reader,
int i)
{
uint rmode = (uint)extendedFlags >> (3 - i) * 4;
if ((rmode & 8) == 0)
{
return null;
}
if (i != 0)
{
uint DosTime = reader.ReadUInt32();
time = Utility.DosDateToDateTime(DosTime);
}
if ((rmode & 4) == 0)
{
time = time.Value.AddSeconds(1);
}
uint nanosecondHundreds = 0;
int count = (int)rmode & 3;
for (int j = 0; j < count; j++)
{
byte b = reader.ReadByte();
nanosecondHundreds |= (((uint)b) << ((j + 3 - count) * 8));
}
//10^-7 to 10^-3
return time.Value.AddMilliseconds(nanosecondHundreds * Math.Pow(10, -4));
}
private static string ConvertPath(string path, HostOS os)
{
#if NO_FILE
return path.Replace('\\', '/');
#else
switch (os)
{
case HostOS.MacOS:
case HostOS.Unix:
{
if (Path.DirectorySeparatorChar == '\\')
{
return path.Replace('/', '\\');
}
}
break;
default:
{
if (Path.DirectorySeparatorChar == '/')
{
return path.Replace('\\', '/');
}
}
break;
}
return path;
#endif
}
internal long DataStartPosition { get; set; }
internal HostOS HostOS { get; private set; }
internal uint FileCRC { get; private set; }
internal DateTime? FileLastModifiedTime { get; private set; }
internal DateTime? FileCreatedTime { get; private set; }
internal DateTime? FileLastAccessedTime { get; private set; }
internal DateTime? FileArchivedTime { get; private set; }
internal byte RarVersion { get; private set; }
internal byte PackingMethod { get; private set; }
internal int FileAttributes { get; private set; }
internal FileFlags FileFlags
{
get { return (FileFlags)base.Flags; }
}
internal long CompressedSize { get; private set; }
internal long UncompressedSize { get; private set; }
internal string FileName { get; private set; }
internal byte[] SubData { get; private set; }
internal int RecoverySectors { get; private set; }
internal byte[] Salt { get; private set; }
public override string ToString()
{
return FileName;
}
public Stream PackedStream { get; set; }
}
}
| |
/* ====================================================================
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;
namespace NPOI.Util
{
/// <summary>
/// 24.08.2009 @author Stefan Stern
/// </summary>
public class IdentifierManager
{
public static long MAX_ID = long.MaxValue - 1;
public static long MIN_ID = 0L;
/**
*
*/
private long upperbound;
/**
*
*/
private long lowerbound;
/**
* List of segments of available identifiers
*/
private List<Segment> segments;
/**
* @param lowerbound the lower limit of the id-range to manage. Must be greater than or equal to {@link #MIN_ID}.
* @param upperbound the upper limit of the id-range to manage. Must be less then or equal {@link #MAX_ID}.
*/
public IdentifierManager(long lowerbound, long upperbound)
{
if (lowerbound > upperbound)
{
throw new ArgumentException("lowerbound must not be greater than upperbound, had " + lowerbound + " and " + upperbound);
}
else if (lowerbound < MIN_ID)
{
String message = "lowerbound must be greater than or equal to " + MIN_ID;
throw new ArgumentException(message);
}
else if (upperbound > MAX_ID)
{
/*
* while MAX_ID is Long.MAX_VALUE, this check is pointless. But if
* someone subclasses / tweaks the limits, this check is fine.
*/
throw new ArgumentException("upperbound must be less than or equal to " + MAX_ID + " but had " + upperbound);
}
this.lowerbound = lowerbound;
this.upperbound = upperbound;
this.segments = new List<Segment>();
segments.Add(new Segment(lowerbound, upperbound));
}
public long Reserve(long id)
{
if (id < lowerbound || id > upperbound)
{
throw new ArgumentException("Value for parameter 'id' was out of bounds");
}
VerifyIdentifiersLeft();
if (id == upperbound)
{
int lastid = segments.Count - 1;
Segment lastSegment = segments[lastid];
if (lastSegment.end == upperbound)
{
lastSegment.end = upperbound - 1;
if (lastSegment.start > lastSegment.end)
{
segments.RemoveAt(lastid);
}
return id;
}
return ReserveNew();
}
if (id == lowerbound)
{
Segment firstSegment = segments[0];
if (firstSegment.start == lowerbound)
{
firstSegment.start = lowerbound + 1;
if (firstSegment.end < firstSegment.start)
{
segments.RemoveAt(0);
}
return id;
}
return ReserveNew();
}
for (int i = 0; i < segments.Count; i++)
{
Segment segment = segments[i];
if (segment.end < id)
{
continue;
}
else if (segment.start > id)
{
break;
}
else if (segment.start == id)
{
segment.start = id + 1;
if (segment.end < segment.start)
{
segments.Remove(segment);
}
return id;
}
else if (segment.end == id)
{
segment.end = id - 1;
if (segment.start > segment.end)
{
segments.Remove(segment);
}
return id;
}
else
{
segments.Add(new Segment(id + 1, segment.end));
segment.end = id - 1;
return id;
}
}
return ReserveNew();
}
/**
* @return a new identifier.
* @throws InvalidOperationException if no more identifiers are available, then an Exception is raised.
*/
public long ReserveNew()
{
VerifyIdentifiersLeft();
Segment segment = segments[0];
long result = segment.start;
segment.start += 1;
if (segment.start > segment.end)
{
segments.RemoveAt(0);
}
return result;
}
/**
* @param id
* the identifier to release. Must be greater than or equal to
* {@link #lowerbound} and must be less than or equal to {@link #upperbound}
* @return true, if the identifier was reserved and has been successfully
* released, false, if the identifier was not reserved.
*/
public bool Release(long id)
{
if (id < lowerbound || id > upperbound)
{
throw new ArgumentException("Value for parameter 'id' was out of bounds, had " + id + ", but should be within [" + lowerbound + ":" + upperbound + "]");
}
if (id == upperbound)
{
int lastid = segments.Count - 1;
Segment lastSegment = segments[lastid];
if (lastSegment.end == upperbound - 1)
{
lastSegment.end = upperbound;
return true;
}
else if (lastSegment.end == upperbound)
{
return false;
}
else
{
segments.Add(new Segment(upperbound, upperbound));
return true;
}
}
if (id == lowerbound)
{
Segment firstSegment = segments[0];
if (firstSegment.start == lowerbound + 1)
{
firstSegment.start = lowerbound;
return true;
}
else if (firstSegment.start == lowerbound)
{
return false;
}
else
{
segments.Insert(0,new Segment(lowerbound, lowerbound));
return true;
}
}
long higher = id + 1;
long lower = id - 1;
for (int i = 0; i < segments.Count; i++)
{
Segment segment = segments[0];
if (segment.end < lower)
{
continue;
}
if (segment.start > higher)
{
segments.Insert(i,new Segment(id, id));
return true;
}
if (segment.start == higher)
{
segment.start = id;
return true;
}
else if (segment.end == lower)
{
segment.end = id;
/* check if releasing this elements glues two segments into one */
if (i+1<segments.Count)
{
Segment next = segments[i + 1];
if (next.start == segment.end + 1)
{
segment.end = next.end;
segments.Remove(next);
}
}
return true;
}
else
{
/* id was not reserved, return false */
break;
}
}
return false;
}
public long GetRemainingIdentifiers()
{
long result = 0;
foreach (Segment segment in segments)
{
result = result - segment.start;
result = result + segment.end + 1;
}
return result;
}
/**
*
*/
private void VerifyIdentifiersLeft()
{
if (segments.Count==0)
{
throw new InvalidOperationException("No identifiers left");
}
}
internal class Segment
{
public Segment(long start, long end)
{
this.start = start;
this.end = end;
}
public long start;
public long end;
/*
* (non-Javadoc)
*
* @see java.lang.Object#ToString()
*/
public override String ToString()
{
return "[" + start + "; " + end + "]";
}
}
}
}
| |
// 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.Runtime.CompilerServices;
namespace System.Numerics
{
// This file contains the definitions for all of the JIT intrinsic methods and properties that are recognized by the current x64 JIT compiler.
// The implementation defined here is used in any circumstance where the JIT fails to recognize these members as intrinsic.
// The JIT recognizes these methods and properties by name and signature: if either is changed, the JIT will no longer recognize the member.
// Some methods declared here are not strictly intrinsic, but delegate to an intrinsic method. For example, only one overload of CopyTo()
public partial struct Vector2
{
/// <summary>
/// The X component of the vector.
/// </summary>
public Single X;
/// <summary>
/// The Y component of the vector.
/// </summary>
public Single Y;
#region Constructors
/// <summary>
/// Constructs a vector whose elements are all the single specified value.
/// </summary>
/// <param name="value">The element to fill the vector with.</param>
[JitIntrinsic]
public Vector2(Single value) : this(value, value) { }
/// <summary>
/// Constructs a vector with the given individual elements.
/// </summary>
/// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param>
[JitIntrinsic]
public Vector2(Single x, Single y)
{
X = x;
Y = y;
}
#endregion Constructors
#region Public Instance Methods
/// <summary>
/// Copies the contents of the vector into the given array.
/// </summary>
/// <param name="array">The destination array.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array)
{
CopyTo(array, 0);
}
/// <summary>
/// Copies the contents of the vector into the given array, starting from the given index.
/// </summary>
/// <exception cref="ArgumentNullException">If array is null.</exception>
/// <exception cref="RankException">If array is multidimensional.</exception>
/// <exception cref="ArgumentOutOfRangeException">If index is greater than end of the array or index is less than zero.</exception>
/// <exception cref="ArgumentException">If number of elements in source vector is greater than those available in destination array
/// or if there are not enough elements to copy.</exception>
public void CopyTo(Single[] array, int index)
{
if (array == null)
{
// Match the JIT's exception type here. For perf, a NullReference is thrown instead of an ArgumentNull.
throw new NullReferenceException(SR.Arg_NullArgumentNullRef);
}
if (index < 0 || index >= array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.Arg_ArgumentOutOfRangeException, index));
}
if ((array.Length - index) < 2)
{
throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index));
}
array[index] = X;
array[index + 1] = Y;
}
/// <summary>
/// Returns a boolean indicating whether the given Vector2 is equal to this Vector2 instance.
/// </summary>
/// <param name="other">The Vector2 to compare this instance to.</param>
/// <returns>True if the other Vector2 is equal to this instance; False otherwise.</returns>
[JitIntrinsic]
public bool Equals(Vector2 other)
{
return this.X == other.X && this.Y == other.Y;
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The dot product.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector2 value1, Vector2 value2)
{
return value1.X * value2.X +
value1.Y * value2.Y;
}
/// <summary>
/// Returns a vector whose elements are the minimum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The minimized vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Min(Vector2 value1, Vector2 value2)
{
return new Vector2(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y);
}
/// <summary>
/// Returns a vector whose elements are the maximum of each of the pairs of elements in the two source vectors
/// </summary>
/// <param name="value1">The first source vector</param>
/// <param name="value2">The second source vector</param>
/// <returns>The maximized vector</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Max(Vector2 value1, Vector2 value2)
{
return new Vector2(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y);
}
/// <summary>
/// Returns a vector whose elements are the absolute values of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The absolute value vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Abs(Vector2 value)
{
return new Vector2(MathF.Abs(value.X), MathF.Abs(value.Y));
}
/// <summary>
/// Returns a vector whose elements are the square root of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The square root vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 SquareRoot(Vector2 value)
{
return new Vector2(MathF.Sqrt(value.X), MathF.Sqrt(value.Y));
}
#endregion Public Static Methods
#region Public Static Operators
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator +(Vector2 left, Vector2 right)
{
return new Vector2(left.X + right.X, left.Y + right.Y);
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(Vector2 left, Vector2 right)
{
return new Vector2(left.X - right.X, left.Y - right.Y);
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(Vector2 left, Vector2 right)
{
return new Vector2(left.X * right.X, left.Y * right.Y);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(Single left, Vector2 right)
{
return new Vector2(left, left) * right;
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(Vector2 left, Single right)
{
return left * new Vector2(right, right);
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator /(Vector2 left, Vector2 right)
{
return new Vector2(left.X / right.X, left.Y / right.Y);
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator /(Vector2 value1, float value2)
{
float invDiv = 1.0f / value2;
return new Vector2(
value1.X * invDiv,
value1.Y * invDiv);
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(Vector2 value)
{
return Zero - value;
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are equal; False otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector2 left, Vector2 right)
{
return left.Equals(right);
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are not equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are not equal; False if they are equal.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Vector2 left, Vector2 right)
{
return !(left == right);
}
#endregion Public Static Operators
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.IO;
using log4net;
using FluorineFx.Context;
using FluorineFx.Messaging.Config;
using FluorineFx.Messaging.Messages;
using FluorineFx.Messaging.Services.Messaging;
using FluorineFx.Messaging.Endpoints;
using FluorineFx.Messaging.Api;
using FluorineFx.IO;
using FluorineFx.Util;
namespace FluorineFx.Messaging.Services
{
/// <summary>
/// The MessageService class is the Service implementation that manages point-to-point and publish-subscribe messaging.
/// </summary>
[CLSCompliant(false)]
public class MessageService : ServiceBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(MessageService));
private MessageService()
{
}
/// <summary>
/// Initializes a new instance of the MessageService class.
/// </summary>
/// <param name="messageBroker"></param>
/// <param name="serviceDefinition"></param>
public MessageService(MessageBroker messageBroker, ServiceDefinition serviceDefinition)
: base(messageBroker, serviceDefinition)
{
}
/// <summary>
/// This method supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// </summary>
/// <param name="destinationDefinition"></param>
/// <returns></returns>
[CLSCompliant(false)]
protected override Destination NewDestination(DestinationDefinition destinationDefinition)
{
return new MessageDestination(this, destinationDefinition);
}
/// <summary>
/// Handles a message routed to the service by the MessageBroker.
/// </summary>
/// <param name="message">The message that should be handled by the service.</param>
/// <returns>The result of the message processing.</returns>
public override object ServiceMessage(IMessage message)
{
CommandMessage commandMessage = message as CommandMessage;
MessageDestination messageDestination = GetDestination(message) as MessageDestination;
if( commandMessage != null )
{
string clientId = commandMessage.clientId as string;
MessageClient messageClient = messageDestination.SubscriptionManager.GetSubscriber(clientId);
AcknowledgeMessage acknowledgeMessage = null;
switch (commandMessage.operation)
{
case CommandMessage.SubscribeOperation:
if (messageClient == null)
{
if (clientId == null)
clientId = Guid.NewGuid().ToString("D");
if (log.IsDebugEnabled)
log.Debug(__Res.GetString(__Res.MessageServiceSubscribe, messageDestination.Id, clientId));
string endpointId = commandMessage.GetHeader(MessageBase.EndpointHeader) as string;
if (_messageBroker.GetEndpoint(endpointId) == null)
{
ServiceException serviceException = new ServiceException("Endpoint was not specified");
serviceException.FaultCode = "Server.Processing.MissingEndpoint";
throw serviceException;
}
commandMessage.clientId = clientId;
if (messageDestination.ServiceAdapter != null && messageDestination.ServiceAdapter.HandlesSubscriptions)
{
try
{
acknowledgeMessage = messageDestination.ServiceAdapter.Manage(commandMessage) as AcknowledgeMessage;
}
catch (MessageException me)
{
acknowledgeMessage = me.GetErrorMessage();
//Leave, do not subscribe
return acknowledgeMessage;
}
catch (Exception ex)
{
//Guard against service adapter failure
acknowledgeMessage = ErrorMessage.GetErrorMessage(commandMessage, ex);
if (log.IsErrorEnabled)
log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex);
//Leave, do not subscribe
return acknowledgeMessage;
}
}
Subtopic subtopic = null;
Selector selector = null;
if (commandMessage.headers != null)
{
if (commandMessage.headers.ContainsKey(CommandMessage.SelectorHeader))
{
selector = Selector.CreateSelector(commandMessage.headers[CommandMessage.SelectorHeader] as string);
}
if (commandMessage.headers.ContainsKey(AsyncMessage.SubtopicHeader))
{
subtopic = new Subtopic(commandMessage.headers[AsyncMessage.SubtopicHeader] as string);
}
}
IClient client = FluorineContext.Current.Client;
client.Renew();
messageClient = messageDestination.SubscriptionManager.AddSubscriber(clientId, endpointId, subtopic, selector);
if (acknowledgeMessage == null)
acknowledgeMessage = new AcknowledgeMessage();
acknowledgeMessage.clientId = clientId;
}
else
{
acknowledgeMessage = new AcknowledgeMessage();
acknowledgeMessage.clientId = clientId;
}
return acknowledgeMessage;
case CommandMessage.UnsubscribeOperation:
if (log.IsDebugEnabled)
log.Debug(__Res.GetString(__Res.MessageServiceUnsubscribe, messageDestination.Id, clientId));
if (messageDestination.ServiceAdapter != null && messageDestination.ServiceAdapter.HandlesSubscriptions)
{
try
{
acknowledgeMessage = messageDestination.ServiceAdapter.Manage(commandMessage) as AcknowledgeMessage;
}
catch (MessageException me)
{
acknowledgeMessage = me.GetErrorMessage();
}
catch (Exception ex)
{
//Guard against service adapter failure
acknowledgeMessage = ErrorMessage.GetErrorMessage(commandMessage, ex);
if (log.IsErrorEnabled)
log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex);
}
}
if (messageClient != null)
messageDestination.SubscriptionManager.RemoveSubscriber(messageClient);
if (acknowledgeMessage == null)
acknowledgeMessage = new AcknowledgeMessage();
return acknowledgeMessage;
case CommandMessage.PollOperation:
{
if (messageClient == null)
{
ServiceException serviceException = new ServiceException(string.Format("MessageClient is not subscribed to {0}", commandMessage.destination));
serviceException.FaultCode = "Server.Processing.NotSubscribed";
throw serviceException;
}
IClient client = FluorineContext.Current.Client;
client.Renew();
try
{
acknowledgeMessage = messageDestination.ServiceAdapter.Manage(commandMessage) as AcknowledgeMessage;
}
catch (MessageException me)
{
acknowledgeMessage = me.GetErrorMessage();
}
catch (Exception ex)
{
//Guard against service adapter failure
acknowledgeMessage = ErrorMessage.GetErrorMessage(commandMessage, ex);
if (log.IsErrorEnabled)
log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex);
}
if (acknowledgeMessage == null)
acknowledgeMessage = new AcknowledgeMessage();
return acknowledgeMessage;
}
case CommandMessage.ClientPingOperation:
if (messageDestination.ServiceAdapter != null && messageDestination.ServiceAdapter.HandlesSubscriptions)
{
try
{
messageDestination.ServiceAdapter.Manage(commandMessage);
}
catch (MessageException)
{
return false;
}
catch (Exception ex)
{
//Guard against service adapter failure
if (log.IsErrorEnabled)
log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex);
return false;
}
}
return true;
default:
if (log.IsDebugEnabled)
log.Debug(__Res.GetString(__Res.MessageServiceUnknown, commandMessage.operation, messageDestination.Id));
try
{
acknowledgeMessage = messageDestination.ServiceAdapter.Manage(commandMessage) as AcknowledgeMessage;
}
catch (MessageException me)
{
acknowledgeMessage = me.GetErrorMessage();
}
catch (Exception ex)
{
//Guard against service adapter failure
acknowledgeMessage = ErrorMessage.GetErrorMessage(commandMessage, ex);
if (log.IsErrorEnabled)
log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex);
}
if (acknowledgeMessage == null)
acknowledgeMessage = new AcknowledgeMessage();
return acknowledgeMessage;
}
}
else
{
if (log.IsDebugEnabled)
log.Debug(__Res.GetString(__Res.MessageServiceRoute, messageDestination.Id, message.clientId));
if (FluorineContext.Current != null && FluorineContext.Current.Client != null)//Not set when user code initiates push
{
IClient client = FluorineContext.Current.Client;
client.Renew();
}
object result = messageDestination.ServiceAdapter.Invoke(message);
return result;
}
}
/// <summary>
/// Returns a collection of client Ids of the clients subscribed to receive this message.
/// If the message has a subtopic header, the subtopics are used to filter the subscribers.
/// If there is no subtopic header, subscribers to the destination with no subtopic are used.
/// Selector expressions if available will be evaluated to filter the subscribers.
/// </summary>
/// <param name="message">The message to send to subscribers.</param>
/// <returns>Collection of subscribers.</returns>
public ICollection GetSubscriber(IMessage message)
{
return GetSubscriber(message, true);
}
/// <summary>
/// Returns a collection of client Ids of the clients subscribed to receive this message.
/// If the message has a subtopic header, the subtopics are used to filter the subscribers.
/// If there is no subtopic header, subscribers to the destination with no subtopic are used.
/// If a subscription has a selector expression associated with it and evalSelector is true,
/// the subscriber is only returned if the selector expression evaluates to true.
/// </summary>
/// <param name="message">The message to send to subscribers.</param>
/// <param name="evalSelector">Indicates whether evaluate selector expressions.</param>
/// <returns>Collection of subscribers.</returns>
/// <remarks>
/// Use this method to do additional processing to the subscribers list.
/// </remarks>
public ICollection GetSubscriber(IMessage message, bool evalSelector)
{
MessageDestination destination = GetDestination(message) as MessageDestination;
SubscriptionManager subscriptionManager = destination.SubscriptionManager;
ICollection subscribers = subscriptionManager.GetSubscribers(message, evalSelector);
return subscribers;
}
/// <summary>
/// Pushes a message to all clients that are subscribed to the destination targeted by this message.
/// </summary>
/// <param name="message">The Message to push to the destination's subscribers.</param>
public void PushMessageToClients(IMessage message)
{
MessageDestination destination = GetDestination(message) as MessageDestination;
SubscriptionManager subscriptionManager = destination.SubscriptionManager;
ICollection subscribers = subscriptionManager.GetSubscribers(message);
if( subscribers != null && subscribers.Count > 0 )
{
PushMessageToClients(subscribers, message);
//Asynchronous invocation sample:
//BeginPushMessageToClients(new AsyncCallback(OnPushEnd), subscribers, message);
}
}
/*
void OnPushEnd(IAsyncResult result)
{
EndPushMessageToClients(result);
}
*/
/// <summary>
/// Pushes a message to the specified clients (subscribers).
/// </summary>
/// <param name="subscribers">Collection of subscribers.</param>
/// <param name="message">The Message to push to the subscribers.</param>
/// <remarks>
/// The Collection of subscribers is a collection of client Id strings.
/// </remarks>
public void PushMessageToClients(ICollection subscribers, IMessage message)
{
MessageDestination destination = GetDestination(message) as MessageDestination;
SubscriptionManager subscriptionManager = destination.SubscriptionManager;
if( subscribers != null && subscribers.Count > 0 )
{
IMessage messageClone = message.Copy() as IMessage;
/*
if( subscribers.Count > 1 )
{
messageClone.SetHeader(MessageBase.DestinationClientIdHeader, BinaryMessage.DestinationClientGuid);
messageClone.clientId = BinaryMessage.DestinationClientGuid;
//Cache the message
MemoryStream ms = new MemoryStream();
AMFSerializer amfSerializer = new AMFSerializer(ms);
//TODO this should depend on endpoint settings
amfSerializer.UseLegacyCollection = false;
amfSerializer.WriteData(ObjectEncoding.AMF3, messageClone);
amfSerializer.Flush();
byte[] cachedContent = ms.ToArray();
ms.Close();
BinaryMessage binaryMessage = new BinaryMessage();
binaryMessage.body = cachedContent;
//binaryMessage.Prepare();
messageClone = binaryMessage;
}
*/
foreach(string clientId in subscribers)
{
MessageClient client = subscriptionManager.GetSubscriber(clientId);
if( client == null )
continue;
if (log.IsDebugEnabled)
{
if( messageClone is BinaryMessage )
log.Debug(__Res.GetString(__Res.MessageServicePushBinary, message.GetType().Name, clientId));
else
log.Debug(__Res.GetString(__Res.MessageServicePush, message.GetType().Name, clientId));
}
IEndpoint endpoint = _messageBroker.GetEndpoint(client.EndpointId);
if (endpoint != null)
endpoint.Push(messageClone, client);
else
{
//We should never get here
if( log.IsErrorEnabled)
log.Error(string.Format("Missing endpoint for message client {0}", client.ClientId));
}
}
}
}
/// <summary>
/// Begins an asynchronous operation to push a message to the specified clients (subscribers).
/// </summary>
/// <param name="asyncCallback">The AsyncCallback delegate.</param>
/// <param name="subscribers">Collection of subscribers.</param>
/// <param name="message">The Message to push to the subscribers.</param>
/// <returns>An IAsyncResult that references the asynchronous invocation.</returns>
/// <remarks>
/// <para>
/// The Collection of subscribers is a collection of client Id strings.
/// </para>
/// <para>
/// You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginPushMessageToClients method.
/// </para>
/// <para>
/// Your callback method should invoke the EndPushMessageToClients method. When your application calls EndPushMessageToClients, the system will use a separate thread to execute the specified callback method, and will block on EndPushMessageToClients until the message is pushed successfully or throws an exception.
/// </para>
/// </remarks>
public IAsyncResult BeginPushMessageToClients(AsyncCallback asyncCallback, ICollection subscribers, IMessage message)
{
// Create IAsyncResult object identifying the asynchronous operation
AsyncResultNoResult ar = new AsyncResultNoResult(asyncCallback, new PushData(FluorineContext.Current, subscribers, message));
// Use a thread pool thread to perform the operation
FluorineFx.Threading.ThreadPoolEx.Global.QueueUserWorkItem(new System.Threading.WaitCallback(OnBeginPushMessageToClients), ar);
// Return the IAsyncResult to the caller
return ar;
}
private void OnBeginPushMessageToClients(object asyncResult)
{
AsyncResultNoResult ar = asyncResult as AsyncResultNoResult;
try
{
// Perform the operation; if sucessful set the result
PushData pushData = ar.AsyncState as PushData;
//Restore context
FluorineWebSafeCallContext.SetData(FluorineContext.FluorineContextKey, pushData.Context);
PushMessageToClients(pushData.Subscribers, pushData.Message);
ar.SetAsCompleted(null, false);
}
catch (Exception ex)
{
// If operation fails, set the exception
ar.SetAsCompleted(ex, false);
}
finally
{
FluorineWebSafeCallContext.FreeNamedDataSlot(FluorineContext.FluorineContextKey);
}
}
/// <summary>
/// Ends a pending asynchronous message push.
/// </summary>
/// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param>
/// <remarks>
/// <para>
/// EndInvoke is a blocking method that completes the asynchronous message push request started in the BeginPushMessageToClients method.
/// </para>
/// <para>
/// Before calling BeginPushMessageToClients, you can create a callback method that implements the AsyncCallback delegate. This callback method executes in a separate thread and is called by the system after BeginPushMessageToClients returns.
/// The callback method must accept the IAsyncResult returned by the BeginPushMessageToClients method as a parameter.
/// </para>
/// <para>Within the callback method you can call the EndPushMessageToClients method to successfully complete the invocation attempt.</para>
/// <para>The BeginPushMessageToClients enables to use the fire and forget pattern too (by not implementing an AsyncCallback delegate), however if the invocation fails the EndPushMessageToClients method is responsible to throw an appropriate exception.
/// Implementing the callback and calling EndPushMessageToClients also allows early garbage collection of the internal objects used in the asynchronous call.</para>
/// </remarks>
public void EndPushMessageToClients(IAsyncResult asyncResult)
{
AsyncResultNoResult ar = asyncResult as AsyncResultNoResult;
// Wait for operation to complete, then return result or throw exception
ar.EndInvoke();
}
}
#region PushData
#if !SILVERLIGHT
class PushData
{
FluorineContext _context;
ICollection _subscribers;
IMessage _message;
public FluorineContext Context
{
get { return _context; }
}
public ICollection Subscribers
{
get { return _subscribers; }
}
public IMessage Message
{
get { return _message; }
}
public PushData(FluorineContext context, ICollection subscribers, IMessage message)
{
_context = context;
_subscribers = subscribers;
_message = message;
}
}
#endif
#endregion PushData
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Testing;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.Server.HttpSys
{
public class RequestBodyTests
{
[ConditionalFact]
public async Task RequestBody_ReadSync_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
Assert.True(httpContext.Request.CanHaveBody());
byte[] input = new byte[100];
httpContext.Features.Get<IHttpBodyControlFeature>().AllowSynchronousIO = true;
int read = httpContext.Request.Body.Read(input, 0, input.Length);
httpContext.Response.ContentLength = read;
httpContext.Response.Body.Write(input, 0, read);
return Task.FromResult(0);
}))
{
string response = await SendRequestAsync(address, "Hello World");
Assert.Equal("Hello World", response);
}
}
[ConditionalFact]
public async Task RequestBody_ReadAsync_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
Assert.True(httpContext.Request.CanHaveBody());
byte[] input = new byte[100];
int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
httpContext.Response.ContentLength = read;
await httpContext.Response.Body.WriteAsync(input, 0, read);
}))
{
string response = await SendRequestAsync(address, "Hello World");
Assert.Equal("Hello World", response);
}
}
[ConditionalFact]
public async Task RequestBody_ReadBeginEnd_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
byte[] input = new byte[100];
int read = httpContext.Request.Body.EndRead(httpContext.Request.Body.BeginRead(input, 0, input.Length, null, null));
httpContext.Response.ContentLength = read;
httpContext.Response.Body.EndWrite(httpContext.Response.Body.BeginWrite(input, 0, read, null, null));
return Task.FromResult(0);
}))
{
string response = await SendRequestAsync(address, "Hello World");
Assert.Equal("Hello World", response);
}
}
[ConditionalFact]
public async Task RequestBody_InvalidBuffer_ArgumentException()
{
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Features.Get<IHttpBodyControlFeature>().AllowSynchronousIO = true;
byte[] input = new byte[100];
Assert.Throws<ArgumentNullException>("buffer", () => httpContext.Request.Body.Read(null, 0, 1));
Assert.Throws<ArgumentOutOfRangeException>("offset", () => httpContext.Request.Body.Read(input, -1, 1));
Assert.Throws<ArgumentOutOfRangeException>("offset", () => httpContext.Request.Body.Read(input, input.Length + 1, 1));
Assert.Throws<ArgumentOutOfRangeException>("size", () => httpContext.Request.Body.Read(input, 10, -1));
Assert.Throws<ArgumentOutOfRangeException>("size", () => httpContext.Request.Body.Read(input, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>("size", () => httpContext.Request.Body.Read(input, 1, input.Length));
Assert.Throws<ArgumentOutOfRangeException>("size", () => httpContext.Request.Body.Read(input, 0, input.Length + 1));
return Task.FromResult(0);
}))
{
string response = await SendRequestAsync(address, "Hello World");
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task RequestBody_ReadSyncPartialBody_Success()
{
StaggardContent content = new StaggardContent();
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
byte[] input = new byte[10];
httpContext.Features.Get<IHttpBodyControlFeature>().AllowSynchronousIO = true;
int read = httpContext.Request.Body.Read(input, 0, input.Length);
Assert.Equal(5, read);
content.Block.Release();
read = httpContext.Request.Body.Read(input, 0, input.Length);
Assert.Equal(5, read);
return Task.FromResult(0);
}))
{
string response = await SendRequestAsync(address, content);
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task RequestBody_ReadAsyncPartialBody_Success()
{
StaggardContent content = new StaggardContent();
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
byte[] input = new byte[10];
int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
Assert.Equal(5, read);
content.Block.Release();
read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
Assert.Equal(5, read);
}))
{
string response = await SendRequestAsync(address, content);
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task RequestBody_PostWithImidateBody_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
byte[] input = new byte[11];
int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
Assert.Equal(10, read);
read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
Assert.Equal(0, read);
httpContext.Response.ContentLength = 10;
await httpContext.Response.Body.WriteAsync(input, 0, 10);
}))
{
string response = await SendSocketRequestAsync(address);
string[] lines = response.Split('\r', '\n');
Assert.Equal(13, lines.Length);
Assert.Equal("HTTP/1.1 200 OK", lines[0]);
Assert.Equal("0123456789", lines[12]);
}
}
[ConditionalFact]
public async Task RequestBody_ChangeContentLength_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
var newContentLength = httpContext.Request.ContentLength + 1000;
httpContext.Request.ContentLength = newContentLength;
Assert.Equal(newContentLength, httpContext.Request.ContentLength);
var contentLengthHeadersCount = 0;
foreach (var header in httpContext.Request.Headers)
{
if (string.Equals(header.Key, "Content-Length", StringComparison.OrdinalIgnoreCase))
{
contentLengthHeadersCount++;
}
}
Assert.Equal(1, contentLengthHeadersCount);
byte[] input = new byte[100];
int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
httpContext.Response.ContentLength = read;
await httpContext.Response.Body.WriteAsync(input, 0, read);
}))
{
string response = await SendRequestAsync(address, "Hello World");
Assert.Equal("Hello World", response);
}
}
[ConditionalFact]
public async Task RequestBody_RemoveHeaderOnEmptyValueSet_Success()
{
var requestWasProcessed = false;
static void CheckHeadersCount(string headerName, int expectedCount, HttpRequest request)
{
var headersCount = 0;
foreach (var header in request.Headers)
{
if (string.Equals(header.Key, headerName, StringComparison.OrdinalIgnoreCase))
{
headersCount++;
}
}
Assert.Equal(expectedCount, headersCount);
}
using (Utilities.CreateHttpServer(out var address, httpContext =>
{
// play with standard header
httpContext.Request.Headers[HeaderNames.ContentLength] = "123";
CheckHeadersCount(HeaderNames.ContentLength, 1, httpContext.Request);
Assert.Equal(123,httpContext.Request.ContentLength);
httpContext.Request.Headers[HeaderNames.ContentLength] = "456";
CheckHeadersCount(HeaderNames.ContentLength, 1, httpContext.Request);
Assert.Equal(456,httpContext.Request.ContentLength);
httpContext.Request.Headers[HeaderNames.ContentLength] = "";
CheckHeadersCount(HeaderNames.ContentLength, 0, httpContext.Request);
Assert.Null(httpContext.Request.ContentLength);
Assert.Equal("", httpContext.Request.Headers[HeaderNames.ContentLength].ToString());
httpContext.Request.ContentLength = 789;
CheckHeadersCount(HeaderNames.ContentLength, 1, httpContext.Request);
Assert.Equal(789,httpContext.Request.ContentLength);
// play with custom header
httpContext.Request.Headers["Custom-Header"] = "foo";
CheckHeadersCount("Custom-Header", 1, httpContext.Request);
httpContext.Request.Headers["Custom-Header"] = "bar";
CheckHeadersCount("Custom-Header", 1, httpContext.Request);
httpContext.Request.Headers["Custom-Header"] = "";
CheckHeadersCount("Custom-Header", 0, httpContext.Request);
Assert.Equal("", httpContext.Request.Headers["Custom-Header"].ToString());
httpContext.Response.StatusCode = 200;
requestWasProcessed = true;
return Task.CompletedTask;
}))
{
await SendRequestAsync(address, "Hello World");
Assert.True(requestWasProcessed);
}
}
private Task<string> SendRequestAsync(string uri, string upload)
{
return SendRequestAsync(uri, new StringContent(upload));
}
private async Task<string> SendRequestAsync(string uri, HttpContent content)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
private async Task<string> SendSocketRequestAsync(string address)
{
// Connect with a socket
Uri uri = new Uri(address);
TcpClient client = new TcpClient();
try
{
await client.ConnectAsync(uri.Host, uri.Port);
NetworkStream stream = client.GetStream();
// Send an HTTP GET request
byte[] requestBytes = BuildPostRequest(uri);
await stream.WriteAsync(requestBytes, 0, requestBytes.Length);
StreamReader reader = new StreamReader(stream);
return await reader.ReadToEndAsync();
}
catch (Exception)
{
((IDisposable)client).Dispose();
throw;
}
}
private byte[] BuildPostRequest(Uri uri)
{
StringBuilder builder = new StringBuilder();
builder.Append("POST");
builder.Append(" ");
builder.Append(uri.PathAndQuery);
builder.Append(" HTTP/1.1");
builder.AppendLine();
builder.Append("Host: ");
builder.Append(uri.Host);
builder.Append(':');
builder.Append(uri.Port);
builder.AppendLine();
builder.AppendLine("Connection: close");
builder.AppendLine("Content-Length: 10");
builder.AppendLine();
builder.Append("0123456789");
return Encoding.ASCII.GetBytes(builder.ToString());
}
private class StaggardContent : HttpContent
{
public StaggardContent()
{
Block = new SemaphoreSlim(0, 1);
}
public SemaphoreSlim Block { get; private set; }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
await stream.WriteAsync(new byte[5], 0, 5);
await stream.FlushAsync();
Assert.True(await Block.WaitAsync(TimeSpan.FromSeconds(10)));
await stream.WriteAsync(new byte[5], 0, 5);
}
protected override bool TryComputeLength(out long length)
{
length = 10;
return true;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Store
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// FileSystemOperations operations.
/// </summary>
public partial interface IFileSystemOperations
{
/// <summary>
/// Appends to the specified file. This method supports multiple
/// concurrent appends to the file. NOTE: ConcurrentAppend and normal
/// (serial) Append CANNOT be used interchangeably; once a file has
/// been appended to using either of these append options, it can
/// only be appended to using that append option. ConcurrentAppend
/// DOES NOT guarantee order and can result in duplicated data
/// landing in the target file.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='filePath'>
/// The Data Lake Store path (starting with '/') of the file to which
/// to append using concurrent append.
/// </param>
/// <param name='streamContents'>
/// The file contents to include when appending to the file.
/// </param>
/// <param name='appendMode'>
/// Indicates the concurrent append call should create the file if it
/// doesn't exist or just open the existing file for append. Possible
/// values include: 'autocreate'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> ConcurrentAppendWithHttpMessagesAsync(string accountName, string filePath, System.IO.Stream streamContents, AppendModeType? appendMode = default(AppendModeType?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Sets or removes the expiration time on the specified file. This
/// operation can only be executed against files. Folders are not
/// supported.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='filePath'>
/// The Data Lake Store path (starting with '/') of the file on which
/// to set or remove the expiration time.
/// </param>
/// <param name='expiryOption'>
/// Indicates the type of expiration to use for the file: 1.
/// NeverExpire: ExpireTime is ignored. 2. RelativeToNow: ExpireTime
/// is an integer in milliseconds representing the expiration date
/// relative to when file expiration is updated. 3.
/// RelativeToCreationDate: ExpireTime is an integer in milliseconds
/// representing the expiration date relative to file creation. 4.
/// Absolute: ExpireTime is an integer in milliseconds, as a Unix
/// timestamp relative to 1/1/1970 00:00:00. Possible values include:
/// 'NeverExpire', 'RelativeToNow', 'RelativeToCreationDate',
/// 'Absolute'
/// </param>
/// <param name='expireTime'>
/// The time that the file will expire, corresponding to the
/// ExpiryOption that was set.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> SetFileExpiryWithHttpMessagesAsync(string accountName, string filePath, ExpiryOptionType expiryOption, long? expireTime = default(long?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Checks if the specified access is available at the given path.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='path'>
/// The Data Lake Store path (starting with '/') of the file or
/// directory for which to check access.
/// </param>
/// <param name='fsaction'>
/// File system operation read/write/execute in string form, matching
/// regex pattern '[rwx-]{3}'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> CheckAccessWithHttpMessagesAsync(string accountName, string path, string fsaction = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a directory.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='path'>
/// The Data Lake Store path (starting with '/') of the directory to
/// create.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// 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>
Task<AzureOperationResponse<FileOperationResult>> MkdirsWithHttpMessagesAsync(string accountName, string path, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Concatenates the list of source files into the destination file,
/// removing all source files upon success.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='destinationPath'>
/// The Data Lake Store path (starting with '/') of the destination
/// file resulting from the concatenation.
/// </param>
/// <param name='sources'>
/// A list of comma seperated Data Lake Store paths (starting with
/// '/') of the files to concatenate, in the order in which they
/// should be concatenated.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> ConcatWithHttpMessagesAsync(string accountName, string destinationPath, IList<string> sources, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Concatenates the list of source files into the destination file,
/// deleting all source files upon success. This method accepts more
/// source file paths than the Concat method. This method and the
/// parameters it accepts are subject to change for usability in an
/// upcoming version.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='msConcatDestinationPath'>
/// The Data Lake Store path (starting with '/') of the destination
/// file resulting from the concatenation.
/// </param>
/// <param name='streamContents'>
/// A list of Data Lake Store paths (starting with '/') of the source
/// files. Must be in the format: sources=<comma separated list>
/// </param>
/// <param name='deleteSourceDirectory'>
/// Indicates that as an optimization instead of deleting each
/// individual source stream, delete the source stream folder if all
/// streams are in the same folder instead. This results in a
/// substantial performance improvement when the only streams in the
/// folder are part of the concatenation operation. WARNING: This
/// includes the deletion of any other files that are not source
/// files. Only set this to true when source files are the only files
/// in the source directory.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> MsConcatWithHttpMessagesAsync(string accountName, string msConcatDestinationPath, System.IO.Stream streamContents, bool? deleteSourceDirectory = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the list of file status objects specified by the file path,
/// with optional pagination parameters
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='listFilePath'>
/// The Data Lake Store path (starting with '/') of the directory to
/// list.
/// </param>
/// <param name='listSize'>
/// Gets or sets the number of items to return. Optional.
/// </param>
/// <param name='listAfter'>
/// Gets or sets the item or lexographical index after which to begin
/// returning results. For example, a file list of 'a','b','d' and
/// listAfter='b' will return 'd', and a listAfter='c' will also
/// return 'd'. Optional.
/// </param>
/// <param name='listBefore'>
/// Gets or sets the item or lexographical index before which to begin
/// returning results. For example, a file list of 'a','b','d' and
/// listBefore='d' will return 'a','b', and a listBefore='c' will
/// also return 'a','b'. Optional.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// 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>
Task<AzureOperationResponse<FileStatusesResult>> ListFileStatusWithHttpMessagesAsync(string accountName, string listFilePath, int? listSize = default(int?), string listAfter = default(string), string listBefore = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the file content summary object specified by the file path.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='getContentSummaryFilePath'>
/// The Data Lake Store path (starting with '/') of the file for which
/// to retrieve the summary.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// 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>
Task<AzureOperationResponse<ContentSummaryResult>> GetContentSummaryWithHttpMessagesAsync(string accountName, string getContentSummaryFilePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the file status object specified by the file path.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='getFilePath'>
/// The Data Lake Store path (starting with '/') of the file or
/// directory for which to retrieve the status.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// 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>
Task<AzureOperationResponse<FileStatusResult>> GetFileStatusWithHttpMessagesAsync(string accountName, string getFilePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Appends to the specified file. This method does not support
/// multiple concurrent appends to the file. NOTE: Concurrent append
/// and normal (serial) append CANNOT be used interchangeably. Once a
/// file has been appended to using either append option, it can only
/// be appended to using that append option. Use the ConcurrentAppend
/// option if you would like support for concurrent appends.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='directFilePath'>
/// The Data Lake Store path (starting with '/') of the file to which
/// to append.
/// </param>
/// <param name='streamContents'>
/// The file contents to include when appending to the file.
/// </param>
/// <param name='offset'>
/// The optional offset in the stream to begin the append operation.
/// Default is to append at the end of the stream.
/// </param>
/// <param name='syncFlag'>
/// Optionally indicates what to do after completion of the append.
/// DATA indicates more data is coming so no sync takes place,
/// METADATA indicates a sync should be done to refresh metadata of
/// the file only. CLOSE indicates that both the stream and metadata
/// should be refreshed upon append completion. Possible values
/// include: 'DATA', 'METADATA', 'CLOSE'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> AppendWithHttpMessagesAsync(string accountName, string directFilePath, System.IO.Stream streamContents, long? offset = default(long?), SyncFlag? syncFlag = default(SyncFlag?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a file with optionally specified content.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='directFilePath'>
/// The Data Lake Store path (starting with '/') of the file to create.
/// </param>
/// <param name='streamContents'>
/// The file contents to include when creating the file. This
/// parameter is optional, resulting in an empty file if not
/// specified.
/// </param>
/// <param name='overwrite'>
/// The indication of if the file should be overwritten.
/// </param>
/// <param name='syncFlag'>
/// Optionally indicates what to do after completion of the append.
/// DATA indicates more data is coming so no sync takes place,
/// METADATA indicates a sync should be done to refresh metadata of
/// the file only. CLOSE indicates that both the stream and metadata
/// should be refreshed upon append completion. Possible values
/// include: 'DATA', 'METADATA', 'CLOSE'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> CreateWithHttpMessagesAsync(string accountName, string directFilePath, System.IO.Stream streamContents = default(System.IO.Stream), bool? overwrite = default(bool?), SyncFlag? syncFlag = default(SyncFlag?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Opens and reads from the specified file.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='directFilePath'>
/// The Data Lake Store path (starting with '/') of the file to open.
/// </param>
/// <param name='length'>
/// The number of bytes that the server will attempt to retrieve. It
/// will retrieve <= length bytes.
/// </param>
/// <param name='offset'>
/// The byte offset to start reading data from.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// 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>
Task<AzureOperationResponse<System.IO.Stream>> OpenWithHttpMessagesAsync(string accountName, string directFilePath, long? length = default(long?), long? offset = default(long?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Sets the Access Control List (ACL) for a file or folder.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='setAclFilePath'>
/// The Data Lake Store path (starting with '/') of the file or
/// directory on which to set the ACL.
/// </param>
/// <param name='aclspec'>
/// The ACL spec included in ACL creation operations in the format
/// '[default:]user|group|other::r|-w|-x|-'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> SetAclWithHttpMessagesAsync(string accountName, string setAclFilePath, string aclspec, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Modifies existing Access Control List (ACL) entries on a file or
/// folder.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='modifyAclFilePath'>
/// The Data Lake Store path (starting with '/') of the file or
/// directory with the ACL being modified.
/// </param>
/// <param name='aclspec'>
/// The ACL specification included in ACL modification operations in
/// the format '[default:]user|group|other::r|-w|-x|-'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> ModifyAclEntriesWithHttpMessagesAsync(string accountName, string modifyAclFilePath, string aclspec, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Removes existing Access Control List (ACL) entries for a file or
/// folder.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='removeAclFilePath'>
/// The Data Lake Store path (starting with '/') of the file or
/// directory with the ACL being removed.
/// </param>
/// <param name='aclspec'>
/// The ACL spec included in ACL removal operations in the format
/// '[default:]user|group|other'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> RemoveAclEntriesWithHttpMessagesAsync(string accountName, string removeAclFilePath, string aclspec, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Removes the existing Default Access Control List (ACL) of the
/// specified directory.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='defaultAclFilePath'>
/// The Data Lake Store path (starting with '/') of the directory with
/// the default ACL being removed.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> RemoveDefaultAclWithHttpMessagesAsync(string accountName, string defaultAclFilePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Removes the existing Access Control List (ACL) of the specified
/// file or directory.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='aclFilePath'>
/// The Data Lake Store path (starting with '/') of the file or
/// directory with the ACL being removed.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> RemoveAclWithHttpMessagesAsync(string accountName, string aclFilePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets Access Control List (ACL) entries for the specified file or
/// directory.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='aclFilePath'>
/// The Data Lake Store path (starting with '/') of the file or
/// directory for which to get the ACL.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// 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>
Task<AzureOperationResponse<AclStatusResult>> GetAclStatusWithHttpMessagesAsync(string accountName, string aclFilePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the requested file or directory, optionally recursively.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='filePath'>
/// The Data Lake Store path (starting with '/') of the file or
/// directory to delete.
/// </param>
/// <param name='recursive'>
/// The optional switch indicating if the delete should be recursive
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// 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>
Task<AzureOperationResponse<FileOperationResult>> DeleteWithHttpMessagesAsync(string accountName, string filePath, bool? recursive = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Rename a file or directory.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='renameFilePath'>
/// The Data Lake Store path (starting with '/') of the file or
/// directory to move/rename.
/// </param>
/// <param name='destination'>
/// The path to move/rename the file or folder to
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// 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>
Task<AzureOperationResponse<FileOperationResult>> RenameWithHttpMessagesAsync(string accountName, string renameFilePath, string destination, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Sets the owner of a file or directory.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='setOwnerFilePath'>
/// The Data Lake Store path (starting with '/') of the file or
/// directory for which to set the owner.
/// </param>
/// <param name='owner'>
/// The AAD Object ID of the user owner of the file or directory. If
/// empty, the property will remain unchanged.
/// </param>
/// <param name='group'>
/// The AAD Object ID of the group owner of the file or directory. If
/// empty, the property will remain unchanged.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> SetOwnerWithHttpMessagesAsync(string accountName, string setOwnerFilePath, string owner = default(string), string group = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Sets the permission of the file or folder.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Store account to execute filesystem operations
/// on.
/// </param>
/// <param name='setPermissionFilePath'>
/// The Data Lake Store path (starting with '/') of the file or
/// directory for which to set the permission.
/// </param>
/// <param name='permission'>
/// A string representation of the permission (i.e 'rwx'). If empty,
/// this property remains unchanged.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AdlsErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> SetPermissionWithHttpMessagesAsync(string accountName, string setPermissionFilePath, string permission = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace SocketHttpListener.Net
{
class RequestStream : Stream
{
byte[] buffer;
int offset;
int length;
long remaining_body;
bool disposed;
Stream stream;
internal RequestStream(Stream stream, byte[] buffer, int offset, int length)
: this(stream, buffer, offset, length, -1)
{
}
internal RequestStream(Stream stream, byte[] buffer, int offset, int length, long contentlength)
{
this.stream = stream;
this.buffer = buffer;
this.offset = offset;
this.length = length;
this.remaining_body = contentlength;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override void Close()
{
disposed = true;
}
public override void Flush()
{
}
// Returns 0 if we can keep reading from the base stream,
// > 0 if we read something from the buffer.
// -1 if we had a content length set and we finished reading that many bytes.
int FillFromBuffer(byte[] buffer, int off, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (off < 0)
throw new ArgumentOutOfRangeException("offset", "< 0");
if (count < 0)
throw new ArgumentOutOfRangeException("count", "< 0");
int len = buffer.Length;
if (off > len)
throw new ArgumentException("destination offset is beyond array size");
if (off > len - count)
throw new ArgumentException("Reading would overrun buffer");
if (this.remaining_body == 0)
return -1;
if (this.length == 0)
return 0;
int size = Math.Min(this.length, count);
if (this.remaining_body > 0)
size = (int)Math.Min(size, this.remaining_body);
if (this.offset > this.buffer.Length - size)
{
size = Math.Min(size, this.buffer.Length - this.offset);
}
if (size == 0)
return 0;
Buffer.BlockCopy(this.buffer, this.offset, buffer, off, size);
this.offset += size;
this.length -= size;
if (this.remaining_body > 0)
remaining_body -= size;
return size;
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
if (disposed)
throw new ObjectDisposedException(typeof(RequestStream).ToString());
// Call FillFromBuffer to check for buffer boundaries even when remaining_body is 0
int nread = FillFromBuffer(buffer, offset, count);
if (nread == -1)
{ // No more bytes available (Content-Length)
return 0;
}
else if (nread > 0)
{
return nread;
}
nread = stream.Read(buffer, offset, count);
if (nread > 0 && remaining_body > 0)
remaining_body -= nread;
return nread;
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count,
AsyncCallback cback, object state)
{
if (disposed)
throw new ObjectDisposedException(typeof(RequestStream).ToString());
int nread = FillFromBuffer(buffer, offset, count);
if (nread > 0 || nread == -1)
{
HttpStreamAsyncResult ares = new HttpStreamAsyncResult();
ares.Buffer = buffer;
ares.Offset = offset;
ares.Count = count;
ares.Callback = cback;
ares.State = state;
ares.SynchRead = Math.Max(0, nread);
ares.Complete();
return ares;
}
// Avoid reading past the end of the request to allow
// for HTTP pipelining
if (remaining_body >= 0 && count > remaining_body)
count = (int)Math.Min(Int32.MaxValue, remaining_body);
return stream.BeginRead(buffer, offset, count, cback, state);
}
public override int EndRead(IAsyncResult ares)
{
if (disposed)
throw new ObjectDisposedException(typeof(RequestStream).ToString());
if (ares == null)
throw new ArgumentNullException("async_result");
if (ares is HttpStreamAsyncResult)
{
HttpStreamAsyncResult r = (HttpStreamAsyncResult)ares;
if (!ares.IsCompleted)
ares.AsyncWaitHandle.WaitOne();
return r.SynchRead;
}
// Close on exception?
int nread = stream.EndRead(ares);
if (remaining_body > 0 && nread > 0)
remaining_body -= nread;
return nread;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count,
AsyncCallback cback, object state)
{
throw new NotSupportedException();
}
public override void EndWrite(IAsyncResult async_result)
{
throw new NotSupportedException();
}
}
}
| |
//
// MemoryBlockStream.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013 Jeffrey Stedfast
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections.Generic;
namespace MimeKit.IO
{
/// <summary>
/// An efficient memory stream implementation that sacrifices the ability to
/// get access to the internal byte buffer in order to drastically improve
/// performance.
/// </summary>
public class MemoryBlockStream : Stream
{
const long MaxCapacity = int.MaxValue * BlockSize;
const long BlockSize = 2048;
readonly List<byte[]> blocks = new List<byte[]> ();
long position, length;
bool disposed;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.IO.MemoryBlockStream"/> class.
/// </summary>
public MemoryBlockStream ()
{
blocks.Add (new byte[BlockSize]);
}
/// <summary>
/// Copies the memory stream into a byte array.
/// </summary>
/// <returns>The array.</returns>
public byte[] ToArray ()
{
var array = new byte[length];
int need = (int) length;
int arrayIndex = 0;
int nread = 0;
int block = 0;
while (nread < length) {
int n = Math.Min ((int) BlockSize, need);
Buffer.BlockCopy (blocks[block], 0, array, arrayIndex, n);
arrayIndex += n;
nread += n;
need -= n;
block++;
}
return array;
}
void CheckDisposed ()
{
if (disposed)
throw new ObjectDisposedException ("stream");
}
#region implemented abstract members of Stream
/// <summary>
/// Checks whether or not the stream supports reading.
/// </summary>
/// <value><c>true</c> if the stream supports reading; otherwise, <c>false</c>.</value>
public override bool CanRead {
get { return true; }
}
/// <summary>
/// Checks whether or not the stream supports writing.
/// </summary>
/// <value>
/// <c>true</c> if the stream supports writing; otherwise, <c>false</c>.
/// </value>
public override bool CanWrite {
get { return true; }
}
/// <summary>
/// Checks whether or not the stream supports seeking.
/// </summary>
/// <value><c>true</c> if the stream supports seeking; otherwise, <c>false</c>.</value>
public override bool CanSeek {
get { return true; }
}
/// <summary>
/// Checks whether or not reading and writing to the stream can timeout.
/// </summary>
/// <value><c>true</c> if reading and writing to the stream can timeout; otherwise, <c>false</c>.</value>
public override bool CanTimeout {
get { return false; }
}
/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
/// <returns>A long value representing the length of the stream in bytes.</returns>
/// <value>The length of the stream.</value>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
public override long Length {
get {
CheckDisposed ();
return length;
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// </summary>
/// <returns>The current position within the stream.</returns>
/// <value>The position of the stream.</value>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support seeking.
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
public override long Position {
get { return position; }
set { Seek (value, SeekOrigin.Begin); }
}
void ValidateArguments (byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException ("offset");
if (count < 0 || offset + count > buffer.Length)
throw new ArgumentOutOfRangeException ("count");
}
/// <summary>
/// Reads a sequence of bytes from the stream and advances the position
/// within the stream by the number of bytes read.
/// </summary>
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many
/// bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
/// <param name="buffer">The buffer to read data into.</param>
/// <param name="offset">The offset into the buffer to start reading data.</param>
/// <param name="count">The number of bytes to read.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
/// <para>-or-</para>
/// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting
/// at the specified <paramref name="offset"/>.</para>
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public override int Read (byte[] buffer, int offset, int count)
{
CheckDisposed ();
ValidateArguments (buffer, offset, count);
if (position == MaxCapacity)
return 0;
int max = Math.Min ((int) (length - position), count);
int startIndex = (int) (position % BlockSize);
int block = (int) (position / BlockSize);
int nread = 0;
while (nread < max && block < blocks.Count) {
int n = Math.Min ((int) BlockSize - startIndex, max - nread);
Buffer.BlockCopy (blocks[block], startIndex, buffer, offset + nread, n);
startIndex = 0;
nread += n;
block++;
}
position += nread;
return nread;
}
/// <summary>
/// Writes a sequence of bytes to the stream and advances the current
/// position within this stream by the number of bytes written.
/// </summary>
/// <param name='buffer'>The buffer to write.</param>
/// <param name='offset'>The offset of the first byte to write.</param>
/// <param name='count'>The number of bytes to write.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
/// <para>-or-</para>
/// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting
/// at the specified <paramref name="offset"/>.</para>
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support writing.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public override void Write (byte[] buffer, int offset, int count)
{
CheckDisposed ();
ValidateArguments (buffer, offset, count);
if (position + count >= MaxCapacity)
throw new IOException (string.Format ("Cannot exceed {0} bytes", MaxCapacity));
int startIndex = (int) (position % BlockSize);
long capacity = blocks.Count * BlockSize;
int block = (int) (position / BlockSize);
int nwritten = 0;
while (capacity < position + count) {
blocks.Add (new byte[BlockSize]);
capacity += BlockSize;
}
while (nwritten < count) {
int n = Math.Min ((int) BlockSize - startIndex, count - nwritten);
Buffer.BlockCopy (buffer, offset + nwritten, blocks[block], startIndex, n);
startIndex = 0;
nwritten += n;
block++;
}
position += nwritten;
length = Math.Max (length, position);
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <returns>The new position within the stream.</returns>
/// <param name="offset">The offset into the stream relative to the <paramref name="origin"/>.</param>
/// <param name="origin">The origin to seek from.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="origin"/> is not a valid <see cref="System.IO.SeekOrigin"/>.
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public override long Seek (long offset, SeekOrigin origin)
{
long real;
CheckDisposed ();
switch (origin) {
case SeekOrigin.Begin:
real = offset;
break;
case SeekOrigin.Current:
real = position + offset;
break;
case SeekOrigin.End:
real = length + offset;
break;
default:
throw new ArgumentOutOfRangeException ("origin", "Invalid SeekOrigin specified");
}
// sanity check the resultant offset
if (real < 0)
throw new IOException ("Cannot seek to a position before the beginning of the stream");
if (real > MaxCapacity)
throw new IOException (string.Format ("Cannot exceed {0} bytes", MaxCapacity));
// short-cut if we are seeking to our current position
if (real == position)
return position;
if (real > length)
throw new IOException ("Cannot seek beyond the end of the stream");
position = real;
return position;
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written
/// to the underlying device.
/// </summary>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
public override void Flush ()
{
CheckDisposed ();
// nothing to do...
}
/// <summary>
/// Sets the length of the stream.
/// </summary>
/// <param name='value'>The desired length of the stream in bytes.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="value"/> is out of range.
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
public override void SetLength (long value)
{
CheckDisposed ();
if (value < 0 || value > MaxCapacity)
throw new ArgumentOutOfRangeException ("value");
long capacity = blocks.Count * BlockSize;
if (value > capacity) {
do {
blocks.Add (new byte[BlockSize]);
capacity += BlockSize;
} while (capacity < value);
} else if (value < length) {
// shed any blocks that are no longer needed
while (capacity - value > BlockSize) {
blocks.RemoveAt (blocks.Count - 1);
capacity -= BlockSize;
}
// reset the range of bytes between the new length and the old length to 0
int count = (int) (Math.Min (length, capacity) - value);
int startIndex = (int) (value % BlockSize);
int block = (int) (value / BlockSize);
Array.Clear (blocks[block], startIndex, count);
}
position = Math.Min (position, value);
length = value;
}
#endregion
/// <summary>
/// Dispose the specified disposing.
/// </summary>
/// <param name="disposing">If set to <c>true</c> disposing.</param>
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
disposed = true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using Csla;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// ProductTypeList (read only list).<br/>
/// This is a generated base class of <see cref="ProductTypeList"/> business object.
/// This class is a root collection.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="ProductTypeInfo"/> objects.
/// No cache. Updated by ProductTypeDynaItem
/// </remarks>
[Serializable]
#if WINFORMS
public partial class ProductTypeList : ReadOnlyBindingListBase<ProductTypeList, ProductTypeInfo>
#else
public partial class ProductTypeList : ReadOnlyListBase<ProductTypeList, ProductTypeInfo>
#endif
{
#region Event handler properties
[NotUndoable]
private static bool _singleInstanceSavedHandler = true;
/// <summary>
/// Gets or sets a value indicating whether only a single instance should handle the Saved event.
/// </summary>
/// <value>
/// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>.
/// </value>
public static bool SingleInstanceSavedHandler
{
get { return _singleInstanceSavedHandler; }
set { _singleInstanceSavedHandler = value; }
}
#endregion
#region Collection Business Methods
/// <summary>
/// Determines whether a <see cref="ProductTypeInfo"/> item is in the collection.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to search for.</param>
/// <returns><c>true</c> if the ProductTypeInfo is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int productTypeId)
{
foreach (var productTypeInfo in this)
{
if (productTypeInfo.ProductTypeId == productTypeId)
{
return true;
}
}
return false;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="ProductTypeList"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="ProductTypeList"/> collection.</returns>
public static ProductTypeList GetProductTypeList()
{
return DataPortal.Fetch<ProductTypeList>();
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="ProductTypeList"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetProductTypeList(EventHandler<DataPortalResult<ProductTypeList>> callback)
{
DataPortal.BeginFetch<ProductTypeList>(callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeList"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductTypeList()
{
// Use factory methods and do not use direct creation.
ProductTypeDynaItemSaved.Register(this);
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = false;
AllowEdit = false;
AllowRemove = false;
RaiseListChangedEvents = rlce;
}
#endregion
#region Saved Event Handler
/// <summary>
/// Handle Saved events of <see cref="ProductTypeDynaItem"/> to update the list of <see cref="ProductTypeInfo"/> objects.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
internal void ProductTypeDynaItemSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
var obj = (ProductTypeDynaItem)e.NewObject;
if (((ProductTypeDynaItem)sender).IsNew)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
Add(ProductTypeInfo.LoadInfo(obj));
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
else if (((ProductTypeDynaItem)sender).IsDeleted)
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.ProductTypeId == obj.ProductTypeId)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
this.RemoveItem(index);
RaiseListChangedEvents = rlce;
IsReadOnly = true;
break;
}
}
}
else
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.ProductTypeId == obj.ProductTypeId)
{
child.UpdatePropertiesOnSaved(obj);
#if !WINFORMS
var notifyCollectionChangedEventArgs =
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index);
OnCollectionChanged(notifyCollectionChangedEventArgs);
#else
var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index);
OnListChanged(listChangedEventArgs);
#endif
break;
}
}
}
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="ProductTypeList"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
var args = new DataPortalHookArgs();
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<IProductTypeListDal>();
var data = dal.Fetch();
Fetch(data);
}
OnFetchPost(args);
}
/// <summary>
/// Loads all <see cref="ProductTypeList"/> collection items from the given list of ProductTypeInfoDto.
/// </summary>
/// <param name="data">The list of <see cref="ProductTypeInfoDto"/>.</param>
private void Fetch(List<ProductTypeInfoDto> data)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
foreach (var dto in data)
{
Add(DataPortal.FetchChild<ProductTypeInfo>(dto));
}
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
#endregion
#region DataPortal Hooks
/// <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);
#endregion
#region ProductTypeDynaItemSaved nested class
// TODO: edit "ProductTypeList.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: ProductTypeDynaItemSaved.Register(this);
/// <summary>
/// Nested class to manage the Saved events of <see cref="ProductTypeDynaItem"/>
/// to update the list of <see cref="ProductTypeInfo"/> objects.
/// </summary>
private static class ProductTypeDynaItemSaved
{
private static List<WeakReference> _references;
private static bool Found(object obj)
{
return _references.Any(reference => Equals(reference.Target, obj));
}
/// <summary>
/// Registers a ProductTypeList instance to handle Saved events.
/// to update the list of <see cref="ProductTypeInfo"/> objects.
/// </summary>
/// <param name="obj">The ProductTypeList instance.</param>
public static void Register(ProductTypeList obj)
{
var mustRegister = _references == null;
if (mustRegister)
_references = new List<WeakReference>();
if (ProductTypeList.SingleInstanceSavedHandler)
_references.Clear();
if (!Found(obj))
_references.Add(new WeakReference(obj));
if (mustRegister)
ProductTypeDynaItem.ProductTypeDynaItemSaved += ProductTypeDynaItemSavedHandler;
}
/// <summary>
/// Handles Saved events of <see cref="ProductTypeDynaItem"/>.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
public static void ProductTypeDynaItemSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
foreach (var reference in _references)
{
if (reference.IsAlive)
((ProductTypeList) reference.Target).ProductTypeDynaItemSavedHandler(sender, e);
}
}
/// <summary>
/// Removes event handling and clears all registered ProductTypeList instances.
/// </summary>
public static void Unregister()
{
ProductTypeDynaItem.ProductTypeDynaItemSaved -= ProductTypeDynaItemSavedHandler;
_references = null;
}
}
#endregion
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace Moscrif.IDE.Option
{
public partial class TextEditorWidget
{
private global::Gtk.Table table1;
private global::Gtk.CheckButton chbAgressivelyTriggerCL;
private global::Gtk.CheckButton chbEnableAnimations;
private global::Gtk.CheckButton chbShowEolMarker;
private global::Gtk.CheckButton chbShowLineNumber;
private global::Gtk.CheckButton chbShowRuler;
private global::Gtk.CheckButton chbShowSpaces;
private global::Gtk.CheckButton chbShowTabs;
private global::Gtk.CheckButton chbTabsToSpace;
private global::Gtk.FontButton fontbutton1;
private global::Gtk.Label label1;
private global::Gtk.Label label2;
private global::Gtk.Label label3;
private global::Gtk.SpinButton spRulerColumn;
private global::Gtk.SpinButton spTabSpace;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget Moscrif.IDE.Option.TextEditorWidget
global::Stetic.BinContainer.Attach (this);
this.Name = "Moscrif.IDE.Option.TextEditorWidget";
// Container child Moscrif.IDE.Option.TextEditorWidget.Gtk.Container+ContainerChild
this.table1 = new global::Gtk.Table (((uint)(9)), ((uint)(3)), false);
this.table1.Name = "table1";
this.table1.RowSpacing = ((uint)(6));
this.table1.ColumnSpacing = ((uint)(6));
// Container child table1.Gtk.Table+TableChild
this.chbAgressivelyTriggerCL = new global::Gtk.CheckButton ();
this.chbAgressivelyTriggerCL.CanFocus = true;
this.chbAgressivelyTriggerCL.Name = "chbAgressivelyTriggerCL";
this.chbAgressivelyTriggerCL.Label = global::Mono.Unix.Catalog.GetString ("Aggressively trigger code completion list");
this.chbAgressivelyTriggerCL.DrawIndicator = true;
this.chbAgressivelyTriggerCL.UseUnderline = true;
this.table1.Add (this.chbAgressivelyTriggerCL);
global::Gtk.Table.TableChild w1 = ((global::Gtk.Table.TableChild)(this.table1 [this.chbAgressivelyTriggerCL]));
w1.LeftAttach = ((uint)(1));
w1.RightAttach = ((uint)(2));
w1.XOptions = ((global::Gtk.AttachOptions)(4));
w1.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.chbEnableAnimations = new global::Gtk.CheckButton ();
this.chbEnableAnimations.CanFocus = true;
this.chbEnableAnimations.Name = "chbEnableAnimations";
this.chbEnableAnimations.Label = global::Mono.Unix.Catalog.GetString ("Enable Animations");
this.chbEnableAnimations.DrawIndicator = true;
this.chbEnableAnimations.UseUnderline = true;
this.table1.Add (this.chbEnableAnimations);
global::Gtk.Table.TableChild w2 = ((global::Gtk.Table.TableChild)(this.table1 [this.chbEnableAnimations]));
w2.TopAttach = ((uint)(5));
w2.BottomAttach = ((uint)(6));
w2.LeftAttach = ((uint)(1));
w2.RightAttach = ((uint)(2));
w2.XOptions = ((global::Gtk.AttachOptions)(4));
w2.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.chbShowEolMarker = new global::Gtk.CheckButton ();
this.chbShowEolMarker.CanFocus = true;
this.chbShowEolMarker.Name = "chbShowEolMarker";
this.chbShowEolMarker.Label = global::Mono.Unix.Catalog.GetString ("Show EOL Marker");
this.chbShowEolMarker.DrawIndicator = true;
this.chbShowEolMarker.UseUnderline = true;
this.table1.Add (this.chbShowEolMarker);
global::Gtk.Table.TableChild w3 = ((global::Gtk.Table.TableChild)(this.table1 [this.chbShowEolMarker]));
w3.TopAttach = ((uint)(3));
w3.BottomAttach = ((uint)(4));
w3.LeftAttach = ((uint)(2));
w3.RightAttach = ((uint)(3));
w3.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.chbShowLineNumber = new global::Gtk.CheckButton ();
this.chbShowLineNumber.CanFocus = true;
this.chbShowLineNumber.Name = "chbShowLineNumber";
this.chbShowLineNumber.Label = global::Mono.Unix.Catalog.GetString ("Show Line Number");
this.chbShowLineNumber.DrawIndicator = true;
this.chbShowLineNumber.UseUnderline = true;
this.table1.Add (this.chbShowLineNumber);
global::Gtk.Table.TableChild w4 = ((global::Gtk.Table.TableChild)(this.table1 [this.chbShowLineNumber]));
w4.TopAttach = ((uint)(4));
w4.BottomAttach = ((uint)(5));
w4.LeftAttach = ((uint)(1));
w4.RightAttach = ((uint)(2));
w4.XOptions = ((global::Gtk.AttachOptions)(4));
w4.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.chbShowRuler = new global::Gtk.CheckButton ();
this.chbShowRuler.CanFocus = true;
this.chbShowRuler.Name = "chbShowRuler";
this.chbShowRuler.Label = global::Mono.Unix.Catalog.GetString ("Show Ruler");
this.chbShowRuler.DrawIndicator = true;
this.chbShowRuler.UseUnderline = true;
this.table1.Add (this.chbShowRuler);
global::Gtk.Table.TableChild w5 = ((global::Gtk.Table.TableChild)(this.table1 [this.chbShowRuler]));
w5.TopAttach = ((uint)(6));
w5.BottomAttach = ((uint)(7));
w5.LeftAttach = ((uint)(1));
w5.RightAttach = ((uint)(2));
w5.XOptions = ((global::Gtk.AttachOptions)(4));
w5.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.chbShowSpaces = new global::Gtk.CheckButton ();
this.chbShowSpaces.CanFocus = true;
this.chbShowSpaces.Name = "chbShowSpaces";
this.chbShowSpaces.Label = global::Mono.Unix.Catalog.GetString ("Show Spaces");
this.chbShowSpaces.DrawIndicator = true;
this.chbShowSpaces.UseUnderline = true;
this.table1.Add (this.chbShowSpaces);
global::Gtk.Table.TableChild w6 = ((global::Gtk.Table.TableChild)(this.table1 [this.chbShowSpaces]));
w6.TopAttach = ((uint)(5));
w6.BottomAttach = ((uint)(6));
w6.LeftAttach = ((uint)(2));
w6.RightAttach = ((uint)(3));
w6.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.chbShowTabs = new global::Gtk.CheckButton ();
this.chbShowTabs.CanFocus = true;
this.chbShowTabs.Name = "chbShowTabs";
this.chbShowTabs.Label = global::Mono.Unix.Catalog.GetString ("Show Tabs");
this.chbShowTabs.DrawIndicator = true;
this.chbShowTabs.UseUnderline = true;
this.table1.Add (this.chbShowTabs);
global::Gtk.Table.TableChild w7 = ((global::Gtk.Table.TableChild)(this.table1 [this.chbShowTabs]));
w7.TopAttach = ((uint)(4));
w7.BottomAttach = ((uint)(5));
w7.LeftAttach = ((uint)(2));
w7.RightAttach = ((uint)(3));
w7.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.chbTabsToSpace = new global::Gtk.CheckButton ();
this.chbTabsToSpace.CanFocus = true;
this.chbTabsToSpace.Name = "chbTabsToSpace";
this.chbTabsToSpace.Label = global::Mono.Unix.Catalog.GetString ("Convert tabs to spaces");
this.chbTabsToSpace.DrawIndicator = true;
this.chbTabsToSpace.UseUnderline = true;
this.table1.Add (this.chbTabsToSpace);
global::Gtk.Table.TableChild w8 = ((global::Gtk.Table.TableChild)(this.table1 [this.chbTabsToSpace]));
w8.TopAttach = ((uint)(3));
w8.BottomAttach = ((uint)(4));
w8.LeftAttach = ((uint)(1));
w8.RightAttach = ((uint)(2));
w8.XOptions = ((global::Gtk.AttachOptions)(4));
w8.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.fontbutton1 = new global::Gtk.FontButton ();
this.fontbutton1.CanFocus = true;
this.fontbutton1.Name = "fontbutton1";
this.fontbutton1.FontName = "Monospace 10";
this.fontbutton1.ShowStyle = false;
this.fontbutton1.UseFont = true;
this.fontbutton1.UseSize = true;
this.table1.Add (this.fontbutton1);
global::Gtk.Table.TableChild w9 = ((global::Gtk.Table.TableChild)(this.table1 [this.fontbutton1]));
w9.TopAttach = ((uint)(1));
w9.BottomAttach = ((uint)(2));
w9.LeftAttach = ((uint)(1));
w9.RightAttach = ((uint)(2));
w9.XOptions = ((global::Gtk.AttachOptions)(4));
w9.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.label1 = new global::Gtk.Label ();
this.label1.Name = "label1";
this.label1.Xalign = 1F;
this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("Font :");
this.table1.Add (this.label1);
global::Gtk.Table.TableChild w10 = ((global::Gtk.Table.TableChild)(this.table1 [this.label1]));
w10.TopAttach = ((uint)(1));
w10.BottomAttach = ((uint)(2));
w10.XOptions = ((global::Gtk.AttachOptions)(4));
w10.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.label2 = new global::Gtk.Label ();
this.label2.Name = "label2";
this.label2.Xalign = 1F;
this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("Tab Size :");
this.table1.Add (this.label2);
global::Gtk.Table.TableChild w11 = ((global::Gtk.Table.TableChild)(this.table1 [this.label2]));
w11.TopAttach = ((uint)(2));
w11.BottomAttach = ((uint)(3));
w11.XOptions = ((global::Gtk.AttachOptions)(4));
w11.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.label3 = new global::Gtk.Label ();
this.label3.Name = "label3";
this.label3.Xalign = 1F;
this.label3.LabelProp = global::Mono.Unix.Catalog.GetString ("Ruler column");
this.table1.Add (this.label3);
global::Gtk.Table.TableChild w12 = ((global::Gtk.Table.TableChild)(this.table1 [this.label3]));
w12.TopAttach = ((uint)(7));
w12.BottomAttach = ((uint)(8));
w12.XOptions = ((global::Gtk.AttachOptions)(4));
w12.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.spRulerColumn = new global::Gtk.SpinButton (0, 100, 1);
this.spRulerColumn.CanFocus = true;
this.spRulerColumn.Name = "spRulerColumn";
this.spRulerColumn.Adjustment.PageIncrement = 1;
this.spRulerColumn.ClimbRate = 1;
this.spRulerColumn.Numeric = true;
this.table1.Add (this.spRulerColumn);
global::Gtk.Table.TableChild w13 = ((global::Gtk.Table.TableChild)(this.table1 [this.spRulerColumn]));
w13.TopAttach = ((uint)(7));
w13.BottomAttach = ((uint)(8));
w13.LeftAttach = ((uint)(1));
w13.RightAttach = ((uint)(2));
w13.XOptions = ((global::Gtk.AttachOptions)(4));
w13.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.spTabSpace = new global::Gtk.SpinButton (0, 20, 1);
this.spTabSpace.CanFocus = true;
this.spTabSpace.Name = "spTabSpace";
this.spTabSpace.Adjustment.PageIncrement = 1;
this.spTabSpace.ClimbRate = 1;
this.spTabSpace.Numeric = true;
this.table1.Add (this.spTabSpace);
global::Gtk.Table.TableChild w14 = ((global::Gtk.Table.TableChild)(this.table1 [this.spTabSpace]));
w14.TopAttach = ((uint)(2));
w14.BottomAttach = ((uint)(3));
w14.LeftAttach = ((uint)(1));
w14.RightAttach = ((uint)(2));
w14.XOptions = ((global::Gtk.AttachOptions)(4));
w14.YOptions = ((global::Gtk.AttachOptions)(4));
this.Add (this.table1);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.Hide ();
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Conditions
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
using NLog.Common;
using NLog.Internal;
/// <summary>
/// Condition method invocation expression (represented by <b>method(p1,p2,p3)</b> syntax).
/// </summary>
internal sealed class ConditionMethodExpression : ConditionExpression
{
private readonly string _conditionMethodName;
private readonly bool _acceptsLogEvent;
private readonly ConditionExpression[] _methodParameters;
private readonly ReflectionHelpers.LateBoundMethod _lateBoundMethod;
private readonly object[] _lateBoundMethodDefaultParameters;
/// <summary>
/// Initializes a new instance of the <see cref="ConditionMethodExpression" /> class.
/// </summary>
/// <param name="conditionMethodName">Name of the condition method.</param>
/// <param name="methodInfo"><see cref="MethodInfo"/> of the condition method.</param>
/// <param name="lateBoundMethod">Precompiled delegate of the condition method.</param>
/// <param name="methodParameters">The method parameters.</param>
public ConditionMethodExpression(string conditionMethodName, MethodInfo methodInfo, ReflectionHelpers.LateBoundMethod lateBoundMethod, IEnumerable<ConditionExpression> methodParameters)
{
MethodInfo = methodInfo;
_lateBoundMethod = lateBoundMethod;
_conditionMethodName = conditionMethodName;
_methodParameters = new List<ConditionExpression>(methodParameters).ToArray();
ParameterInfo[] formalParameters = MethodInfo.GetParameters();
if (formalParameters.Length > 0 && formalParameters[0].ParameterType == typeof(LogEventInfo))
{
_acceptsLogEvent = true;
}
_lateBoundMethodDefaultParameters = CreateMethodDefaultParameters(formalParameters, _methodParameters, _acceptsLogEvent ? 1 : 0);
int actualParameterCount = _methodParameters.Length;
if (_acceptsLogEvent)
{
actualParameterCount++;
}
// Count the number of required and optional parameters
CountParmameters(formalParameters, out var requiredParametersCount, out var optionalParametersCount);
if ( !( ( actualParameterCount >= requiredParametersCount ) && ( actualParameterCount <= formalParameters.Length ) ) )
{
string message;
if ( optionalParametersCount > 0 )
{
message = string.Format(
CultureInfo.InvariantCulture,
"Condition method '{0}' requires between {1} and {2} parameters, but passed {3}.",
conditionMethodName,
requiredParametersCount,
formalParameters.Length,
actualParameterCount );
}
else
{
message = string.Format(
CultureInfo.InvariantCulture,
"Condition method '{0}' requires {1} parameters, but passed {2}.",
conditionMethodName,
requiredParametersCount,
actualParameterCount );
}
InternalLogger.Error(message);
throw new ConditionParseException(message);
}
}
/// <summary>
/// Gets the method info.
/// </summary>
public MethodInfo MethodInfo { get; }
private static object[] CreateMethodDefaultParameters(ParameterInfo[] formalParameters, ConditionExpression[] methodParameters, int parameterOffset)
{
var defaultParameterCount = formalParameters.Length - methodParameters.Length - parameterOffset;
if (defaultParameterCount <= 0)
return ArrayHelper.Empty<object>();
var extraDefaultParameters = new object[defaultParameterCount];
for (int i = methodParameters.Length + parameterOffset; i < formalParameters.Length; ++i)
{
ParameterInfo param = formalParameters[i];
extraDefaultParameters[i - methodParameters.Length + parameterOffset] = param.DefaultValue;
}
return extraDefaultParameters;
}
private static void CountParmameters(ParameterInfo[] formalParameters, out int requiredParametersCount, out int optionalParametersCount)
{
requiredParametersCount = 0;
optionalParametersCount = 0;
foreach (var param in formalParameters)
{
if (param.IsOptional)
++optionalParametersCount;
else
++requiredParametersCount;
}
}
/// <summary>
/// Returns a string representation of the expression.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the condition expression.
/// </returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(_conditionMethodName);
sb.Append("(");
string separator = string.Empty;
foreach (var expr in _methodParameters)
{
sb.Append(separator);
sb.Append(expr);
separator = ", ";
}
sb.Append(")");
return sb.ToString();
}
/// <summary>
/// Evaluates the expression.
/// </summary>
/// <param name="context">Evaluation context.</param>
/// <returns>Expression result.</returns>
protected override object EvaluateNode(LogEventInfo context)
{
object[] callParameters = GenerateCallParameters(context);
return _lateBoundMethod(null, callParameters); // Static-method so object-instance = null
}
private object[] GenerateCallParameters(LogEventInfo context)
{
int parameterOffset = _acceptsLogEvent ? 1 : 0;
int callParametersCount = _methodParameters.Length + parameterOffset + _lateBoundMethodDefaultParameters.Length;
if (callParametersCount == 0)
return ArrayHelper.Empty<object>();
var callParameters = new object[callParametersCount];
if (_acceptsLogEvent)
{
callParameters[0] = context;
}
//Memory profiling pointed out that using a foreach-loop was allocating
//an Enumerator. Switching to a for-loop avoids the memory allocation.
for (int i = 0; i < _methodParameters.Length; i++)
{
ConditionExpression ce = _methodParameters[i];
callParameters[i + parameterOffset] = ce.Evaluate(context);
}
if (_lateBoundMethodDefaultParameters.Length > 0)
{
for (int i = _lateBoundMethodDefaultParameters.Length - 1; i >= 0; --i)
{
callParameters[callParameters.Length - i - 1] = _lateBoundMethodDefaultParameters[i];
}
}
return callParameters;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using log4net;
namespace Multiverse.ToolBox
{
public class ExcludedKey
{
protected string key;
protected string modifier;
protected Keys keyCode;
protected Keys modifierCode;
public ExcludedKey(string key, string modifier)
{
this.key = key;
this.modifier = modifier;
}
public string Key
{
get
{
return key;
}
set
{
key = value;
}
}
public string Modifier
{
get
{
return modifier;
}
set
{
modifier = value;
}
}
public Keys KeyCode
{
get
{
return keyCode;
}
set
{
keyCode = value;
}
}
public Keys ModifierCode
{
get
{
return modifierCode;
}
set
{
modifierCode = value;
}
}
}
public class EventObject
{
protected EventHandler handler;
protected string context;
protected string text;
protected string evstring;
protected bool mouseButtonEvent = false;
public EventObject(EventHandler hand, string con, string txt, string evstr)
{
handler = hand;
context = con;
text = txt;
evstring = evstr;
}
public EventObject(EventHandler hand, string con, string txt, string evstr, bool mouseEvent)
{
handler = hand;
context = con;
text = txt;
evstring = evstr;
mouseButtonEvent = mouseEvent;
}
public EventObject(XmlReader r)
{
fromXml(r);
}
public void fromXml(XmlReader r)
{
for( int i = 0; i < r.AttributeCount; i++)
{
r.MoveToAttribute(i);
switch (r.Name)
{
case "Context":
context = r.Value;
break;
case "Text":
text = r.Value;
break;
case "EventString":
evstring = r.Value;
break;
}
}
r.MoveToElement();
}
public void ToXml(XmlWriter w)
{
w.WriteStartElement("Event");
w.WriteAttributeString("EventString",evstring);
w.WriteAttributeString("Text", text);
w.WriteAttributeString("Context", context);
w.WriteEndElement();
}
public EventHandler Handler
{
get
{
return handler;
}
set
{
handler = value;
}
}
public string Context
{
get
{
return context;
}
}
public string Text
{
get
{
return text;
}
}
public string EvString
{
get
{
return evstring;
}
}
public bool MouseButtonEvent
{
get
{
return mouseButtonEvent;
}
set
{
mouseButtonEvent = value;
}
}
}
public class UserCommand
{
protected Keys keycode;
protected string keystring;
protected string context;
protected string activity;
protected string modifier;
protected Keys modifiercode;
protected string evstring;
protected EventObject ev;
protected UserCommandMapping parent;
protected List<ExcludedKey> exKeys;
log4net.ILog log = log4net.LogManager.GetLogger(typeof(UserCommand));
public UserCommand( XmlReader r, UserCommandMapping par)
{
parent = par;
fromXml(r);
}
public UserCommand(EventObject handler, string key, string activity, string modifier, string evstr, UserCommandMapping par)
{
//if (handler == null)
//{
// log.ErrorFormat("handler == null");
//}
//if (par == null)
//{
// log.ErrorFormat("par == null");
//}
ev = handler;
parent = par;
this.activity = activity;
this.modifier = modifier;
this.modifiercode = parent.ParseStringToKeyCode(modifier);
this.evstring = evstr;
this.keystring = key;
this.keycode = parent.ParseStringToKeyCode(keystring);
this.context = ev.Context;
}
public UserCommand Clone(UserCommandMapping par)
{
UserCommand rv = new UserCommand(ev, keystring, activity, modifier, evstring, par);
return rv;
}
private void fromXml(XmlReader r)
{
for (int i = 0; i < r.AttributeCount; i++)
{
r.MoveToAttribute(i);
switch (r.Name)
{
case "Event":
this.evstring = r.Value;
break;
case "Modifier":
foreach(string mod in parent.Modifiers)
{
if(String.Equals(mod, r.Value))
{
this.modifier = mod;
modifiercode = parent.ParseModifierToCode(mod);
break;
}
}
break;
case "Key":
keystring = r.Value;
keycode = parent.ParseStringToKeyCode(r.Value);
break;
case "Activity":
foreach (string act in parent.Activities)
{
if (String.Equals(act.ToString(), r.Value))
{
this.activity = act;
break;
}
}
break;
case "Context":
context = r.Value;
break;
}
}
r.MoveToElement();
foreach (EventObject ev in parent.Events)
{
if (String.Equals(ev.EvString, this.evstring))
{
this.ev = ev;
}
}
return;
}
public void ToXml(XmlWriter w)
{
w.WriteStartElement("CommandBinding");
w.WriteAttributeString("Event", this.evstring);
w.WriteAttributeString("Modifier", this.modifier);
w.WriteAttributeString("Key", this.keystring);
w.WriteAttributeString("Activity", this.activity);
w.WriteAttributeString("Context", this.context);
w.WriteEndElement();
}
public EventObject Event
{
get
{
return ev;
}
}
public string Context
{
get
{
return context;
}
}
public string Activity
{
get
{
return activity;
}
set
{
activity = value;
}
}
public string Modifier
{
get
{
return modifier;
}
set
{
modifier = value;
modifiercode = parent.ParseStringToKeyCode(value);
}
}
public Keys ModifierCode
{
get
{
return modifiercode;
}
}
public Keys KeyCode
{
get
{
return keycode;
}
}
public string Key
{
get
{
return keystring;
}
set
{
keystring = value;
keycode = parent.ParseStringToKeyCode(value);
}
}
public string EvString
{
get
{
return evstring;
}
}
}
public class UserCommandMapping
{
protected static string[] activityarray = { "up", "down" };
protected static string[] modifiersarray = { "Ctrl", "Alt", "Shift", "none" };
protected List<string> activities = new List<string>(activityarray);
protected List<string> modifiers = new List<string>(modifiersarray);
protected List<UserCommand> commands = new List<UserCommand>();
protected List<EventObject> events;
protected List<string> context;
protected static string[] keysarray = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "[", "]", "\\", ";", "'", "`", ",", ".",
"/", "DELETE", "INSERT", "HOME", "PAGEUP", "PAGEDOWN", "END", "NUMPAD1", "NUMPAD2", "NUMPAD3", "NUMPAD4", "NUMPAD5", "NUMPAD6",
"NUMPAD7", "NUMPAD8", "NUMPAD9", "NUMPAD0", "UP", "DOWN", "LEFT", "RIGHT", "MBUTTON", "LBUTTON", "RBUTTON", "TAB", "ADD",
"SUBTRACT", "DIVIDE", "MULTIPLY", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12" };
protected List<string> keys = new List<string>(keysarray);
protected List<ExcludedKey> excludedKeys;
public UserCommandMapping(XmlReader r, List<EventObject> events, List<string> context, List<ExcludedKey> excludekeys)
{
this.events = events;
this.context = context;
this.commands = new List<UserCommand>();
this.excludedKeys = excludekeys;
while (r.Read())
{
switch (r.Name)
{
case "CommandBindings":
fromXml(r);
break;
}
if (r.NodeType == XmlNodeType.EndElement)
{
break;
}
}
foreach(ExcludedKey exKey in excludedKeys)
{
exKey.KeyCode = ParseStringToKeyCode(exKey.Key);
exKey.ModifierCode = ParseModifierToCode(exKey.Modifier);
}
}
public Keys ParseStringToKeyCode(string value)
{
Keys keycode = 0;
switch (value)
{
case "A":
keycode = Keys.A;
break;
case "B":
keycode = Keys.B;
break;
case "C":
keycode = Keys.C;
break;
case "D":
keycode = Keys.D;
break;
case "E":
keycode = Keys.E;
break;
case "F":
keycode = Keys.F;
break;
case "G":
keycode = Keys.G;
break;
case "H":
keycode = Keys.H;
break;
case "I":
keycode = Keys.I;
break;
case "J":
keycode = Keys.J;
break;
case "K":
keycode = Keys.K;
break;
case "L":
keycode = Keys.L;
break;
case "M":
keycode = Keys.M;
break;
case "N":
keycode = Keys.N;
break;
case "O":
keycode = Keys.O;
break;
case "P":
keycode = Keys.P;
break;
case "Q":
keycode = Keys.Q;
break;
case "R":
keycode = Keys.R;
break;
case "S":
keycode = Keys.S;
break;
case "T":
keycode = Keys.T;
break;
case "U":
keycode = Keys.U;
break;
case "V":
keycode = Keys.V;
break;
case "W":
keycode = Keys.W;
break;
case "X":
keycode = Keys.X;
break;
case "Y":
keycode = Keys.Y;
break;
case "Z":
keycode = Keys.Z;
break;
case "1":
keycode = Keys.D1;
break;
case "2":
keycode = Keys.D2;
break;
case "3":
keycode = Keys.D3;
break;
case "4":
keycode = Keys.D4;
break;
case "5":
keycode = Keys.D5;
break;
case "6":
keycode = Keys.D6;
break;
case "7":
keycode = Keys.D7;
break;
case "8":
keycode = Keys.D8;
break;
case "9":
keycode = Keys.D9;
break;
case "0":
keycode = Keys.D0;
break;
case "-":
keycode = Keys.OemMinus;
break;
case "[":
keycode = Keys.OemOpenBrackets;
break;
case "]":
keycode = Keys.OemCloseBrackets;
break;
case "\\":
keycode = Keys.OemBackslash;
break;
case ";":
keycode = Keys.OemSemicolon;
break;
case "'":
keycode = Keys.OemQuotes;
break;
case "`":
keycode = Keys.Oemtilde;
break;
case ",":
keycode = Keys.Oemcomma;
break;
case ".":
keycode = Keys.OemPeriod;
break;
case "/":
keycode = Keys.OemQuestion;
break;
case "DELETE":
keycode = Keys.Delete;
break;
case "INSERT":
keycode = Keys.Insert;
break;
case "HOME":
keycode = Keys.Home;
break;
case "PAGEUP":
keycode = Keys.PageUp;
break;
case "PAGEDOWN":
keycode = Keys.PageDown;
break;
case "END":
keycode = Keys.End;
break;
case "NUMPAD1":
keycode = Keys.NumPad1;
break;
case "NUMPAD2":
keycode = Keys.NumPad2;
break;
case "NUMPAD3":
keycode = Keys.NumPad3;
break;
case "NUMPAD4":
keycode = Keys.NumPad4;
break;
case "NUMPAD5":
keycode = Keys.NumPad5;
break;
case "NUMPAD6":
keycode = Keys.NumPad6;
break;
case "NUMPAD7":
keycode = Keys.NumPad7;
break;
case "NUMPAD8":
keycode = Keys.NumPad8;
break;
case "NUMPAD9":
keycode = Keys.NumPad9;
break;
case "NUMPAD0":
keycode = Keys.NumPad0;
break;
case "UP":
keycode = Keys.Up;
break;
case "DOWN":
keycode = Keys.Down;
break;
case "LEFT":
keycode = Keys.Left;
break;
case "RIGHT":
keycode = Keys.Right;
break;
case "MBUTTON":
keycode = Keys.MButton;
break;
case "LBUTTON":
keycode = Keys.LButton;
break;
case "RBUTTON":
keycode = Keys.RButton;
break;
case "TAB":
keycode = Keys.Tab;
break;
case "ADD":
keycode = Keys.Add;
break;
case "SUBTRACT":
keycode = Keys.Subtract;
break;
case "DIVIDE":
keycode = Keys.Divide;
break;
case "MULTIPLY":
keycode = Keys.Multiply;
break;
case "F1":
keycode = Keys.F1;
break;
case "F2":
keycode = Keys.F2;
break;
case "F3":
keycode = Keys.F3;
break;
case "F4":
keycode = Keys.F4;
break;
case "F5":
keycode = Keys.F5;
break;
case "F6":
keycode = Keys.F6;
break;
case "F7":
keycode = Keys.F7;
break;
case "F8":
keycode = Keys.F8;
break;
case "F9":
keycode = Keys.F9;
break;
case "F10":
keycode = Keys.F10;
break;
case "F11":
keycode = Keys.F11;
break;
case "F12":
keycode = Keys.F12;
break;
}
return keycode;
}
public Keys ParseModifierToCode(string mod)
{
Keys keycode = 0;
switch (mod)
{
case "Ctrl":
keycode = Keys.Control;
break;
case "Alt":
keycode = Keys.Alt;
break;
case "Shift":
keycode = Keys.Shift;
break;
case "none":
keycode = Keys.None;
break;
}
return keycode;
}
public UserCommandMapping(List<EventObject> events, List<string> context, List<ExcludedKey> exKeys)
{
this.events = events;
this.context = context;
foreach (ExcludedKey eKey in exKeys)
{
eKey.KeyCode = ParseStringToKeyCode(eKey.Key);
eKey.ModifierCode = ParseModifierToCode(eKey.Modifier);
}
}
public UserCommandMapping(List<EventObject> events, List<string> context, List<UserCommand> com, List<ExcludedKey> exKeys)
{
this.events = events;
this.context = context;
this.excludedKeys = exKeys;
foreach (UserCommand comm in com)
{
UserCommand uc = comm.Clone(this);
this.commands.Add(uc);
}
foreach (ExcludedKey eKey in exKeys)
{
eKey.KeyCode = ParseStringToKeyCode(eKey.Key);
eKey.ModifierCode = ParseModifierToCode(eKey.Modifier);
}
}
private void fromXml(XmlReader r)
{
while (r.Read())
{
switch(r.Name)
{
case "CommandBinding":
UserCommand uc = new UserCommand(r, this);
this.commands.Add(uc);
break;
}
}
}
public void ToXml(XmlWriter w)
{
w.WriteStartElement("CommandBindings");
foreach (UserCommand command in commands)
{
command.ToXml(w);
}
w.WriteEndElement();
}
public List<UserCommand> Commands
{
get
{
return this.commands;
}
set
{
this.commands = value;
}
}
public EventObject GetMatch(Keys mod, Keys key, string act, string con)
{
foreach (UserCommand cmd in commands)
{
if(cmd.ModifierCode == mod && cmd.KeyCode == key && String.Equals(cmd.Activity, act) && String.Equals(cmd.Context, con))
{
return cmd.Event;
}
}
return null;
}
public List<EventObject> GetEventsForContext(string con)
{
List<EventObject> list = new List<EventObject>();
foreach (EventObject events in Events)
{
if (String.Equals(events.Context, con))
{
list.Add(events);
}
}
return list;
}
public List<UserCommand> GetCommandsForContext(string con)
{
List<UserCommand> rv = new List<UserCommand>();
foreach (UserCommand command in commands)
{
if (String.Equals(command.Event.Context, con))
{
rv.Add(command);
}
}
return rv;
}
public UserCommand GetCommandForEvent(string evstring)
{
foreach (UserCommand command in commands)
{
if(String.Equals(command.EvString, evstring))
{
return command;
}
}
return null;
}
public List<ExcludedKey> ExcludedKeys
{
get
{
return excludedKeys;
}
}
public List<string> Modifiers
{
get
{
return modifiers;
}
}
public List<string> Activities
{
get
{
return activities;
}
}
public List<EventObject> Events
{
get
{
return events;
}
}
public List<string> Context
{
get
{
return context;
}
}
public List<string> Key
{
get
{
return keys;
}
}
public UserCommandMapping Clone()
{
UserCommandMapping clone;
clone = new UserCommandMapping(events, context, commands, excludedKeys);
return clone;
}
public void Dispose()
{
return;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition.Factories;
using System.ComponentModel.Composition.Hosting;
using Xunit;
namespace System.ComponentModel.Composition.AttributedModel
{
public class INotifyImportTests
{
[Export(typeof(PartWithoutImports))]
public class PartWithoutImports : IPartImportsSatisfiedNotification
{
public bool ImportsSatisfiedInvoked { get; private set; }
public void OnImportsSatisfied()
{
this.ImportsSatisfiedInvoked = true;
}
}
[Fact]
public void ImportsSatisfiedOnComponentWithoutImports()
{
CompositionContainer container = ContainerFactory.CreateWithAttributedCatalog(typeof(PartWithoutImports));
PartWithoutImports partWithoutImports = container.GetExportedValue<PartWithoutImports>();
Assert.NotNull(partWithoutImports);
Assert.True(partWithoutImports.ImportsSatisfiedInvoked);
}
[Fact]
public void ImportCompletedTest()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
var entrypoint = new UpperCaseStringComponent();
batch.AddParts(new LowerCaseString("abc"), entrypoint);
container.Compose(batch);
batch = new CompositionBatch();
batch.AddParts(new object());
container.Compose(batch);
Assert.Equal(entrypoint.LowerCaseStrings.Count, 1);
Assert.Equal(entrypoint.ImportCompletedCallCount, 1);
Assert.Equal(entrypoint.UpperCaseStrings.Count, 1);
Assert.Equal(entrypoint.LowerCaseStrings[0].Value.String, "abc");
Assert.Equal(entrypoint.UpperCaseStrings[0], "ABC");
}
[Fact]
public void ImportCompletedWithRecomposing()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
var entrypoint = new UpperCaseStringComponent();
batch.AddParts(new LowerCaseString("abc"), entrypoint);
container.Compose(batch);
Assert.Equal(entrypoint.LowerCaseStrings.Count, 1);
Assert.Equal(entrypoint.ImportCompletedCallCount, 1);
Assert.Equal(entrypoint.UpperCaseStrings.Count, 1);
Assert.Equal(entrypoint.LowerCaseStrings[0].Value.String, "abc");
Assert.Equal(entrypoint.UpperCaseStrings[0], "ABC");
// Add another component to verify recomposing
batch = new CompositionBatch();
batch.AddParts(new LowerCaseString("def"));
container.Compose(batch);
Assert.Equal(entrypoint.LowerCaseStrings.Count, 2);
Assert.Equal(entrypoint.ImportCompletedCallCount, 2);
Assert.Equal(entrypoint.UpperCaseStrings.Count, 2);
Assert.Equal(entrypoint.LowerCaseStrings[1].Value.String, "def");
Assert.Equal(entrypoint.UpperCaseStrings[1], "DEF");
// Verify that adding a random component doesn't cause
// the OnImportsSatisfied to be called again.
batch = new CompositionBatch();
batch.AddParts(new object());
container.Compose(batch);
Assert.Equal(entrypoint.LowerCaseStrings.Count, 2);
Assert.Equal(entrypoint.ImportCompletedCallCount, 2);
Assert.Equal(entrypoint.UpperCaseStrings.Count, 2);
}
[Fact]
[ActiveIssue(700940)]
public void ImportCompletedUsingSatisfyImportsOnce()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
var entrypoint = new UpperCaseStringComponent();
var entrypointPart = AttributedModelServices.CreatePart(entrypoint);
batch.AddParts(new LowerCaseString("abc"));
container.Compose(batch);
container.SatisfyImportsOnce(entrypointPart);
Assert.Equal(1, entrypoint.LowerCaseStrings.Count);
Assert.Equal(1, entrypoint.ImportCompletedCallCount);
Assert.Equal(1, entrypoint.UpperCaseStrings.Count);
Assert.Equal("abc", entrypoint.LowerCaseStrings[0].Value.String);
Assert.Equal("ABC", entrypoint.UpperCaseStrings[0]);
batch = new CompositionBatch();
batch.AddParts(new object());
container.Compose(batch);
container.SatisfyImportsOnce(entrypointPart);
Assert.Equal(1, entrypoint.LowerCaseStrings.Count);
Assert.Equal(1, entrypoint.ImportCompletedCallCount);
Assert.Equal(1, entrypoint.UpperCaseStrings.Count);
Assert.Equal("abc", entrypoint.LowerCaseStrings[0].Value.String);
Assert.Equal("ABC", entrypoint.UpperCaseStrings[0]);
batch.AddParts(new LowerCaseString("def"));
container.Compose(batch);
container.SatisfyImportsOnce(entrypointPart);
Assert.Equal(2, entrypoint.LowerCaseStrings.Count);
Assert.Equal(2, entrypoint.ImportCompletedCallCount);
Assert.Equal(2, entrypoint.UpperCaseStrings.Count);
Assert.Equal("abc", entrypoint.LowerCaseStrings[0].Value.String);
Assert.Equal("ABC", entrypoint.UpperCaseStrings[0]);
Assert.Equal("def", entrypoint.LowerCaseStrings[1].Value.String);
Assert.Equal("DEF", entrypoint.UpperCaseStrings[1]);
}
[Fact]
[ActiveIssue(654513)]
public void ImportCompletedCalledAfterAllImportsAreFullyComposed()
{
int importSatisfationCount = 0;
var importer1 = new MyEventDrivenFullComposedNotifyImporter1();
var importer2 = new MyEventDrivenFullComposedNotifyImporter2();
Action<object, EventArgs> verificationAction = (object sender, EventArgs e) =>
{
Assert.True(importer1.AreAllImportsFullyComposed);
Assert.True(importer2.AreAllImportsFullyComposed);
++importSatisfationCount;
};
importer1.ImportsSatisfied += new EventHandler(verificationAction);
importer2.ImportsSatisfied += new EventHandler(verificationAction);
// importer1 added first
var batch = new CompositionBatch();
batch.AddParts(importer1, importer2);
var container = ContainerFactory.Create();
container.ComposeExportedValue<ICompositionService>(container);
container.Compose(batch);
Assert.Equal(2, importSatisfationCount);
// importer2 added first
importSatisfationCount = 0;
batch = new CompositionBatch();
batch.AddParts(importer2, importer1);
container = ContainerFactory.Create();
container.ComposeExportedValue<ICompositionService>(container);
container.Compose(batch);
Assert.Equal(2, importSatisfationCount);
}
[Fact]
public void ImportCompletedAddPartAndBindComponent()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
batch.AddParts(new CallbackImportNotify(delegate
{
batch = new CompositionBatch();
batch.AddPart(new object());
container.Compose(batch);
}));
container.Compose(batch);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void ImportCompletedChildNeedsParentContainer()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var parent = new CompositionContainer(cat);
CompositionBatch parentBatch = new CompositionBatch();
CompositionBatch childBatch = new CompositionBatch();
CompositionBatch child2Batch = new CompositionBatch();
parentBatch.AddExportedValue<ICompositionService>(parent);
parent.Compose(parentBatch);
var child = new CompositionContainer(parent);
var child2 = new CompositionContainer(parent);
var parentImporter = new MyNotifyImportImporter(parent);
var childImporter = new MyNotifyImportImporter(child);
var child2Importer = new MyNotifyImportImporter(child2);
parentBatch = new CompositionBatch();
parentBatch.AddPart(parentImporter);
childBatch.AddPart(childImporter);
child2Batch.AddPart(child2Importer);
parent.Compose(parentBatch);
child.Compose(childBatch);
child2.Compose(child2Batch);
Assert.Equal(1, parentImporter.ImportCompletedCallCount);
Assert.Equal(1, childImporter.ImportCompletedCallCount);
Assert.Equal(1, child2Importer.ImportCompletedCallCount);
MyNotifyImportExporter parentExporter = parent.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
Assert.Equal(1, parentExporter.ImportCompletedCallCount);
MyNotifyImportExporter childExporter = child.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
Assert.Equal(1, childExporter.ImportCompletedCallCount);
MyNotifyImportExporter child2Exporter = child2.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
Assert.Equal(1, child2Exporter.ImportCompletedCallCount);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void ImportCompletedChildDoesnotNeedParentContainer()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var parent = new CompositionContainer(cat);
CompositionBatch parentBatch = new CompositionBatch();
CompositionBatch childBatch = new CompositionBatch();
parentBatch.AddExportedValue<ICompositionService>(parent);
parent.Compose(parentBatch);
var child = new CompositionContainer(parent);
var parentImporter = new MyNotifyImportImporter(parent);
var childImporter = new MyNotifyImportImporter(child);
parentBatch = new CompositionBatch();
parentBatch.AddPart(parentImporter);
childBatch.AddParts(childImporter, new MyNotifyImportExporter());
child.Compose(childBatch);
Assert.Equal(0, parentImporter.ImportCompletedCallCount);
Assert.Equal(1, childImporter.ImportCompletedCallCount);
// Parent will become bound at this point.
MyNotifyImportExporter parentExporter = parent.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
parent.Compose(parentBatch);
Assert.Equal(1, parentImporter.ImportCompletedCallCount);
Assert.Equal(1, parentExporter.ImportCompletedCallCount);
MyNotifyImportExporter childExporter = child.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
Assert.Equal(1, childExporter.ImportCompletedCallCount);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void ImportCompletedBindChildIndirectlyThroughParentContainerBind()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var parent = new CompositionContainer(cat);
CompositionBatch parentBatch = new CompositionBatch();
CompositionBatch childBatch = new CompositionBatch();
parentBatch.AddExportedValue<ICompositionService>(parent);
parent.Compose(parentBatch);
var child = new CompositionContainer(parent);
var parentImporter = new MyNotifyImportImporter(parent);
var childImporter = new MyNotifyImportImporter(child);
parentBatch = new CompositionBatch();
parentBatch.AddPart(parentImporter);
childBatch.AddParts(childImporter, new MyNotifyImportExporter());
parent.Compose(parentBatch);
child.Compose(childBatch);
Assert.Equal(1, parentImporter.ImportCompletedCallCount);
Assert.Equal(1, childImporter.ImportCompletedCallCount);
MyNotifyImportExporter parentExporter = parent.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
Assert.Equal(1, parentExporter.ImportCompletedCallCount);
MyNotifyImportExporter childExporter = child.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
Assert.Equal(1, childExporter.ImportCompletedCallCount);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void ImportCompletedGetExportedValueLazy()
{
var cat = CatalogFactory.CreateDefaultAttributed();
CompositionContainer container = new CompositionContainer(cat);
NotifyImportExportee.InstanceCount = 0;
NotifyImportExportsLazy notifyee = container.GetExportedValue<NotifyImportExportsLazy>("NotifyImportExportsLazy");
Assert.NotNull(notifyee);
Assert.NotNull(notifyee.Imports);
Assert.True(notifyee.NeedRefresh);
Assert.Equal(3, notifyee.Imports.Count);
Assert.Equal(0, NotifyImportExportee.InstanceCount);
Assert.Equal(0, notifyee.realImports.Count);
Assert.Equal(2, notifyee.RealImports.Count);
Assert.Equal(1, notifyee.RealImports[0].Id);
Assert.Equal(3, notifyee.RealImports[1].Id);
Assert.Equal(2, NotifyImportExportee.InstanceCount);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void ImportCompletedGetExportedValueEager()
{
var cat = CatalogFactory.CreateDefaultAttributed();
CompositionContainer container = new CompositionContainer(cat);
NotifyImportExportee.InstanceCount = 0;
var notifyee = container.GetExportedValue<NotifyImportExportsEager>("NotifyImportExportsEager");
Assert.NotNull(notifyee);
Assert.NotNull(notifyee.Imports);
Assert.Equal(3, notifyee.Imports.Count);
Assert.Equal(2, NotifyImportExportee.InstanceCount);
Assert.Equal(2, notifyee.realImports.Count);
Assert.Equal(2, notifyee.RealImports.Count);
Assert.Equal(1, notifyee.RealImports[0].Id);
Assert.Equal(3, notifyee.RealImports[1].Id);
Assert.Equal(2, NotifyImportExportee.InstanceCount);
}
}
public class NotifyImportExportee
{
public NotifyImportExportee(int id)
{
Id = id;
InstanceCount++;
}
public int Id { get; set; }
public static int InstanceCount { get; set; }
}
public class NotifyImportExporter
{
public NotifyImportExporter()
{
}
[Export()]
[ExportMetadata("Filter", false)]
public NotifyImportExportee Export1
{
get
{
return new NotifyImportExportee(1);
}
}
[Export()]
[ExportMetadata("Filter", true)]
public NotifyImportExportee Export2
{
get
{
return new NotifyImportExportee(2);
}
}
[Export()]
[ExportMetadata("Filter", false)]
public NotifyImportExportee Export3
{
get
{
return new NotifyImportExportee(3);
}
}
}
[Export("NotifyImportExportsLazy")]
public class NotifyImportExportsLazy : IPartImportsSatisfiedNotification
{
public NotifyImportExportsLazy()
{
NeedRefresh = false;
}
[ImportMany(typeof(NotifyImportExportee))]
public Collection<Lazy<NotifyImportExportee, IDictionary<string, object>>> Imports { get; set; }
public bool NeedRefresh { get; set; }
public void OnImportsSatisfied()
{
NeedRefresh = true;
}
internal Collection<NotifyImportExportee> realImports = new Collection<NotifyImportExportee>();
public Collection<NotifyImportExportee> RealImports
{
get
{
if (NeedRefresh)
{
realImports.Clear();
foreach (var import in Imports)
{
if (!((bool)import.Metadata["Filter"]))
{
realImports.Add(import.Value);
}
}
NeedRefresh = false;
}
return realImports;
}
}
}
[Export("NotifyImportExportsEager")]
public class NotifyImportExportsEager : IPartImportsSatisfiedNotification
{
public NotifyImportExportsEager()
{
}
[ImportMany]
public Collection<Lazy<NotifyImportExportee, IDictionary<string, object>>> Imports { get; set; }
public void OnImportsSatisfied()
{
realImports.Clear();
foreach (var import in Imports)
{
if (!((bool)import.Metadata["Filter"]))
{
realImports.Add(import.Value);
}
}
}
internal Collection<NotifyImportExportee> realImports = new Collection<NotifyImportExportee>();
public Collection<NotifyImportExportee> RealImports
{
get
{
return realImports;
}
}
}
public class MyEventDrivenNotifyImporter : IPartImportsSatisfiedNotification
{
[Import]
public ICompositionService ImportSomethingSoIGetImportCompletedCalled { get; set; }
public event EventHandler ImportsSatisfied;
public void OnImportsSatisfied()
{
if (this.ImportsSatisfied != null)
{
this.ImportsSatisfied(this, new EventArgs());
}
}
}
[Export]
public class MyEventDrivenFullComposedNotifyImporter1 : MyEventDrivenNotifyImporter
{
[Import]
public MyEventDrivenFullComposedNotifyImporter2 FullyComposedImport { get; set; }
public bool AreAllImportsSet
{
get
{
return (this.ImportSomethingSoIGetImportCompletedCalled != null)
&& (this.FullyComposedImport != null);
}
}
public bool AreAllImportsFullyComposed
{
get
{
return this.AreAllImportsSet && this.FullyComposedImport.AreAllImportsSet;
}
}
}
[Export]
public class MyEventDrivenFullComposedNotifyImporter2 : MyEventDrivenNotifyImporter
{
[Import]
public MyEventDrivenFullComposedNotifyImporter1 FullyComposedImport { get; set; }
public bool AreAllImportsSet
{
get
{
return (this.ImportSomethingSoIGetImportCompletedCalled != null)
&& (this.FullyComposedImport != null);
}
}
public bool AreAllImportsFullyComposed
{
get
{
return this.AreAllImportsSet && this.FullyComposedImport.AreAllImportsSet;
}
}
}
[Export("MyNotifyImportExporter")]
public class MyNotifyImportExporter : IPartImportsSatisfiedNotification
{
[Import]
public ICompositionService ImportSomethingSoIGetImportCompletedCalled { get; set; }
public int ImportCompletedCallCount { get; set; }
public void OnImportsSatisfied()
{
ImportCompletedCallCount++;
}
}
public class MyNotifyImportImporter : IPartImportsSatisfiedNotification
{
private CompositionContainer container;
public MyNotifyImportImporter(CompositionContainer container)
{
this.container = container;
}
[Import("MyNotifyImportExporter")]
public MyNotifyImportExporter MyNotifyImportExporter { get; set; }
public int ImportCompletedCallCount { get; set; }
public void OnImportsSatisfied()
{
ImportCompletedCallCount++;
}
}
[Export("LowerCaseString")]
public class LowerCaseString
{
public string String { get; private set; }
public LowerCaseString(string s)
{
String = s.ToLower();
}
}
public class UpperCaseStringComponent : IPartImportsSatisfiedNotification
{
public UpperCaseStringComponent()
{
UpperCaseStrings = new List<string>();
}
Collection<Lazy<LowerCaseString>> lowerCaseString = new Collection<Lazy<LowerCaseString>>();
[ImportMany("LowerCaseString", AllowRecomposition = true)]
public Collection<Lazy<LowerCaseString>> LowerCaseStrings
{
get { return lowerCaseString; }
set { lowerCaseString = value; }
}
public List<string> UpperCaseStrings { get; set; }
public int ImportCompletedCallCount { get; set; }
// This method gets called whenever a bind is completed and any of
// of the imports have changed, but ar safe to use now.
public void OnImportsSatisfied()
{
UpperCaseStrings.Clear();
foreach (var i in LowerCaseStrings)
UpperCaseStrings.Add(i.Value.String.ToUpper());
ImportCompletedCallCount++;
}
}
}
| |
// 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;
/// <summary>
/// System.Array.Sort<T>(T [],System.Int32,System.Int32,System.Collections.IComparer<T>)
/// </summary>
public class ArraySort10
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
//Bug 385712: Won't fix
//retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1:Sort a string array using generics and customized comparer");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Mike",
"Peter",
"Tom",
"Allin"};
string[] s2 = new string[6]{"Jack",
"Mary",
"Mike",
"Allin",
"Peter",
"Tom"};
A a1 = new A();
Array.Sort<string>(s1, 3, 3, a1);
for (int i = 0; i < 6; i++)
{
if (s1[i] != s2[i])
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array using customized comparer<T> ");
try
{
// We'll add two here since we later do things like subtract two from length
int length = 2 + TestLibrary.Generator.GetByte();
int[] i1 = new int[length];
int[] i2 = new int[length];
for (int i = 0; i < length; i++)
{
int value = TestLibrary.Generator.GetByte();
i1[i] = value;
i2[i] = value;
}
IComparer<int> b1 = new B<int>();
int startIdx = GetInt(0, length - 2);
int endIdx = GetInt(startIdx, length - 1);
int count = endIdx - startIdx + 1;
Array.Sort<int>(i1, startIdx, count, b1);
for (int i = startIdx; i < endIdx; i++) //manually quich sort
{
for (int j = i + 1; j <= endIdx; j++)
{
if (i2[i] > i2[j])
{
int temp = i2[i];
i2[i] = i2[j];
i2[j] = temp;
}
}
}
for (int i = 0; i < length; i++)
{
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,the start index is:" + startIdx.ToString() + "the end index is:" + endIdx.ToString());
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array using reverse comparer<T> ");
try
{
char[] c1 = new char[10] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] d1 = new char[10] { 'a', 'e', 'd', 'c', 'b', 'f', 'g', 'h', 'i', 'j' };
IComparer<char> b2 = new B<char>();
Array.Sort<char>(c1, 1, 4, b2);
for (int i = 0; i < 10; i++)
{
if (c1[i] != d1[i])
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Sort customized type array using default customized comparer");
try
{
C<int>[] c_array = new C<int>[5];
C<int>[] c_result = new C<int>[5];
for (int i = 0; i < 5; i++)
{
int value = TestLibrary.Generator.GetInt32();
C<int> c1 = new C<int>(value);
c_array.SetValue(c1, i);
c_result.SetValue(c1, i);
}
//sort manually
C<int> temp;
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < 4; i++)
{
if (c_result[i].value > c_result[i + 1].value)
{
temp = c_result[i];
c_result[i] = c_result[i + 1];
c_result[i + 1] = temp;
}
}
}
Array.Sort<C<int>>(c_array, 0, 5, null);
for (int i = 0; i < 5; i++)
{
if (c_result[i].value != c_array[i].value)
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The array to be sorted is null reference ");
try
{
string[] s1 = null;
Array.Sort<string>(s1, 0, 2, null);
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected ");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The start index is less than the minimal bound of the array");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Peter",
"Mike",
"Tom",
"Allin"};
Array.Sort<string>(s1, -1, 4, null);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException is not throw as expected ");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: Length is less than zero");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Peter",
"Mike",
"Tom",
"Allin"};
Array.Sort<string>(s1, 3, -3, null);
TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException is not throw as expected ");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: The start index and length do not specify a valid range in array");
try
{
int length = TestLibrary.Generator.GetByte();
string[] s1 = new string[length];
for (int i = 0; i < length; i++)
{
string value = TestLibrary.Generator.GetString(false, 0, 10);
s1[i] = value;
}
int startIdx = GetInt(0, Byte.MaxValue);
int increment = length + 1;
Array.Sort<string>(s1, startIdx + increment, 0, null);
TestLibrary.TestFramework.LogError("107", "The ArgumentException is not throw as expected ");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5:The implementation of comparer caused an error during the sort");
try
{
int[] i1 = new int[9] { 2, 34, 56, 87, 34, 23, 209, 34, 87 };
IComparer<int> d1 = new D<int>();
Array.Sort<int>(i1, 0, 9, d1);
TestLibrary.TestFramework.LogError("109", "The ArgumentException is not throw as expected ");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: Elements in array do not implement the IComparable interface");
try
{
E[] a1 = new E[4] { new E(), new E(), new E(), new E() };
IComparer<E> d2 = null;
Array.Sort<E>(a1, 0, 4, d2);
TestLibrary.TestFramework.LogError("111", "The InvalidOperationException is not throw as expected ");
retVal = false;
}
catch (InvalidOperationException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ArraySort10 test = new ArraySort10();
TestLibrary.TestFramework.BeginTestCase("ArraySort10");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
class A : IComparer<string>
{
#region IComparer<string> Members
public int Compare(string x, string y)
{
return x.CompareTo(y);
}
#endregion
}
class B<T> : IComparer<T> where T : IComparable
{
#region IComparer<T> Members
public int Compare(T x, T y)
{
if (typeof(T) == typeof(char))
{
return -x.CompareTo(y);
}
return x.CompareTo(y);
}
#endregion
}
class C<T> : IComparable where T : IComparable
{
public T value;
public C(T a)
{
this.value = a;
}
#region IComparable Members
public int CompareTo(object obj)
{
return value.CompareTo(((C<T>)obj).value);
}
#endregion
}
class D<T> : IComparer<T> where T : IComparable
{
#region IComparer<T> Members
public int Compare(T x, T y)
{
if (x.CompareTo(x) == 0)
return -1;
return 1;
}
#endregion
}
class E
{
public E()
{
}
}
#region Help method for geting test data
private Int32 GetInt(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32() % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
#if !NETSTANDARD2_0
using Internal.Runtime.CompilerServices;
#endif
namespace System.Runtime.CompilerServices
{
/// <summary>Provides an awaitable type that enables configured awaits on a <see cref="ValueTask"/>.</summary>
[StructLayout(LayoutKind.Auto)]
public readonly struct ConfiguredValueTaskAwaitable
{
/// <summary>The wrapped <see cref="Task"/>.</summary>
private readonly ValueTask _value;
/// <summary>Initializes the awaitable.</summary>
/// <param name="value">The wrapped <see cref="ValueTask"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ConfiguredValueTaskAwaitable(in ValueTask value) => _value = value;
/// <summary>Returns an awaiter for this <see cref="ConfiguredValueTaskAwaitable"/> instance.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ConfiguredValueTaskAwaiter GetAwaiter() => new ConfiguredValueTaskAwaiter(in _value);
/// <summary>Provides an awaiter for a <see cref="ConfiguredValueTaskAwaitable"/>.</summary>
[StructLayout(LayoutKind.Auto)]
public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, IStateMachineBoxAwareAwaiter
{
/// <summary>The value being awaited.</summary>
private readonly ValueTask _value;
/// <summary>Initializes the awaiter.</summary>
/// <param name="value">The value to be awaited.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ConfiguredValueTaskAwaiter(in ValueTask value) => _value = value;
/// <summary>Gets whether the <see cref="ConfiguredValueTaskAwaitable"/> has completed.</summary>
public bool IsCompleted
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _value.IsCompleted;
}
/// <summary>Gets the result of the ValueTask.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GetResult() => _value.ThrowIfCompletedUnsuccessfully();
/// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable"/>.</summary>
public void OnCompleted(Action continuation)
{
object? obj = _value._obj;
Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource);
if (obj is Task t)
{
t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
}
else if (obj != null)
{
Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token,
ValueTaskSourceOnCompletedFlags.FlowExecutionContext |
(_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None));
}
else
{
ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
}
}
/// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable"/>.</summary>
public void UnsafeOnCompleted(Action continuation)
{
object? obj = _value._obj;
Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource);
if (obj is Task t)
{
t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
}
else if (obj != null)
{
Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token,
_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None);
}
else
{
ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
}
}
void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box)
{
object? obj = _value._obj;
Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource);
if (obj is Task t)
{
TaskAwaiter.UnsafeOnCompletedInternal(t, box, _value._continueOnCapturedContext);
}
else if (obj != null)
{
Unsafe.As<IValueTaskSource>(obj).OnCompleted(ThreadPoolGlobals.s_invokeAsyncStateMachineBox, box, _value._token,
_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None);
}
else
{
TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value._continueOnCapturedContext);
}
}
}
}
/// <summary>Provides an awaitable type that enables configured awaits on a <see cref="ValueTask{TResult}"/>.</summary>
/// <typeparam name="TResult">The type of the result produced.</typeparam>
[StructLayout(LayoutKind.Auto)]
public readonly struct ConfiguredValueTaskAwaitable<TResult>
{
/// <summary>The wrapped <see cref="ValueTask{TResult}"/>.</summary>
private readonly ValueTask<TResult> _value;
/// <summary>Initializes the awaitable.</summary>
/// <param name="value">The wrapped <see cref="ValueTask{TResult}"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ConfiguredValueTaskAwaitable(in ValueTask<TResult> value) => _value = value;
/// <summary>Returns an awaiter for this <see cref="ConfiguredValueTaskAwaitable{TResult}"/> instance.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ConfiguredValueTaskAwaiter GetAwaiter() => new ConfiguredValueTaskAwaiter(in _value);
/// <summary>Provides an awaiter for a <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary>
[StructLayout(LayoutKind.Auto)]
public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, IStateMachineBoxAwareAwaiter
{
/// <summary>The value being awaited.</summary>
private readonly ValueTask<TResult> _value;
/// <summary>Initializes the awaiter.</summary>
/// <param name="value">The value to be awaited.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ConfiguredValueTaskAwaiter(in ValueTask<TResult> value) => _value = value;
/// <summary>Gets whether the <see cref="ConfiguredValueTaskAwaitable{TResult}"/> has completed.</summary>
public bool IsCompleted
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _value.IsCompleted;
}
/// <summary>Gets the result of the ValueTask.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TResult GetResult() => _value.Result;
/// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary>
public void OnCompleted(Action continuation)
{
object? obj = _value._obj;
Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>);
if (obj is Task<TResult> t)
{
t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
}
else if (obj != null)
{
Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token,
ValueTaskSourceOnCompletedFlags.FlowExecutionContext |
(_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None));
}
else
{
ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
}
}
/// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary>
public void UnsafeOnCompleted(Action continuation)
{
object? obj = _value._obj;
Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>);
if (obj is Task<TResult> t)
{
t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
}
else if (obj != null)
{
Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token,
_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None);
}
else
{
ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
}
}
void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box)
{
object? obj = _value._obj;
Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>);
if (obj is Task<TResult> t)
{
TaskAwaiter.UnsafeOnCompletedInternal(t, box, _value._continueOnCapturedContext);
}
else if (obj != null)
{
Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ThreadPoolGlobals.s_invokeAsyncStateMachineBox, box, _value._token,
_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None);
}
else
{
TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value._continueOnCapturedContext);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial class SolutionCrawlerRegistrationService
{
private partial class WorkCoordinator
{
private abstract class AsyncWorkItemQueue<TKey> : IDisposable
where TKey : class
{
private readonly object _gate;
private readonly AsyncSemaphore _semaphore;
private readonly SolutionCrawlerProgressReporter _progressReporter;
// map containing cancellation source for the item given out.
private readonly Dictionary<object, CancellationTokenSource> _cancellationMap;
public AsyncWorkItemQueue(SolutionCrawlerProgressReporter progressReporter)
{
_gate = new object();
_semaphore = new AsyncSemaphore(initialCount: 0);
_cancellationMap = new Dictionary<object, CancellationTokenSource>();
_progressReporter = progressReporter;
}
protected abstract int WorkItemCount_NoLock { get; }
protected abstract void Dispose_NoLock();
protected abstract bool AddOrReplace_NoLock(WorkItem item);
protected abstract bool TryTake_NoLock(TKey key, out WorkItem workInfo);
protected abstract bool TryTakeAnyWork_NoLock(ProjectId preferableProjectId, out WorkItem workItem);
public bool HasAnyWork
{
get
{
lock (_gate)
{
return HasAnyWork_NoLock;
}
}
}
public int WorkItemCount
{
get
{
lock (_gate)
{
return WorkItemCount_NoLock;
}
}
}
public void RemoveCancellationSource(object key)
{
lock (_gate)
{
// just remove cancellation token from the map.
// the cancellation token might be passed out to other service
// so don't call cancel on the source only because we are done using it.
_cancellationMap.Remove(key);
}
}
public virtual Task WaitAsync(CancellationToken cancellationToken)
{
return _semaphore.WaitAsync(cancellationToken);
}
public bool AddOrReplace(WorkItem item)
{
if (!HasAnyWork)
{
// first work is added.
_progressReporter.Start();
}
lock (_gate)
{
if (AddOrReplace_NoLock(item))
{
// increase count
_semaphore.Release();
return true;
}
return false;
}
}
public void RequestCancellationOnRunningTasks()
{
lock (_gate)
{
// request to cancel all running works
CancelAll_NoLock();
}
}
public void Dispose()
{
lock (_gate)
{
// here we don't need to care about progress reporter since
// it will be only called when host is shutting down.
// we do the below since we want to kill any pending tasks
Dispose_NoLock();
CancelAll_NoLock();
}
}
private bool HasAnyWork_NoLock
{
get
{
return WorkItemCount_NoLock > 0;
}
}
private void CancelAll_NoLock()
{
// nothing to do
if (_cancellationMap.Count == 0)
{
return;
}
var cancellations = _cancellationMap.Values.ToList();
// it looks like Cancel can cause some code to run at the same thread, which can cause _cancellationMap to be changed.
// make a copy of the list and call cancellation
cancellations.Do(s => s.Cancel());
// clear cancellation map
_cancellationMap.Clear();
}
protected void Cancel_NoLock(object key)
{
CancellationTokenSource source;
if (_cancellationMap.TryGetValue(key, out source))
{
source.Cancel();
_cancellationMap.Remove(key);
}
}
public bool TryTake(TKey key, out WorkItem workInfo, out CancellationTokenSource source)
{
lock (_gate)
{
if (TryTake_NoLock(key, out workInfo))
{
if (!HasAnyWork_NoLock)
{
// last work is done.
_progressReporter.Stop();
}
source = GetNewCancellationSource_NoLock(key);
workInfo.AsyncToken.Dispose();
return true;
}
else
{
source = null;
return false;
}
}
}
public bool TryTakeAnyWork(ProjectId preferableProjectId, out WorkItem workItem, out CancellationTokenSource source)
{
lock (_gate)
{
// there must be at least one item in the map when this is called unless host is shutting down.
if (TryTakeAnyWork_NoLock(preferableProjectId, out workItem))
{
if (!HasAnyWork_NoLock)
{
// last work is done.
_progressReporter.Stop();
}
source = GetNewCancellationSource_NoLock(workItem.Key);
workItem.AsyncToken.Dispose();
return true;
}
else
{
source = null;
return false;
}
}
}
protected CancellationTokenSource GetNewCancellationSource_NoLock(object key)
{
Contract.Requires(!_cancellationMap.ContainsKey(key));
var source = new CancellationTokenSource();
_cancellationMap.Add(key, source);
return source;
}
}
}
}
}
| |
#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
// .NET Compact Framework 1.0 has no support for reading assembly attributes
// and uses the CompactRepositorySelector instead
#if !NETCF
using System;
using System.Collections;
using System.Configuration;
using System.Reflection;
using log4net.Config;
using log4net.Util;
using log4net.Repository;
namespace log4net.Core
{
/// <summary>
/// The default implementation of the <see cref="IRepositorySelector"/> interface.
/// </summary>
/// <remarks>
/// <para>
/// Uses attributes defined on the calling assembly to determine how to
/// configure the hierarchy for the repository.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class DefaultRepositorySelector : IRepositorySelector
{
#region Public Events
/// <summary>
/// Event to notify that a logger repository has been created.
/// </summary>
/// <value>
/// Event to notify that a logger repository has been created.
/// </value>
/// <remarks>
/// <para>
/// Event raised when a new repository is created.
/// The event source will be this selector. The event args will
/// be a <see cref="LoggerRepositoryCreationEventArgs"/> which
/// holds the newly created <see cref="ILoggerRepository"/>.
/// </para>
/// </remarks>
public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent
{
add { m_loggerRepositoryCreatedEvent += value; }
remove { m_loggerRepositoryCreatedEvent -= value; }
}
#endregion Public Events
#region Public Instance Constructors
/// <summary>
/// Creates a new repository selector.
/// </summary>
/// <param name="defaultRepositoryType">The type of the repositories to create, must implement <see cref="ILoggerRepository"/></param>
/// <remarks>
/// <para>
/// Create an new repository selector.
/// The default type for repositories must be specified,
/// an appropriate value would be <see cref="log4net.Repository.Hierarchy.Hierarchy"/>.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="defaultRepositoryType"/> is <see langword="null" />.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="defaultRepositoryType"/> does not implement <see cref="ILoggerRepository"/>.</exception>
public DefaultRepositorySelector(Type defaultRepositoryType)
{
if (defaultRepositoryType == null)
{
throw new ArgumentNullException("defaultRepositoryType");
}
// Check that the type is a repository
if (! (typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) )
{
throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", defaultRepositoryType, "Parameter: defaultRepositoryType, Value: [" + defaultRepositoryType + "] out of range. Argument must implement the ILoggerRepository interface");
}
m_defaultRepositoryType = defaultRepositoryType;
LogLog.Debug(declaringType, "defaultRepositoryType [" + m_defaultRepositoryType + "]");
}
#endregion Public Instance Constructors
#region Implementation of IRepositorySelector
/// <summary>
/// Gets the <see cref="ILoggerRepository"/> for the specified assembly.
/// </summary>
/// <param name="repositoryAssembly">The assembly use to lookup the <see cref="ILoggerRepository"/>.</param>
/// <remarks>
/// <para>
/// The type of the <see cref="ILoggerRepository"/> created and the repository
/// to create can be overridden by specifying the <see cref="log4net.Config.RepositoryAttribute"/>
/// attribute on the <paramref name="repositoryAssembly"/>.
/// </para>
/// <para>
/// The default values are to use the <see cref="log4net.Repository.Hierarchy.Hierarchy"/>
/// implementation of the <see cref="ILoggerRepository"/> interface and to use the
/// <see cref="AssemblyName.Name"/> as the name of the repository.
/// </para>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be automatically configured using
/// any <see cref="log4net.Config.ConfiguratorAttribute"/> attributes defined on
/// the <paramref name="repositoryAssembly"/>.
/// </para>
/// </remarks>
/// <returns>The <see cref="ILoggerRepository"/> for the assembly</returns>
/// <exception cref="ArgumentNullException"><paramref name="repositoryAssembly"/> is <see langword="null" />.</exception>
public ILoggerRepository GetRepository(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
return CreateRepository(repositoryAssembly, m_defaultRepositoryType);
}
/// <summary>
/// Gets the <see cref="ILoggerRepository"/> for the specified repository.
/// </summary>
/// <param name="repositoryName">The repository to use to lookup the <see cref="ILoggerRepository"/>.</param>
/// <returns>The <see cref="ILoggerRepository"/> for the specified repository.</returns>
/// <remarks>
/// <para>
/// Returns the named repository. If <paramref name="repositoryName"/> is <c>null</c>
/// a <see cref="ArgumentNullException"/> is thrown. If the repository
/// does not exist a <see cref="LogException"/> is thrown.
/// </para>
/// <para>
/// Use <see cref="CreateRepository(string, Type)"/> to create a repository.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="repositoryName"/> is <see langword="null" />.</exception>
/// <exception cref="LogException"><paramref name="repositoryName"/> does not exist.</exception>
public ILoggerRepository GetRepository(string repositoryName)
{
if (repositoryName == null)
{
throw new ArgumentNullException("repositoryName");
}
lock(this)
{
// Lookup in map
ILoggerRepository rep = m_name2repositoryMap[repositoryName] as ILoggerRepository;
if (rep == null)
{
throw new LogException("Repository [" + repositoryName + "] is NOT defined.");
}
return rep;
}
}
/// <summary>
/// Create a new repository for the assembly specified
/// </summary>
/// <param name="repositoryAssembly">the assembly to use to create the repository to associate with the <see cref="ILoggerRepository"/>.</param>
/// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>.</param>
/// <returns>The repository created.</returns>
/// <remarks>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be associated with the repository
/// specified such that a call to <see cref="GetRepository(Assembly)"/> with the
/// same assembly specified will return the same repository instance.
/// </para>
/// <para>
/// The type of the <see cref="ILoggerRepository"/> created and
/// the repository to create can be overridden by specifying the
/// <see cref="log4net.Config.RepositoryAttribute"/> attribute on the
/// <paramref name="repositoryAssembly"/>. The default values are to use the
/// <paramref name="repositoryType"/> implementation of the
/// <see cref="ILoggerRepository"/> interface and to use the
/// <see cref="AssemblyName.Name"/> as the name of the repository.
/// </para>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be automatically
/// configured using any <see cref="log4net.Config.ConfiguratorAttribute"/>
/// attributes defined on the <paramref name="repositoryAssembly"/>.
/// </para>
/// <para>
/// If a repository for the <paramref name="repositoryAssembly"/> already exists
/// that repository will be returned. An error will not be raised and that
/// repository may be of a different type to that specified in <paramref name="repositoryType"/>.
/// Also the <see cref="log4net.Config.RepositoryAttribute"/> attribute on the
/// assembly may be used to override the repository type specified in
/// <paramref name="repositoryType"/>.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="repositoryAssembly"/> is <see langword="null" />.</exception>
public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType)
{
return CreateRepository(repositoryAssembly, repositoryType, DefaultRepositoryName, true);
}
/// <summary>
/// Creates a new repository for the assembly specified.
/// </summary>
/// <param name="repositoryAssembly">the assembly to use to create the repository to associate with the <see cref="ILoggerRepository"/>.</param>
/// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>.</param>
/// <param name="repositoryName">The name to assign to the created repository</param>
/// <param name="readAssemblyAttributes">Set to <c>true</c> to read and apply the assembly attributes</param>
/// <returns>The repository created.</returns>
/// <remarks>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be associated with the repository
/// specified such that a call to <see cref="GetRepository(Assembly)"/> with the
/// same assembly specified will return the same repository instance.
/// </para>
/// <para>
/// The type of the <see cref="ILoggerRepository"/> created and
/// the repository to create can be overridden by specifying the
/// <see cref="log4net.Config.RepositoryAttribute"/> attribute on the
/// <paramref name="repositoryAssembly"/>. The default values are to use the
/// <paramref name="repositoryType"/> implementation of the
/// <see cref="ILoggerRepository"/> interface and to use the
/// <see cref="AssemblyName.Name"/> as the name of the repository.
/// </para>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be automatically
/// configured using any <see cref="log4net.Config.ConfiguratorAttribute"/>
/// attributes defined on the <paramref name="repositoryAssembly"/>.
/// </para>
/// <para>
/// If a repository for the <paramref name="repositoryAssembly"/> already exists
/// that repository will be returned. An error will not be raised and that
/// repository may be of a different type to that specified in <paramref name="repositoryType"/>.
/// Also the <see cref="log4net.Config.RepositoryAttribute"/> attribute on the
/// assembly may be used to override the repository type specified in
/// <paramref name="repositoryType"/>.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="repositoryAssembly"/> is <see langword="null" />.</exception>
public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType, string repositoryName, bool readAssemblyAttributes)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
// If the type is not set then use the default type
if (repositoryType == null)
{
repositoryType = m_defaultRepositoryType;
}
lock(this)
{
// Lookup in map
ILoggerRepository rep = m_assembly2repositoryMap[repositoryAssembly] as ILoggerRepository;
if (rep == null)
{
// Not found, therefore create
LogLog.Debug(declaringType, "Creating repository for assembly [" + repositoryAssembly + "]");
// Must specify defaults
string actualRepositoryName = repositoryName;
Type actualRepositoryType = repositoryType;
if (readAssemblyAttributes)
{
// Get the repository and type from the assembly attributes
GetInfoForAssembly(repositoryAssembly, ref actualRepositoryName, ref actualRepositoryType);
}
LogLog.Debug(declaringType, "Assembly [" + repositoryAssembly + "] using repository [" + actualRepositoryName + "] and repository type [" + actualRepositoryType + "]");
// Lookup the repository in the map (as this may already be defined)
rep = m_name2repositoryMap[actualRepositoryName] as ILoggerRepository;
if (rep == null)
{
// Create the repository
rep = CreateRepository(actualRepositoryName, actualRepositoryType);
if (readAssemblyAttributes)
{
try
{
// Look for aliasing attributes
LoadAliases(repositoryAssembly, rep);
// Look for plugins defined on the assembly
LoadPlugins(repositoryAssembly, rep);
// Configure the repository using the assembly attributes
ConfigureRepository(repositoryAssembly, rep);
}
catch (Exception ex)
{
LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex);
}
}
}
else
{
LogLog.Debug(declaringType, "repository [" + actualRepositoryName + "] already exists, using repository type [" + rep.GetType().FullName + "]");
if (readAssemblyAttributes)
{
try
{
// Look for plugins defined on the assembly
LoadPlugins(repositoryAssembly, rep);
}
catch (Exception ex)
{
LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex);
}
}
}
m_assembly2repositoryMap[repositoryAssembly] = rep;
}
return rep;
}
}
/// <summary>
/// Creates a new repository for the specified repository.
/// </summary>
/// <param name="repositoryName">The repository to associate with the <see cref="ILoggerRepository"/>.</param>
/// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>.
/// If this param is <see langword="null" /> then the default repository type is used.</param>
/// <returns>The new repository.</returns>
/// <remarks>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be associated with the repository
/// specified such that a call to <see cref="GetRepository(string)"/> with the
/// same repository specified will return the same repository instance.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="repositoryName"/> is <see langword="null" />.</exception>
/// <exception cref="LogException"><paramref name="repositoryName"/> already exists.</exception>
public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType)
{
if (repositoryName == null)
{
throw new ArgumentNullException("repositoryName");
}
// If the type is not set then use the default type
if (repositoryType == null)
{
repositoryType = m_defaultRepositoryType;
}
lock(this)
{
ILoggerRepository rep = null;
// First check that the repository does not exist
rep = m_name2repositoryMap[repositoryName] as ILoggerRepository;
if (rep != null)
{
throw new LogException("Repository [" + repositoryName + "] is already defined. Repositories cannot be redefined.");
}
else
{
// Lookup an alias before trying to create the new repository
ILoggerRepository aliasedRepository = m_alias2repositoryMap[repositoryName] as ILoggerRepository;
if (aliasedRepository != null)
{
// Found an alias
// Check repository type
if (aliasedRepository.GetType() == repositoryType)
{
// Repository type is compatible
LogLog.Debug(declaringType, "Aliasing repository [" + repositoryName + "] to existing repository [" + aliasedRepository.Name + "]");
rep = aliasedRepository;
// Store in map
m_name2repositoryMap[repositoryName] = rep;
}
else
{
// Invalid repository type for alias
LogLog.Error(declaringType, "Failed to alias repository [" + repositoryName + "] to existing repository ["+aliasedRepository.Name+"]. Requested repository type ["+repositoryType.FullName+"] is not compatible with existing type [" + aliasedRepository.GetType().FullName + "]");
// We now drop through to create the repository without aliasing
}
}
// If we could not find an alias
if (rep == null)
{
LogLog.Debug(declaringType, "Creating repository [" + repositoryName + "] using type [" + repositoryType + "]");
// Call the no arg constructor for the repositoryType
rep = (ILoggerRepository)Activator.CreateInstance(repositoryType);
// Set the name of the repository
rep.Name = repositoryName;
// Store in map
m_name2repositoryMap[repositoryName] = rep;
// Notify listeners that the repository has been created
OnLoggerRepositoryCreatedEvent(rep);
}
}
return rep;
}
}
/// <summary>
/// Test if a named repository exists
/// </summary>
/// <param name="repositoryName">the named repository to check</param>
/// <returns><c>true</c> if the repository exists</returns>
/// <remarks>
/// <para>
/// Test if a named repository exists. Use <see cref="CreateRepository(string, Type)"/>
/// to create a new repository and <see cref="GetRepository(string)"/> to retrieve
/// a repository.
/// </para>
/// </remarks>
public bool ExistsRepository(string repositoryName)
{
lock(this)
{
return m_name2repositoryMap.ContainsKey(repositoryName);
}
}
/// <summary>
/// Gets a list of <see cref="ILoggerRepository"/> objects
/// </summary>
/// <returns>an array of all known <see cref="ILoggerRepository"/> objects</returns>
/// <remarks>
/// <para>
/// Gets an array of all of the repositories created by this selector.
/// </para>
/// </remarks>
public ILoggerRepository[] GetAllRepositories()
{
lock(this)
{
ICollection reps = m_name2repositoryMap.Values;
ILoggerRepository[] all = new ILoggerRepository[reps.Count];
reps.CopyTo(all, 0);
return all;
}
}
#endregion Implementation of IRepositorySelector
#region Public Instance Methods
/// <summary>
/// Aliases a repository to an existing repository.
/// </summary>
/// <param name="repositoryAlias">The repository to alias.</param>
/// <param name="repositoryTarget">The repository that the repository is aliased to.</param>
/// <remarks>
/// <para>
/// The repository specified will be aliased to the repository when created.
/// The repository must not already exist.
/// </para>
/// <para>
/// When the repository is created it must utilize the same repository type as
/// the repository it is aliased to, otherwise the aliasing will fail.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="repositoryAlias" /> is <see langword="null" />.</para>
/// <para>-or-</para>
/// <para><paramref name="repositoryTarget" /> is <see langword="null" />.</para>
/// </exception>
public void AliasRepository(string repositoryAlias, ILoggerRepository repositoryTarget)
{
if (repositoryAlias == null)
{
throw new ArgumentNullException("repositoryAlias");
}
if (repositoryTarget == null)
{
throw new ArgumentNullException("repositoryTarget");
}
lock(this)
{
// Check if the alias is already set
if (m_alias2repositoryMap.Contains(repositoryAlias))
{
// Check if this is a duplicate of the current alias
if (repositoryTarget != ((ILoggerRepository)m_alias2repositoryMap[repositoryAlias]))
{
// Cannot redefine existing alias
throw new InvalidOperationException("Repository [" + repositoryAlias + "] is already aliased to repository [" + ((ILoggerRepository)m_alias2repositoryMap[repositoryAlias]).Name + "]. Aliases cannot be redefined.");
}
}
// Check if the alias is already mapped to a repository
else if (m_name2repositoryMap.Contains(repositoryAlias))
{
// Check if this is a duplicate of the current mapping
if ( repositoryTarget != ((ILoggerRepository)m_name2repositoryMap[repositoryAlias]) )
{
// Cannot define alias for already mapped repository
throw new InvalidOperationException("Repository [" + repositoryAlias + "] already exists and cannot be aliased to repository [" + repositoryTarget.Name + "].");
}
}
else
{
// Set the alias
m_alias2repositoryMap[repositoryAlias] = repositoryTarget;
}
}
}
#endregion Public Instance Methods
#region Protected Instance Methods
/// <summary>
/// Notifies the registered listeners that the repository has been created.
/// </summary>
/// <param name="repository">The repository that has been created.</param>
/// <remarks>
/// <para>
/// Raises the <see cref="LoggerRepositoryCreatedEvent"/> event.
/// </para>
/// </remarks>
protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository)
{
LoggerRepositoryCreationEventHandler handler = m_loggerRepositoryCreatedEvent;
if (handler != null)
{
handler(this, new LoggerRepositoryCreationEventArgs(repository));
}
}
#endregion Protected Instance Methods
#region Private Instance Methods
/// <summary>
/// Gets the repository name and repository type for the specified assembly.
/// </summary>
/// <param name="assembly">The assembly that has a <see cref="log4net.Config.RepositoryAttribute"/>.</param>
/// <param name="repositoryName">in/out param to hold the repository name to use for the assembly, caller should set this to the default value before calling.</param>
/// <param name="repositoryType">in/out param to hold the type of the repository to create for the assembly, caller should set this to the default value before calling.</param>
/// <exception cref="ArgumentNullException"><paramref name="assembly" /> is <see langword="null" />.</exception>
private void GetInfoForAssembly(Assembly assembly, ref string repositoryName, ref Type repositoryType)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
try
{
LogLog.Debug(declaringType, "Assembly [" + assembly.FullName + "] Loaded From [" + SystemInfo.AssemblyLocationInfo(assembly) + "]");
}
catch
{
// Ignore exception from debug call
}
try
{
// Look for the RepositoryAttribute on the assembly
object[] repositoryAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.RepositoryAttribute), false);
if (repositoryAttributes == null || repositoryAttributes.Length == 0)
{
// This is not a problem, but its nice to know what is going on.
LogLog.Debug(declaringType, "Assembly [" + assembly + "] does not have a RepositoryAttribute specified.");
}
else
{
if (repositoryAttributes.Length > 1)
{
LogLog.Error(declaringType, "Assembly [" + assembly + "] has multiple log4net.Config.RepositoryAttribute assembly attributes. Only using first occurrence.");
}
log4net.Config.RepositoryAttribute domAttr = repositoryAttributes[0] as log4net.Config.RepositoryAttribute;
if (domAttr == null)
{
LogLog.Error(declaringType, "Assembly [" + assembly + "] has a RepositoryAttribute but it does not!.");
}
else
{
// If the Name property is set then override the default
if (domAttr.Name != null)
{
repositoryName = domAttr.Name;
}
// If the RepositoryType property is set then override the default
if (domAttr.RepositoryType != null)
{
// Check that the type is a repository
if (typeof(ILoggerRepository).IsAssignableFrom(domAttr.RepositoryType))
{
repositoryType = domAttr.RepositoryType;
}
else
{
LogLog.Error(declaringType, "DefaultRepositorySelector: Repository Type [" + domAttr.RepositoryType + "] must implement the ILoggerRepository interface.");
}
}
}
}
}
catch (Exception ex)
{
LogLog.Error(declaringType, "Unhandled exception in GetInfoForAssembly", ex);
}
}
/// <summary>
/// Configures the repository using information from the assembly.
/// </summary>
/// <param name="assembly">The assembly containing <see cref="log4net.Config.ConfiguratorAttribute"/>
/// attributes which define the configuration for the repository.</param>
/// <param name="repository">The repository to configure.</param>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="assembly" /> is <see langword="null" />.</para>
/// <para>-or-</para>
/// <para><paramref name="repository" /> is <see langword="null" />.</para>
/// </exception>
private void ConfigureRepository(Assembly assembly, ILoggerRepository repository)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
if (repository == null)
{
throw new ArgumentNullException("repository");
}
// Look for the Configurator attributes (e.g. XmlConfiguratorAttribute) on the assembly
object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.ConfiguratorAttribute), false);
if (configAttributes != null && configAttributes.Length > 0)
{
// Sort the ConfiguratorAttributes in priority order
Array.Sort(configAttributes);
// Delegate to the attribute the job of configuring the repository
foreach(log4net.Config.ConfiguratorAttribute configAttr in configAttributes)
{
if (configAttr != null)
{
try
{
configAttr.Configure(assembly, repository);
}
catch (Exception ex)
{
LogLog.Error(declaringType, "Exception calling ["+configAttr.GetType().FullName+"] .Configure method.", ex);
}
}
}
}
if (repository.Name == DefaultRepositoryName)
{
// Try to configure the default repository using an AppSettings specified config file
// Do this even if the repository has been configured (or claims to be), this allows overriding
// of the default config files etc, if that is required.
string repositoryConfigFile = SystemInfo.GetAppSetting("log4net.Config");
if (repositoryConfigFile != null && repositoryConfigFile.Length > 0)
{
string applicationBaseDirectory = null;
try
{
applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
}
catch(Exception ex)
{
LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. appSettings log4net.Config path ["+repositoryConfigFile+"] will be treated as an absolute URI", ex);
}
// As we are not going to watch the config file it is easiest to just resolve it as a
// URI and pass that to the Configurator
Uri repositoryConfigUri = null;
try
{
if (applicationBaseDirectory != null)
{
// Resolve the config path relative to the application base directory URI
repositoryConfigUri = new Uri(new Uri(applicationBaseDirectory), repositoryConfigFile);
}
else
{
repositoryConfigUri = new Uri(repositoryConfigFile);
}
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Exception while parsing log4net.Config file path ["+repositoryConfigFile+"]", ex);
}
if (repositoryConfigUri != null)
{
LogLog.Debug(declaringType, "Loading configuration for default repository from AppSettings specified Config URI ["+repositoryConfigUri.ToString()+"]");
try
{
// TODO: Support other types of configurator
XmlConfigurator.Configure(repository, repositoryConfigUri);
}
catch (Exception ex)
{
LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri ["+repositoryConfigUri+"]", ex);
}
}
}
}
}
/// <summary>
/// Loads the attribute defined plugins on the assembly.
/// </summary>
/// <param name="assembly">The assembly that contains the attributes.</param>
/// <param name="repository">The repository to add the plugins to.</param>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="assembly" /> is <see langword="null" />.</para>
/// <para>-or-</para>
/// <para><paramref name="repository" /> is <see langword="null" />.</para>
/// </exception>
private void LoadPlugins(Assembly assembly, ILoggerRepository repository)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
if (repository == null)
{
throw new ArgumentNullException("repository");
}
// Look for the PluginAttribute on the assembly
object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.PluginAttribute), false);
if (configAttributes != null && configAttributes.Length > 0)
{
foreach(log4net.Plugin.IPluginFactory configAttr in configAttributes)
{
try
{
// Create the plugin and add it to the repository
repository.PluginMap.Add(configAttr.CreatePlugin());
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to create plugin. Attribute [" + configAttr.ToString() + "]", ex);
}
}
}
}
/// <summary>
/// Loads the attribute defined aliases on the assembly.
/// </summary>
/// <param name="assembly">The assembly that contains the attributes.</param>
/// <param name="repository">The repository to alias to.</param>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="assembly" /> is <see langword="null" />.</para>
/// <para>-or-</para>
/// <para><paramref name="repository" /> is <see langword="null" />.</para>
/// </exception>
private void LoadAliases(Assembly assembly, ILoggerRepository repository)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
if (repository == null)
{
throw new ArgumentNullException("repository");
}
// Look for the AliasRepositoryAttribute on the assembly
object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.AliasRepositoryAttribute), false);
if (configAttributes != null && configAttributes.Length > 0)
{
foreach(log4net.Config.AliasRepositoryAttribute configAttr in configAttributes)
{
try
{
AliasRepository(configAttr.Name, repository);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to alias repository [" + configAttr.Name + "]", ex);
}
}
}
}
#endregion Private Instance Methods
#region Private Static Fields
/// <summary>
/// The fully qualified type of the DefaultRepositorySelector class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(DefaultRepositorySelector);
private const string DefaultRepositoryName = "log4net-default-repository";
#endregion Private Static Fields
#region Private Instance Fields
private readonly Hashtable m_name2repositoryMap = new Hashtable();
private readonly Hashtable m_assembly2repositoryMap = new Hashtable();
private readonly Hashtable m_alias2repositoryMap = new Hashtable();
private readonly Type m_defaultRepositoryType;
private event LoggerRepositoryCreationEventHandler m_loggerRepositoryCreatedEvent;
#endregion Private Instance Fields
}
}
#endif // !NETCF
| |
//-----------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// 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 Microsoft.IdentityModel.Test;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IdentityModel.Configuration;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel.Security;
using Attributes = System.IdentityModel.Tokens.JwtConfigurationStrings.Attributes;
using AttributeValues = System.IdentityModel.Tokens.JwtConfigurationStrings.AttributeValues;
using CertMode = System.ServiceModel.Security.X509CertificateValidationMode;
using Elements = System.IdentityModel.Tokens.JwtConfigurationStrings.Elements;
namespace System.IdentityModel.Test
{
public class ExpectedJwtSecurityTokenRequirement
{
public ExpectedJwtSecurityTokenRequirement
(
uint? tokenSize = null, Int32? clock = null, uint? life = null, X509CertificateValidator cert = null, string name = JwtConstants.ReservedClaims.Sub, string role = null, X509RevocationMode? revMode = null, X509CertificateValidationMode? certMode = null, StoreLocation? storeLoc = null, ExpectedException expectedException = null,
string handler = JwtSecurityTokenHandlerType, string requirement = Elements.JwtSecurityTokenRequirement,
string attributeEx1 = "", string attributeEx2 = "", string attributeEx3 = "", string attributeEx4 = "",
string elementEx1 = comment, string elementEx2 = comment, string elementEx3 = comment, string elementEx4 = comment, string elementEx5 = comment, string elementEx6 = comment,
string elementClose = closeRequirement
)
{
MaxTokenSizeInBytes = tokenSize;
NameClaimType = name;
RoleClaimType = role;
CertValidator = cert;
ClockSkewInSeconds = clock;
DefaultTokenLifetimeInMinutes = life;
CertRevocationMode = revMode;
CertValidationMode = certMode;
CertStoreLocation = storeLoc;
ExpectedException = expectedException ?? ExpectedException.NoExceptionExpected;
string[] sParams =
{
handler,
requirement,
CertRevocationMode == null ? string.Empty : Attribute( Attributes.RevocationMode, CertRevocationMode.Value.ToString() ),
attributeEx1,
CertValidationMode == null ? string.Empty : Attribute( Attributes.ValidationMode, CertValidationMode.Value.ToString() ),
attributeEx2,
CertValidator == null ? string.Empty : Attribute( Attributes.Validator, CertValidator.GetType().ToString() +", System.IdentityModel.Tokens.Jwt.Tests" ),
attributeEx3,
CertStoreLocation == null ? string.Empty : Attribute( Attributes.TrustedStoreLocation, CertStoreLocation.ToString() ),
attributeEx4,
elementEx1,
ClockSkewInSeconds == null ? string.Empty : ElementValue( Elements.MaxClockSkewInMinutes, ClockSkewInSeconds.Value.ToString() ),
elementEx2,
MaxTokenSizeInBytes == null ? string.Empty : ElementValue( Elements.MaxTokenSizeInBytes, MaxTokenSizeInBytes.Value.ToString() ),
elementEx3,
DefaultTokenLifetimeInMinutes == null ? string.Empty : ElementValue( Elements.DefaultTokenLifetimeInMinutes, DefaultTokenLifetimeInMinutes.Value.ToString() ),
elementEx4,
NameClaimType == null ? string.Empty : ElementValue( Elements.NameClaimType, NameClaimType ),
elementEx5,
RoleClaimType == null ? string.Empty : ElementValue( Elements.RoleClaimType, RoleClaimType ),
elementEx6,
elementClose,
};
Config = string.Format(ElementTemplate, sParams);
}
public bool AsExpected(JwtSecurityTokenRequirement requirement)
{
bool asExpected = true;
JwtSecurityTokenRequirement controlRequirement = new JwtSecurityTokenRequirement();
if (requirement == null)
{
return false;
}
Assert.IsFalse(
MaxTokenSizeInBytes != null && MaxTokenSizeInBytes.Value != requirement.MaximumTokenSizeInBytes,
string.Format(CultureInfo.InvariantCulture,
"MaximumTokenSizeInBytes (expected, config): '{0}'. '{1}'.",
MaxTokenSizeInBytes.ToString(),
requirement.MaximumTokenSizeInBytes.ToString()));
Assert.IsFalse(
MaxTokenSizeInBytes == null
&& requirement.MaximumTokenSizeInBytes != controlRequirement.MaximumTokenSizeInBytes,
string.Format(CultureInfo.InvariantCulture,
"MaximumTokenSizeInBytes should be default (default, config): '{0}'. '{1}'.",
controlRequirement.MaximumTokenSizeInBytes.ToString(),
requirement.MaximumTokenSizeInBytes.ToString()));
Assert.IsFalse(
ClockSkewInSeconds != null && ClockSkewInSeconds.Value != requirement.ClockSkewInSeconds,
string.Format(CultureInfo.InvariantCulture,
"ClockSkew (expected, config): '{0}'. '{1}'.",
ClockSkewInSeconds.ToString(),
requirement.ClockSkewInSeconds.ToString()));
Assert.IsFalse(
ClockSkewInSeconds == null && requirement.ClockSkewInSeconds != controlRequirement.ClockSkewInSeconds,
string.Format(CultureInfo.InvariantCulture,
"ClockSkew should be default (default, config): '{0}'. '{1}'.",
controlRequirement.ClockSkewInSeconds.ToString(),
requirement.ClockSkewInSeconds.ToString()));
Assert.IsFalse(
DefaultTokenLifetimeInMinutes != null
&& DefaultTokenLifetimeInMinutes.Value != requirement.DefaultTokenLifetimeInMinutes,
string.Format(CultureInfo.InvariantCulture,
"DefaultTokenLifetimeInMinutes (expected, config): '{0}'. '{1}'.",
DefaultTokenLifetimeInMinutes.ToString(),
requirement.DefaultTokenLifetimeInMinutes.ToString()));
Assert.IsFalse(
DefaultTokenLifetimeInMinutes == null
&& requirement.DefaultTokenLifetimeInMinutes != controlRequirement.DefaultTokenLifetimeInMinutes,
string.Format(CultureInfo.InvariantCulture,
"DefaultTokenLifetimeInMinutes should be default (default, config): '{0}'. '{1}'.",
controlRequirement.DefaultTokenLifetimeInMinutes.ToString(),
requirement.DefaultTokenLifetimeInMinutes.ToString()));
// make sure nameclaim and roleclaim are same, or null together.
Assert.IsFalse(NameClaimType == null && requirement.NameClaimType != null, "NameClaimType == null && requirement.NameClaimType != null");
Assert.IsFalse(NameClaimType != null && requirement.NameClaimType == null, "NameClaimType != null && requirement.NameClaimType == null");
if ((NameClaimType != null && requirement.NameClaimType != null)
&& (NameClaimType != requirement.NameClaimType))
{
Assert.Fail(string.Format(CultureInfo.InvariantCulture, "NameClaimType (expected, config): '{0}'. '{1}'.", NameClaimType, requirement.NameClaimType));
asExpected = false;
}
Assert.IsFalse(RoleClaimType == null && requirement.RoleClaimType != null, "RoleClaimType == null && requirement.RoleClaimType != null");
Assert.IsFalse(RoleClaimType != null && requirement.RoleClaimType == null, "RoleClaimType != null && requirement.RoleClaimType == null");
if ((RoleClaimType != null && requirement.RoleClaimType != null)
&& (RoleClaimType != requirement.RoleClaimType))
{
Assert.Fail(string.Format(CultureInfo.InvariantCulture, "RoleClaimType (expected, config): '{0}'. '{1}'.", RoleClaimType, requirement.RoleClaimType));
asExpected = false;
}
// != null => this variation sets a custom validator.
if (CertValidator != null)
{
if (requirement.CertificateValidator == null)
{
return false;
}
Assert.IsFalse(CertValidator.GetType() != requirement.CertificateValidator.GetType(), string.Format("CertificateValidator.GetType() != requirement.CertificateValidator.GetType(). (expected, config): '{0}'. '{1}'.", CertValidator.GetType(), requirement.CertificateValidator.GetType()));
}
else
{
if (CertValidationMode.HasValue || CertRevocationMode.HasValue || CertStoreLocation.HasValue)
{
Assert.IsFalse(requirement.CertificateValidator == null, string.Format("X509CertificateValidationMode.HasValue || X09RevocationMode.HasValue || StoreLocation.HasValue is true, there should be a validator"));
// get and check _certificateValidationMode
Type type = requirement.CertificateValidator.GetType();
FieldInfo fi = type.GetField("validator", BindingFlags.NonPublic | BindingFlags.Instance);
X509CertificateValidator validator = (X509CertificateValidator)fi.GetValue(requirement.CertificateValidator);
// make sure we created the right validator
if (CertValidationMode == CertMode.ChainTrust && (validator.GetType() != X509CertificateValidator.ChainTrust.GetType())
|| CertValidationMode == CertMode.PeerTrust && (validator.GetType() != X509CertificateValidator.PeerTrust.GetType())
|| CertValidationMode == CertMode.PeerOrChainTrust && (validator.GetType() != X509CertificateValidator.PeerOrChainTrust.GetType())
|| CertValidationMode == CertMode.None && (validator.GetType() != X509CertificateValidator.None.GetType()))
{
Assert.Fail(string.Format(CultureInfo.InvariantCulture, "X509CertificateValidator type. expected: '{0}', actual: '{1}'", CertValidationMode.HasValue ? CertValidationMode.Value.ToString() : "null", validator.GetType().ToString()));
asExpected = false;
}
// if these 'Modes' HasValue, then it should be matched, otherwise expect default.
fi = type.GetField("certificateValidationMode", BindingFlags.NonPublic | BindingFlags.Instance);
CertMode certMode = (CertMode)fi.GetValue(requirement.CertificateValidator);
if (CertValidationMode.HasValue)
{
Assert.IsFalse(CertValidationMode.Value != certMode, string.Format(CultureInfo.InvariantCulture, "X509CertificateValidationMode. expected: '{0}', actual: '{1}'", CertValidationMode.Value.ToString(), certMode.ToString()));
// if mode includes chain building, revocation mode Policy s/b null.
if (CertValidationMode.Value == X509CertificateValidationMode.ChainTrust
|| CertValidationMode.Value == X509CertificateValidationMode.PeerOrChainTrust)
{
// check inner policy
if (CertRevocationMode.HasValue)
{
fi = type.GetField("chainPolicy", BindingFlags.NonPublic | BindingFlags.Instance);
X509ChainPolicy chainPolicy =
(X509ChainPolicy)fi.GetValue(requirement.CertificateValidator);
Assert.IsFalse(
chainPolicy.RevocationMode != CertRevocationMode.Value,
string.Format(
CultureInfo.InvariantCulture,
"chainPolicy.RevocationMode. . expected: '{0}', actual: '{1}'",
CertRevocationMode.Value.ToString(),
chainPolicy.RevocationMode.ToString()));
}
}
}
}
}
return asExpected;
}
public uint? MaxTokenSizeInBytes { get; set; }
public Int32? ClockSkewInSeconds { get; set; }
public string NameClaimType { get; set; }
public string RoleClaimType { get; set; }
public X509CertificateValidator CertValidator { get; set; }
public uint? DefaultTokenLifetimeInMinutes { get; set; }
public X509RevocationMode? CertRevocationMode { get; set; }
public X509CertificateValidationMode? CertValidationMode { get; set; }
public StoreLocation? CertStoreLocation { get; set; }
public ExpectedException ExpectedException { get; set; }
public string Config { get; set; }
public const string ElementTemplate = @"<add type='{0}'><{1} {2} {3} {4} {5} {6} {7} {8} {9} >{10}{11}{12}{13}{14}{15}{16}{17}{18}{19}{20}{21}</add>";
public const string JwtSecurityTokenHandlerType = "System.IdentityModel.Tokens.JwtSecurityTokenHandler, System.IdentityModel.Tokens.Jwt";
public const string AlwaysSucceedCertificateValidator = "System.IdentityModel.Test.AlwaysSucceedCertificateValidator, System.IdentityModel.Tokens.Jwt.Test";
public const string comment = @"<!-- Comment -->";
public const string closeRequirement = "</" + Elements.JwtSecurityTokenRequirement + ">";
public static string CloseElement(string element) { return "</" + element + ">"; }
public static string ElementValue(string element, string value) { return "<" + element + " " + Attributes.Value + "='" + value + "' />"; }
public static string Attribute(string attribute, string value) { return attribute + "='" + value + "'"; }
public string[] StringParams(string handler = JwtSecurityTokenHandlerType, string requirement = Elements.JwtSecurityTokenRequirement,
string attributeEx1 = "", string attributeEx2 = "", string attributeEx3 = "", string attributeEx4 = "",
string elementEx1 = comment, string elementEx2 = comment, string elementEx3 = comment, string elementEx4 = comment, string elementEx5 = comment, string elementEx6 = comment,
string elementClose = closeRequirement)
{
return new string[]
{
handler,
requirement,
CertRevocationMode == null ? string.Empty : Attribute( Attributes.RevocationMode, CertRevocationMode.Value.ToString() ),
attributeEx1,
CertValidationMode == null ? string.Empty : Attribute( Attributes.ValidationMode, CertValidationMode.Value.ToString() ),
attributeEx2,
CertValidator == null ? string.Empty : Attribute( Attributes.Validator, CertValidator.GetType().ToString() +", System.IdentityModel.Tokens.JWT.Test" ),
attributeEx3,
CertStoreLocation == null ? string.Empty : Attribute( Attributes.TrustedStoreLocation, CertStoreLocation.ToString() ),
attributeEx4,
elementEx1,
ClockSkewInSeconds == null ? string.Empty : ElementValue( Elements.MaxClockSkewInMinutes, ClockSkewInSeconds.Value.ToString() ),
elementEx2,
MaxTokenSizeInBytes == null ? string.Empty : ElementValue( Elements.MaxTokenSizeInBytes, MaxTokenSizeInBytes.Value.ToString() ),
elementEx3,
DefaultTokenLifetimeInMinutes == null ? string.Empty : ElementValue( Elements.DefaultTokenLifetimeInMinutes, DefaultTokenLifetimeInMinutes.Value.ToString() ),
elementEx4,
NameClaimType == null ? string.Empty : ElementValue( Elements.NameClaimType, NameClaimType ),
elementEx5,
RoleClaimType == null ? string.Empty : ElementValue( Elements.RoleClaimType, RoleClaimType ),
elementEx6,
elementClose,
};
}
};
public class JwtHandlerConfigVariation
{
public ExpectedJwtSecurityTokenRequirement ExpectedJwtSecurityTokenRequirement { get; set; }
public JwtSecurityTokenHandler ExpectedSecurityTokenHandler { get; set; }
public static List<ExpectedJwtSecurityTokenRequirement> RequirementVariations;
public static string ElementValue(string element, string value, string attributeValue = Attributes.Value, int count = 1)
{
string attributePart = string.Empty;
string postfix = string.Empty;
for (int i = 0; i < count; i++)
{
attributePart += attributeValue + (i == 0 ? string.Empty : i.ToString()) + "='" + value + "' ";
}
return "<" + element + " " + attributePart + " />";
}
//public static string ElementValue( string element, string value, string attributeValue = Attributes.Value ) { return "<" + element + " " + attributeValue + "='" + value + "' />"; }
public static string ElementValueMultipleAttributes(string element, string value, string value2) { return "<" + element + " " + Attributes.Value + "='" + value + " " + Attributes.Value + "='" + value2 + "' />"; }
public static string Attribute(string attribute, string value) { return attribute + "='" + value + "'"; }
public static void BuildExpectedRequirements()
{
RequirementVariations = new List<ExpectedJwtSecurityTokenRequirement>();
// Empty Element
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(elementEx1: "<>", expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "initialize", inner: typeof(ConfigurationErrorsException))));
// unknown element
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(elementEx1: ElementValue("UnknownElement", "@http://AllItemsSet/nameClaim"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10611")));
// element.Localname empty
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(elementEx1: ElementValue("", "@http://AllItemsSet/nameClaim"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "initialize", inner: typeof(ConfigurationErrorsException))));
// Element attribute name is not 'value'
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(elementEx1: ElementValue(Elements.DefaultTokenLifetimeInMinutes, "6000", attributeValue: "NOTvalue"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10610:")));
// Attribute name empty
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(attributeEx1: Attribute("", AttributeValues.X509CertificateValidationModeChainTrust), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "initialize", inner: typeof(ConfigurationErrorsException))));
// Attribute value empty
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(attributeEx1: Attribute(Attributes.ValidationMode, ""), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10600", inner: typeof(InvalidOperationException))));
// Multiple Attributes
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(elementEx1: ElementValue(Elements.NameClaimType, "Bob", count: 2), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10609")));
// No Attributes
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(elementEx1: ElementValue(Elements.NameClaimType, "Bob", count: 0), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10607")));
// for each variation, make sure a validator is created.
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(revMode: X509RevocationMode.NoCheck, storeLoc: StoreLocation.CurrentUser, certMode: X509CertificateValidationMode.ChainTrust, expectedException: ExpectedException.NoExceptionExpected));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(revMode: X509RevocationMode.Offline, expectedException: ExpectedException.NoExceptionExpected));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(revMode: X509RevocationMode.Online, expectedException: ExpectedException.NoExceptionExpected));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(certMode: X509CertificateValidationMode.ChainTrust, expectedException: ExpectedException.NoExceptionExpected));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(certMode: X509CertificateValidationMode.Custom, expectedException: ExpectedException.ConfigurationErrorsException("Jwt10612")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(certMode: X509CertificateValidationMode.None, expectedException: ExpectedException.NoExceptionExpected));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(certMode: X509CertificateValidationMode.PeerOrChainTrust, expectedException: ExpectedException.NoExceptionExpected));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(certMode: X509CertificateValidationMode.PeerTrust, expectedException: ExpectedException.NoExceptionExpected));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(storeLoc: StoreLocation.CurrentUser, expectedException: ExpectedException.NoExceptionExpected));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(storeLoc: StoreLocation.LocalMachine, expectedException: ExpectedException.NoExceptionExpected));
// Error Conditions - lifetime
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(life: 0, expectedException: ExpectedException.ConfigurationErrorsException(inner: typeof(ArgumentOutOfRangeException), substringExpected: "Jwt10603")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(elementEx1: ElementValue(Elements.DefaultTokenLifetimeInMinutes, "-1"), expectedException: ExpectedException.ConfigurationErrorsException(inner: typeof(ArgumentOutOfRangeException), substringExpected: "Jwt10603")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(elementEx1: ElementValue(Elements.DefaultTokenLifetimeInMinutes, "abc"), expectedException: ExpectedException.ConfigurationErrorsException(inner: typeof(FormatException))));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(elementEx1: ElementValue(Elements.DefaultTokenLifetimeInMinutes, "15372286729"), expectedException: ExpectedException.ConfigurationErrorsException(inner: typeof(OverflowException))));
// Error Conditions - tokensSize
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(tokenSize: 0, expectedException: ExpectedException.ConfigurationErrorsException(inner: typeof(ArgumentOutOfRangeException), substringExpected: "Jwt10603")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(elementEx1: ElementValue(Elements.MaxTokenSizeInBytes, "-1"), expectedException: ExpectedException.ConfigurationErrorsException(inner: typeof(ArgumentOutOfRangeException), substringExpected: "Jwt10603")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(elementEx1: ElementValue(Elements.MaxTokenSizeInBytes, "abc"), expectedException: ExpectedException.ConfigurationErrorsException(inner: typeof(FormatException))));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(elementEx1: ElementValue(Elements.MaxTokenSizeInBytes, "4294967296"), expectedException: ExpectedException.ConfigurationErrorsException(inner: typeof(OverflowException))));
// Duplicate Elements, we have to catch them.
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(tokenSize: 1000, revMode: X509RevocationMode.NoCheck, elementEx1: ElementValue(Elements.MaxTokenSizeInBytes, "1024"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10616")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(tokenSize: 1000, revMode: X509RevocationMode.NoCheck, elementEx3: ElementValue(Elements.MaxTokenSizeInBytes, "1024"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10616")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(name: @"http://AllItemsSet/nameClaim", revMode: X509RevocationMode.NoCheck, elementEx3: ElementValue(Elements.NameClaimType, "1024"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10616")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(name: @"http://AllItemsSet/nameClaim", revMode: X509RevocationMode.NoCheck, elementEx5: ElementValue(Elements.NameClaimType, "1024"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10616")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(role: @"http://AllItemsSet/roleClaim", revMode: X509RevocationMode.NoCheck, elementEx3: ElementValue(Elements.RoleClaimType, "1024"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10616")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(role: @"http://AllItemsSet/roleClaim", revMode: X509RevocationMode.NoCheck, elementEx6: ElementValue(Elements.RoleClaimType, "1024"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10616")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(clock: 15, certMode: X509CertificateValidationMode.PeerTrust, elementEx1: ElementValue(Elements.MaxClockSkewInMinutes, "5"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10616")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(clock: 15, revMode: X509RevocationMode.NoCheck, elementEx2: ElementValue(Elements.MaxClockSkewInMinutes, "5"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10616")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(life: 1000, revMode: X509RevocationMode.NoCheck, elementEx1: ElementValue(Elements.DefaultTokenLifetimeInMinutes, "60"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10616")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(life: 1000, revMode: X509RevocationMode.NoCheck, elementEx4: ElementValue(Elements.DefaultTokenLifetimeInMinutes, "60"), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10616")));
// Duplicate Attributes, System.Configuration will catch them.
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(revMode: X509RevocationMode.NoCheck, attributeEx1: Attribute(Attributes.RevocationMode, AttributeValues.X509RevocationModeNoCheck.ToString()), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "initialize", inner: typeof(ConfigurationErrorsException))));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(certMode: X509CertificateValidationMode.PeerTrust, attributeEx2: Attribute(Attributes.ValidationMode, AttributeValues.X509CertificateValidationModeNone.ToString()), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "initialize", inner: typeof(ConfigurationErrorsException))));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(storeLoc: StoreLocation.LocalMachine, attributeEx4: Attribute(Attributes.TrustedStoreLocation, StoreLocation.LocalMachine.ToString()), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "initialize", inner: typeof(ConfigurationErrorsException))));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(cert: new AlwaysSucceedCertificateValidator(), attributeEx1: Attribute(Attributes.Validator, typeof(AlwaysSucceedCertificateValidator).ToString()), expectedException: ExpectedException.ConfigurationErrorsException(substringExpected: "initialize", inner: typeof(ConfigurationErrorsException))));
// certificate validator *40
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(certMode: X509CertificateValidationMode.Custom, cert: new AlwaysSucceedCertificateValidator()));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(tokenSize: 1000));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(tokenSize: 2147483647));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(name: @"http://AllItemsSet/nameClaim"));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(role: @"http://AllItemsSet/roleClaim"));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(cert: new AlwaysSucceedCertificateValidator(), expectedException: ExpectedException.ConfigurationErrorsException("Jwt10619")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(clock: 15));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(name: @"http://AllItemsSet/nameClaim", role: @"http://AllItemsSet/roleClaim"));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(cert: new AlwaysSucceedCertificateValidator(), clock: 15, expectedException: ExpectedException.ConfigurationErrorsException("Jwt10619")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(tokenSize: 1000, name: @"http://AllItemsSet/nameClaim", role: @"http://AllItemsSet/roleClaim", clock: 15));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(tokenSize: 1000, name: @"http://AllItemsSet/nameClaim", role: @"http://AllItemsSet/roleClaim", clock: 15, cert: new AlwaysSucceedCertificateValidator(), certMode: X509CertificateValidationMode.Custom));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(tokenSize: 1000, name: @"http://AllItemsSet/nameClaim", role: @"http://AllItemsSet/roleClaim", clock: 15, cert: new AlwaysSucceedCertificateValidator(), expectedException: ExpectedException.ConfigurationErrorsException("Jwt10619")));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(role: @"http://AllItemsSet/roleClaim", cert: new AlwaysSucceedCertificateValidator(), clock: 15, certMode: X509CertificateValidationMode.Custom));
RequirementVariations.Add(new ExpectedJwtSecurityTokenRequirement(certMode: X509CertificateValidationMode.PeerTrust, cert: new AlwaysSucceedCertificateValidator(), expectedException: ExpectedException.ConfigurationErrorsException("Jwt10619")));
}
public static ExpectedJwtSecurityTokenRequirement Variation(string variation)
{
if (RequirementVariations == null)
{
BuildExpectedRequirements();
}
return RequirementVariations[Convert.ToInt32(variation)];
}
//public static JwtHandlerConfigVariation BuildVariation( Int32 variation )
//{
// return new JwtHandlerConfigVariation()
// {
// ExpectedSecurityTokenHandler = new JwtSecurityTokenHandler(),
// ExpectedJwtSecurityTokenRequirement = RequirementVariations[variation],
// };
//}
}
[TestClass]
public class JwtSecurityTokenHandlerConfigTest : ConfigurationTest
{
static Dictionary<string, string> _testCases = new Dictionary<string, string>();
public static string ElementValue(string element, string value, string attributeValue = Attributes.Value, int count = 1)
{
string attributePart = string.Empty;
string postfix = string.Empty;
for (int i = 0; i < count; i++)
{
attributePart += attributeValue + (i == 0 ? string.Empty : i.ToString()) + "='" + value + "' ";
}
return "<" + element + " " + attributePart + " />";
}
//public static string ElementValue( string element, string value, string attributeValue = Attributes.Value ) { return "<" + element + " " + attributeValue + "='" + value + "' />"; }
public static string ElementValueMultipleAttributes(string element, string value, string value2) { return "<" + element + " " + Attributes.Value + "='" + value + " " + Attributes.Value + "='" + value2 + "' />"; }
public static string Attribute(string attribute, string value) { return attribute + "='" + value + "'"; }
/// <summary>
/// Test Context Wrapper instance on top of TestContext. Provides better accessor functions
/// </summary>
protected TestContextProvider _testContextProvider;
public JwtSecurityTokenHandlerConfigTest()
{
}
[ClassInitialize]
public static void ClassSetup(TestContext testContext)
{
}
[TestInitialize]
public void Initialize()
{
_testContextProvider = new TestContextProvider(TestContext);
}
/// <summary>
/// The test context that is set by Visual Studio and TAEF - need to keep this exact signature
/// </summary>
public TestContext TestContext { get; set; }
protected override string GetConfiguration(string variationId)
{
ExpectedJwtSecurityTokenRequirement variation = JwtHandlerConfigVariation.Variation(variationId);
string config = @"<system.identityModel><identityConfiguration><securityTokenHandlers>"
+ variation.Config
+ @"</securityTokenHandlers></identityConfiguration></system.identityModel>";
Console.WriteLine(string.Format("\n===================================\nTesting variation: '{0}'\nConfig:\n{1}", variationId, config));
return config;
}
protected override void ValidateTestCase(string variationId)
{
ExpectedJwtSecurityTokenRequirement variation = JwtHandlerConfigVariation.Variation(variationId);
try
{
IdentityConfiguration identityConfig = new IdentityConfiguration(IdentityConfiguration.DefaultServiceName);
variation.ExpectedException.ProcessNoException();
VerifyConfig(identityConfig, variation);
}
catch (Exception ex)
{
try
{
variation.ExpectedException.ProcessException(ex);
}
catch (Exception innerException)
{
Assert.Fail("\nConfig case failed:\n'{0}'\nConfig:\n'{1}'\nException:\n'{2}'.", variationId, variation.Config, innerException.ToString());
}
}
}
private void VerifyConfig(IdentityConfiguration identityconfig, ExpectedJwtSecurityTokenRequirement variation)
{
JwtSecurityTokenHandler handler = identityconfig.SecurityTokenHandlers[typeof(JwtSecurityToken)] as JwtSecurityTokenHandler;
Assert.IsFalse(!variation.AsExpected(handler.JwtSecurityTokenRequirement), "JwtSecurityTokenRequirement was not as expected");
}
[TestMethod]
[TestProperty("TestCaseID", "1E62250E-9208-4917-8677-0C82EFE6823E")]
[Description("JwtSecurityTokenHandler Configuration Tests")]
public void JwtSecurityTokenHandler_ConfigTests()
{
JwtHandlerConfigVariation.BuildExpectedRequirements();
for (int i = 39; i < JwtHandlerConfigVariation.RequirementVariations.Count; i++)
{
RunTestCase(i.ToString());
}
}
}
}
| |
/**
* 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.
*/
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Generated from: class_hierarchy.proto
namespace Org.Apache.REEF.Tang.Protobuf
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"Node")]
public partial class Node : global::ProtoBuf.IExtensible
{
public Node() {}
private string _name;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"name", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string name
{
get { return _name; }
set { _name = value; }
}
private string _full_name;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"full_name", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string full_name
{
get { return _full_name; }
set { _full_name = value; }
}
private ClassNode _class_node = null;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"class_node", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public ClassNode class_node
{
get { return _class_node; }
set { _class_node = value; }
}
private NamedParameterNode _named_parameter_node = null;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"named_parameter_node", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public NamedParameterNode named_parameter_node
{
get { return _named_parameter_node; }
set { _named_parameter_node = value; }
}
private PackageNode _package_node = null;
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"package_node", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public PackageNode package_node
{
get { return _package_node; }
set { _package_node = value; }
}
private readonly global::System.Collections.Generic.List<Node> _children = new global::System.Collections.Generic.List<Node>();
[global::ProtoBuf.ProtoMember(6, Name=@"children", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<Node> children
{
get { return _children; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ClassNode")]
public partial class ClassNode : global::ProtoBuf.IExtensible
{
public ClassNode() {}
private bool _is_injection_candidate;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"is_injection_candidate", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool is_injection_candidate
{
get { return _is_injection_candidate; }
set { _is_injection_candidate = value; }
}
private bool _is_external_constructor;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"is_external_constructor", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool is_external_constructor
{
get { return _is_external_constructor; }
set { _is_external_constructor = value; }
}
private bool _is_unit;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"is_unit", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool is_unit
{
get { return _is_unit; }
set { _is_unit = value; }
}
private readonly global::System.Collections.Generic.List<ConstructorDef> _InjectableConstructors = new global::System.Collections.Generic.List<ConstructorDef>();
[global::ProtoBuf.ProtoMember(4, Name=@"InjectableConstructors", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<ConstructorDef> InjectableConstructors
{
get { return _InjectableConstructors; }
}
private readonly global::System.Collections.Generic.List<ConstructorDef> _OtherConstructors = new global::System.Collections.Generic.List<ConstructorDef>();
[global::ProtoBuf.ProtoMember(5, Name=@"OtherConstructors", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<ConstructorDef> OtherConstructors
{
get { return _OtherConstructors; }
}
private readonly global::System.Collections.Generic.List<string> _impl_full_names = new global::System.Collections.Generic.List<string>();
[global::ProtoBuf.ProtoMember(6, Name=@"impl_full_names", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<string> impl_full_names
{
get { return _impl_full_names; }
}
private string _default_implementation = "";
[global::ProtoBuf.ProtoMember(7, IsRequired = false, Name=@"default_implementation", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string default_implementation
{
get { return _default_implementation; }
set { _default_implementation = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"NamedParameterNode")]
public partial class NamedParameterNode : global::ProtoBuf.IExtensible
{
public NamedParameterNode() {}
private string _simple_arg_class_name;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"simple_arg_class_name", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string simple_arg_class_name
{
get { return _simple_arg_class_name; }
set { _simple_arg_class_name = value; }
}
private string _full_arg_class_name;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"full_arg_class_name", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string full_arg_class_name
{
get { return _full_arg_class_name; }
set { _full_arg_class_name = value; }
}
private bool _is_set;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"is_set", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool is_set
{
get { return _is_set; }
set { _is_set = value; }
}
private bool _is_list;
[global::ProtoBuf.ProtoMember(4, IsRequired = true, Name=@"is_list", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool is_list
{
get { return _is_list; }
set { _is_list = value; }
}
private string _documentation = "";
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"documentation", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string documentation
{
get { return _documentation; }
set { _documentation = value; }
}
private string _short_name = "";
[global::ProtoBuf.ProtoMember(6, IsRequired = false, Name=@"short_name", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string short_name
{
get { return _short_name; }
set { _short_name = value; }
}
private readonly global::System.Collections.Generic.List<string> _instance_default = new global::System.Collections.Generic.List<string>();
[global::ProtoBuf.ProtoMember(7, Name=@"instance_default", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<string> instance_default
{
get { return _instance_default; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PackageNode")]
public partial class PackageNode : global::ProtoBuf.IExtensible
{
public PackageNode() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ConstructorDef")]
public partial class ConstructorDef : global::ProtoBuf.IExtensible
{
public ConstructorDef() {}
private string _full_class_name;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"full_class_name", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string full_class_name
{
get { return _full_class_name; }
set { _full_class_name = value; }
}
private readonly global::System.Collections.Generic.List<ConstructorArg> _args = new global::System.Collections.Generic.List<ConstructorArg>();
[global::ProtoBuf.ProtoMember(2, Name=@"args", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<ConstructorArg> args
{
get { return _args; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ConstructorArg")]
public partial class ConstructorArg : global::ProtoBuf.IExtensible
{
public ConstructorArg() {}
private string _full_arg_class_name;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"full_arg_class_name", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string full_arg_class_name
{
get { return _full_arg_class_name; }
set { _full_arg_class_name = value; }
}
private string _named_parameter_name = "";
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"named_parameter_name", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string named_parameter_name
{
get { return _named_parameter_name; }
set { _named_parameter_name = value; }
}
private bool _is_injection_future;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"is_injection_future", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool is_injection_future
{
get { return _is_injection_future; }
set { _is_injection_future = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This Class defines behaviors specific to a writing system.
// A writing system is the collection of scripts and
// orthographic rules required to represent a language as text.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Text;
namespace System.Globalization
{
[Serializable]
public partial class TextInfo : ICloneable, IDeserializationCallback
{
////--------------------------------------------------------------------//
//// Internal Information //
////--------------------------------------------------------------------//
private enum Tristate : byte
{
NotInitialized,
True,
False,
}
////
//// Variables.
////
[OptionalField(VersionAdded = 2)]
private String _listSeparator;
[OptionalField(VersionAdded = 2)]
private bool _isReadOnly = false;
//// _cultureName is the name of the creating culture. Note that we consider this authoratative,
//// if the culture's textinfo changes when deserializing, then behavior may change.
//// (ala Whidbey behavior). This is the only string Arrowhead needs to serialize.
//// _cultureData is the data that backs this class.
//// _textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO)
//// this can be the same as _cultureName on Silverlight since the OS knows
//// how to do the sorting. However in the desktop, when we call the sorting dll, it doesn't
//// know how to resolve custom locle names to sort ids so we have to have alredy resolved this.
////
[OptionalField(VersionAdded = 3)]
private String _cultureName; // Name of the culture that created this text info
[NonSerialized]
private CultureData _cultureData; // Data record for the culture that made us, not for this textinfo
[NonSerialized]
private String _textInfoName; // Name of the text info we're using (ie: _cultureData.STEXTINFO)
[NonSerialized]
private Tristate _isAsciiCasingSameAsInvariant = Tristate.NotInitialized;
// _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant
[NonSerialized]
private readonly bool _invariantMode = GlobalizationMode.Invariant;
// Invariant text info
internal static TextInfo Invariant
{
get
{
if (s_Invariant == null)
s_Invariant = new TextInfo(CultureData.Invariant);
return s_Invariant;
}
}
internal volatile static TextInfo s_Invariant;
//////////////////////////////////////////////////////////////////////////
////
//// TextInfo Constructors
////
//// Implements CultureInfo.TextInfo.
////
//////////////////////////////////////////////////////////////////////////
internal unsafe TextInfo(CultureData cultureData)
{
// This is our primary data source, we don't need most of the rest of this
_cultureData = cultureData;
_cultureName = _cultureData.CultureName;
_textInfoName = _cultureData.STEXTINFO;
FinishInitialization(_textInfoName);
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx) { }
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
// Clear these so we can check if we've fixed them yet
_cultureData = null;
_cultureName = null;
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
OnDeserialized();
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
OnDeserialized();
}
private void OnDeserialized()
{
// this method will be called twice because of the support of IDeserializationCallback
if (_cultureData == null)
{
// Get the text info name belonging to that culture
_cultureData = CultureInfo.GetCultureInfo(_cultureName)._cultureData;
_textInfoName = _cultureData.STEXTINFO;
FinishInitialization(_textInfoName);
}
}
//
// Internal ordinal comparison functions
//
internal static int GetHashCodeOrdinalIgnoreCase(String s)
{
// This is the same as an case insensitive hash for Invariant
// (not necessarily true for sorting, but OK for casing & then we apply normal hash code rules)
return (Invariant.GetCaseInsensitiveHashCode(s));
}
// Currently we don't have native functions to do this, so we do it the hard way
internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
if (count > source.Length || count < 0 || startIndex < 0 || startIndex >= source.Length || startIndex + count > source.Length)
{
return -1;
}
return CultureInfo.InvariantCulture.CompareInfo.IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
// Currently we don't have native functions to do this, so we do it the hard way
internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
if (count > source.Length || count < 0 || startIndex < 0 || startIndex > source.Length - 1 || (startIndex - count + 1 < 0))
{
return -1;
}
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
////////////////////////////////////////////////////////////////////////
//
// CodePage
//
// Returns the number of the code page used by this writing system.
// The type parameter can be any of the following values:
// ANSICodePage
// OEMCodePage
// MACCodePage
//
////////////////////////////////////////////////////////////////////////
public virtual int ANSICodePage
{
get
{
return (_cultureData.IDEFAULTANSICODEPAGE);
}
}
public virtual int OEMCodePage
{
get
{
return (_cultureData.IDEFAULTOEMCODEPAGE);
}
}
public virtual int MacCodePage
{
get
{
return (_cultureData.IDEFAULTMACCODEPAGE);
}
}
public virtual int EBCDICCodePage
{
get
{
return (_cultureData.IDEFAULTEBCDICCODEPAGE);
}
}
public int LCID
{
get
{
// Just use the LCID from our text info name
return CultureInfo.GetCultureInfo(_textInfoName).LCID;
}
}
//////////////////////////////////////////////////////////////////////////
////
//// CultureName
////
//// The name of the culture associated with the current TextInfo.
////
//////////////////////////////////////////////////////////////////////////
public string CultureName
{
get
{
return _textInfoName;
}
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
public bool IsReadOnly
{
get { return (_isReadOnly); }
}
//////////////////////////////////////////////////////////////////////////
////
//// Clone
////
//// Is the implementation of ICloneable.
////
//////////////////////////////////////////////////////////////////////////
public virtual object Clone()
{
object o = MemberwiseClone();
((TextInfo)o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
public static TextInfo ReadOnly(TextInfo textInfo)
{
if (textInfo == null) { throw new ArgumentNullException(nameof(textInfo)); }
Contract.EndContractBlock();
if (textInfo.IsReadOnly) { return (textInfo); }
TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone());
clonedTextInfo.SetReadOnlyState(true);
return (clonedTextInfo);
}
private void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
_isReadOnly = readOnly;
}
////////////////////////////////////////////////////////////////////////
//
// ListSeparator
//
// Returns the string used to separate items in a list.
//
////////////////////////////////////////////////////////////////////////
public virtual String ListSeparator
{
get
{
if (_listSeparator == null)
{
_listSeparator = _cultureData.SLIST;
}
return (_listSeparator);
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String);
}
VerifyWritable();
_listSeparator = value;
}
}
////////////////////////////////////////////////////////////////////////
//
// ToLower
//
// Converts the character or string to lower case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual char ToLower(char c)
{
if (_invariantMode || (IsAscii(c) && IsAsciiCasingSameAsInvariant))
{
return ToLowerAsciiInvariant(c);
}
return (ChangeCase(c, toUpper: false));
}
public unsafe virtual String ToLower(String str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
if (_invariantMode)
{
return ToLowerAsciiInvariant(str);
}
return ChangeCase(str, toUpper: false);
}
private unsafe string ToLowerAsciiInvariant(string s)
{
if (s.Length == 0)
{
return string.Empty;
}
fixed (char* pSource = s)
{
int i = 0;
while (i < s.Length)
{
if ((uint)(pSource[i] - 'A') <= (uint)('Z' - 'A'))
{
break;
}
i++;
}
if (i >= s.Length)
{
return s;
}
string result = string.FastAllocateString(s.Length);
fixed (char* pResult = result)
{
for (int j = 0; j < i; j++)
{
pResult[j] = pSource[j];
}
pResult[i] = (Char)(pSource[i] | 0x20);
i++;
while (i < s.Length)
{
pResult[i] = ToLowerAsciiInvariant(pSource[i]);
i++;
}
}
return result;
}
}
private unsafe string ToUpperAsciiInvariant(string s)
{
if (s.Length == 0)
{
return string.Empty;
}
fixed (char* pSource = s)
{
int i = 0;
while (i < s.Length)
{
if ((uint)(pSource[i] - 'a') <= (uint)('z' - 'a'))
{
break;
}
i++;
}
if (i >= s.Length)
{
return s;
}
string result = string.FastAllocateString(s.Length);
fixed (char* pResult = result)
{
for (int j = 0; j < i; j++)
{
pResult[j] = pSource[j];
}
pResult[i] = (char)(pSource[i] & ~0x20);
i++;
while (i < s.Length)
{
pResult[i] = ToUpperAsciiInvariant(pSource[i]);
i++;
}
}
return result;
}
}
private static Char ToLowerAsciiInvariant(Char c)
{
if ((uint)(c - 'A') <= (uint)('Z' - 'A'))
{
c = (Char)(c | 0x20);
}
return c;
}
////////////////////////////////////////////////////////////////////////
//
// ToUpper
//
// Converts the character or string to upper case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual char ToUpper(char c)
{
if (_invariantMode || (IsAscii(c) && IsAsciiCasingSameAsInvariant))
{
return ToUpperAsciiInvariant(c);
}
return (ChangeCase(c, toUpper: true));
}
public unsafe virtual String ToUpper(String str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
if (_invariantMode)
{
return ToUpperAsciiInvariant(str);
}
return ChangeCase(str, toUpper: true);
}
private static Char ToUpperAsciiInvariant(Char c)
{
if ((uint)(c - 'a') <= (uint)('z' - 'a'))
{
c = (Char)(c & ~0x20);
}
return c;
}
private static bool IsAscii(Char c)
{
return c < 0x80;
}
private bool IsAsciiCasingSameAsInvariant
{
get
{
if (_isAsciiCasingSameAsInvariant == Tristate.NotInitialized)
{
_isAsciiCasingSameAsInvariant = CultureInfo.GetCultureInfo(_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
CompareOptions.IgnoreCase) == 0 ? Tristate.True : Tristate.False;
}
return _isAsciiCasingSameAsInvariant == Tristate.True;
}
}
// IsRightToLeft
//
// Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars
//
public bool IsRightToLeft
{
get
{
return _cultureData.IsRightToLeft;
}
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CultureInfo as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object obj)
{
TextInfo that = obj as TextInfo;
if (that != null)
{
return this.CultureName.Equals(that.CultureName);
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for CultureInfo A
// and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.CultureName.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// TextInfo.
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return ("TextInfo - " + _cultureData.CultureName);
}
//
// Titlecasing:
// -----------
// Titlecasing refers to a casing practice wherein the first letter of a word is an uppercase letter
// and the rest of the letters are lowercase. The choice of which words to titlecase in headings
// and titles is dependent on language and local conventions. For example, "The Merry Wives of Windor"
// is the appropriate titlecasing of that play's name in English, with the word "of" not titlecased.
// In German, however, the title is "Die lustigen Weiber von Windsor," and both "lustigen" and "von"
// are not titlecased. In French even fewer words are titlecased: "Les joyeuses commeres de Windsor."
//
// Moreover, the determination of what actually constitutes a word is language dependent, and this can
// influence which letter or letters of a "word" are uppercased when titlecasing strings. For example
// "l'arbre" is considered two words in French, whereas "can't" is considered one word in English.
//
public unsafe String ToTitleCase(String str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
if (str.Length == 0)
{
return (str);
}
StringBuilder result = new StringBuilder();
string lowercaseData = null;
// Store if the current culture is Dutch (special case)
bool isDutchCulture = CultureName.StartsWith("nl-", StringComparison.OrdinalIgnoreCase);
for (int i = 0; i < str.Length; i++)
{
UnicodeCategory charType;
int charLen;
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
if (Char.CheckLetter(charType))
{
// Special case to check for Dutch specific titlecasing with "IJ" characters
// at the beginning of a word
if (isDutchCulture && i < str.Length - 1 && (str[i] == 'i' || str[i] == 'I') && (str[i+1] == 'j' || str[i+1] == 'J'))
{
result.Append("IJ");
i += 2;
}
else
{
// Do the titlecasing for the first character of the word.
i = AddTitlecaseLetter(ref result, ref str, i, charLen) + 1;
}
//
// Convert the characters until the end of the this word
// to lowercase.
//
int lowercaseStart = i;
//
// Use hasLowerCase flag to prevent from lowercasing acronyms (like "URT", "USA", etc)
// This is in line with Word 2000 behavior of titlecasing.
//
bool hasLowerCase = (charType == UnicodeCategory.LowercaseLetter);
// Use a loop to find all of the other letters following this letter.
while (i < str.Length)
{
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
if (IsLetterCategory(charType))
{
if (charType == UnicodeCategory.LowercaseLetter)
{
hasLowerCase = true;
}
i += charLen;
}
else if (str[i] == '\'')
{
i++;
if (hasLowerCase)
{
if (lowercaseData == null)
{
lowercaseData = this.ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, i - lowercaseStart);
}
else
{
result.Append(str, lowercaseStart, i - lowercaseStart);
}
lowercaseStart = i;
hasLowerCase = true;
}
else if (!IsWordSeparator(charType))
{
// This category is considered to be part of the word.
// This is any category that is marked as false in wordSeprator array.
i+= charLen;
}
else
{
// A word separator. Break out of the loop.
break;
}
}
int count = i - lowercaseStart;
if (count > 0)
{
if (hasLowerCase)
{
if (lowercaseData == null)
{
lowercaseData = this.ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, count);
}
else
{
result.Append(str, lowercaseStart, count);
}
}
if (i < str.Length)
{
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
else
{
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
return (result.ToString());
}
private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
if (charLen == 2)
{
// Surrogate pair
result.Append(input[inputIndex++]);
result.Append(input[inputIndex]);
}
else
{
result.Append(input[inputIndex]);
}
return inputIndex;
}
private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
// for surrogate pairs do a simple ToUpper operation on the substring
if (charLen == 2)
{
// Surrogate pair
result.Append(ToUpper(input.Substring(inputIndex, charLen)));
inputIndex++;
}
else
{
switch (input[inputIndex])
{
//
// For AppCompat, the Titlecase Case Mapping data from NDP 2.0 is used below.
case (char) 0x01C4: // DZ with Caron -> Dz with Caron
case (char) 0x01C5: // Dz with Caron -> Dz with Caron
case (char) 0x01C6: // dz with Caron -> Dz with Caron
result.Append((char) 0x01C5);
break;
case (char) 0x01C7: // LJ -> Lj
case (char) 0x01C8: // Lj -> Lj
case (char) 0x01C9: // lj -> Lj
result.Append((char) 0x01C8);
break;
case (char) 0x01CA: // NJ -> Nj
case (char) 0x01CB: // Nj -> Nj
case (char) 0x01CC: // nj -> Nj
result.Append((char) 0x01CB);
break;
case (char) 0x01F1: // DZ -> Dz
case (char) 0x01F2: // Dz -> Dz
case (char) 0x01F3: // dz -> Dz
result.Append((char) 0x01F2);
break;
default:
result.Append(ToUpper(input[inputIndex]));
break;
}
}
return inputIndex;
}
//
// Used in ToTitleCase():
// When we find a starting letter, the following array decides if a category should be
// considered as word seprator or not.
//
private const int c_wordSeparatorMask =
/* false */ (0 << 0) | // UppercaseLetter = 0,
/* false */ (0 << 1) | // LowercaseLetter = 1,
/* false */ (0 << 2) | // TitlecaseLetter = 2,
/* false */ (0 << 3) | // ModifierLetter = 3,
/* false */ (0 << 4) | // OtherLetter = 4,
/* false */ (0 << 5) | // NonSpacingMark = 5,
/* false */ (0 << 6) | // SpacingCombiningMark = 6,
/* false */ (0 << 7) | // EnclosingMark = 7,
/* false */ (0 << 8) | // DecimalDigitNumber = 8,
/* false */ (0 << 9) | // LetterNumber = 9,
/* false */ (0 << 10) | // OtherNumber = 10,
/* true */ (1 << 11) | // SpaceSeparator = 11,
/* true */ (1 << 12) | // LineSeparator = 12,
/* true */ (1 << 13) | // ParagraphSeparator = 13,
/* true */ (1 << 14) | // Control = 14,
/* true */ (1 << 15) | // Format = 15,
/* false */ (0 << 16) | // Surrogate = 16,
/* false */ (0 << 17) | // PrivateUse = 17,
/* true */ (1 << 18) | // ConnectorPunctuation = 18,
/* true */ (1 << 19) | // DashPunctuation = 19,
/* true */ (1 << 20) | // OpenPunctuation = 20,
/* true */ (1 << 21) | // ClosePunctuation = 21,
/* true */ (1 << 22) | // InitialQuotePunctuation = 22,
/* true */ (1 << 23) | // FinalQuotePunctuation = 23,
/* true */ (1 << 24) | // OtherPunctuation = 24,
/* true */ (1 << 25) | // MathSymbol = 25,
/* true */ (1 << 26) | // CurrencySymbol = 26,
/* true */ (1 << 27) | // ModifierSymbol = 27,
/* true */ (1 << 28) | // OtherSymbol = 28,
/* false */ (0 << 29); // OtherNotAssigned = 29;
private static bool IsWordSeparator(UnicodeCategory category)
{
return (c_wordSeparatorMask & (1 << (int) category)) != 0;
}
private static bool IsLetterCategory(UnicodeCategory uc)
{
return (uc == UnicodeCategory.UppercaseLetter
|| uc == UnicodeCategory.LowercaseLetter
|| uc == UnicodeCategory.TitlecaseLetter
|| uc == UnicodeCategory.ModifierLetter
|| uc == UnicodeCategory.OtherLetter);
}
//
// Get case-insensitive hash code for the specified string.
//
internal unsafe int GetCaseInsensitiveHashCode(String str)
{
// Validate inputs
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
// This code assumes that ASCII casing is safe for whatever context is passed in.
// this is true today, because we only ever call these methods on Invariant. It would be ideal to refactor
// these methods so they were correct by construction and we could only ever use Invariant.
uint hash = 5381;
uint c;
// Note: We assume that str contains only ASCII characters until
// we hit a non-ASCII character to optimize the common case.
for (int i = 0; i < str.Length; i++)
{
c = str[i];
if (c >= 0x80)
{
return GetCaseInsensitiveHashCodeSlow(str);
}
// If we have a lowercase character, ANDing off 0x20
// will make it an uppercase character.
if ((c - 'a') <= ('z' - 'a'))
{
c = (uint)((int)c & ~0x20);
}
hash = ((hash << 5) + hash) ^ c;
}
return (int)hash;
}
private unsafe int GetCaseInsensitiveHashCodeSlow(String str)
{
Debug.Assert(str != null);
string upper = ToUpper(str);
uint hash = 5381;
uint c;
for (int i = 0; i < upper.Length; i++)
{
c = upper[i];
hash = ((hash << 5) + hash) ^ c;
}
return (int)hash;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
///This file contains all the typed enums that the client rest api spec exposes.
///This file is automatically generated from https://github.com/elasticsearch/elasticsearch-rest-api-spec
///Generated of commit 5f64a7f7e8
namespace Elasticsearch.Net
{
public enum ConsistencyOptions
{
[EnumMember(Value = "one")]
One,
[EnumMember(Value = "quorum")]
Quorum,
[EnumMember(Value = "all")]
All
}
public enum ReplicationOptions
{
[EnumMember(Value = "sync")]
Sync,
[EnumMember(Value = "async")]
Async
}
public enum BytesOptions
{
[EnumMember(Value = "b")]
B,
[EnumMember(Value = "k")]
K,
[EnumMember(Value = "m")]
M,
[EnumMember(Value = "g")]
G
}
public enum LevelOptions
{
[EnumMember(Value = "cluster")]
Cluster,
[EnumMember(Value = "indices")]
Indices,
[EnumMember(Value = "shards")]
Shards
}
public enum WaitForStatusOptions
{
[EnumMember(Value = "green")]
Green,
[EnumMember(Value = "yellow")]
Yellow,
[EnumMember(Value = "red")]
Red
}
public enum ExpandWildcardsOptions
{
[EnumMember(Value = "open")]
Open,
[EnumMember(Value = "closed")]
Closed
}
public enum VersionTypeOptions
{
[EnumMember(Value = "internal")]
Internal,
[EnumMember(Value = "external")]
External,
[EnumMember(Value = "external_gte")]
ExternalGte,
[EnumMember(Value = "force")]
Force
}
public enum DefaultOperatorOptions
{
[EnumMember(Value = "AND")]
And,
[EnumMember(Value = "OR")]
Or
}
public enum OpTypeOptions
{
[EnumMember(Value = "index")]
Index,
[EnumMember(Value = "create")]
Create
}
public enum FormatOptions
{
[EnumMember(Value = "detailed")]
Detailed,
[EnumMember(Value = "text")]
Text
}
public enum SearchTypeOptions
{
[EnumMember(Value = "query_then_fetch")]
QueryThenFetch,
[EnumMember(Value = "query_and_fetch")]
QueryAndFetch,
[EnumMember(Value = "dfs_query_then_fetch")]
DfsQueryThenFetch,
[EnumMember(Value = "dfs_query_and_fetch")]
DfsQueryAndFetch,
[EnumMember(Value = "count")]
Count,
[EnumMember(Value = "scan")]
Scan
}
public enum TypeOptions
{
[EnumMember(Value = "cpu")]
Cpu,
[EnumMember(Value = "wait")]
Wait,
[EnumMember(Value = "block")]
Block
}
public enum SuggestModeOptions
{
[EnumMember(Value = "missing")]
Missing,
[EnumMember(Value = "popular")]
Popular,
[EnumMember(Value = "always")]
Always
}
public enum ClusterStateMetric
{
[EnumMember(Value = "_all")]
All,
[EnumMember(Value = "blocks")]
Blocks,
[EnumMember(Value = "metadata")]
Metadata,
[EnumMember(Value = "nodes")]
Nodes,
[EnumMember(Value = "routing_table")]
RoutingTable,
[EnumMember(Value = "master_node")]
MasterNode,
[EnumMember(Value = "version")]
Version
}
public enum IndicesStatsMetric
{
[EnumMember(Value = "_all")]
All,
[EnumMember(Value = "completion")]
Completion,
[EnumMember(Value = "docs")]
Docs,
[EnumMember(Value = "fielddata")]
Fielddata,
[EnumMember(Value = "filter_cache")]
FilterCache,
[EnumMember(Value = "flush")]
Flush,
[EnumMember(Value = "get")]
Get,
[EnumMember(Value = "id_cache")]
IdCache,
[EnumMember(Value = "indexing")]
Indexing,
[EnumMember(Value = "merge")]
Merge,
[EnumMember(Value = "percolate")]
Percolate,
[EnumMember(Value = "refresh")]
Refresh,
[EnumMember(Value = "search")]
Search,
[EnumMember(Value = "segments")]
Segments,
[EnumMember(Value = "store")]
Store,
[EnumMember(Value = "warmer")]
Warmer
}
public enum NodesInfoMetric
{
[EnumMember(Value = "settings")]
Settings,
[EnumMember(Value = "os")]
Os,
[EnumMember(Value = "process")]
Process,
[EnumMember(Value = "jvm")]
Jvm,
[EnumMember(Value = "thread_pool")]
ThreadPool,
[EnumMember(Value = "network")]
Network,
[EnumMember(Value = "transport")]
Transport,
[EnumMember(Value = "http")]
Http,
[EnumMember(Value = "plugins")]
Plugins
}
public enum NodesStatsMetric
{
[EnumMember(Value = "_all")]
All,
[EnumMember(Value = "breaker")]
Breaker,
[EnumMember(Value = "fs")]
Fs,
[EnumMember(Value = "http")]
Http,
[EnumMember(Value = "indices")]
Indices,
[EnumMember(Value = "jvm")]
Jvm,
[EnumMember(Value = "network")]
Network,
[EnumMember(Value = "os")]
Os,
[EnumMember(Value = "process")]
Process,
[EnumMember(Value = "thread_pool")]
ThreadPool,
[EnumMember(Value = "transport")]
Transport
}
public enum NodesStatsIndexMetric
{
[EnumMember(Value = "_all")]
All,
[EnumMember(Value = "completion")]
Completion,
[EnumMember(Value = "docs")]
Docs,
[EnumMember(Value = "fielddata")]
Fielddata,
[EnumMember(Value = "filter_cache")]
FilterCache,
[EnumMember(Value = "flush")]
Flush,
[EnumMember(Value = "get")]
Get,
[EnumMember(Value = "id_cache")]
IdCache,
[EnumMember(Value = "indexing")]
Indexing,
[EnumMember(Value = "merge")]
Merge,
[EnumMember(Value = "percolate")]
Percolate,
[EnumMember(Value = "refresh")]
Refresh,
[EnumMember(Value = "search")]
Search,
[EnumMember(Value = "segments")]
Segments,
[EnumMember(Value = "store")]
Store,
[EnumMember(Value = "warmer")]
Warmer
}
public static class KnownEnums
{
public static string Resolve(Enum e)
{
if (e is ConsistencyOptions)
{
switch((ConsistencyOptions)e)
{
case ConsistencyOptions.One: return "one";
case ConsistencyOptions.Quorum: return "quorum";
case ConsistencyOptions.All: return "all";
}
}
if (e is ReplicationOptions)
{
switch((ReplicationOptions)e)
{
case ReplicationOptions.Sync: return "sync";
case ReplicationOptions.Async: return "async";
}
}
if (e is BytesOptions)
{
switch((BytesOptions)e)
{
case BytesOptions.B: return "b";
case BytesOptions.K: return "k";
case BytesOptions.M: return "m";
case BytesOptions.G: return "g";
}
}
if (e is LevelOptions)
{
switch((LevelOptions)e)
{
case LevelOptions.Cluster: return "cluster";
case LevelOptions.Indices: return "indices";
case LevelOptions.Shards: return "shards";
}
}
if (e is WaitForStatusOptions)
{
switch((WaitForStatusOptions)e)
{
case WaitForStatusOptions.Green: return "green";
case WaitForStatusOptions.Yellow: return "yellow";
case WaitForStatusOptions.Red: return "red";
}
}
if (e is ExpandWildcardsOptions)
{
switch((ExpandWildcardsOptions)e)
{
case ExpandWildcardsOptions.Open: return "open";
case ExpandWildcardsOptions.Closed: return "closed";
}
}
if (e is VersionTypeOptions)
{
switch((VersionTypeOptions)e)
{
case VersionTypeOptions.Internal: return "internal";
case VersionTypeOptions.External: return "external";
case VersionTypeOptions.ExternalGte: return "external_gte";
case VersionTypeOptions.Force: return "force";
}
}
if (e is DefaultOperatorOptions)
{
switch((DefaultOperatorOptions)e)
{
case DefaultOperatorOptions.And: return "AND";
case DefaultOperatorOptions.Or: return "OR";
}
}
if (e is OpTypeOptions)
{
switch((OpTypeOptions)e)
{
case OpTypeOptions.Index: return "index";
case OpTypeOptions.Create: return "create";
}
}
if (e is FormatOptions)
{
switch((FormatOptions)e)
{
case FormatOptions.Detailed: return "detailed";
case FormatOptions.Text: return "text";
}
}
if (e is SearchTypeOptions)
{
switch((SearchTypeOptions)e)
{
case SearchTypeOptions.QueryThenFetch: return "query_then_fetch";
case SearchTypeOptions.QueryAndFetch: return "query_and_fetch";
case SearchTypeOptions.DfsQueryThenFetch: return "dfs_query_then_fetch";
case SearchTypeOptions.DfsQueryAndFetch: return "dfs_query_and_fetch";
case SearchTypeOptions.Count: return "count";
case SearchTypeOptions.Scan: return "scan";
}
}
if (e is TypeOptions)
{
switch((TypeOptions)e)
{
case TypeOptions.Cpu: return "cpu";
case TypeOptions.Wait: return "wait";
case TypeOptions.Block: return "block";
}
}
if (e is SuggestModeOptions)
{
switch((SuggestModeOptions)e)
{
case SuggestModeOptions.Missing: return "missing";
case SuggestModeOptions.Popular: return "popular";
case SuggestModeOptions.Always: return "always";
}
}
if (e is ClusterStateMetric)
{
switch((ClusterStateMetric)e)
{
case ClusterStateMetric.All: return "_all";
case ClusterStateMetric.Blocks: return "blocks";
case ClusterStateMetric.Metadata: return "metadata";
case ClusterStateMetric.Nodes: return "nodes";
case ClusterStateMetric.RoutingTable: return "routing_table";
case ClusterStateMetric.MasterNode: return "master_node";
case ClusterStateMetric.Version: return "version";
}
}
if (e is IndicesStatsMetric)
{
switch((IndicesStatsMetric)e)
{
case IndicesStatsMetric.All: return "_all";
case IndicesStatsMetric.Completion: return "completion";
case IndicesStatsMetric.Docs: return "docs";
case IndicesStatsMetric.Fielddata: return "fielddata";
case IndicesStatsMetric.FilterCache: return "filter_cache";
case IndicesStatsMetric.Flush: return "flush";
case IndicesStatsMetric.Get: return "get";
case IndicesStatsMetric.IdCache: return "id_cache";
case IndicesStatsMetric.Indexing: return "indexing";
case IndicesStatsMetric.Merge: return "merge";
case IndicesStatsMetric.Percolate: return "percolate";
case IndicesStatsMetric.Refresh: return "refresh";
case IndicesStatsMetric.Search: return "search";
case IndicesStatsMetric.Segments: return "segments";
case IndicesStatsMetric.Store: return "store";
case IndicesStatsMetric.Warmer: return "warmer";
}
}
if (e is NodesInfoMetric)
{
switch((NodesInfoMetric)e)
{
case NodesInfoMetric.Settings: return "settings";
case NodesInfoMetric.Os: return "os";
case NodesInfoMetric.Process: return "process";
case NodesInfoMetric.Jvm: return "jvm";
case NodesInfoMetric.ThreadPool: return "thread_pool";
case NodesInfoMetric.Network: return "network";
case NodesInfoMetric.Transport: return "transport";
case NodesInfoMetric.Http: return "http";
case NodesInfoMetric.Plugins: return "plugins";
}
}
if (e is NodesStatsMetric)
{
switch((NodesStatsMetric)e)
{
case NodesStatsMetric.All: return "_all";
case NodesStatsMetric.Breaker: return "breaker";
case NodesStatsMetric.Fs: return "fs";
case NodesStatsMetric.Http: return "http";
case NodesStatsMetric.Indices: return "indices";
case NodesStatsMetric.Jvm: return "jvm";
case NodesStatsMetric.Network: return "network";
case NodesStatsMetric.Os: return "os";
case NodesStatsMetric.Process: return "process";
case NodesStatsMetric.ThreadPool: return "thread_pool";
case NodesStatsMetric.Transport: return "transport";
}
}
if (e is NodesStatsIndexMetric)
{
switch((NodesStatsIndexMetric)e)
{
case NodesStatsIndexMetric.All: return "_all";
case NodesStatsIndexMetric.Completion: return "completion";
case NodesStatsIndexMetric.Docs: return "docs";
case NodesStatsIndexMetric.Fielddata: return "fielddata";
case NodesStatsIndexMetric.FilterCache: return "filter_cache";
case NodesStatsIndexMetric.Flush: return "flush";
case NodesStatsIndexMetric.Get: return "get";
case NodesStatsIndexMetric.IdCache: return "id_cache";
case NodesStatsIndexMetric.Indexing: return "indexing";
case NodesStatsIndexMetric.Merge: return "merge";
case NodesStatsIndexMetric.Percolate: return "percolate";
case NodesStatsIndexMetric.Refresh: return "refresh";
case NodesStatsIndexMetric.Search: return "search";
case NodesStatsIndexMetric.Segments: return "segments";
case NodesStatsIndexMetric.Store: return "store";
case NodesStatsIndexMetric.Warmer: return "warmer";
}
}
return "UNKNOWNENUM";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
[assembly: SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Scope = "type", Target = "System.ComponentModel.BindingList`1")]
namespace System.ComponentModel
{
[Serializable]
[TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class BindingList<T> : Collection<T>, IBindingList, ICancelAddNew, IRaiseItemChangedEvents
{
private int addNewPos = -1; // Do not rename (binary serialization)
private bool raiseListChangedEvents = true; // Do not rename (binary serialization)
private bool raiseItemChangedEvents; // Do not rename (binary serialization)
[NonSerialized]
private PropertyDescriptorCollection _itemTypeProperties;
[NonSerialized]
private PropertyChangedEventHandler _propertyChangedEventHandler;
[NonSerialized]
private AddingNewEventHandler _onAddingNew;
[NonSerialized]
private ListChangedEventHandler _onListChanged;
[NonSerialized]
private int _lastChangeIndex = -1;
private bool allowNew = true; // Do not rename (binary serialization)
private bool allowEdit = true; // Do not rename (binary serialization)
private bool allowRemove = true; // Do not rename (binary serialization)
private bool userSetAllowNew; // Do not rename (binary serialization)
#region Constructors
public BindingList() => Initialize();
/// <summary>
/// Constructor that allows substitution of the inner list with a custom list.
/// </summary>
public BindingList(IList<T> list) : base(list)
{
Initialize();
}
private void Initialize()
{
// Set the default value of AllowNew based on whether type T has a default constructor
allowNew = ItemTypeHasDefaultConstructor;
// Check for INotifyPropertyChanged
if (typeof(INotifyPropertyChanged).IsAssignableFrom(typeof(T)))
{
// Supports INotifyPropertyChanged
raiseItemChangedEvents = true;
// Loop thru the items already in the collection and hook their change notification.
foreach (T item in Items)
{
HookPropertyChanged(item);
}
}
}
private bool ItemTypeHasDefaultConstructor
{
get
{
Type itemType = typeof(T);
if (itemType.IsPrimitive)
{
return true;
}
const BindingFlags BindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance;
return itemType.GetConstructor(BindingFlags, null, Array.Empty<Type>(), null) != null;
}
}
#endregion
#region AddingNew event
/// <summary>
/// Event that allows a custom item to be provided as the new item added to the list by AddNew().
/// </summary>
public event AddingNewEventHandler AddingNew
{
add
{
bool allowNewWasTrue = AllowNew;
_onAddingNew += value;
if (allowNewWasTrue != AllowNew)
{
FireListChanged(ListChangedType.Reset, -1);
}
}
remove
{
bool allowNewWasTrue = AllowNew;
_onAddingNew -= value;
if (allowNewWasTrue != AllowNew)
{
FireListChanged(ListChangedType.Reset, -1);
}
}
}
/// <summary>
/// Raises the AddingNew event.
/// </summary>
protected virtual void OnAddingNew(AddingNewEventArgs e) => _onAddingNew?.Invoke(this, e);
// Private helper method
private object FireAddingNew()
{
AddingNewEventArgs e = new AddingNewEventArgs(null);
OnAddingNew(e);
return e.NewObject;
}
#endregion
#region ListChanged event
/// <summary>
/// Event that reports changes to the list or to items in the list.
/// </summary>
public event ListChangedEventHandler ListChanged
{
add => _onListChanged += value;
remove => _onListChanged -= value;
}
/// <summary>
/// Raises the ListChanged event.
/// </summary>
protected virtual void OnListChanged(ListChangedEventArgs e) => _onListChanged?.Invoke(this, e);
public bool RaiseListChangedEvents
{
get => raiseListChangedEvents;
set => raiseListChangedEvents = value;
}
public void ResetBindings() => FireListChanged(ListChangedType.Reset, -1);
public void ResetItem(int position)
{
FireListChanged(ListChangedType.ItemChanged, position);
}
// Private helper method
private void FireListChanged(ListChangedType type, int index)
{
if (raiseListChangedEvents)
{
OnListChanged(new ListChangedEventArgs(type, index));
}
}
#endregion
#region Collection<T> overrides
// Collection<T> funnels all list changes through the four virtual methods below.
// We override these so that we can commit any pending new item and fire the proper ListChanged events.
protected override void ClearItems()
{
EndNew(addNewPos);
if (raiseItemChangedEvents)
{
foreach (T item in Items)
{
UnhookPropertyChanged(item);
}
}
base.ClearItems();
FireListChanged(ListChangedType.Reset, -1);
}
protected override void InsertItem(int index, T item)
{
EndNew(addNewPos);
base.InsertItem(index, item);
if (raiseItemChangedEvents)
{
HookPropertyChanged(item);
}
FireListChanged(ListChangedType.ItemAdded, index);
}
protected override void RemoveItem(int index)
{
// Need to all RemoveItem if this on the AddNew item
if (!allowRemove && !(addNewPos >= 0 && addNewPos == index))
{
throw new NotSupportedException();
}
EndNew(addNewPos);
if (raiseItemChangedEvents)
{
UnhookPropertyChanged(this[index]);
}
base.RemoveItem(index);
FireListChanged(ListChangedType.ItemDeleted, index);
}
protected override void SetItem(int index, T item)
{
if (raiseItemChangedEvents)
{
UnhookPropertyChanged(this[index]);
}
base.SetItem(index, item);
if (raiseItemChangedEvents)
{
HookPropertyChanged(item);
}
FireListChanged(ListChangedType.ItemChanged, index);
}
#endregion
#region ICancelAddNew interface
/// <summary>
/// If item added using AddNew() is still cancellable, then remove that item from the list.
/// </summary>
public virtual void CancelNew(int itemIndex)
{
if (addNewPos >= 0 && addNewPos == itemIndex)
{
RemoveItem(addNewPos);
addNewPos = -1;
}
}
/// <summary>
/// If item added using AddNew() is still cancellable, then commit that item.
/// </summary>
public virtual void EndNew(int itemIndex)
{
if (addNewPos >= 0 && addNewPos == itemIndex)
{
addNewPos = -1;
}
}
#endregion
#region IBindingList interface
/// <summary>
/// Adds a new item to the list. Calls <see cref='AddNewCore'> to create and add the item.
///
/// Add operations are cancellable via the <see cref='ICancelAddNew'> interface. The position of the
/// new item is tracked until the add operation is either cancelled by a call to <see cref='CancelNew'>,
/// explicitly commited by a call to <see cref='EndNew'>, or implicitly commmited some other operation
/// changes the contents of the list (such as an Insert or Remove). When an add operation is
/// cancelled, the new item is removed from the list.
/// </summary>
public T AddNew() => (T)((this as IBindingList).AddNew());
object IBindingList.AddNew()
{
// Create new item and add it to list
object newItem = AddNewCore();
// Record position of new item (to support cancellation later on)
addNewPos = (newItem != null) ? IndexOf((T)newItem) : -1;
// Return new item to caller
return newItem;
}
private bool AddingNewHandled => _onAddingNew != null && _onAddingNew.GetInvocationList().Length > 0;
/// <summary>
/// Creates a new item and adds it to the list.
///
/// The base implementation raises the AddingNew event to allow an event handler to
/// supply a custom item to add to the list. Otherwise an item of type T is created.
/// The new item is then added to the end of the list.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods")]
protected virtual object AddNewCore()
{
// Allow event handler to supply the new item for us
object newItem = FireAddingNew();
// If event hander did not supply new item, create one ourselves
if (newItem == null)
{
Type type = typeof(T);
newItem = SecurityUtils.SecureCreateInstance(type);
}
// Add item to end of list. Note: If event handler returned an item not of type T,
// the cast below will trigger an InvalidCastException. This is by design.
Add((T)newItem);
// Return new item to caller
return newItem;
}
/// <summary>
/// </summary>
public bool AllowNew
{
get
{
// If the user set AllowNew, return what they set. If we have a default constructor, allowNew will be
// true and we should just return true.
if (userSetAllowNew || allowNew)
{
return allowNew;
}
// Even if the item doesn't have a default constructor, the user can hook AddingNew to provide an item.
// If there's a handler for this, we should allow new.
return AddingNewHandled;
}
set
{
bool oldAllowNewValue = AllowNew;
userSetAllowNew = true;
// Note that we don't want to set allowNew only if AllowNew didn't match value,
// since AllowNew can depend on onAddingNew handler
allowNew = value;
if (oldAllowNewValue != value)
{
FireListChanged(ListChangedType.Reset, -1);
}
}
}
bool IBindingList.AllowNew => AllowNew;
public bool AllowEdit
{
get => allowEdit;
set
{
if (allowEdit != value)
{
allowEdit = value;
FireListChanged(ListChangedType.Reset, -1);
}
}
}
bool IBindingList.AllowEdit => AllowEdit;
public bool AllowRemove
{
get => allowRemove;
set
{
if (allowRemove != value)
{
allowRemove = value;
FireListChanged(ListChangedType.Reset, -1);
}
}
}
bool IBindingList.AllowRemove => AllowRemove;
bool IBindingList.SupportsChangeNotification => SupportsChangeNotificationCore;
protected virtual bool SupportsChangeNotificationCore => true;
bool IBindingList.SupportsSearching => SupportsSearchingCore;
protected virtual bool SupportsSearchingCore => false;
bool IBindingList.SupportsSorting => SupportsSortingCore;
protected virtual bool SupportsSortingCore => false;
bool IBindingList.IsSorted => IsSortedCore;
protected virtual bool IsSortedCore => false;
PropertyDescriptor IBindingList.SortProperty => SortPropertyCore;
protected virtual PropertyDescriptor SortPropertyCore => null;
ListSortDirection IBindingList.SortDirection => SortDirectionCore;
protected virtual ListSortDirection SortDirectionCore => ListSortDirection.Ascending;
void IBindingList.ApplySort(PropertyDescriptor prop, ListSortDirection direction)
{
ApplySortCore(prop, direction);
}
protected virtual void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
throw new NotSupportedException();
}
void IBindingList.RemoveSort() => RemoveSortCore();
protected virtual void RemoveSortCore()
{
throw new NotSupportedException();
}
int IBindingList.Find(PropertyDescriptor prop, object key) => FindCore(prop, key);
protected virtual int FindCore(PropertyDescriptor prop, object key)
{
throw new NotSupportedException();
}
void IBindingList.AddIndex(PropertyDescriptor prop)
{
// Not supported
}
void IBindingList.RemoveIndex(PropertyDescriptor prop)
{
// Not supported
}
#endregion
#region Property Change Support
private void HookPropertyChanged(T item)
{
// Note: inpc may be null if item is null, so always check.
if (item is INotifyPropertyChanged inpc)
{
if (_propertyChangedEventHandler == null)
{
_propertyChangedEventHandler = new PropertyChangedEventHandler(Child_PropertyChanged);
}
inpc.PropertyChanged += _propertyChangedEventHandler;
}
}
private void UnhookPropertyChanged(T item)
{
// Note: inpc may be null if item is null, so always check.
if (item is INotifyPropertyChanged inpc && _propertyChangedEventHandler != null)
{
inpc.PropertyChanged -= _propertyChangedEventHandler;
}
}
private void Child_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (RaiseListChangedEvents)
{
if (sender == null || e == null || string.IsNullOrEmpty(e.PropertyName))
{
// Fire reset event (per INotifyPropertyChanged spec)
ResetBindings();
}
else
{
// The change event is broken should someone pass an item to us that is not
// of type T. Still, if they do so, detect it and ignore. It is an incorrect
// and rare enough occurrence that we do not want to slow the mainline path
// with "is" checks.
T item;
try
{
item = (T)sender;
}
catch (InvalidCastException)
{
ResetBindings();
return;
}
// Find the position of the item. This should never be -1. If it is,
// somehow the item has been removed from our list without our knowledge.
int pos = _lastChangeIndex;
if (pos < 0 || pos >= Count || !this[pos].Equals(item))
{
pos = IndexOf(item);
_lastChangeIndex = pos;
}
if (pos == -1)
{
// The item was removed from the list but we still get change notifications or
// the sender is invalid and was never added to the list.
UnhookPropertyChanged(item);
ResetBindings();
}
else
{
// Get the property descriptor
if (null == _itemTypeProperties)
{
// Get Shape
_itemTypeProperties = TypeDescriptor.GetProperties(typeof(T));
Debug.Assert(_itemTypeProperties != null);
}
PropertyDescriptor pd = _itemTypeProperties.Find(e.PropertyName, true);
// Create event args. If there was no matching property descriptor,
// we raise the list changed anyway.
ListChangedEventArgs args = new ListChangedEventArgs(ListChangedType.ItemChanged, pos, pd);
// Fire the ItemChanged event
OnListChanged(args);
}
}
}
}
#endregion
#region IRaiseItemChangedEvents interface
/// <summary>
/// Returns false to indicate that BindingList<T> does NOT raise ListChanged events
/// of type ItemChanged as a result of property changes on individual list items
/// unless those items support INotifyPropertyChanged.
/// </summary>
bool IRaiseItemChangedEvents.RaisesItemChangedEvents => raiseItemChangedEvents;
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.Libraryagent.v1
{
/// <summary>The Libraryagent Service.</summary>
public class LibraryagentService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public LibraryagentService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public LibraryagentService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Shelves = new ShelvesResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "libraryagent";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://libraryagent.googleapis.com/";
#else
"https://libraryagent.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://libraryagent.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Library Agent API.</summary>
public class Scope
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Library Agent API.</summary>
public static class ScopeConstants
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Gets the Shelves resource.</summary>
public virtual ShelvesResource Shelves { get; }
}
/// <summary>A base abstract class for Libraryagent requests.</summary>
public abstract class LibraryagentBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new LibraryagentBaseServiceRequest instance.</summary>
protected LibraryagentBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Libraryagent parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "shelves" collection of methods.</summary>
public class ShelvesResource
{
private const string Resource = "shelves";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ShelvesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Books = new BooksResource(service);
}
/// <summary>Gets the Books resource.</summary>
public virtual BooksResource Books { get; }
/// <summary>The "books" collection of methods.</summary>
public class BooksResource
{
private const string Resource = "books";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public BooksResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Borrow a book from the library. Returns the book if it is borrowed successfully. Returns NOT_FOUND if
/// the book does not exist in the library. Returns quota exceeded error if the amount of books borrowed
/// exceeds allocation quota in any dimensions.
/// </summary>
/// <param name="name">Required. The name of the book to borrow.</param>
public virtual BorrowRequest Borrow(string name)
{
return new BorrowRequest(service, name);
}
/// <summary>
/// Borrow a book from the library. Returns the book if it is borrowed successfully. Returns NOT_FOUND if
/// the book does not exist in the library. Returns quota exceeded error if the amount of books borrowed
/// exceeds allocation quota in any dimensions.
/// </summary>
public class BorrowRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Book>
{
/// <summary>Constructs a new Borrow request.</summary>
public BorrowRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the book to borrow.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "borrow";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:borrow";
/// <summary>Initializes Borrow parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^shelves/[^/]+/books/[^/]+$",
});
}
}
/// <summary>Gets a book. Returns NOT_FOUND if the book does not exist.</summary>
/// <param name="name">Required. The name of the book to retrieve.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets a book. Returns NOT_FOUND if the book does not exist.</summary>
public class GetRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Book>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the book to retrieve.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^shelves/[^/]+/books/[^/]+$",
});
}
}
/// <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>
/// <param name="parent">Required. The name of the shelf whose books we'd like to list.</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <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 class ListRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1ListBooksResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The name of the shelf whose books we'd like to list.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Requested page size. Server may return fewer books than requested. If unspecified, server will pick
/// an appropriate default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// A token identifying a page of results the server should return. Typically, this is the value of
/// ListBooksResponse.next_page_token. returned from the previous call to `ListBooks` method.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/books";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^shelves/[^/]+$",
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Return a book to the library. Returns the book if it is returned to the library successfully. Returns
/// error if the book does not belong to the library or the users didn't borrow before.
/// </summary>
/// <param name="name">Required. The name of the book to return.</param>
public virtual LibraryagentReturnRequest LibraryagentReturn(string name)
{
return new LibraryagentReturnRequest(service, name);
}
/// <summary>
/// Return a book to the library. Returns the book if it is returned to the library successfully. Returns
/// error if the book does not belong to the library or the users didn't borrow before.
/// </summary>
public class LibraryagentReturnRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Book>
{
/// <summary>Constructs a new LibraryagentReturn request.</summary>
public LibraryagentReturnRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the book to return.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "return";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:return";
/// <summary>Initializes LibraryagentReturn parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^shelves/[^/]+/books/[^/]+$",
});
}
}
}
/// <summary>Gets a shelf. Returns NOT_FOUND if the shelf does not exist.</summary>
/// <param name="name">Required. The name of the shelf to retrieve.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets a shelf. Returns NOT_FOUND if the shelf does not exist.</summary>
public class GetRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Shelf>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the shelf to retrieve.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^shelves/[^/]+$",
});
}
}
/// <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 ListRequest List()
{
return new ListRequest(service);
}
/// <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 class ListRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1ListShelvesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service) : base(service)
{
InitParameters();
}
/// <summary>
/// Requested page size. Server may return fewer shelves than requested. If unspecified, server will pick an
/// appropriate default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// A token identifying a page of results the server should return. Typically, this is the value of
/// ListShelvesResponse.next_page_token returned from the previous call to `ListShelves` method.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/shelves";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Libraryagent.v1.Data
{
/// <summary>A single book in the library.</summary>
public class GoogleExampleLibraryagentV1Book : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The name of the book author.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("author")]
public virtual string Author { get; set; }
/// <summary>
/// The resource name of the book. Book names have the form `shelves/{shelf_id}/books/{book_id}`. The name is
/// ignored when creating a book.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Value indicating whether the book has been read.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("read")]
public virtual System.Nullable<bool> Read { get; set; }
/// <summary>The title of the book.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for LibraryAgent.ListBooks.</summary>
public class GoogleExampleLibraryagentV1ListBooksResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of books.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("books")]
public virtual System.Collections.Generic.IList<GoogleExampleLibraryagentV1Book> Books { get; set; }
/// <summary>
/// A token to retrieve next page of results. Pass this value in the ListBooksRequest.page_token field in the
/// subsequent call to `ListBooks` method to retrieve the next page of results.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for LibraryAgent.ListShelves.</summary>
public class GoogleExampleLibraryagentV1ListShelvesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// A token to retrieve next page of results. Pass this value in the ListShelvesRequest.page_token field in the
/// subsequent call to `ListShelves` method to retrieve the next page of results.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The list of shelves.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("shelves")]
public virtual System.Collections.Generic.IList<GoogleExampleLibraryagentV1Shelf> Shelves { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A Shelf contains a collection of books with a theme.</summary>
public class GoogleExampleLibraryagentV1Shelf : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. The resource name of the shelf. Shelf names have the form `shelves/{shelf_id}`. The name is
/// ignored when creating a shelf.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The theme of the shelf</summary>
[Newtonsoft.Json.JsonPropertyAttribute("theme")]
public virtual string Theme { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
using System.Diagnostics;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Bloom.Properties;
using Bloom.Publish.BloomLibrary;
using L10NSharp;
using SIL.Code;
using SIL.Reporting;
namespace Bloom.WebLibraryIntegration
{
/// <summary>
/// this class manages the login process for Bloom, including signing up for new accounts.
/// (This is a bit clumsy, but makes it easy to switch to login if the user enters a known address,
/// or switch to signup if the user tries to log in with an unknown email.
/// It also saves passing another object around.)
/// Much of this logic unfortunately is or will be duplicated in the web site itself.
/// We may at some point consider embedding a part of the web site itself in a Gecko window instead for login;
/// but in the current state of my (JohnT's) knowledge, it was easier to do a plain C# version.
/// </summary>
public partial class LoginDialog : SIL.Windows.Forms.Miscellaneous.FormForUsingPortableClipboard
{
private BloomParseClient _client;
private int _originalHeight;
public LoginDialog(BloomParseClient client)
{
Require.That(client != null);
_client = client;
InitializeComponent();
_showPasswordCheckBox.Checked = Settings.Default.WebShowPassword;
oldText = this.Text;
oldLogin = _loginButton.Text;
_originalHeight = Height;
ShowTermsOfUse(false);
}
private void Login(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(_emailBox.Text))
{
Settings.Default.WebUserId = _emailBox.Text;
Settings.Default.WebPassword = _passwordBox.Text; // Review: password is saved in clear text. Is this a security risk? How could we prevent it?
Settings.Default.Save();
}
if (_doingSignup)
{
DoSignUp();
return;
}
bool logIn;
try
{
logIn = _client.LogIn(_emailBox.Text, _passwordBox.Text);
}
catch (Exception exc)
{
LogAndInformButDontReportFailureToConnectToServer(exc);
return;
}
if (logIn)
{
DialogResult = DialogResult.OK;
Close();
}
else
{
MessageBox.Show(this, LocalizationManager.GetString("PublishTab.Upload.Login.PasswordMismatch", "Password and user ID did not match"),
LoginFailureString,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public static string LoginFailureString
{
get
{
return LocalizationManager.GetString("PublishTab.Upload.Login.LoginFailed", "Login failed");
}
}
private static string LoginOrSignupConnectionFailedString
{
get
{
return LocalizationManager.GetString("PublishTab.Upload.Login.LoginOrSignupConnectionFailed",
"Bloom could not connect to the server to complete your login or signup. This could be a problem with your internet connection, our server, or some equipment in between.");
}
}
private void LogAndInformButDontReportFailureToConnectToServer(Exception exc)
{
MessageBox.Show(this, LoginOrSignupConnectionFailedString, LoginFailureString, MessageBoxButtons.OK, MessageBoxIcon.Error);
Logger.WriteEvent("Failure connecting to parse server " + exc.Message);
Close();
}
private void DoSignUp()
{
if (!_termsOfUseCheckBox.Checked)
{
MessageBox.Show(this,
LocalizationManager.GetString("PublishTab.Upload.Login.MustAgreeTerms",
"In order to sign up for a BloomLibrary.org account, you must check the box indicating that you agree to the BloomLibrary Terms of Use."),
LocalizationManager.GetString("PublishTab.Upload.Login.PleaseAgreeTerms", "Please agree to terms of use"),
MessageBoxButtons.OK);
return;
}
bool userExists;
try
{
userExists = _client.UserExists(_emailBox.Text);
}
catch (Exception exc)
{
LogAndInformButDontReportFailureToConnectToServer(exc);
return;
}
if (userExists)
{
if (
MessageBox.Show(this,
LocalizationManager.GetString("PublishTab.Upload.Login.AlreadyHaveAccount", "We cannot sign you up with that address, because we already have an account with that address. Would you like to log in instead?"),
LocalizationManager.GetString("PublishTab.Upload.Login.AccountAlreadyExists", "Account Already Exists"),
MessageBoxButtons.YesNo)
== DialogResult.Yes)
{
RestoreToLogin();
return;
}
}
try
{
_client.CreateUser(_emailBox.Text, _passwordBox.Text);
if (_client.LogIn(_emailBox.Text, _passwordBox.Text))
Close();
}
catch (Exception exc)
{
LogAndInformButDontReportFailureToConnectToServer(exc);
}
}
private bool _doingSignup;
string oldText;
private string oldLogin;
/// <summary>
/// Adapt the dialog to use it for signup and run it.
/// Return true if successfully signed up (or possibly logged on with an existing account).
/// </summary>
/// <returns></returns>
public bool SignUp(IWin32Window owner)
{
Settings.Default.WebUserId = _emailBox.Text = "";
Settings.Default.WebPassword = _passwordBox.Text = "";
SwitchToSignUp();
if (ShowDialog(owner) == DialogResult.Cancel)
return false;
return true;
}
private void SwitchToSignUp()
{
_forgotLabel.Visible = false;
this.Text = LocalizationManager.GetString("PublishTab.Upload.Login.Signup", "Sign up for Bloom Library.");
_loginButton.Text = LocalizationManager.GetString("PublishTab.Upload.Login.Signup", "Sign up");
_doingSignup = true;
ShowTermsOfUse(true);
}
private void RestoreToLogin()
{
_doingSignup = false;
this.Text = oldText;
_loginButton.Text = oldLogin;
_forgotLabel.Visible = true;
ShowTermsOfUse(false);
}
private void ShowTermsOfUse(bool show)
{
Height = show ? _originalHeight : _termsOfUseCheckBox.Top - 2 + (Height - ClientRectangle.Height);
_termsOfUseCheckBox.Visible = show;
_showTermsOfUse.Visible = show;
}
protected override void OnClosed(EventArgs e)
{
RestoreToLogin();
base.OnClosed(e);
}
/// <summary>
/// This may be called by clients to log us in using the saved settings, if any.
/// </summary>
/// <returns></returns>
public bool LogIn()
{
if (string.IsNullOrEmpty(Settings.Default.WebUserId))
return false;
return _client.LogIn(Settings.Default.WebUserId, Settings.Default.WebPassword);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_emailBox.Text = Settings.Default.WebUserId;
_passwordBox.Text = Settings.Default.WebPassword;
UpdateDisplay();
}
protected override void OnShown(EventArgs e)
{
_emailBox.Select();
base.OnShown(e);
}
private void _forgotLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (HaveGoodEmail())
{
try
{
if (_client.UserExists(_emailBox.Text))
{
var msg = string.Format(
LocalizationManager.GetString("PublishTab.Upload.Login.SendingResetPassword",
"We are sending an email to {0} with instructions for how to reset your password."), _emailBox.Text);
MessageBox.Show(this, msg, LocalizationManager.GetString("PublishTab.Upload.Login.ResetPassword", "Resetting Password"));
_client.SendResetPassword(_emailBox.Text);
}
else
{
if (MessageBox.Show(this, LocalizationManager.GetString("PublishTab.Upload.Login.NoRecordOfUser",
"We don't have a user on record with that email. Would you like to sign up?"),
LocalizationManager.GetString("PublishTab.Upload.Login.UnknownUser", "Unknown user"),
MessageBoxButtons.YesNo)
== DialogResult.Yes)
{
SwitchToSignUp();
}
}
}
catch (Exception)
{
MessageBox.Show(this, LocalizationManager.GetString("PublishTab.Upload.Login.ResetConnectFailed", "Bloom could not connect to the server to reset your password. Please check your network connection."),
LocalizationManager.GetString("PublishTab.Upload.Login.ResetFailed", "Reset Password failed"),
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
else
{
var msg = LocalizationManager.GetString("PublishTab.Upload.Login.PleaseProvideEmail", "Please enter a valid email address. We will send an email to this address so you can reset your password.");
MessageBox.Show(this, msg, LocalizationManager.GetString("PublishTab.Upload.Login.Need Email", "Email Needed"));
}
}
public static bool IsValidEmail(string email)
{
// source: http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx
Regex rx = new Regex(
@"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
return rx.IsMatch(email);
}
private bool HaveGoodEmail()
{
return IsValidEmail(_emailBox.Text);
}
private void _emailBox_TextChanged(object sender, EventArgs e)
{
UpdateDisplay();
}
private void UpdateDisplay()
{
_borderLabel.BackColor = HaveGoodEmail() ? this.BackColor : Color.Red;
_loginButton.Enabled = HaveGoodEmail() && !string.IsNullOrWhiteSpace(_passwordBox.Text);
}
private void _passwordBox_TextChanged(object sender, EventArgs e)
{
UpdateDisplay();
}
private void _showPasswordCheckBox_CheckedChanged(object sender, EventArgs e)
{
Settings.Default.WebShowPassword = _showPasswordCheckBox.Checked;
Settings.Default.Save();
_passwordBox.UseSystemPasswordChar = !_showPasswordCheckBox.Checked;
}
private void _showTermsOfUse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start(BloomLibraryPublishControl.BloomLibraryUrlPrefix + "/terms");
}
}
}
| |
/*
* Unity VSCode Support
*
* Seamless support for Microsoft Visual Studio Code in Unity
*
* Version:
* 1.95
*
* Authors:
* Matthew Davey <matthew.davey@dotbunny.com>
*/
// REQUIRES: VSCode 0.8.0 - Settings directory moved to .vscode
// TODO: Currently VSCode will not debug mono on Windows -- need a solution.
namespace dotBunny.Unity
{
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
public static class VSCode
{
#region Properties
/// <summary>
/// Should debug information be displayed in the Unity terminal?
/// </summary>
public static bool Debug
{
get
{
return EditorPrefs.GetBool("VSCode_Debug", false);
}
set
{
EditorPrefs.SetBool("VSCode_Debug", value);
}
}
/// <summary>
/// Is the Visual Studio Code Integration Enabled?
/// </summary>
/// <remarks>
/// We do not want to automatically turn it on, for in larger projects not everyone is using VSCode
/// </remarks>
public static bool Enabled
{
get
{
return EditorPrefs.GetBool("VSCode_Enabled", false);
}
set
{
EditorPrefs.SetBool("VSCode_Enabled", value);
}
}
/// <summary>
/// Should the launch.json file be written?
/// </summary>
/// <remarks>
/// Useful to disable if someone has their own custom one rigged up
/// </remarks>
public static bool WriteLaunchFile
{
get
{
return EditorPrefs.GetBool("VSCode_WriteLaunchFile", true);
}
set
{
EditorPrefs.SetBool("VSCode_WriteLaunchFile", value);
}
}
/// <summary>
/// Quick reference to the VSCode settings folder
/// </summary>
static string SettingsFolder
{
get
{
return ProjectPath + System.IO.Path.DirectorySeparatorChar + "Client" + System.IO.Path.DirectorySeparatorChar + ".vscode";
}
}
/// <summary>
/// Quick reference to the VSCode launch settings file
/// </summary>
static string LaunchPath
{
get
{
return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "launch.json";
}
}
/// <summary>
/// The full path to the project
/// </summary>
static string ProjectPath
{
get
{
string s = System.IO.Path.GetDirectoryName(UnityEngine.Application.dataPath);
return System.IO.Path.GetDirectoryName(s);
//return System.IO.Path.GetDirectoryName(UnityEngine.Application.dataPath);
}
}
static string ProjectPath_Client
{
get
{
return ProjectPath+System.IO.Path.DirectorySeparatorChar+"Client";
}
}
static string SettingsPath
{
get
{
return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "settings.json";
}
}
#endregion
/// <summary>
/// Fail safe integration constructor
/// </summary>
static VSCode()
{
if (Enabled)
{
UpdateUnityPreferences(true);
}
}
#region Public Members
/// <summary>
/// Force Unity To Write Project File
/// </summary>
/// <remarks>
/// Reflection!
/// </remarks>
public static void SyncSolution()
{
System.Type T = System.Type.GetType("UnityEditor.SyncVS,UnityEditor");
System.Reflection.MethodInfo SyncSolution = T.GetMethod("SyncSolution", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
SyncSolution.Invoke(null, null);
}
/// <summary>
/// Update the solution files so that they work with VS Code
/// </summary>
public static void UpdateSolution()
{
// No need to process if we are not enabled
if (!VSCode.Enabled)
{
return;
}
if (VSCode.Debug)
{
UnityEngine.Debug.Log("[VSCode] Updating Solution & Project Files");
}
var currentDirectory = Directory.GetCurrentDirectory();
var solutionFiles = Directory.GetFiles(currentDirectory, "*.sln");
var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj");
foreach (var filePath in solutionFiles)
{
string content = File.ReadAllText(filePath);
content = ScrubSolutionContent(content);
File.WriteAllText(filePath, content);
ScrubFile(filePath);
}
foreach (var filePath in projectFiles)
{
string content = File.ReadAllText(filePath);
content = ScrubProjectContent(content);
File.WriteAllText(filePath, content);
ScrubFile(filePath);
}
}
#endregion
#region Private Members
/// <summary>
/// Call VSCode with arguements
/// </summary>
static void CallVSCode(string args)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
#if UNITY_EDITOR_OSX
proc.StartInfo.FileName = "open";
proc.StartInfo.Arguments = " -n -b \"com.microsoft.VSCode\" --args " + args;
proc.StartInfo.UseShellExecute = false;
#elif UNITY_EDITOR_WIN
proc.StartInfo.FileName = "code";
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
#else
//TODO: Allow for manual path to code?
proc.StartInfo.FileName = "code";
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
#endif
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
}
/// <summary>
/// Determine what port Unity is listening for on Windows
/// </summary>
static int GetDebugPort()
{
#if UNITY_EDITOR_WIN
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "netstat";
process.StartInfo.Arguments = "-a -n -o -p TCP";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
string[] lines = output.Split('\n');
process.WaitForExit();
foreach (string line in lines)
{
string[] tokens = Regex.Split(line, "\\s+");
if (tokens.Length > 4)
{
int test = -1;
int.TryParse(tokens[5], out test);
if (test > 1023)
{
try
{
var p = System.Diagnostics.Process.GetProcessById(test);
if (p.ProcessName == "Unity")
{
return test;
}
}
catch
{
}
}
}
}
#else
System.Diagnostics.Process process = new System.Diagnostics.Process ();
process.StartInfo.FileName = "lsof";
process.StartInfo.Arguments = "-c /^Unity$/ -i 4tcp -a";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start ();
// Not thread safe (yet!)
string output = process.StandardOutput.ReadToEnd ();
string[] lines = output.Split ('\n');
process.WaitForExit ();
foreach (string line in lines) {
int port = -1;
if (line.StartsWith ("Unity")) {
string[] portions = line.Split (new string[] { "TCP *:" }, System.StringSplitOptions.None);
if (portions.Length >= 2) {
Regex digitsOnly = new Regex (@"[^\d]");
string cleanPort = digitsOnly.Replace (portions [1], "");
if (int.TryParse (cleanPort, out port)) {
if (port > -1) {
return port;
}
}
}
}
}
#endif
return -1;
}
/// <summary>
/// VS Code Integration Preferences Item
/// </summary>
/// <remarks>
/// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off
/// </remarks>
[PreferenceItem( "VSCode" )]
static void VSCodePreferencesItem()
{
EditorGUILayout.BeginVertical();
EditorGUILayout.HelpBox("Support development of this plugin, follow @reapazor and @dotbunny on Twitter.", MessageType.Info);
EditorGUI.BeginChangeCheck();
Enabled = EditorGUILayout.Toggle("Enable Integration", Enabled);
EditorGUILayout.Space();
EditorGUI.BeginDisabledGroup(!Enabled);
Debug = EditorGUILayout.Toggle("Output Messages To Console", Debug);
WriteLaunchFile = EditorGUILayout.Toggle("Always Write Launch File", WriteLaunchFile);
EditorGUI.EndDisabledGroup();
EditorGUILayout.Space();
if( EditorGUI.EndChangeCheck())
{
UpdateUnityPreferences(Enabled);
if (VSCode.Debug)
{
if (Enabled)
{
UnityEngine.Debug.Log("[VSCode] Integration Enabled");
}
else {
UnityEngine.Debug.Log("[VSCode] Integration Disabled");
}
}
}
if (GUILayout.Button("Write Workspace Settings"))
{
WriteWorkspaceSettings();
}
EditorGUILayout.EndVertical();
}
[MenuItem("Assets/Open C# Project In Code", false, 1000)]
static void MenuOpenProject()
{
// Force the project files to be sync
SyncSolution();
// Load Project
CallVSCode("\"" + ProjectPath + "\" -r");
}
[MenuItem("Assets/Open C# Project In Code", true, 1000)]
static bool ValidateMenuOpenProject()
{
return Enabled;
}
/// <summary>
/// Asset Open Callback (from Unity)
/// </summary>
/// <remarks>
/// Called when Unity is about to open an asset.
/// </remarks>
[UnityEditor.Callbacks.OnOpenAssetAttribute()]
static bool OnOpenedAsset(int instanceID, int line)
{
// bail out if we are not on a Mac or if we don't want to use VSCode
if (!Enabled)
{
return false;
}
// current path without the asset folder
string appPath = ProjectPath_Client;
// determine asset that has been double clicked in the project view
UnityEngine.Object selected = EditorUtility.InstanceIDToObject(instanceID);
if (selected.GetType().ToString() == "UnityEditor.MonoScript")
{
string completeFilepath = appPath + Path.DirectorySeparatorChar + AssetDatabase.GetAssetPath(selected);
string args = null;
if (line == -1)
{
args = "\"" + ProjectPath + "\" \"" + completeFilepath + "\" -r";
}
else
{
args = "\"" + ProjectPath + "\" -g \"" + completeFilepath + ":" + line.ToString() + "\" -r";
}
// call 'open'
CallVSCode(args);
return true;
}
// Didnt find a code file? let Unity figure it out
return false;
}
/// <summary>
/// Executed when the Editor's playmode changes allowing for capture of required data
/// </summary>
static void OnPlaymodeStateChanged()
{
if (VSCode.Enabled && VSCode.WriteLaunchFile && UnityEngine.Application.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode)
{
int port = GetDebugPort();
if (port > -1)
{
if (!Directory.Exists(VSCode.SettingsFolder))
System.IO.Directory.CreateDirectory(VSCode.SettingsFolder);
UpdateLaunchFile(port);
if (VSCode.Debug)
{
UnityEngine.Debug.Log("[VSCode] Debug Port Found (" + port + ")");
}
}
else
{
if (VSCode.Debug)
{
UnityEngine.Debug.LogWarning("[VSCode] Unable to determine debug port.");
}
}
}
}
/// <summary>
/// Detect when scripts are reloaded and relink playmode detection
/// </summary>
[UnityEditor.Callbacks.DidReloadScripts()]
static void OnScriptReload()
{
EditorApplication.playmodeStateChanged -= OnPlaymodeStateChanged;
EditorApplication.playmodeStateChanged += OnPlaymodeStateChanged;
}
/// <summary>
/// Remove extra/erroneous lines from a file.
static void ScrubFile(string path)
{
string[] lines = File.ReadAllLines(path);
System.Collections.Generic.List<string> newLines = new System.Collections.Generic.List<string>();
for (int i = 0; i < lines.Length; i++)
{
// Check Empty
if (string.IsNullOrEmpty(lines[i].Trim()) || lines[i].Trim() == "\t" || lines[i].Trim() == "\t\t")
{
}
else
{
newLines.Add(lines[i]);
}
}
File.WriteAllLines(path, newLines.ToArray());
}
/// <summary>
/// Remove extra/erroneous data from project file (content).
/// </summary>
static string ScrubProjectContent(string content)
{
if (content.Length == 0)
return "";
// Make sure our reference framework is 2.0, still the base for Unity
if (content.IndexOf("<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>") != -1)
{
content = Regex.Replace(content, "<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>", "<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>");
}
string targetPath = "<TargetPath>Temp\\bin\\Debug\\</TargetPath>"; //OutputPath
string langVersion = "<LangVersion>default</LangVersion>";
bool found = true;
int location = 0;
string addedOptions = "";
int startLocation = -1;
int endLocation = -1;
int endLength = 0;
while (found)
{
startLocation = -1;
endLocation = -1;
endLength = 0;
addedOptions = "";
startLocation = content.IndexOf("<PropertyGroup", location);
if (startLocation != -1)
{
endLocation = content.IndexOf("</PropertyGroup>", startLocation);
endLength = (endLocation - startLocation);
if (endLocation == -1)
{
found = false;
continue;
}
else
{
found = true;
location = endLocation;
}
if (content.Substring(startLocation, endLength).IndexOf("<TargetPath>") == -1)
{
addedOptions += "\n\r\t" + targetPath + "\n\r";
}
if (content.Substring(startLocation, endLength).IndexOf("<LangVersion>") == -1)
{
addedOptions += "\n\r\t" + langVersion + "\n\r";
}
if (!string.IsNullOrEmpty(addedOptions))
{
content = content.Substring(0, endLocation) + addedOptions + content.Substring(endLocation);
}
}
else
{
found = false;
}
}
return content;
}
/// <summary>
/// Remove extra/erroneous data from solution file (content).
/// </summary>
static string ScrubSolutionContent(string content)
{
// Replace Solution Version
content = content.Replace(
"Microsoft Visual Studio Solution File, Format Version 11.00\r\n# Visual Studio 2008\r\n",
"\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio 2012");
// Remove Solution Properties (Unity Junk)
int startIndex = content.IndexOf("GlobalSection(SolutionProperties) = preSolution");
if (startIndex != -1)
{
int endIndex = content.IndexOf("EndGlobalSection", startIndex);
content = content.Substring(0, startIndex) + content.Substring(endIndex + 16);
}
return content;
}
/// <summary>
/// Update Visual Studio Code Launch file
/// </summary>
static void UpdateLaunchFile(int port)
{
// Write out proper formatted JSON (hence no more SimpleJSON here)
string fileContent = "{\n\t\"version\":\"0.1.0\",\n\t\"configurations\":[ \n\t\t{\n\t\t\t\"name\":\"Unity\",\n\t\t\t\"type\":\"mono\",\n\t\t\t\"address\":\"localhost\",\n\t\t\t\"port\":" + port + "\n\t\t}\n\t]\n}";
File.WriteAllText(VSCode.LaunchPath, fileContent);
}
/// <summary>
/// Update Unity Editor Preferences
static void UpdateUnityPreferences(bool enabled)
{
if (enabled)
{
#if UNITY_EDITOR_OSX
var newPath = "/Applications/Visual Studio Code.app";
#elif UNITY_EDITOR_WIN
var newPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar + "Code" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "code.cmd";
#else
var newPath = "/usr/local/bin/code";
#endif
// App
if (EditorPrefs.GetString("kScriptsDefaultApp") != newPath)
{
EditorPrefs.SetString("VSCode_PreviousApp", EditorPrefs.GetString("kScriptsDefaultApp"));
}
EditorPrefs.SetString("kScriptsDefaultApp", newPath);
// Arguments
if (EditorPrefs.GetString("kScriptEditorArgs") != "-r -g \"$(File):$(Line)\"")
{
EditorPrefs.SetString("VSCode_PreviousArgs", EditorPrefs.GetString("kScriptEditorArgs"));
}
EditorPrefs.SetString("kScriptEditorArgs", "-r -g \"$(File):$(Line)\"");
// MonoDevelop Solution
if (EditorPrefs.GetBool("kMonoDevelopSolutionProperties", false))
{
EditorPrefs.SetBool("VSCode_PreviousMD", true);
}
EditorPrefs.SetBool("kMonoDevelopSolutionProperties", false);
// Support Unity Proj (JS)
if (EditorPrefs.GetBool("kExternalEditorSupportsUnityProj", false))
{
EditorPrefs.SetBool("VSCode_PreviousUnityProj", true);
}
EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", false);
// Attach to Editor
if (!EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", false))
{
EditorPrefs.SetBool("VSCode_PreviousAttach", false);
}
EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", true);
}
else
{
// Restore previous app
if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousApp")))
{
EditorPrefs.SetString("kScriptsDefaultApp", EditorPrefs.GetString("VSCode_PreviousApp"));
}
// Restore previous args
if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousArgs")))
{
EditorPrefs.SetString("kScriptEditorArgs", EditorPrefs.GetString("VSCode_PreviousArgs"));
}
// Restore MD setting
if (EditorPrefs.GetBool("VSCode_PreviousMD", false))
{
EditorPrefs.SetBool("kMonoDevelopSolutionProperties", true);
}
// Restore MD setting
if (EditorPrefs.GetBool("VSCode_PreviousUnityProj", false))
{
EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", true);
}
// Restore previous attach
if (!EditorPrefs.GetBool("VSCode_PreviousAttach", true))
{
EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", false);
}
}
}
/// <summary>
/// Write Default Workspace Settings
/// </summary>
static void WriteWorkspaceSettings()
{
if (Debug)
{
UnityEngine.Debug.Log("[VSCode] Workspace Settigns Written");
}
if (!Directory.Exists(VSCode.SettingsFolder))
{
System.IO.Directory.CreateDirectory(VSCode.SettingsFolder);
}
string exclusions =
"{\n" +
"\t\"files.exclude\":\n" +
"\t{\n" +
// Hidden Files
"\t\t\"**/.DS_Store\":true,\n" +
"\t\t\"**/.git\":true,\n" +
// Project Files
"\t\t\"**/*.booproj\":true,\n" +
"\t\t\"**/*.pidb\":true,\n" +
"\t\t\"**/*.suo\":true,\n" +
"\t\t\"**/*.user\":true,\n" +
"\t\t\"**/*.userprefs\":true,\n" +
"\t\t\"**/*.unityproj\":true,\n" +
"\t\t\"**/*.dll\":true,\n" +
"\t\t\"**/*.exe\":true,\n" +
// Media Files
"\t\t\"**/*.pdf\":true,\n" +
// Audio
"\t\t\"**/*.mid\":true,\n" +
"\t\t\"**/*.midi\":true,\n" +
"\t\t\"**/*.wav\":true,\n" +
// Textures
"\t\t\"**/*.gif\":true,\n" +
"\t\t\"**/*.ico\":true,\n" +
"\t\t\"**/*.jpg\":true,\n" +
"\t\t\"**/*.jpeg\":true,\n" +
"\t\t\"**/*.png\":true,\n" +
"\t\t\"**/*.psd\":true,\n" +
"\t\t\"**/*.tga\":true,\n" +
"\t\t\"**/*.tif\":true,\n" +
"\t\t\"**/*.tiff\":true,\n" +
// Models
"\t\t\"**/*.3ds\":true,\n" +
"\t\t\"**/*.3DS\":true,\n" +
"\t\t\"**/*.fbx\":true,\n" +
"\t\t\"**/*.FBX\":true,\n" +
"\t\t\"**/*.lxo\":true,\n" +
"\t\t\"**/*.LXO\":true,\n" +
"\t\t\"**/*.ma\":true,\n" +
"\t\t\"**/*.MA\":true,\n" +
"\t\t\"**/*.obj\":true,\n" +
"\t\t\"**/*.OBJ\":true,\n" +
// Unity File Types
"\t\t\"**/*.asset\":true,\n" +
"\t\t\"**/*.cubemap\":true,\n" +
"\t\t\"**/*.flare\":true,\n" +
"\t\t\"**/*.mat\":true,\n" +
"\t\t\"**/*.meta\":true,\n" +
"\t\t\"**/*.prefab\":true,\n" +
"\t\t\"**/*.unity\":true,\n" +
// Folders
"\t\t\"build/\":true,\n" +
"\t\t\"Build/\":true,\n" +
"\t\t\"Library/\":true,\n" +
"\t\t\"library/\":true,\n" +
"\t\t\"obj/\":true,\n" +
"\t\t\"Obj/\":true,\n" +
"\t\t\"ProjectSettings/\":true,\r" +
"\t\t\"temp/\":true,\n" +
"\t\t\"Temp/\":true\n" +
"\t}\n" +
"}";
// Dont like the replace but it fixes the issue with the JSON
File.WriteAllText(VSCode.SettingsPath, exclusions);
}
#endregion
}
/// <summary>
/// VSCode Asset AssetPostprocessor
/// <para>This will ensure any time that the project files are generated the VSCode versions will be made</para>
/// </summary>
/// <remarks>Undocumented Event</remarks>
public class VSCodeAssetPostprocessor : AssetPostprocessor
{
/// <summary>
/// On documented, project generation event callback
/// </summary>
private static void OnGeneratedCSProjectFiles()
{
// Force execution of VSCode update
VSCode.UpdateSolution();
}
}
}
| |
#region License
/* Copyright (c) 2006 Leslie Sanford
*
* 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
#region Contact
/*
* Leslie Sanford
* Email: jabberdabber@hotmail.com
*/
#endregion
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Sanford.Threading;
namespace Sanford.Multimedia.Midi
{
public abstract class OutputDeviceBase : MidiDevice
{
[DllImport("winmm.dll")]
protected static extern int midiOutReset(IntPtr handle);
[DllImport("winmm.dll")]
protected static extern int midiOutShortMsg(IntPtr handle, int message);
[DllImport("winmm.dll")]
protected static extern int midiOutPrepareHeader(IntPtr handle,
IntPtr headerPtr, int sizeOfMidiHeader);
[DllImport("winmm.dll")]
protected static extern int midiOutUnprepareHeader(IntPtr handle,
IntPtr headerPtr, int sizeOfMidiHeader);
[DllImport("winmm.dll")]
protected static extern int midiOutLongMsg(IntPtr handle,
IntPtr headerPtr, int sizeOfMidiHeader);
[DllImport("winmm.dll")]
protected static extern int midiOutGetDevCaps(IntPtr deviceID,
ref MidiOutCaps caps, int sizeOfMidiOutCaps);
[DllImport("winmm.dll")]
protected static extern int midiOutGetNumDevs();
protected const int MOM_OPEN = 0x3C7;
protected const int MOM_CLOSE = 0x3C8;
protected const int MOM_DONE = 0x3C9;
protected delegate void GenericDelegate<T>(T args);
// Represents the method that handles messages from Windows.
protected delegate void MidiOutProc(IntPtr hnd, int msg, IntPtr instance, IntPtr param1, IntPtr param2);
// For releasing buffers.
protected DelegateQueue delegateQueue = new DelegateQueue();
protected readonly object lockObject = new object();
// The number of buffers still in the queue.
protected int bufferCount = 0;
// Builds MidiHeader structures for sending system exclusive messages.
private MidiHeaderBuilder headerBuilder = new MidiHeaderBuilder();
// The device handle.
protected IntPtr handle = IntPtr.Zero;
public OutputDeviceBase(int deviceID) : base(deviceID)
{
}
~OutputDeviceBase()
{
Dispose(false);
}
protected override void Dispose(bool disposing)
{
if(disposing)
{
delegateQueue.Dispose();
}
base.Dispose(disposing);
}
public virtual void Send(ChannelMessage message)
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
#endregion
Send(message.Message);
}
public virtual void SendShort(int message)
{
#region Require
if (IsDisposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
#endregion
Send(message);
}
public virtual void Send(SysExMessage message)
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
#endregion
lock(lockObject)
{
headerBuilder.InitializeBuffer(message);
headerBuilder.Build();
// Prepare system exclusive buffer.
int result = midiOutPrepareHeader(Handle, headerBuilder.Result, SizeOfMidiHeader);
// If the system exclusive buffer was prepared successfully.
if(result == MidiDeviceException.MMSYSERR_NOERROR)
{
bufferCount++;
// Send system exclusive message.
result = midiOutLongMsg(Handle, headerBuilder.Result, SizeOfMidiHeader);
// If the system exclusive message could not be sent.
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
midiOutUnprepareHeader(Handle, headerBuilder.Result, SizeOfMidiHeader);
bufferCount--;
headerBuilder.Destroy();
// Throw an exception.
throw new OutputDeviceException(result);
}
}
// Else the system exclusive buffer could not be prepared.
else
{
// Destroy system exclusive buffer.
headerBuilder.Destroy();
// Throw an exception.
throw new OutputDeviceException(result);
}
}
}
public virtual void Send(SysCommonMessage message)
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
#endregion
Send(message.Message);
}
public virtual void Send(SysRealtimeMessage message)
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
#endregion
Send(message.Message);
}
public override void Reset()
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
#endregion
lock(lockObject)
{
// Reset the OutputDevice.
int result = midiOutReset(Handle);
if(result == MidiDeviceException.MMSYSERR_NOERROR)
{
while(bufferCount > 0)
{
Monitor.Wait(lockObject);
}
}
else
{
// Throw an exception.
throw new OutputDeviceException(result);
}
}
}
protected void Send(int message)
{
lock(lockObject)
{
int result = midiOutShortMsg(Handle, message);
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
throw new OutputDeviceException(result);
}
}
}
public static MidiOutCaps GetDeviceCapabilities(int deviceID)
{
MidiOutCaps caps = new MidiOutCaps();
// Get the device's capabilities.
IntPtr devId = (IntPtr)deviceID;
int result = midiOutGetDevCaps(devId, ref caps, Marshal.SizeOf(caps));
// If the capabilities could not be retrieved.
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
// Throw an exception.
throw new OutputDeviceException(result);
}
return caps;
}
// Handles Windows messages.
protected virtual void HandleMessage(IntPtr hnd, int msg, IntPtr instance, IntPtr param1, IntPtr param2)
{
if(msg == MOM_OPEN)
{
}
else if(msg == MOM_CLOSE)
{
}
else if(msg == MOM_DONE)
{
delegateQueue.Post(ReleaseBuffer, param1);
}
}
// Releases buffers.
private void ReleaseBuffer(object state)
{
lock(lockObject)
{
IntPtr headerPtr = (IntPtr)state;
// Unprepare the buffer.
int result = midiOutUnprepareHeader(Handle, headerPtr, SizeOfMidiHeader);
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
Exception ex = new OutputDeviceException(result);
OnError(new ErrorEventArgs(ex));
}
// Release the buffer resources.
headerBuilder.Destroy(headerPtr);
bufferCount--;
Monitor.Pulse(lockObject);
Debug.Assert(bufferCount >= 0);
}
}
public override void Dispose()
{
#region Guard
if(IsDisposed)
{
return;
}
#endregion
lock(lockObject)
{
Close();
}
}
public override IntPtr Handle
{
get
{
return handle;
}
}
public static int DeviceCount
{
get
{
return midiOutGetNumDevs();
}
}
}
}
| |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http.Features;
using Newtonsoft.Json.Serialization;
using Hangfire;
using Hangfire.PostgreSql;
using HetsApi.Authorization;
using HetsApi.Authentication;
using HetsData.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerUI;
using HetsData.Hangfire;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Hosting;
using HetsApi.Middlewares;
using AutoMapper;
using HetsData.Mappings;
using HetsData.Repositories;
using Serilog.Ui.Web;
using Serilog.Ui.PostgreSqlProvider.Extensions;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using System.Net.Mime;
using System.Text.Json;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace HetsApi
{
/// <summary>
/// Application startup class
/// </summary>
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
string connectionString = GetConnectionString();
// add http context accessor
services.AddHttpContextAccessor();
// add auto mapper
var mappingConfig = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new EntityToDtoProfile());
cfg.AddProfile(new DtoToEntityProfile());
cfg.AddProfile(new EntityToEntityProfile());
});
var mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddSerilogUi(options => options.UseNpgSql(connectionString, "het_log"));
// add database context
services.AddDbContext<DbAppContext>(options =>
{
options.UseNpgsql(connectionString, o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
options.ConfigureWarnings(o => o.Ignore(CoreEventId.RowLimitingOperationWithoutOrderByWarning));
});
services.AddDbContext<DbAppMonitorContext>(options =>
{
options.UseNpgsql(connectionString, o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
options.ConfigureWarnings(o => o.Ignore(CoreEventId.RowLimitingOperationWithoutOrderByWarning));
});
services.AddScoped<IAnnualRollover, AnnualRollover>();
services
.AddControllers(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
options.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = Configuration.GetValue<string>("JWT:Authority");
options.Audience = Configuration.GetValue<string>("JWT:Audience");
options.IncludeErrorDetails = true;
options.EventsType = typeof(HetsJwtBearerEvents);
});
// setup authorization
services.AddAuthorization();
services.RegisterPermissionHandler();
services.AddScoped<HetsJwtBearerEvents>();
// repository
services.AddScoped<IEquipmentRepository, EquipmentRepository>();
services.AddScoped<IOwnerRepository, OwnerRepository>();
services.AddScoped<IProjectRepository, ProjectRepository>();
services.AddScoped<IRentalAgreementRepository, RentalAgreementRepository>();
services.AddScoped<IRentalRequestRepository, RentalRequestRepository>();
services.AddScoped<IUserRepository, UserRepository>();
// allow for large files to be uploaded
services.Configure<FormOptions>(options =>
{
options.MultipartBodyLengthLimit = 1073741824; // 1 GB
});
//enable Hangfire
services.AddHangfire(configuration =>
configuration
.UseSerilogLogProvider()
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UsePostgreSqlStorage(connectionString)
);
services.AddHangfireServer(options =>
{
options.WorkerCount = 1;
});
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "HETS REST API",
Description = "Hired Equipment Tracking System"
});
});
services.AddHealthChecks()
.AddNpgSql(connectionString, name: "HETS-DB-Check", failureStatus: HealthStatus.Degraded, tags: new string[] { "postgresql", "db" });
}
/// <summary>
/// Configure the HTTP request pipeline
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseMiddleware<ExceptionMiddleware>();
var healthCheckOptions = new HealthCheckOptions
{
ResponseWriter = async (c, r) =>
{
c.Response.ContentType = MediaTypeNames.Application.Json;
var result = JsonSerializer.Serialize(
new
{
checks = r.Entries.Select(e =>
new {
description = e.Key,
status = e.Value.Status.ToString(),
tags = e.Value.Tags,
responseTime = e.Value.Duration.TotalMilliseconds
}),
totalResponseTime = r.TotalDuration.TotalMilliseconds
});
await c.Response.WriteAsync(result);
}
};
app.UseHealthChecks("/healthz", healthCheckOptions);
app.UseHangfireDashboard();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSerilogUi();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger();
string swaggerApi = Configuration.GetSection("Constants:SwaggerApiUrl").Value;
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint(swaggerApi, "HETS REST API v1");
options.DocExpansion(DocExpansion.None);
});
}
/// <summary>
/// Retrieve database connection string
/// </summary>
/// <returns></returns>
private string GetConnectionString()
{
string connectionString;
string host = Configuration["DATABASE_SERVICE_NAME"];
string username = Configuration["POSTGRESQL_USER"];
string password = Configuration["POSTGRESQL_PASSWORD"];
string database = Configuration["POSTGRESQL_DATABASE"];
if (string.IsNullOrEmpty(host) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(database))
{
connectionString = Configuration.GetConnectionString("HETS");
}
else
{
// environment variables override all other settings (OpenShift)
connectionString = $"Host={host};Username={username};Password={password};Database={database}";
}
connectionString += ";Timeout=600;CommandTimeout=0;";
return connectionString;
}
}
}
| |
#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
using System;
using System.Globalization;
using log4net.Core;
using log4net.Repository;
using log4net.Util;
namespace log4net.Ext.MarshalByRef
{
/// <summary>
/// Marshal By Reference implementation of <see cref="ILog"/>
/// </summary>
/// <remarks>
/// <para>
/// Logger wrapper that is <see cref="MarshalByRefObject"/>. These objects
/// can be passed by reference across a remoting boundary.
/// </para>
/// </remarks>
public sealed class MarshalByRefLogImpl : MarshalByRefObject, ILog
{
private readonly static Type ThisDeclaringType = typeof(MarshalByRefLogImpl);
private readonly ILogger m_logger;
private Level m_levelDebug;
private Level m_levelInfo;
private Level m_levelWarn;
private Level m_levelError;
private Level m_levelFatal;
#region Public Instance Constructors
public MarshalByRefLogImpl(ILogger logger)
{
m_logger = logger;
// Listen for changes to the repository
logger.Repository.ConfigurationChanged += new LoggerRepositoryConfigurationChangedEventHandler(LoggerRepositoryConfigurationChanged);
// load the current levels
ReloadLevels(logger.Repository);
}
#endregion Public Instance Constructors
private void ReloadLevels(ILoggerRepository repository)
{
LevelMap levelMap = repository.LevelMap;
m_levelDebug = levelMap.LookupWithDefault(Level.Debug);
m_levelInfo = levelMap.LookupWithDefault(Level.Info);
m_levelWarn = levelMap.LookupWithDefault(Level.Warn);
m_levelError = levelMap.LookupWithDefault(Level.Error);
m_levelFatal = levelMap.LookupWithDefault(Level.Fatal);
}
private void LoggerRepositoryConfigurationChanged(object sender, EventArgs e)
{
ILoggerRepository repository = sender as ILoggerRepository;
if (repository != null)
{
ReloadLevels(repository);
}
}
#region Implementation of ILog
public void Debug(object message)
{
Logger.Log(ThisDeclaringType, m_levelDebug, message, null);
}
public void Debug(object message, Exception t)
{
Logger.Log(ThisDeclaringType, m_levelDebug, message, t);
}
public void DebugFormat(string format, params object[] args)
{
if (IsDebugEnabled)
{
Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null);
}
}
public void DebugFormat(string format, object arg0)
{
if (IsDebugEnabled)
{
Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null);
}
}
public void DebugFormat(string format, object arg0, object arg1)
{
if (IsDebugEnabled)
{
Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null);
}
}
public void DebugFormat(string format, object arg0, object arg1, object arg2)
{
if (IsDebugEnabled)
{
Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null);
}
}
public void DebugFormat(IFormatProvider provider, string format, params object[] args)
{
if (IsDebugEnabled)
{
Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(provider, format, args), null);
}
}
public void Info(object message)
{
Logger.Log(ThisDeclaringType, m_levelInfo, message, null);
}
public void Info(object message, Exception t)
{
Logger.Log(ThisDeclaringType, m_levelInfo, message, t);
}
public void InfoFormat(string format, params object[] args)
{
if (IsInfoEnabled)
{
Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null);
}
}
public void InfoFormat(string format, object arg0)
{
if (IsInfoEnabled)
{
Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null);
}
}
public void InfoFormat(string format, object arg0, object arg1)
{
if (IsInfoEnabled)
{
Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null);
}
}
public void InfoFormat(string format, object arg0, object arg1, object arg2)
{
if (IsInfoEnabled)
{
Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null);
}
}
public void InfoFormat(IFormatProvider provider, string format, params object[] args)
{
if (IsInfoEnabled)
{
Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(provider, format, args), null);
}
}
public void Warn(object message)
{
Logger.Log(ThisDeclaringType, m_levelWarn, message, null);
}
public void Warn(object message, Exception t)
{
Logger.Log(ThisDeclaringType, m_levelWarn, message, t);
}
public void WarnFormat(string format, params object[] args)
{
if (IsWarnEnabled)
{
Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null);
}
}
public void WarnFormat(string format, object arg0)
{
if (IsWarnEnabled)
{
Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null);
}
}
public void WarnFormat(string format, object arg0, object arg1)
{
if (IsWarnEnabled)
{
Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null);
}
}
public void WarnFormat(string format, object arg0, object arg1, object arg2)
{
if (IsWarnEnabled)
{
Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null);
}
}
public void WarnFormat(IFormatProvider provider, string format, params object[] args)
{
if (IsWarnEnabled)
{
Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(provider, format, args), null);
}
}
public void Error(object message)
{
Logger.Log(ThisDeclaringType, m_levelError, message, null);
}
public void Error(object message, Exception t)
{
Logger.Log(ThisDeclaringType, m_levelError, message, t);
}
public void ErrorFormat(string format, params object[] args)
{
if (IsErrorEnabled)
{
Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null);
}
}
public void ErrorFormat(string format, object arg0)
{
if (IsErrorEnabled)
{
Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null);
}
}
public void ErrorFormat(string format, object arg0, object arg1)
{
if (IsErrorEnabled)
{
Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null);
}
}
public void ErrorFormat(string format, object arg0, object arg1, object arg2)
{
if (IsErrorEnabled)
{
Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null);
}
}
public void ErrorFormat(IFormatProvider provider, string format, params object[] args)
{
if (IsErrorEnabled)
{
Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(provider, format, args), null);
}
}
public void Fatal(object message)
{
Logger.Log(ThisDeclaringType, m_levelFatal, message, null);
}
public void Fatal(object message, Exception t)
{
Logger.Log(ThisDeclaringType, m_levelFatal, message, t);
}
public void FatalFormat(string format, params object[] args)
{
if (IsFatalEnabled)
{
Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null);
}
}
public void FatalFormat(string format, object arg0)
{
if (IsFatalEnabled)
{
Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null);
}
}
public void FatalFormat(string format, object arg0, object arg1)
{
if (IsFatalEnabled)
{
Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null);
}
}
public void FatalFormat(string format, object arg0, object arg1, object arg2)
{
if (IsFatalEnabled)
{
Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null);
}
}
public void FatalFormat(IFormatProvider provider, string format, params object[] args)
{
if (IsFatalEnabled)
{
Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(provider, format, args), null);
}
}
public bool IsDebugEnabled
{
get { return Logger.IsEnabledFor(m_levelDebug); }
}
public bool IsInfoEnabled
{
get { return Logger.IsEnabledFor(m_levelInfo); }
}
public bool IsWarnEnabled
{
get { return Logger.IsEnabledFor(m_levelWarn); }
}
public bool IsErrorEnabled
{
get { return Logger.IsEnabledFor(m_levelError); }
}
public bool IsFatalEnabled
{
get { return Logger.IsEnabledFor(m_levelFatal); }
}
#endregion Implementation of ILog
#region Implementation of ILoggerWrapper
public ILogger Logger
{
get { return m_logger; }
}
#endregion
/// <summary>
/// Live forever
/// </summary>
/// <returns><c>null</c></returns>
public override object InitializeLifetimeService()
{
return null;
}
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// 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.Text;
using Alachisoft.NCache.Runtime.Caching;
using Alachisoft.NCache.Web.Caching;
using Alachisoft.NCache.Runtime;
using System.Collections;
using System.Threading;
using Alachisoft.NCache.Integrations.Memcached.Provider.Exceptions;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Alachisoft.NCache.Web.Net;
namespace Alachisoft.NCache.Integrations.Memcached.Provider
{
public class MemcachedProvider : IMemcachedProvider
{
private Cache _cache;
private Timer _timer;
public static IMemcachedProvider Instance { get; internal set; }
private const string ItemVersionKey = "Item_Version_Value";
private const ulong ItemVersionValue = 1;
#region Public Interface Implemented Methods
public OperationResult InitCache(string cacheID)
{
if (string.IsNullOrEmpty(cacheID))
ThrowInvalidArgumentsException();
OperationResult returnObject = new OperationResult();
try
{
_cache = Alachisoft.NCache.Web.Caching.NCache.InitializeCache(cacheID);
if (!_cache.Contains(ItemVersionKey))
{
_cache.Add(ItemVersionKey, ItemVersionValue);
}
returnObject = CreateReturnObject(Result.SUCCESS, null);
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return returnObject;
}
public OperationResult Set(string key, uint flags, long expirationTimeInSeconds, object dataBlock)
{
if (string.IsNullOrEmpty(key) || dataBlock == null)
ThrowInvalidArgumentsException();
OperationResult returnObject = InsertItemSuccessfully(key, flags, expirationTimeInSeconds, dataBlock);
return returnObject;
}
public OperationResult Add(string key, uint flags, long expirationTimeInSeconds, object dataBlock)
{
if (string.IsNullOrEmpty(key) || dataBlock == null)
ThrowInvalidArgumentsException();
OperationResult returnObject = new OperationResult();
try
{
returnObject = AddItemSuccessfully(key, flags, expirationTimeInSeconds, dataBlock);
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return returnObject;
}
public OperationResult Replace(string key, uint flags, long expirationTimeInSeconds, object dataBlock)
{
if (string.IsNullOrEmpty(key) || dataBlock == null)
ThrowInvalidArgumentsException();
OperationResult returnObject = new OperationResult();
try
{
if (_cache.Contains(key))
returnObject = InsertItemSuccessfully(key, flags, expirationTimeInSeconds, dataBlock);
else
returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return returnObject;
}
public OperationResult CheckAndSet(string key, uint flags, long expirationTimeInSeconds, ulong casUnique, object dataBlock)
{
if (string.IsNullOrEmpty(key) || dataBlock == null )
ThrowInvalidArgumentsException();
OperationResult returnObject = new OperationResult();
try
{
CacheItem getCacheItem = _cache.GetCacheItem(key);
if (getCacheItem == null)
returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
else
{
MemcachedItem memCacheItem = (MemcachedItem)getCacheItem.Value;
if (memCacheItem.InternalVersion == casUnique)
returnObject = InsertItemSuccessfully(key, flags, expirationTimeInSeconds, dataBlock);
else
returnObject = CreateReturnObject(Result.ITEM_MODIFIED, null);
}
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return returnObject;
}
public List<GetOpResult> Get(string[] keys)
{
if (keys.Length == 0)
ThrowInvalidArgumentsException();
List<GetOpResult> getObjects = new List<GetOpResult>();
try
{
for (int i = 0; i < keys.Length; i++)
{
CacheItem getObject = _cache.GetCacheItem(keys[i]);
if (getObject != null)
getObjects.Add(CreateGetObject(keys[i], getObject));
}
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return getObjects;
}
public OperationResult Delete(string key, ulong casUnique)
{
if (string.IsNullOrEmpty(key))
ThrowInvalidArgumentsException();
OperationResult returnObject = new OperationResult();
try
{
if (casUnique == 0)
{
Object obj = _cache.Remove(key);
if (obj == null)
returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
else
returnObject = CreateReturnObject(Result.SUCCESS, null);
}
else
{
CacheItem item = _cache.GetCacheItem(key);
if (item == null)
returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
else
{
MemcachedItem memCacheItem = (MemcachedItem)item.Value;
if (memCacheItem.InternalVersion != casUnique)
{
returnObject = CreateReturnObject(Result.ITEM_MODIFIED, null);
}
else
{
_cache.Delete(key);
returnObject = CreateReturnObject(Result.SUCCESS, null);
}
}
}
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return returnObject;
}
public OperationResult Append(string key, object dataToAppend, ulong casUnique)
{
return Concat(key, dataToAppend, casUnique, UpdateType.Append);
}
public OperationResult Prepend(string key, object dataToPrepend, ulong casUnique)
{
return Concat(key, dataToPrepend, casUnique, UpdateType.Prepend);
}
public MutateOpResult Increment(string key, ulong value, object initialValue, long expirationTimeInSeconds, ulong casUnique)
{
return Mutate(key, value, initialValue, expirationTimeInSeconds, casUnique, UpdateType.Increment);
}
public MutateOpResult Decrement(string key, ulong value, object initialValue, long expirationTimeInSeconds, ulong casUnique)
{
return Mutate(key, value, initialValue, expirationTimeInSeconds, casUnique, UpdateType.Decrement);
}
public OperationResult Flush_All(long expirationTimeInSeconds)
{
OperationResult returnObject = new OperationResult();
try
{
if (expirationTimeInSeconds == 0)
{
ulong getVersion =(ulong) _cache.Get(ItemVersionKey);
_cache.Clear();
if (getVersion != null)
{
_cache.Insert(ItemVersionKey, getVersion);
}
else
{
_cache.Insert(ItemVersionKey, ItemVersionValue);
}
}
else
{
long dueTimeInMilliseconds = expirationTimeInSeconds*1000;
_timer = new Timer(FlushExpirationCallBack, null, dueTimeInMilliseconds, 0);
}
returnObject = CreateReturnObject(Result.SUCCESS, null);
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return returnObject;
}
public OperationResult Touch(string key, long expirationTimeInSeconds)
{
if (string.IsNullOrEmpty(key))
ThrowInvalidArgumentsException();
OperationResult returnObject = new OperationResult();
try
{
CacheItemAttributes attributes = new CacheItemAttributes();
attributes.AbsoluteExpiration = CreateExpirationDate(expirationTimeInSeconds);
bool result = _cache.SetAttributes(key, attributes);
if (result)
returnObject = CreateReturnObject(Result.SUCCESS, null);
else
returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return returnObject;
}
public OperationResult GetVersion()
{
return CreateReturnObject(Result.SUCCESS, "1.4.5_4_gaa7839e");
}
public OperationResult GetStatistics(string argument)
{
Hashtable allStatistics = new Hashtable();
switch (argument)
{
case null:
case "":
allStatistics = GeneralStats();
break;
case "settings":
allStatistics = SettingsStats();
break;
case "items":
allStatistics = ItemsStats();
break;
case "sizes":
allStatistics = ItemSizesStats();
break;
case "slabs":
allStatistics = SlabsStats();
break;
default:
break;
}
OperationResult returnObject = CreateReturnObject(Result.SUCCESS, allStatistics);
return returnObject;
}
public OperationResult ReassignSlabs(int sourceClassID, int destinationClassID)
{
OperationResult returnObject = CreateReturnObject(Result.SUCCESS, null);
return returnObject;
}
public OperationResult AutomoveSlabs(int option)
{
OperationResult returnObject = CreateReturnObject(Result.SUCCESS, null);
return returnObject;
}
public OperationResult SetVerbosityLevel(int verbosityLevel)
{
OperationResult returnObject = CreateReturnObject(Result.SUCCESS, null);
return returnObject;
}
public void Dispose()
{
try
{
_cache.Dispose();
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
}
#endregion
#region Private Utility Methods
private OperationResult InsertItemSuccessfully(string key, uint flags, long expirationTimeInSeconds, object dataBlock)
{
if (expirationTimeInSeconds < 0)
return CreateReturnObject(Result.SUCCESS, 0);
OperationResult returnObject = new OperationResult();
try
{
ulong getVersion = GetLatestVersion();
CacheItem cacheItem = CreateCacheItem(flags, dataBlock, expirationTimeInSeconds, getVersion);
_cache.Insert(key, cacheItem);
returnObject.Value = getVersion;
returnObject.ReturnResult = Result.SUCCESS;
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return returnObject;
}
private OperationResult AddItemSuccessfully(string key, uint flags, long expirationTimeInSeconds, object dataBlock)
{
if (expirationTimeInSeconds < 0)
return CreateReturnObject(Result.SUCCESS, 0);
OperationResult returnObject = new OperationResult();
try
{
ulong getVersion = GetLatestVersion();
CacheItem cacheItem = CreateCacheItem(flags, dataBlock, expirationTimeInSeconds, getVersion);
_cache.Add(key, cacheItem);
returnObject.Value = getVersion;
returnObject.ReturnResult = Result.SUCCESS;
}
catch (Alachisoft.NCache.Runtime.Exceptions.OperationFailedException e)
{
returnObject = CreateReturnObject(Result.ITEM_EXISTS, null);
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return returnObject;
}
private OperationResult Concat(string key, object dataToPrepend, ulong casUnique, UpdateType updateType)
{
if (string.IsNullOrEmpty(key) || dataToPrepend == null)
ThrowInvalidArgumentsException();
OperationResult returnObject = new OperationResult();
try
{
CacheItem getObject = _cache.GetCacheItem(key);
if (getObject == null)
returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
else if (getObject.Value == null)
returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
else
{
MemcachedItem memCacheItem = (MemcachedItem)getObject.Value;
if ((casUnique > 0 && memCacheItem.InternalVersion == casUnique) || casUnique == 0)
returnObject = JoinObjects(key, getObject, dataToPrepend, updateType);
else
returnObject = CreateReturnObject(Result.ITEM_MODIFIED, null);
}
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return returnObject;
}
private MutateOpResult Mutate(string key, ulong value, object initialValue, long expirationTimeInSeconds, ulong casUnique, UpdateType updateType)
{
if (string.IsNullOrEmpty(key)|| (initialValue != null && IsUnsignedNumeric(initialValue) == false))
ThrowInvalidArgumentsException();
MutateOpResult returnObject = new MutateOpResult();
try
{
CacheItem getObject = _cache.GetCacheItem(key);
if (getObject == null)
{
if (initialValue == null || expirationTimeInSeconds == uint.MaxValue)
{
returnObject.ReturnResult = Result.ITEM_NOT_FOUND;
returnObject.Value = null;
}
else
{
OperationResult opResult = InsertItemSuccessfully(key, 10, expirationTimeInSeconds,
BitConverter.GetBytes(Convert.ToUInt32(initialValue)));
returnObject.Value = opResult.Value;
returnObject.ReturnResult = opResult.ReturnResult;
returnObject.MutateResult = Convert.ToUInt64(initialValue);
}
}
else
{
MemcachedItem memCacheItem = (MemcachedItem)getObject.Value;
if ((casUnique > 0 && memCacheItem.InternalVersion == casUnique) || casUnique == 0)
returnObject = UpdateIfNumeric(key, getObject, value, updateType);
else
{
returnObject.ReturnResult = Result.ITEM_MODIFIED;
returnObject.Value = null;
}
}
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return returnObject;
}
//whenever the item is updated, the version is incremented by 1
private CacheItem CreateCacheItem(uint flags, object dataBlock, long expirationTimeInSeconds, ulong version)
{
MemcachedItem memCacheItem = new MemcachedItem();
memCacheItem.Data = CreateObjectArray(flags, dataBlock);
memCacheItem.InternalVersion = version;
CacheItem cacheItem = new CacheItem(memCacheItem);
;
if (expirationTimeInSeconds != 0)
cacheItem.AbsoluteExpiration = CreateExpirationDate(expirationTimeInSeconds);
return cacheItem;
}
private byte[] CreateObjectArray(uint flags, object dataBlock)
{
byte[] flagBytes = BitConverter.GetBytes(flags);
byte[] dataBytes = (byte[])dataBlock;
byte[] objectArray = new byte[flagBytes.Length + dataBytes.Length];
System.Buffer.BlockCopy(flagBytes, 0, objectArray, 0, flagBytes.Length);
System.Buffer.BlockCopy(dataBytes, 0, objectArray, flagBytes.Length, dataBytes.Length);
return objectArray;
}
private ObjectArrayData GetObjectArrayData(object retrievedObject)
{
byte[] objectArray = (byte[])retrievedObject;
byte[] dataArray = new byte[objectArray.Length - 4];
System.Buffer.BlockCopy(objectArray, 4, dataArray, 0, dataArray.Length);
ObjectArrayData objectArrayData = new ObjectArrayData();
objectArrayData.flags = BitConverter.ToUInt32(objectArray, 0);
objectArrayData.dataBytes = dataArray;
return objectArrayData;
}
private DateTime CreateExpirationDate(long expirationTimeInSeconds)
{
DateTime dateTime;
if (expirationTimeInSeconds <= 2592000)
dateTime = DateTime.Now.AddSeconds(expirationTimeInSeconds);
else
{
System.DateTime unixTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
unixTime = unixTime.AddSeconds(expirationTimeInSeconds).ToLocalTime();
dateTime = unixTime;
}
return dateTime;
}
private OperationResult CreateReturnObject(Result result, object value)
{
OperationResult returnObject = new OperationResult();
returnObject.ReturnResult = result;
returnObject.Value = value;
return returnObject;
}
private GetOpResult CreateGetObject(string key, CacheItem cacheItem)
{
GetOpResult getObject = new GetOpResult();
MemcachedItem memCacheItem = (MemcachedItem)cacheItem.Value;
ObjectArrayData objectArrayData = GetObjectArrayData(memCacheItem.Data);
getObject.Key = key;
getObject.Flag = objectArrayData.flags;
getObject.Value = objectArrayData.dataBytes;
getObject.Version = memCacheItem.InternalVersion;
getObject.ReturnResult = Result.SUCCESS;
return getObject;
}
private OperationResult JoinObjects(string key, CacheItem cacheItem, object objectToJoin, UpdateType updateType)
{
OperationResult returnObject = new OperationResult();
ObjectArrayData objectDataArray = GetObjectArrayData(((MemcachedItem)cacheItem.Value).Data);
byte[] originalByteObject = objectDataArray.dataBytes;
byte[] byteObjectToJoin = (byte[])objectToJoin;
byte[] joinedObject = new byte[originalByteObject.Length + byteObjectToJoin.Length];
if (updateType == UpdateType.Append)
{
System.Buffer.BlockCopy(originalByteObject, 0, joinedObject, 0, originalByteObject.Length);
System.Buffer.BlockCopy(byteObjectToJoin, 0, joinedObject, originalByteObject.Length, byteObjectToJoin.Length);
}
else
{
System.Buffer.BlockCopy(byteObjectToJoin, 0, joinedObject, 0, byteObjectToJoin.Length);
System.Buffer.BlockCopy(originalByteObject, 0, joinedObject, byteObjectToJoin.Length, originalByteObject.Length);
}
try
{
MemcachedItem memCacheItem = new MemcachedItem();
memCacheItem.Data = CreateObjectArray(objectDataArray.flags, joinedObject);
ulong getVersion = GetLatestVersion();
memCacheItem.InternalVersion = getVersion;
cacheItem.Value = memCacheItem;
_cache.Insert(key, cacheItem);
returnObject = CreateReturnObject(Result.SUCCESS, getVersion);
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
return returnObject;
}
private ulong GetLatestVersion()
{
ulong version;
if (_cache.Contains(ItemVersionKey))
{
version = (ulong) _cache.Get(ItemVersionKey);
version++;
}
else
{
version = ItemVersionValue;
}
_cache.Insert(ItemVersionKey, version);
return version;
}
private MutateOpResult UpdateIfNumeric(string key, CacheItem cacheItem, ulong value, UpdateType updateType)
{
MutateOpResult returnObject = new MutateOpResult();
MemcachedItem memCachedItem = (MemcachedItem)cacheItem.Value;
if (memCachedItem != null)
{
ObjectArrayData objectDataArray = GetObjectArrayData(memCachedItem.Data);
string tempObjectString = "";
try
{
tempObjectString = Encoding.ASCII.GetString(objectDataArray.dataBytes);
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
if (IsUnsignedNumeric(tempObjectString))
{
ulong originalValue = Convert.ToUInt64(tempObjectString);
ulong finalValue;
if (updateType == UpdateType.Increment)
{
finalValue = originalValue + value;
}
else
{
if (value > originalValue)
finalValue = 0;
else
finalValue = originalValue - value;
}
try
{
MemcachedItem memCacheItem = new MemcachedItem();
memCacheItem.Data = CreateObjectArray(objectDataArray.flags, Encoding.ASCII.GetBytes(finalValue + ""));
ulong getVersion = GetLatestVersion();
memCacheItem.InternalVersion = getVersion;
cacheItem.Value = memCacheItem;
_cache.Insert(key, cacheItem);
returnObject.ReturnResult = Result.SUCCESS;
returnObject.Value = getVersion;
returnObject.MutateResult = finalValue;
}
catch (Exception e)
{
ThrowCacheRuntimeException(e);
}
}
else
{
returnObject.ReturnResult = Result.ITEM_TYPE_MISMATCHED;
returnObject.Value = null;
returnObject.MutateResult = 0;
}
}
return returnObject;
}
private bool IsUnsignedNumeric(object item)
{
try
{
Convert.ToUInt64(item);
return true;
}
catch (Exception e)
{
return false;
}
}
private void FlushExpirationCallBack(Object stateInfo)
{
try
{
ulong getVersion = (ulong)_cache.Get(ItemVersionKey);
_cache.Clear();
if (getVersion != null)
{
_cache.Insert(ItemVersionKey, getVersion);
}
else
{
_cache.Insert(ItemVersionKey, ItemVersionValue);
}
_timer.Dispose();
}
catch (Exception e)
{
//Do nothing
}
}
private void ThrowInvalidArgumentsException()
{
InvalidArgumentsException exception = new InvalidArgumentsException("Invalid Arguments Specified.");
throw exception;
}
private void ThrowCacheRuntimeException(Exception ex)
{
CacheRuntimeException exception = new CacheRuntimeException("Exception Occured at server. " + ex.Message, ex);
throw exception;
}
private Hashtable GeneralStats()
{
Hashtable generalStatistics = new Hashtable();
string statValue;
statValue = "0";
generalStatistics.Add("pid", statValue);
statValue = "0";
generalStatistics.Add("uptime", statValue);
statValue = "0";
generalStatistics.Add("time", statValue);
statValue = "0";
generalStatistics.Add("version", statValue);
statValue = "0";
generalStatistics.Add("pointer_size", statValue);
statValue = "0";
generalStatistics.Add("rusage_user", statValue);
statValue = "0";
generalStatistics.Add("rusage_system", statValue);
statValue = "0";
generalStatistics.Add("curr_items", statValue);
statValue = "0";
generalStatistics.Add("total_items", statValue);
statValue = "0";
generalStatistics.Add("bytes", statValue);
statValue = "0";
generalStatistics.Add("curr_connections", statValue);
statValue = "0";
generalStatistics.Add("total_connections", statValue);
statValue = "0";
generalStatistics.Add("connection_structures", statValue);
statValue = "0";
generalStatistics.Add("reserved_fds ", statValue);
statValue = "0";
generalStatistics.Add("cmd_get", statValue);
statValue = "0";
generalStatistics.Add("cmd_set", statValue);
statValue = "0";
generalStatistics.Add("cmd_flush", statValue);
statValue = "0";
generalStatistics.Add("cmd_touch", statValue);
statValue = "0";
generalStatistics.Add("get_hits", statValue);
statValue = "0";
generalStatistics.Add("get_misses", statValue);
statValue = "0";
generalStatistics.Add("delete_misses", statValue);
statValue = "0";
generalStatistics.Add("delete_hits", statValue);
statValue = "0";
generalStatistics.Add("incr_misses", statValue);
statValue = "0";
generalStatistics.Add("incr_hits", statValue);
statValue = "0";
generalStatistics.Add("decr_misses", statValue);
statValue = "0";
generalStatistics.Add("decr_hits", statValue);
statValue = "0";
generalStatistics.Add("cas_misses", statValue);
statValue = "0";
generalStatistics.Add("cas_hits", statValue);
statValue = "0";
generalStatistics.Add("cas_badval", statValue);
statValue = "0";
generalStatistics.Add("touch_hits", statValue);
statValue = "0";
generalStatistics.Add("touch_misses", statValue);
statValue = "0";
generalStatistics.Add("auth_cmds", statValue);
statValue = "0";
generalStatistics.Add("auth_errors", statValue);
statValue = "0";
generalStatistics.Add("evictions", statValue);
statValue = "0";
generalStatistics.Add("reclaimed", statValue);
statValue = "0";
generalStatistics.Add("bytes_read", statValue);
statValue = "0";
generalStatistics.Add("bytes_written", statValue);
statValue = "0";
generalStatistics.Add("limit_maxbytes", statValue);
statValue = "0";
generalStatistics.Add("threads", statValue);
statValue = "0";
generalStatistics.Add("conn_yields", statValue);
statValue = "0";
generalStatistics.Add("hash_power_level", statValue);
statValue = "0";
generalStatistics.Add("hash_bytes", statValue);
statValue = "0";
generalStatistics.Add("hash_is_expanding", statValue);
statValue = "0";
generalStatistics.Add("expired_unfetched", statValue);
statValue = "0";
generalStatistics.Add("evicted_unfetched", statValue);
statValue = "0";
generalStatistics.Add("slab_reassign_running", statValue);
statValue = "0";
generalStatistics.Add("slabs_moved ", statValue);
return generalStatistics;
}
private Hashtable SettingsStats()
{
Hashtable settingsStatistics = new Hashtable();
string statValue;
statValue = "0";
settingsStatistics.Add("maxbytes", statValue);
statValue = "0";
settingsStatistics.Add("maxconns", statValue);
statValue = "0";
settingsStatistics.Add("tcpport", statValue);
statValue = "0";
settingsStatistics.Add("udpport", statValue);
statValue = "0";
settingsStatistics.Add("inter", statValue);
statValue = "0";
settingsStatistics.Add("verbosity", statValue);
statValue = "0";
settingsStatistics.Add("oldest", statValue);
statValue = "0";
settingsStatistics.Add("evictions", statValue);
statValue = "0";
settingsStatistics.Add("domain_socket", statValue);
statValue = "0";
settingsStatistics.Add("umask", statValue);
statValue = "0";
settingsStatistics.Add("growth_factor", statValue);
statValue = "0";
settingsStatistics.Add("chunk_size", statValue);
statValue = "0";
settingsStatistics.Add("num_threads", statValue);
statValue = "0";
settingsStatistics.Add("stat_key_prefix", statValue);
statValue = "0";
settingsStatistics.Add("detail_enabled", statValue);
statValue = "0";
settingsStatistics.Add("reqs_per_event", statValue);
statValue = "0";
settingsStatistics.Add("cas_enabled", statValue);
statValue = "0";
settingsStatistics.Add("tcp_backlog", statValue);
statValue = "0";
settingsStatistics.Add("auth_enabled_sasl", statValue);
statValue = "0";
settingsStatistics.Add("item_size_max", statValue);
statValue = "0";
settingsStatistics.Add("maxconns_fast", statValue);
statValue = "0";
settingsStatistics.Add("hashpower_init", statValue);
statValue = "0";
settingsStatistics.Add("slab_reassign", statValue);
statValue = "0";
settingsStatistics.Add("slab_automove", statValue);
return settingsStatistics;
}
private Hashtable ItemsStats()
{
Hashtable itemsStatistics = new Hashtable();
string statValue;
statValue = "0";
itemsStatistics.Add("number", statValue);
statValue = "0";
itemsStatistics.Add("age", statValue);
statValue = "0";
itemsStatistics.Add("evicted", statValue);
statValue = "0";
itemsStatistics.Add("evicted_nonzero", statValue);
statValue = "0";
itemsStatistics.Add("evicted_time", statValue);
statValue = "0";
itemsStatistics.Add("outofmemory", statValue);
statValue = "0";
itemsStatistics.Add("tailrepairs", statValue);
statValue = "0";
itemsStatistics.Add("reclaimed", statValue);
statValue = "0";
itemsStatistics.Add("expired_unfetched", statValue);
statValue = "0";
itemsStatistics.Add("evicted_unfetched", statValue);
return itemsStatistics;
}
private Hashtable ItemSizesStats()
{
Hashtable itemSizesStatistics = new Hashtable();
itemSizesStatistics.Add("0", "0");
return itemSizesStatistics;
}
private Hashtable SlabsStats()
{
Hashtable generalStatistics = new Hashtable();
string statValue;
statValue = "0";
generalStatistics.Add("pid", statValue);
statValue = "0";
generalStatistics.Add("uptime", statValue);
statValue = "0";
generalStatistics.Add("time", statValue);
statValue = "0";
generalStatistics.Add("version", statValue);
statValue = "0";
generalStatistics.Add("pointer_size", statValue);
statValue = "0";
generalStatistics.Add("rusage_user", statValue);
statValue = "0";
generalStatistics.Add("rusage_system", statValue);
statValue = "0";
generalStatistics.Add("curr_items", statValue);
statValue = "0";
generalStatistics.Add("total_items", statValue);
statValue = "0";
generalStatistics.Add("bytes", statValue);
statValue = "0";
generalStatistics.Add("curr_connections", statValue);
statValue = "0";
generalStatistics.Add("total_connections", statValue);
statValue = "0";
generalStatistics.Add("connection_structures", statValue);
statValue = "0";
generalStatistics.Add("reserved_fds ", statValue);
statValue = "0";
generalStatistics.Add("cmd_get", statValue);
statValue = "0";
generalStatistics.Add("cmd_set", statValue);
statValue = "0";
generalStatistics.Add("cmd_flush", statValue);
statValue = "0";
generalStatistics.Add("cmd_touch", statValue);
statValue = "0";
generalStatistics.Add("get_hits", statValue);
statValue = "0";
generalStatistics.Add("get_misses", statValue);
statValue = "0";
generalStatistics.Add("delete_misses", statValue);
statValue = "0";
generalStatistics.Add("delete_hits", statValue);
statValue = "0";
generalStatistics.Add("incr_misses", statValue);
statValue = "0";
generalStatistics.Add("incr_hits", statValue);
statValue = "0";
generalStatistics.Add("decr_misses", statValue);
statValue = "0";
generalStatistics.Add("decr_hits", statValue);
statValue = "0";
generalStatistics.Add("cas_misses", statValue);
statValue = "0";
generalStatistics.Add("cas_hits", statValue);
statValue = "0";
generalStatistics.Add("cas_badval", statValue);
statValue = "0";
generalStatistics.Add("touch_hits", statValue);
statValue = "0";
generalStatistics.Add("touch_misses", statValue);
statValue = "0";
generalStatistics.Add("auth_cmds", statValue);
statValue = "0";
generalStatistics.Add("auth_errors", statValue);
statValue = "0";
generalStatistics.Add("evictions", statValue);
statValue = "0";
generalStatistics.Add("reclaimed", statValue);
statValue = "0";
generalStatistics.Add("bytes_read", statValue);
statValue = "0";
generalStatistics.Add("bytes_written", statValue);
statValue = "0";
generalStatistics.Add("limit_maxbytes", statValue);
statValue = "0";
generalStatistics.Add("threads", statValue);
statValue = "0";
generalStatistics.Add("conn_yields", statValue);
statValue = "0";
generalStatistics.Add("hash_power_level", statValue);
statValue = "0";
generalStatistics.Add("hash_bytes", statValue);
statValue = "0";
generalStatistics.Add("hash_is_expanding", statValue);
statValue = "0";
generalStatistics.Add("expired_unfetched", statValue);
statValue = "0";
generalStatistics.Add("evicted_unfetched", statValue);
statValue = "0";
generalStatistics.Add("slab_reassign_running", statValue);
statValue = "0";
generalStatistics.Add("slabs_moved ", statValue);
return generalStatistics;
}
#endregion
private enum UpdateType
{
Append,
Prepend,
Increment,
Decrement
}
private struct ObjectArrayData
{
public uint flags;
public byte[] dataBytes;
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.LogicalTree;
using Xunit;
namespace Avalonia.Styling.UnitTests
{
public class SelectorTests_Descendant
{
[Fact]
public void Descendant_Matches_Control_When_It_Is_Child_OfType()
{
var parent = new TestLogical1();
var child = new TestLogical2();
child.LogicalParent = parent;
var selector = default(Selector).OfType<TestLogical1>().Descendant().OfType<TestLogical2>();
Assert.True(selector.Match(child).ImmediateResult);
}
[Fact]
public void Descendant_Matches_Control_When_It_Is_Descendant_OfType()
{
var grandparent = new TestLogical1();
var parent = new TestLogical2();
var child = new TestLogical3();
parent.LogicalParent = grandparent;
child.LogicalParent = parent;
var selector = default(Selector).OfType<TestLogical1>().Descendant().OfType<TestLogical3>();
Assert.True(selector.Match(child).ImmediateResult);
}
[Fact]
public async Task Descendant_Matches_Control_When_It_Is_Descendant_OfType_And_Class()
{
var grandparent = new TestLogical1();
var parent = new TestLogical2();
var child = new TestLogical3();
grandparent.Classes.Add("foo");
parent.LogicalParent = grandparent;
child.LogicalParent = parent;
var selector = default(Selector).OfType<TestLogical1>().Class("foo").Descendant().OfType<TestLogical3>();
var activator = selector.Match(child).ObservableResult;
Assert.True(await activator.Take(1));
}
[Fact]
public async Task Descendant_Doesnt_Match_Control_When_It_Is_Descendant_OfType_But_Wrong_Class()
{
var grandparent = new TestLogical1();
var parent = new TestLogical2();
var child = new TestLogical3();
grandparent.Classes.Add("bar");
parent.LogicalParent = grandparent;
parent.Classes.Add("foo");
child.LogicalParent = parent;
var selector = default(Selector).OfType<TestLogical1>().Class("foo").Descendant().OfType<TestLogical3>();
var activator = selector.Match(child).ObservableResult;
Assert.False(await activator.Take(1));
}
[Fact]
public async Task Descendant_Matches_Any_Ancestor()
{
var grandparent = new TestLogical1();
var parent = new TestLogical1();
var child = new TestLogical3();
parent.LogicalParent = grandparent;
child.LogicalParent = parent;
var selector = default(Selector).OfType<TestLogical1>().Class("foo").Descendant().OfType<TestLogical3>();
var activator = selector.Match(child).ObservableResult;
Assert.False(await activator.Take(1));
parent.Classes.Add("foo");
Assert.True(await activator.Take(1));
grandparent.Classes.Add("foo");
Assert.True(await activator.Take(1));
parent.Classes.Remove("foo");
Assert.True(await activator.Take(1));
grandparent.Classes.Remove("foo");
Assert.False(await activator.Take(1));
}
[Fact]
public void Descendant_Selector_Should_Have_Correct_String_Representation()
{
var selector = default(Selector).OfType<TestLogical1>().Class("foo").Descendant().OfType<TestLogical3>();
Assert.Equal("TestLogical1.foo TestLogical3", selector.ToString());
}
public abstract class TestLogical : ILogical, IStyleable
{
public TestLogical()
{
Classes = new Classes();
}
public event EventHandler<AvaloniaPropertyChangedEventArgs> PropertyChanged;
public event EventHandler<LogicalTreeAttachmentEventArgs> AttachedToLogicalTree;
public event EventHandler<LogicalTreeAttachmentEventArgs> DetachedFromLogicalTree;
public Classes Classes { get; }
public string Name { get; set; }
public bool IsAttachedToLogicalTree { get; }
public IAvaloniaReadOnlyList<ILogical> LogicalChildren { get; set; }
public ILogical LogicalParent { get; set; }
public Type StyleKey { get; }
public ITemplatedControl TemplatedParent { get; }
IAvaloniaReadOnlyList<string> IStyleable.Classes => Classes;
IObservable<IStyleable> IStyleable.StyleDetach { get; }
public object GetValue(AvaloniaProperty property)
{
throw new NotImplementedException();
}
public T GetValue<T>(AvaloniaProperty<T> property)
{
throw new NotImplementedException();
}
public void SetValue(AvaloniaProperty property, object value, BindingPriority priority)
{
throw new NotImplementedException();
}
public void SetValue<T>(AvaloniaProperty<T> property, T value, BindingPriority priority = BindingPriority.LocalValue)
{
throw new NotImplementedException();
}
public IDisposable Bind(AvaloniaProperty property, IObservable<object> source, BindingPriority priority = BindingPriority.LocalValue)
{
throw new NotImplementedException();
}
public bool IsAnimating(AvaloniaProperty property)
{
throw new NotImplementedException();
}
public bool IsSet(AvaloniaProperty property)
{
throw new NotImplementedException();
}
public IDisposable Bind<T>(AvaloniaProperty<T> property, IObservable<T> source, BindingPriority priority = BindingPriority.LocalValue)
{
throw new NotImplementedException();
}
public void NotifyAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
throw new NotImplementedException();
}
public void NotifyDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
throw new NotImplementedException();
}
public void NotifyResourcesChanged(ResourcesChangedEventArgs e)
{
throw new NotImplementedException();
}
}
public class TestLogical1 : TestLogical
{
}
public class TestLogical2 : TestLogical
{
}
public class TestLogical3 : TestLogical
{
}
}
}
| |
namespace Pathfinding {
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public struct AstarWorkItem {
/** Init function.
* May be null if no initialization is needed.
* Will be called once, right before the first call to #update.
*/
public System.Action init;
/** Init function.
* May be null if no initialization is needed.
* Will be called once, right before the first call to #update.
*
* A context object is sent as a parameter. This can be used
* to for example queue a flood fill that will be executed either
* when a work item calls EnsureValidFloodFill or all work items have
* been completed. If multiple work items are updating nodes
* so that they need a flood fill afterwards, using the QueueFloodFill
* method is preferred since then only a single flood fill needs
* to be performed for all of the work items instead of one
* per work item.
*/
public System.Action<IWorkItemContext> initWithContext;
/** Update function, called once per frame when the work item executes.
* Takes a param \a force. If that is true, the work item should try to complete the whole item in one go instead
* of spreading it out over multiple frames.
* \returns True when the work item is completed.
*/
public System.Func<bool, bool> update;
/** Update function, called once per frame when the work item executes.
* Takes a param \a force. If that is true, the work item should try to complete the whole item in one go instead
* of spreading it out over multiple frames.
* \returns True when the work item is completed.
*
* A context object is sent as a parameter. This can be used
* to for example queue a flood fill that will be executed either
* when a work item calls EnsureValidFloodFill or all work items have
* been completed. If multiple work items are updating nodes
* so that they need a flood fill afterwards, using the QueueFloodFill
* method is preferred since then only a single flood fill needs
* to be performed for all of the work items instead of one
* per work item.
*/
public System.Func<IWorkItemContext, bool, bool> updateWithContext;
public AstarWorkItem (System.Func<bool, bool> update) {
this.init = null;
this.initWithContext = null;
this.updateWithContext = null;
this.update = update;
}
public AstarWorkItem (System.Func<IWorkItemContext, bool, bool> update) {
this.init = null;
this.initWithContext = null;
this.updateWithContext = update;
this.update = null;
}
public AstarWorkItem (System.Action init, System.Func<bool, bool> update = null) {
this.init = init;
this.initWithContext = null;
this.update = update;
this.updateWithContext = null;
}
public AstarWorkItem (System.Action<IWorkItemContext> init, System.Func<IWorkItemContext, bool, bool> update = null) {
this.init = null;
this.initWithContext = init;
this.update = null;
this.updateWithContext = update;
}
}
/** Interface to expose a subset of the WorkItemProcessor functionality */
public interface IWorkItemContext {
/** Call during work items to queue a flood fill.
* An instant flood fill can be done via FloodFill()
* but this method can be used to batch several updates into one
* to increase performance.
* WorkItems which require a valid Flood Fill in their execution can call EnsureValidFloodFill
* to ensure that a flood fill is done if any earlier work items queued one.
*
* Once a flood fill is queued it will be done after all WorkItems have been executed.
*/
void QueueFloodFill ();
/** If a WorkItem needs to have a valid flood fill during execution, call this method to ensure there are no pending flood fills */
void EnsureValidFloodFill ();
}
class WorkItemProcessor : IWorkItemContext {
/** Used to prevent waiting for work items to complete inside other work items as that will cause the program to hang */
bool workItemsInProgressRightNow = false;
readonly AstarPath astar;
readonly IndexedQueue<AstarWorkItem> workItems = new IndexedQueue<AstarWorkItem>();
/** True if any work items have queued a flood fill.
* \see QueueWorkItemFloodFill
*/
bool queuedWorkItemFloodFill = false;
/**
* True while a batch of work items are being processed.
* Set to true when a work item is started to be processed, reset to false when all work items are complete.
*
* Work item updates are often spread out over several frames, this flag will be true during the whole time the
* updates are in progress.
*/
public bool workItemsInProgress {get; private set;}
/** Similar to Queue<T> but allows random access */
class IndexedQueue<T> {
T[] buffer = new T[4];
int start;
int length;
public T this[int index] {
get {
if (index < 0 || index >= length) throw new System.IndexOutOfRangeException();
return buffer[(start + index) % buffer.Length];
}
set {
if (index < 0 || index >= length) throw new System.IndexOutOfRangeException();
buffer[(start + index) % buffer.Length] = value;
}
}
public int Count {
get {
return length;
}
}
public void Enqueue (T item) {
if (length == buffer.Length) {
var newBuffer = new T[buffer.Length*2];
for (int i = 0; i < length; i++) {
newBuffer[i] = this[i];
}
buffer = newBuffer;
start = 0;
}
buffer[(start + length) % buffer.Length] = item;
length++;
}
public T Dequeue () {
if (length == 0) throw new System.InvalidOperationException();
var item = buffer[start];
start = (start + 1) % buffer.Length;
length--;
return item;
}
}
/** Call during work items to queue a flood fill.
* An instant flood fill can be done via FloodFill()
* but this method can be used to batch several updates into one
* to increase performance.
* WorkItems which require a valid Flood Fill in their execution can call EnsureValidFloodFill
* to ensure that a flood fill is done if any earlier work items queued one.
*
* Once a flood fill is queued it will be done after all WorkItems have been executed.
*/
void IWorkItemContext.QueueFloodFill () {
queuedWorkItemFloodFill = true;
}
/** If a WorkItem needs to have a valid flood fill during execution, call this method to ensure there are no pending flood fills */
public void EnsureValidFloodFill () {
if (queuedWorkItemFloodFill) {
astar.FloodFill();
}
}
public WorkItemProcessor (AstarPath astar) {
this.astar = astar;
}
public void OnFloodFill () {
queuedWorkItemFloodFill = false;
}
/** Add a work item to be processed when pathfinding is paused.
*
* \see ProcessWorkItems
*/
public void AddWorkItem (AstarWorkItem itm) {
workItems.Enqueue (itm);
}
/** Process graph updating work items.
* Process all queued work items, e.g graph updates and the likes.
*
* \returns
* - false if there are still items to be processed.
* - true if the last work items was processed and pathfinding threads are ready to be resumed.
*
* \see AddWorkItem
* \see threadSafeUpdateState
* \see Update
*/
public bool ProcessWorkItems (bool force) {
if (workItemsInProgressRightNow) throw new System.Exception ("Processing work items recursively. Please do not wait for other work items to be completed inside work items. " +
"If you think this is not caused by any of your scripts, this might be a bug.");
workItemsInProgressRightNow = true;
while (workItems.Count > 0) {
// Working on a new batch
if (!workItemsInProgress) {
workItemsInProgress = true;
queuedWorkItemFloodFill = false;
}
// Peek at first item in the queue
AstarWorkItem itm = workItems[0];
// Call init the first time the item is seen
if (itm.init != null) {
itm.init ();
itm.init = null;
}
if (itm.initWithContext != null) {
itm.initWithContext(this);
itm.initWithContext = null;
}
// Make sure the item in the queue is up to date
workItems[0] = itm;
bool status;
try {
if (itm.update != null) {
status = itm.update (force);
} else if (itm.updateWithContext != null) {
status = itm.updateWithContext(this, force);
} else {
status = true;
}
} catch {
workItems.Dequeue();
workItemsInProgressRightNow = false;
throw;
}
if (!status) {
if (force) {
Debug.LogError ("Misbehaving WorkItem. 'force'=true but the work item did not complete.\nIf force=true is passed to a WorkItem it should always return true.");
}
// Still work items to process
workItemsInProgressRightNow = false;
return false;
} else {
workItems.Dequeue();
}
}
EnsureValidFloodFill ();
workItemsInProgressRightNow = false;
workItemsInProgress = false;
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Client.GameTicking.Managers;
using Content.Client.HUD.UI;
using Content.Shared.Roles;
using Content.Shared.Station;
using Robust.Client.Console;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using Robust.Client.Utility;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes;
using Robust.Shared.Utility;
using static Robust.Client.UserInterface.Controls.BoxContainer;
namespace Content.Client.LateJoin
{
public sealed class LateJoinGui : DefaultWindow
{
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly IClientConsoleHost _consoleHost = default!;
public event Action<(StationId, string)> SelectedId;
private readonly Dictionary<StationId, Dictionary<string, JobButton>> _jobButtons = new();
private readonly Dictionary<StationId, Dictionary<string, BoxContainer>> _jobCategories = new();
private readonly List<ScrollContainer> _jobLists = new();
private readonly Control _base;
public LateJoinGui()
{
MinSize = SetSize = (360, 560);
IoCManager.InjectDependencies(this);
var gameTicker = EntitySystem.Get<ClientGameTicker>();
Title = Loc.GetString("late-join-gui-title");
_base = new BoxContainer()
{
Orientation = LayoutOrientation.Vertical,
VerticalExpand = true,
Margin = new Thickness(0),
};
Contents.AddChild(_base);
RebuildUI();
SelectedId += x =>
{
var (station, jobId) = x;
Logger.InfoS("latejoin", $"Late joining as ID: {jobId}");
_consoleHost.ExecuteCommand($"joingame {CommandParsing.Escape(jobId)} {station.Id}");
Close();
};
gameTicker.LobbyJobsAvailableUpdated += JobsAvailableUpdated;
}
private void RebuildUI()
{
_base.RemoveAllChildren();
_jobLists.Clear();
_jobButtons.Clear();
_jobCategories.Clear();
var gameTicker = EntitySystem.Get<ClientGameTicker>();
foreach (var (id, name) in gameTicker.StationNames)
{
var jobList = new BoxContainer
{
Orientation = LayoutOrientation.Vertical
};
var collapseButton = new ContainerButton()
{
HorizontalAlignment = HAlignment.Right,
ToggleMode = true,
Children =
{
new TextureRect
{
StyleClasses = { OptionButton.StyleClassOptionTriangle },
Margin = new Thickness(8, 0),
HorizontalAlignment = HAlignment.Center,
VerticalAlignment = VAlignment.Center,
}
}
};
_base.AddChild(new StripeBack()
{
Children = {
new PanelContainer()
{
Children =
{
new Label()
{
StyleClasses = { "LabelBig" },
Text = name,
Align = Label.AlignMode.Center,
},
collapseButton
}
}
}
});
var jobListScroll = new ScrollContainer()
{
VerticalExpand = true,
Children = {jobList},
Visible = false,
};
if (_jobLists.Count == 0)
jobListScroll.Visible = true;
_jobLists.Add(jobListScroll);
_base.AddChild(jobListScroll);
collapseButton.OnToggled += _ =>
{
foreach (var section in _jobLists)
{
section.Visible = false;
}
jobListScroll.Visible = true;
};
var firstCategory = true;
foreach (var job in gameTicker.JobsAvailable[id].OrderBy(x => x.Key))
{
var prototype = _prototypeManager.Index<JobPrototype>(job.Key);
foreach (var department in prototype.Departments)
{
if (!_jobCategories.TryGetValue(id, out var _))
_jobCategories[id] = new Dictionary<string, BoxContainer>();
if (!_jobButtons.TryGetValue(id, out var _))
_jobButtons[id] = new Dictionary<string, JobButton>();
if (!_jobCategories[id].TryGetValue(department, out var category))
{
category = new BoxContainer
{
Orientation = LayoutOrientation.Vertical,
Name = department,
ToolTip = Loc.GetString("late-join-gui-jobs-amount-in-department-tooltip",
("departmentName", department))
};
if (firstCategory)
{
firstCategory = false;
}
else
{
category.AddChild(new Control
{
MinSize = new Vector2(0, 23),
});
}
category.AddChild(new PanelContainer
{
Children =
{
new Label
{
StyleClasses = { "LabelBig" },
Text = Loc.GetString("late-join-gui-department-jobs-label", ("departmentName", department))
}
}
});
_jobCategories[id][department] = category;
jobList.AddChild(category);
}
var jobButton = new JobButton(prototype.ID, job.Value);
var jobSelector = new BoxContainer
{
Orientation = LayoutOrientation.Horizontal,
HorizontalExpand = true
};
var icon = new TextureRect
{
TextureScale = (2, 2),
Stretch = TextureRect.StretchMode.KeepCentered
};
if (prototype.Icon != null)
{
var specifier = new SpriteSpecifier.Rsi(new ResourcePath("/Textures/Interface/Misc/job_icons.rsi"), prototype.Icon);
icon.Texture = specifier.Frame0();
}
jobSelector.AddChild(icon);
var jobLabel = new Label
{
Text = job.Value >= 0 ?
Loc.GetString("late-join-gui-job-slot-capped", ("jobName", prototype.Name), ("amount", job.Value)) :
Loc.GetString("late-join-gui-job-slot-uncapped", ("jobName", prototype.Name))
};
jobSelector.AddChild(jobLabel);
jobButton.AddChild(jobSelector);
category.AddChild(jobButton);
jobButton.OnPressed += _ =>
{
SelectedId?.Invoke((id, jobButton.JobId));
};
if (job.Value == 0)
{
jobButton.Disabled = true;
}
_jobButtons[id][prototype.ID] = jobButton;
}
}
}
}
private void JobsAvailableUpdated(IReadOnlyDictionary<StationId, Dictionary<string, int>> _)
{
RebuildUI();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
EntitySystem.Get<ClientGameTicker>().LobbyJobsAvailableUpdated -= JobsAvailableUpdated;
_jobButtons.Clear();
_jobCategories.Clear();
}
}
}
sealed class JobButton : ContainerButton
{
public string JobId { get; }
public int Amount { get; }
public JobButton(string jobId, int amount)
{
JobId = jobId;
Amount = amount;
AddStyleClass(StyleClassButton);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Collections
{
public static class __ArrayList
{
public static IObservable<System.Collections.ArrayList> Adapter(IObservable<System.Collections.IList> list)
{
return Observable.Select(list, (listLambda) => System.Collections.ArrayList.Adapter(listLambda));
}
public static IObservable<System.Int32> Add(this IObservable<System.Collections.ArrayList> ArrayListValue,
IObservable<System.Object> value)
{
return Observable.Zip(ArrayListValue, value,
(ArrayListValueLambda, valueLambda) => ArrayListValueLambda.Add(valueLambda));
}
public static IObservable<System.Reactive.Unit> AddRange(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Collections.ICollection> c)
{
return ObservableExt.ZipExecute(ArrayListValue, c,
(ArrayListValueLambda, cLambda) => ArrayListValueLambda.AddRange(cLambda));
}
public static IObservable<System.Int32> BinarySearch(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> index,
IObservable<System.Int32> count, IObservable<System.Object> value,
IObservable<System.Collections.IComparer> comparer)
{
return Observable.Zip(ArrayListValue, index, count, value, comparer,
(ArrayListValueLambda, indexLambda, countLambda, valueLambda, comparerLambda) =>
ArrayListValueLambda.BinarySearch(indexLambda, countLambda, valueLambda, comparerLambda));
}
public static IObservable<System.Int32> BinarySearch(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Object> value)
{
return Observable.Zip(ArrayListValue, value,
(ArrayListValueLambda, valueLambda) => ArrayListValueLambda.BinarySearch(valueLambda));
}
public static IObservable<System.Int32> BinarySearch(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Object> value,
IObservable<System.Collections.IComparer> comparer)
{
return Observable.Zip(ArrayListValue, value, comparer,
(ArrayListValueLambda, valueLambda, comparerLambda) =>
ArrayListValueLambda.BinarySearch(valueLambda, comparerLambda));
}
public static IObservable<System.Reactive.Unit> Clear(
this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Do(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.Clear()).ToUnit();
}
public static IObservable<System.Object> Clone(this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Select(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.Clone());
}
public static IObservable<System.Boolean> Contains(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Object> item)
{
return Observable.Zip(ArrayListValue, item,
(ArrayListValueLambda, itemLambda) => ArrayListValueLambda.Contains(itemLambda));
}
public static IObservable<System.Reactive.Unit> CopyTo(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Array> array)
{
return ObservableExt.ZipExecute(ArrayListValue, array,
(ArrayListValueLambda, arrayLambda) => ArrayListValueLambda.CopyTo(arrayLambda));
}
public static IObservable<System.Reactive.Unit> CopyTo(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Array> array,
IObservable<System.Int32> arrayIndex)
{
return ObservableExt.ZipExecute(ArrayListValue, array, arrayIndex,
(ArrayListValueLambda, arrayLambda, arrayIndexLambda) =>
ArrayListValueLambda.CopyTo(arrayLambda, arrayIndexLambda));
}
public static IObservable<System.Reactive.Unit> CopyTo(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> index,
IObservable<System.Array> array, IObservable<System.Int32> arrayIndex, IObservable<System.Int32> count)
{
return ObservableExt.ZipExecute(ArrayListValue, index, array, arrayIndex, count,
(ArrayListValueLambda, indexLambda, arrayLambda, arrayIndexLambda, countLambda) =>
ArrayListValueLambda.CopyTo(indexLambda, arrayLambda, arrayIndexLambda, countLambda));
}
public static IObservable<System.Collections.IList> FixedSize(IObservable<System.Collections.IList> list)
{
return Observable.Select(list, (listLambda) => System.Collections.ArrayList.FixedSize(listLambda));
}
public static IObservable<System.Collections.ArrayList> FixedSize(IObservable<System.Collections.ArrayList> list)
{
return Observable.Select(list, (listLambda) => System.Collections.ArrayList.FixedSize(listLambda));
}
public static IObservable<System.Collections.IEnumerator> GetEnumerator(
this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Select(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.GetEnumerator());
}
public static IObservable<System.Collections.IEnumerator> GetEnumerator(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> index,
IObservable<System.Int32> count)
{
return Observable.Zip(ArrayListValue, index, count,
(ArrayListValueLambda, indexLambda, countLambda) =>
ArrayListValueLambda.GetEnumerator(indexLambda, countLambda));
}
public static IObservable<System.Int32> IndexOf(this IObservable<System.Collections.ArrayList> ArrayListValue,
IObservable<System.Object> value)
{
return Observable.Zip(ArrayListValue, value,
(ArrayListValueLambda, valueLambda) => ArrayListValueLambda.IndexOf(valueLambda));
}
public static IObservable<System.Int32> IndexOf(this IObservable<System.Collections.ArrayList> ArrayListValue,
IObservable<System.Object> value, IObservable<System.Int32> startIndex)
{
return Observable.Zip(ArrayListValue, value, startIndex,
(ArrayListValueLambda, valueLambda, startIndexLambda) =>
ArrayListValueLambda.IndexOf(valueLambda, startIndexLambda));
}
public static IObservable<System.Int32> IndexOf(this IObservable<System.Collections.ArrayList> ArrayListValue,
IObservable<System.Object> value, IObservable<System.Int32> startIndex, IObservable<System.Int32> count)
{
return Observable.Zip(ArrayListValue, value, startIndex, count,
(ArrayListValueLambda, valueLambda, startIndexLambda, countLambda) =>
ArrayListValueLambda.IndexOf(valueLambda, startIndexLambda, countLambda));
}
public static IObservable<System.Reactive.Unit> Insert(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> index,
IObservable<System.Object> value)
{
return ObservableExt.ZipExecute(ArrayListValue, index, value,
(ArrayListValueLambda, indexLambda, valueLambda) =>
ArrayListValueLambda.Insert(indexLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> InsertRange(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> index,
IObservable<System.Collections.ICollection> c)
{
return ObservableExt.ZipExecute(ArrayListValue, index, c,
(ArrayListValueLambda, indexLambda, cLambda) => ArrayListValueLambda.InsertRange(indexLambda, cLambda));
}
public static IObservable<System.Int32> LastIndexOf(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Object> value)
{
return Observable.Zip(ArrayListValue, value,
(ArrayListValueLambda, valueLambda) => ArrayListValueLambda.LastIndexOf(valueLambda));
}
public static IObservable<System.Int32> LastIndexOf(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Object> value,
IObservable<System.Int32> startIndex)
{
return Observable.Zip(ArrayListValue, value, startIndex,
(ArrayListValueLambda, valueLambda, startIndexLambda) =>
ArrayListValueLambda.LastIndexOf(valueLambda, startIndexLambda));
}
public static IObservable<System.Int32> LastIndexOf(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Object> value,
IObservable<System.Int32> startIndex, IObservable<System.Int32> count)
{
return Observable.Zip(ArrayListValue, value, startIndex, count,
(ArrayListValueLambda, valueLambda, startIndexLambda, countLambda) =>
ArrayListValueLambda.LastIndexOf(valueLambda, startIndexLambda, countLambda));
}
public static IObservable<System.Collections.IList> ReadOnly(IObservable<System.Collections.IList> list)
{
return Observable.Select(list, (listLambda) => System.Collections.ArrayList.ReadOnly(listLambda));
}
public static IObservable<System.Collections.ArrayList> ReadOnly(IObservable<System.Collections.ArrayList> list)
{
return Observable.Select(list, (listLambda) => System.Collections.ArrayList.ReadOnly(listLambda));
}
public static IObservable<System.Reactive.Unit> Remove(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Object> obj)
{
return ObservableExt.ZipExecute(ArrayListValue, obj,
(ArrayListValueLambda, objLambda) => ArrayListValueLambda.Remove(objLambda));
}
public static IObservable<System.Reactive.Unit> RemoveAt(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> index)
{
return ObservableExt.ZipExecute(ArrayListValue, index,
(ArrayListValueLambda, indexLambda) => ArrayListValueLambda.RemoveAt(indexLambda));
}
public static IObservable<System.Reactive.Unit> RemoveRange(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> index,
IObservable<System.Int32> count)
{
return ObservableExt.ZipExecute(ArrayListValue, index, count,
(ArrayListValueLambda, indexLambda, countLambda) =>
ArrayListValueLambda.RemoveRange(indexLambda, countLambda));
}
public static IObservable<System.Collections.ArrayList> Repeat(IObservable<System.Object> value,
IObservable<System.Int32> count)
{
return Observable.Zip(value, count,
(valueLambda, countLambda) => System.Collections.ArrayList.Repeat(valueLambda, countLambda));
}
public static IObservable<System.Reactive.Unit> Reverse(
this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Do(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.Reverse()).ToUnit();
}
public static IObservable<System.Reactive.Unit> Reverse(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> index,
IObservable<System.Int32> count)
{
return ObservableExt.ZipExecute(ArrayListValue, index, count,
(ArrayListValueLambda, indexLambda, countLambda) =>
ArrayListValueLambda.Reverse(indexLambda, countLambda));
}
public static IObservable<System.Reactive.Unit> SetRange(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> index,
IObservable<System.Collections.ICollection> c)
{
return ObservableExt.ZipExecute(ArrayListValue, index, c,
(ArrayListValueLambda, indexLambda, cLambda) => ArrayListValueLambda.SetRange(indexLambda, cLambda));
}
public static IObservable<System.Collections.ArrayList> GetRange(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> index,
IObservable<System.Int32> count)
{
return Observable.Zip(ArrayListValue, index, count,
(ArrayListValueLambda, indexLambda, countLambda) =>
ArrayListValueLambda.GetRange(indexLambda, countLambda));
}
public static IObservable<System.Reactive.Unit> Sort(
this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Do(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.Sort()).ToUnit();
}
public static IObservable<System.Reactive.Unit> Sort(
this IObservable<System.Collections.ArrayList> ArrayListValue,
IObservable<System.Collections.IComparer> comparer)
{
return ObservableExt.ZipExecute(ArrayListValue, comparer,
(ArrayListValueLambda, comparerLambda) => ArrayListValueLambda.Sort(comparerLambda));
}
public static IObservable<System.Reactive.Unit> Sort(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> index,
IObservable<System.Int32> count, IObservable<System.Collections.IComparer> comparer)
{
return ObservableExt.ZipExecute(ArrayListValue, index, count, comparer,
(ArrayListValueLambda, indexLambda, countLambda, comparerLambda) =>
ArrayListValueLambda.Sort(indexLambda, countLambda, comparerLambda));
}
public static IObservable<System.Collections.IList> Synchronized(IObservable<System.Collections.IList> list)
{
return Observable.Select(list, (listLambda) => System.Collections.ArrayList.Synchronized(listLambda));
}
public static IObservable<System.Collections.ArrayList> Synchronized(
IObservable<System.Collections.ArrayList> list)
{
return Observable.Select(list, (listLambda) => System.Collections.ArrayList.Synchronized(listLambda));
}
public static IObservable<System.Object[]> ToArray(this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Select(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.ToArray());
}
public static IObservable<System.Array> ToArray(this IObservable<System.Collections.ArrayList> ArrayListValue,
IObservable<System.Type> type)
{
return Observable.Zip(ArrayListValue, type,
(ArrayListValueLambda, typeLambda) => ArrayListValueLambda.ToArray(typeLambda));
}
public static IObservable<System.Reactive.Unit> TrimToSize(
this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Do(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.TrimToSize()).ToUnit();
}
public static IObservable<System.Int32> get_Capacity(
this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Select(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.Capacity);
}
public static IObservable<System.Int32> get_Count(this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Select(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.Count);
}
public static IObservable<System.Boolean> get_IsFixedSize(
this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Select(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.IsFixedSize);
}
public static IObservable<System.Boolean> get_IsReadOnly(
this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Select(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.IsReadOnly);
}
public static IObservable<System.Boolean> get_IsSynchronized(
this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Select(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.IsSynchronized);
}
public static IObservable<System.Object> get_SyncRoot(
this IObservable<System.Collections.ArrayList> ArrayListValue)
{
return Observable.Select(ArrayListValue, (ArrayListValueLambda) => ArrayListValueLambda.SyncRoot);
}
public static IObservable<System.Object> get_Item(this IObservable<System.Collections.ArrayList> ArrayListValue,
IObservable<System.Int32> index)
{
return Observable.Zip(ArrayListValue, index,
(ArrayListValueLambda, indexLambda) => ArrayListValueLambda[indexLambda]);
}
public static IObservable<System.Reactive.Unit> set_Capacity(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(ArrayListValue, value,
(ArrayListValueLambda, valueLambda) => ArrayListValueLambda.Capacity = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Item(
this IObservable<System.Collections.ArrayList> ArrayListValue, IObservable<System.Int32> index,
IObservable<System.Object> value)
{
return ObservableExt.ZipExecute(ArrayListValue, index, value,
(ArrayListValueLambda, indexLambda, valueLambda) => ArrayListValueLambda[indexLambda] = valueLambda);
}
}
}
| |
/*
* CurrencyManager.cs - Implementation of the
* "System.Windows.Forms.CurrencyManager" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Windows.Forms
{
using System.ComponentModel;
using System.Collections;
public class CurrencyManager : BindingManagerBase
{
// Internal state.
private Object dataSource;
private IList list;
private int position;
// Constructor.
internal CurrencyManager(Object dataSource)
{
this.dataSource = dataSource;
this.list = (dataSource as IList);
if(list != null)
{
this.position = 0;
}
else
{
this.position = -1;
}
}
// Get the number of rows managed by the manager base.
public override int Count
{
get
{
if(list != null)
{
return list.Count;
}
return 0;
}
}
// Get the current object.
public override Object Current
{
get
{
return GetItem(Position);
}
}
// Get the list for this currency manager.
public IList List
{
get
{
return list;
}
}
// Get or set the current position.
public override int Position
{
get
{
return position;
}
set
{
if(list != null)
{
if(value < 0)
{
value = 0;
}
if(value >= list.Count)
{
value = list.Count - 1;
}
if(position != value)
{
position = value;
if(onPositionChangedHandler != null)
{
onPositionChangedHandler
(this, EventArgs.Empty);
}
}
}
}
}
// Get the item at a specific position.
private Object GetItem(int index)
{
if(index >= 0 && index < list.Count)
{
return list[index];
}
else
{
throw new IndexOutOfRangeException
(S._("SWF_Binding_IndexRange"));
}
}
// Add a new item.
public override void AddNew()
{
#if CONFIG_COMPONENT_MODEL
if(!(list is IBindingList))
{
throw new NotSupportedException();
}
((IBindingList)list).AddNew();
position = list.Count - 1;
if(onPositionChangedHandler != null)
{
onPositionChangedHandler
(this, EventArgs.Empty);
}
#else
throw new NotSupportedException();
#endif
}
// Cancel the current edit operation.
public override void CancelCurrentEdit()
{
if(position >= 0 && position < Count)
{
#if CONFIG_COMPONENT_MODEL
Object item = GetItem(position);
if(item is IEditableObject)
{
((IEditableObject)item).CancelEdit();
}
#endif
OnItemChanged(new ItemChangedEventArgs(position));
}
}
// End the current edit operation.
public override void EndCurrentEdit()
{
#if CONFIG_COMPONENT_MODEL
if(position >= 0 && position < Count)
{
Object item = GetItem(position);
if(item is IEditableObject)
{
((IEditableObject)item).EndEdit();
}
}
#endif
}
// Refresh the bound controls.
[TODO]
public void Refresh()
{
return;
}
// Remove an entry at a specific index.
public override void RemoveAt(int index)
{
list.RemoveAt(index);
}
// Resume data binding.
[TODO]
public override void ResumeBinding()
{
return;
}
// Suspend data binding.
[TODO]
public override void SuspendBinding()
{
return;
}
// Check if the list is empty.
protected void CheckEmpty()
{
if(dataSource == null || list == null || list.Count == 0)
{
throw new InvalidOperationException
(S._("SWF_Binding_Empty"));
}
}
// Get the name of list that supplies data for the binding.
protected internal override String GetListName(ArrayList listAccessors)
{
#if CONFIG_COMPONENT_MODEL
if(list is ITypedList)
{
PropertyDescriptor[] props;
props = new PropertyDescriptor [listAccessors.Count];
listAccessors.CopyTo(props, 0);
return ((ITypedList)list).GetListName(props);
}
#endif
return String.Empty;
}
[TODO]
// Update the binding.
protected override void UpdateIsBinding()
{
return;
}
// Raise the "CurrentChanged" event.
protected internal override void OnCurrentChanged(EventArgs e)
{
if(onCurrentChangedHandler != null)
{
onCurrentChangedHandler(this, e);
}
}
// Event that is emitted when an item changes.
public event ItemChangedEventHandler ItemChanged;
// Emit the "ItemChanged" event.
protected virtual void OnItemChanged(ItemChangedEventArgs e)
{
if(ItemChanged != null)
{
ItemChanged(this, e);
}
}
// Event that is emitted when the list metadata changes.
public event EventHandler MetaDataChanged;
#if CONFIG_COMPONENT_MODEL
[TODO]
// Get the property descriptors for the binding.
public override PropertyDescriptorCollection GetItemProperties()
{
return null;
}
#endif // CONFIG_COMPONENT_MODEL
}; // class CurrencyManager
}; // namespace System.Windows.Forms
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !WINDOWS_PHONE_7
namespace NLog.UnitTests.Internal.NetworkSenders
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
#endif
using NLog.Internal.NetworkSenders;
[TestFixture]
public class TcpNetworkSenderTests : NLogTestBase
{
[Test]
public void TcpHappyPathTest()
{
foreach (bool async in new[] { false, true })
{
var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified)
{
Async = async,
};
sender.Initialize();
byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
var exceptions = new List<Exception>();
for (int i = 1; i < 8; i *= 2)
{
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions) exceptions.Add(ex);
});
}
var mre = new ManualResetEvent(false);
sender.FlushAsync(ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
}
mre.Set();
});
mre.WaitOne();
var actual = sender.Log.ToString();
Assert.IsTrue(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.IsTrue(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.IsTrue(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.IsTrue(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.IsTrue(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.IsTrue(actual.IndexOf("send async 0 4 'quic'") != -1);
mre.Reset();
for (int i = 1; i < 8; i *= 2)
{
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions) exceptions.Add(ex);
});
}
sender.Close(ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
}
mre.Set();
});
mre.WaitOne();
actual = sender.Log.ToString();
Assert.IsTrue(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.IsTrue(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.IsTrue(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.IsTrue(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.IsTrue(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.IsTrue(actual.IndexOf("send async 0 4 'quic'") != -1);
Assert.IsTrue(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.IsTrue(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.IsTrue(actual.IndexOf("send async 0 4 'quic'") != -1);
Assert.IsTrue(actual.IndexOf("close") != -1);
foreach (var ex in exceptions)
{
Assert.IsNull(ex);
}
}
}
[Test]
public void TcpProxyTest()
{
var sender = new TcpNetworkSender("tcp://foo:1234", AddressFamily.Unspecified);
var socket = sender.CreateSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Assert.IsInstanceOfType(typeof(SocketProxy), socket);
}
[Test]
public void TcpConnectFailureTest()
{
var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified)
{
ConnectFailure = 1,
Async = true,
};
sender.Initialize();
byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
var exceptions = new List<Exception>();
var allSent = new ManualResetEvent(false);
for (int i = 1; i < 8; i++)
{
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (exceptions.Count == 7)
{
allSent.Set();
}
}
});
}
#if SILVERLIGHT
Assert.IsTrue(allSent.WaitOne(3000));
#else
Assert.IsTrue(allSent.WaitOne(3000, false));
#endif
var mre = new ManualResetEvent(false);
sender.FlushAsync(ex => mre.Set());
#if SILVERLIGHT
mre.WaitOne(3000);
#else
mre.WaitOne(3000, false);
#endif
var actual = sender.Log.ToString();
Assert.IsTrue(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.IsTrue(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.IsTrue(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.IsTrue(actual.IndexOf("failed") != -1);
foreach (var ex in exceptions)
{
Assert.IsNotNull(ex);
}
}
[Test]
public void TcpSendFailureTest()
{
var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified)
{
SendFailureIn = 3, // will cause failure on 3rd send
Async = true,
};
sender.Initialize();
byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
var exceptions = new Exception[9];
var writeFinished = new ManualResetEvent(false);
int remaining = exceptions.Length;
for (int i = 1; i < 10; i++)
{
int pos = i - 1;
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions)
{
exceptions[pos] = ex;
if (--remaining == 0)
{
writeFinished.Set();
}
}
});
}
var mre = new ManualResetEvent(false);
writeFinished.WaitOne();
sender.Close(ex => mre.Set());
mre.WaitOne();
var actual = sender.Log.ToString();
Assert.IsTrue(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.IsTrue(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.IsTrue(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.IsTrue(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.IsTrue(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.IsTrue(actual.IndexOf("send async 0 3 'qui'") != -1);
Assert.IsTrue(actual.IndexOf("failed") != -1);
Assert.IsTrue(actual.IndexOf("close") != -1);
for (int i = 0; i < exceptions.Length; ++i)
{
if (i < 2)
{
Assert.IsNull(exceptions[i], "EXCEPTION: " + exceptions[i]);
}
else
{
Assert.IsNotNull(exceptions[i]);
}
}
}
internal class MyTcpNetworkSender : TcpNetworkSender
{
public StringWriter Log { get; set; }
public MyTcpNetworkSender(string url, AddressFamily addressFamily)
: base(url, addressFamily)
{
this.Log = new StringWriter();
}
protected internal override ISocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
return new MockSocket(addressFamily, socketType, protocolType, this);
}
protected override EndPoint ParseEndpointAddress(Uri uri, AddressFamily addressFamily)
{
this.Log.WriteLine("Parse endpoint address {0} {1}", uri, addressFamily);
return new MockEndPoint(uri);
}
public int ConnectFailure { get; set; }
public bool Async { get; set; }
public int SendFailureIn { get; set; }
}
internal class MockSocket : ISocket
{
private readonly MyTcpNetworkSender sender;
private readonly StringWriter log;
private bool faulted = false;
public MockSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, MyTcpNetworkSender sender)
{
this.sender = sender;
this.log = sender.Log;
this.log.WriteLine("create socket {0} {1} {2}", addressFamily, socketType, protocolType);
}
public bool ConnectAsync(SocketAsyncEventArgs args)
{
this.log.WriteLine("connect async to {0}", args.RemoteEndPoint);
lock (this)
{
if (this.sender.ConnectFailure > 0)
{
this.sender.ConnectFailure--;
this.faulted = true;
args.SocketError = SocketError.SocketError;
this.log.WriteLine("failed");
}
}
return InvokeCallback(args);
}
private bool InvokeCallback(SocketAsyncEventArgs args)
{
lock (this)
{
var args2 = args as TcpNetworkSender.MySocketAsyncEventArgs;
if (this.sender.Async)
{
ThreadPool.QueueUserWorkItem(s =>
{
Thread.Sleep(10);
args2.RaiseCompleted();
});
return true;
}
else
{
return false;
}
}
}
public void Close()
{
lock (this)
{
this.log.WriteLine("close");
}
}
public bool SendAsync(SocketAsyncEventArgs args)
{
lock (this)
{
this.log.WriteLine("send async {0} {1} '{2}'", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count));
if (this.sender.SendFailureIn > 0)
{
this.sender.SendFailureIn--;
if (this.sender.SendFailureIn == 0)
{
this.faulted = true;
}
}
if (this.faulted)
{
this.log.WriteLine("failed");
args.SocketError = SocketError.SocketError;
}
}
return InvokeCallback(args);
}
public bool SendToAsync(SocketAsyncEventArgs args)
{
lock (this)
{
this.log.WriteLine("sendto async {0} {1} '{2}' {3}", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count), args.RemoteEndPoint);
return InvokeCallback(args);
}
}
}
internal class MockEndPoint : EndPoint
{
private readonly Uri uri;
public MockEndPoint(Uri uri)
{
this.uri = uri;
}
public override AddressFamily AddressFamily
{
get
{
return (System.Net.Sockets.AddressFamily)10000;
}
}
public override string ToString()
{
return "{mock end point: " + this.uri + "}";
}
}
}
}
#endif
| |
namespace Epi.Windows.Analysis.Dialogs
{
partial class ReadDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ReadDialog));
this.txtDataSource = new System.Windows.Forms.TextBox();
this.lblDataSource = new System.Windows.Forms.Label();
this.lblDataSourceDrivers = new System.Windows.Forms.Label();
this.cmbDataSourcePlugIns = new System.Windows.Forms.ComboBox();
this.btnClear = new System.Windows.Forms.Button();
this.btnFindDataSource = new System.Windows.Forms.Button();
this.btnHelp = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.btnSaveOnly = new System.Windows.Forms.Button();
this.gbxExplorer = new System.Windows.Forms.GroupBox();
this.lvDataSourceObjects = new System.Windows.Forms.ListView();
this.columnHeaderItem = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.panel1 = new System.Windows.Forms.Panel();
this.gbxShow = new System.Windows.Forms.GroupBox();
this.chkTables = new System.Windows.Forms.CheckBox();
this.chkViews = new System.Windows.Forms.CheckBox();
this.gbxExplorer.SuspendLayout();
this.panel1.SuspendLayout();
this.gbxShow.SuspendLayout();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
//
// txtDataSource
//
resources.ApplyResources(this.txtDataSource, "txtDataSource");
this.txtDataSource.Name = "txtDataSource";
this.txtDataSource.ReadOnly = true;
this.txtDataSource.TextChanged += new System.EventHandler(this.txtDataSource_TextChanged);
//
// lblDataSource
//
this.lblDataSource.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblDataSource, "lblDataSource");
this.lblDataSource.Name = "lblDataSource";
//
// lblDataSourceDrivers
//
this.lblDataSourceDrivers.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblDataSourceDrivers, "lblDataSourceDrivers");
this.lblDataSourceDrivers.Name = "lblDataSourceDrivers";
//
// cmbDataSourcePlugIns
//
resources.ApplyResources(this.cmbDataSourcePlugIns, "cmbDataSourcePlugIns");
this.cmbDataSourcePlugIns.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbDataSourcePlugIns.Name = "cmbDataSourcePlugIns";
this.cmbDataSourcePlugIns.SelectedIndexChanged += new System.EventHandler(this.cmbDataSourcePlugIns_SelectedIndexChanged);
//
// btnClear
//
resources.ApplyResources(this.btnClear, "btnClear");
this.btnClear.Name = "btnClear";
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// btnFindDataSource
//
resources.ApplyResources(this.btnFindDataSource, "btnFindDataSource");
this.btnFindDataSource.Name = "btnFindDataSource";
this.btnFindDataSource.Click += new System.EventHandler(this.btnFindDataSource_Click);
//
// btnHelp
//
resources.ApplyResources(this.btnHelp, "btnHelp");
this.btnHelp.Name = "btnHelp";
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
//
// btnOK
//
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.Name = "btnOK";
//
// btnSaveOnly
//
resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly");
this.btnSaveOnly.Name = "btnSaveOnly";
//
// gbxExplorer
//
resources.ApplyResources(this.gbxExplorer, "gbxExplorer");
this.gbxExplorer.Controls.Add(this.lvDataSourceObjects);
this.gbxExplorer.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.gbxExplorer.Name = "gbxExplorer";
this.gbxExplorer.TabStop = false;
//
// lvDataSourceObjects
//
resources.ApplyResources(this.lvDataSourceObjects, "lvDataSourceObjects");
this.lvDataSourceObjects.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeaderItem});
this.lvDataSourceObjects.FullRowSelect = true;
this.lvDataSourceObjects.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.lvDataSourceObjects.MultiSelect = false;
this.lvDataSourceObjects.Name = "lvDataSourceObjects";
this.lvDataSourceObjects.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.lvDataSourceObjects.UseCompatibleStateImageBehavior = false;
this.lvDataSourceObjects.View = System.Windows.Forms.View.Details;
this.lvDataSourceObjects.SelectedIndexChanged += new System.EventHandler(this.lvDataSourceObjects_SelectedIndexChanged);
this.lvDataSourceObjects.DoubleClick += new System.EventHandler(this.lvDataSourceObjects_DoubleClick);
this.lvDataSourceObjects.Resize += new System.EventHandler(this.lvDataSourceObjects_Resize);
//
// columnHeaderItem
//
resources.ApplyResources(this.columnHeaderItem, "columnHeaderItem");
//
// panel1
//
this.panel1.Controls.Add(this.btnOK);
this.panel1.Controls.Add(this.btnClear);
this.panel1.Controls.Add(this.btnSaveOnly);
this.panel1.Controls.Add(this.btnCancel);
this.panel1.Controls.Add(this.btnHelp);
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Name = "panel1";
//
// gbxShow
//
this.gbxShow.Controls.Add(this.chkTables);
this.gbxShow.Controls.Add(this.chkViews);
resources.ApplyResources(this.gbxShow, "gbxShow");
this.gbxShow.Name = "gbxShow";
this.gbxShow.TabStop = false;
//
// chkTables
//
resources.ApplyResources(this.chkTables, "chkTables");
this.chkTables.Name = "chkTables";
this.chkTables.UseVisualStyleBackColor = true;
this.chkTables.CheckedChanged += new System.EventHandler(this.CheckBox_CheckedChanged);
//
// chkViews
//
resources.ApplyResources(this.chkViews, "chkViews");
this.chkViews.Checked = true;
this.chkViews.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkViews.Name = "chkViews";
this.chkViews.UseVisualStyleBackColor = true;
this.chkViews.CheckedChanged += new System.EventHandler(this.CheckBox_CheckedChanged);
//
// ReadDialog
//
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.gbxShow);
this.Controls.Add(this.panel1);
this.Controls.Add(this.gbxExplorer);
this.Controls.Add(this.btnFindDataSource);
this.Controls.Add(this.cmbDataSourcePlugIns);
this.Controls.Add(this.txtDataSource);
this.Controls.Add(this.lblDataSource);
this.Controls.Add(this.lblDataSourceDrivers);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ReadDialog";
this.ShowIcon = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.Load += new System.EventHandler(this.ReadDialog_Load);
this.gbxExplorer.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.gbxShow.ResumeLayout(false);
this.gbxShow.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtDataSource;
private System.Windows.Forms.Label lblDataSource;
private System.Windows.Forms.Label lblDataSourceDrivers;
private System.Windows.Forms.ComboBox cmbDataSourcePlugIns;
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Button btnSaveOnly;
private System.Windows.Forms.Button btnFindDataSource;
private System.Windows.Forms.GroupBox gbxExplorer;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.ListView lvDataSourceObjects;
private System.Windows.Forms.ColumnHeader columnHeaderItem;
private System.Windows.Forms.GroupBox gbxShow;
private System.Windows.Forms.CheckBox chkTables;
private System.Windows.Forms.CheckBox chkViews;
}
}
| |
// Copyright 2016 Google 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.
// ReSharper disable InconsistentNaming
// ReSharper disable DelegateSubtraction
// ReSharper disable UseObjectOrCollectionInitializer
// ReSharper disable UnusedParameter.Local
// ReSharper disable UnusedMember.Local
// ReSharper disable ConvertIfStatementToConditionalTernaryExpression
using System;
using System.Runtime.InteropServices;
using System.Text;
using WindowHandle = System.IntPtr;
using BOOL = System.Int32;
namespace WindowsAccessBridgeInterop {
/// <summary>
/// Common (i.e. legacy and non-legacy) abstraction over <code>WindowsAccessBridge DLL</code> functions
/// </summary>
public abstract class AccessBridgeFunctions {
public abstract bool ActivateAccessibleHyperlink(int vmid, JavaObjectHandle accessibleContext, JavaObjectHandle accessibleHyperlink);
public abstract void AddAccessibleSelectionFromContext(int vmid, JavaObjectHandle asel, int i);
public abstract void ClearAccessibleSelectionFromContext(int vmid, JavaObjectHandle asel);
public abstract bool DoAccessibleActions(int vmid, JavaObjectHandle accessibleContext, ref AccessibleActionsToDo actionsToDo, out int failure);
public abstract bool GetAccessibleActions(int vmid, JavaObjectHandle accessibleContext, out AccessibleActions actions);
/// <summary>
/// Returns the accessible context of the <paramref name="i" />'th child of
/// the component associated to <paramref name="ac" />. Returns an
/// <code>null</code> accessible context if there is no such child.
/// </summary>
public abstract JavaObjectHandle GetAccessibleChildFromContext(int vmid, JavaObjectHandle ac, int i);
public abstract bool GetAccessibleContextAt(int vmid, JavaObjectHandle acParent, int x, int y, out JavaObjectHandle ac);
public abstract bool GetAccessibleContextFromHWND(WindowHandle window, out int vmid, out JavaObjectHandle ac);
/// <summary>
/// Retrieves the <see cref="AccessibleContextInfo" /> of the component
/// corresponding to the given accessible context.
/// </summary>
public abstract bool GetAccessibleContextInfo(int vmid, JavaObjectHandle ac, out AccessibleContextInfo info);
public abstract bool GetAccessibleContextWithFocus(WindowHandle window, out int vmid, out JavaObjectHandle ac);
public abstract bool GetAccessibleHyperlink(int vmid, JavaObjectHandle hypertext, int nIndex, out AccessibleHyperlinkInfo hyperlinkInfo);
public abstract int GetAccessibleHyperlinkCount(int vmid, JavaObjectHandle accessibleContext);
public abstract bool GetAccessibleHypertext(int vmid, JavaObjectHandle accessibleContext, out AccessibleHypertextInfo hypertextInfo);
public abstract bool GetAccessibleHypertextExt(int vmid, JavaObjectHandle accessibleContext, int nStartIndex, out AccessibleHypertextInfo hypertextInfo);
public abstract int GetAccessibleHypertextLinkIndex(int vmid, JavaObjectHandle hypertext, int nIndex);
public abstract bool GetAccessibleIcons(int vmid, JavaObjectHandle accessibleContext, out AccessibleIcons icons);
public abstract bool GetAccessibleKeyBindings(int vmid, JavaObjectHandle accessibleContext, out AccessibleKeyBindings keyBindings);
/// <summary>
/// Returns the accessible context of the parent of the component associated
/// to <paramref name="ac" />. Returns an <code>null</code> accessible
/// context if there is no parent.
/// </summary>
public abstract JavaObjectHandle GetAccessibleParentFromContext(int vmid, JavaObjectHandle ac);
public abstract bool GetAccessibleRelationSet(int vmid, JavaObjectHandle accessibleContext, out AccessibleRelationSetInfo relationSetInfo);
public abstract int GetAccessibleSelectionCountFromContext(int vmid, JavaObjectHandle asel);
public abstract JavaObjectHandle GetAccessibleSelectionFromContext(int vmid, JavaObjectHandle asel, int i);
public abstract bool GetAccessibleTableCellInfo(int vmid, JavaObjectHandle at, int row, int column, out AccessibleTableCellInfo tableCellInfo);
/// <summary>
/// Return the column number for a cell at a given index
/// </summary>
public abstract int GetAccessibleTableColumn(int vmid, JavaObjectHandle table, int index);
public abstract JavaObjectHandle GetAccessibleTableColumnDescription(int vmid, JavaObjectHandle acParent, int column);
public abstract bool GetAccessibleTableColumnHeader(int vmid, JavaObjectHandle acParent, out AccessibleTableInfo tableInfo);
public abstract int GetAccessibleTableColumnSelectionCount(int vmid, JavaObjectHandle table);
public abstract bool GetAccessibleTableColumnSelections(int vmid, JavaObjectHandle table, int count, [Out]int[] selections);
/// <summary>
/// Return the index of a cell at a given row and column
/// </summary>
public abstract int GetAccessibleTableIndex(int vmid, JavaObjectHandle table, int row, int column);
public abstract bool GetAccessibleTableInfo(int vmid, JavaObjectHandle ac, out AccessibleTableInfo tableInfo);
/// <summary>
/// Return the row number for a cell at a given index
/// </summary>
public abstract int GetAccessibleTableRow(int vmid, JavaObjectHandle table, int index);
public abstract JavaObjectHandle GetAccessibleTableRowDescription(int vmid, JavaObjectHandle acParent, int row);
public abstract bool GetAccessibleTableRowHeader(int vmid, JavaObjectHandle acParent, out AccessibleTableInfo tableInfo);
public abstract int GetAccessibleTableRowSelectionCount(int vmid, JavaObjectHandle table);
public abstract bool GetAccessibleTableRowSelections(int vmid, JavaObjectHandle table, int count, [Out]int[] selections);
public abstract bool GetAccessibleTextAttributes(int vmid, JavaObjectHandle at, int index, out AccessibleTextAttributesInfo attributes);
public abstract bool GetAccessibleTextInfo(int vmid, JavaObjectHandle at, out AccessibleTextInfo textInfo, int x, int y);
public abstract bool GetAccessibleTextItems(int vmid, JavaObjectHandle at, out AccessibleTextItemsInfo textItems, int index);
public abstract bool GetAccessibleTextLineBounds(int vmid, JavaObjectHandle at, int index, out int startIndex, out int endIndex);
public abstract bool GetAccessibleTextRange(int vmid, JavaObjectHandle at, int start, int end, [Out]char[] text, short len);
public abstract bool GetAccessibleTextRect(int vmid, JavaObjectHandle at, out AccessibleTextRectInfo rectInfo, int index);
public abstract bool GetAccessibleTextSelectionInfo(int vmid, JavaObjectHandle at, out AccessibleTextSelectionInfo textSelection);
public abstract JavaObjectHandle GetActiveDescendent(int vmid, JavaObjectHandle ac);
public abstract bool GetCaretLocation(int vmid, JavaObjectHandle ac, out AccessibleTextRectInfo rectInfo, int index);
public abstract bool GetCurrentAccessibleValueFromContext(int vmid, JavaObjectHandle av, StringBuilder value, short len);
/// <summary>
/// Returns the window handle corresponding to given root component
/// accessible context.
/// </summary>
public abstract WindowHandle GetHWNDFromAccessibleContext(int vmid, JavaObjectHandle ac);
public abstract bool GetMaximumAccessibleValueFromContext(int vmid, JavaObjectHandle av, StringBuilder value, short len);
public abstract bool GetMinimumAccessibleValueFromContext(int vmid, JavaObjectHandle av, StringBuilder value, short len);
public abstract int GetObjectDepth(int vmid, JavaObjectHandle ac);
public abstract JavaObjectHandle GetParentWithRole(int vmid, JavaObjectHandle ac, string role);
public abstract JavaObjectHandle GetParentWithRoleElseRoot(int vmid, JavaObjectHandle ac, string role);
public abstract bool GetTextAttributesInRange(int vmid, JavaObjectHandle accessibleContext, int startIndex, int endIndex, out AccessibleTextAttributesInfo attributes, out short len);
public abstract JavaObjectHandle GetTopLevelObject(int vmid, JavaObjectHandle ac);
public abstract bool GetVersionInfo(int vmid, out AccessBridgeVersionInfo info);
public abstract bool GetVirtualAccessibleName(int vmid, JavaObjectHandle ac, StringBuilder name, int len);
public abstract bool GetVisibleChildren(int vmid, JavaObjectHandle accessibleContext, int startIndex, out VisibleChildrenInfo children);
public abstract int GetVisibleChildrenCount(int vmid, JavaObjectHandle accessibleContext);
public abstract bool IsAccessibleChildSelectedFromContext(int vmid, JavaObjectHandle asel, int i);
public abstract bool IsAccessibleTableColumnSelected(int vmid, JavaObjectHandle table, int column);
public abstract bool IsAccessibleTableRowSelected(int vmid, JavaObjectHandle table, int row);
/// <summary>
/// Returns <code>true</code> if the given window handle belongs to a Java
/// application.
/// </summary>
public abstract bool IsJavaWindow(WindowHandle window);
/// <summary>
/// Returns <code>true</code> if both java object handles reference the same
/// object. Note that the function may return <cdoe>false</cdoe> for
/// tansient objects, e.g. for items of tables/list/trees.
/// </summary>
public abstract bool IsSameObject(int vmid, JavaObjectHandle obj1, JavaObjectHandle obj2);
public abstract void RemoveAccessibleSelectionFromContext(int vmid, JavaObjectHandle asel, int i);
public abstract void SelectAllAccessibleSelectionFromContext(int vmid, JavaObjectHandle asel);
public abstract bool SetTextContents(int vmid, JavaObjectHandle ac, string text);
/// <summary>
/// Initialization, needs to be called before any other entry point.
/// </summary>
public abstract void Windows_run();
}
/// <summary>
/// Common (i.e. legacy and non-legacy) abstraction over <code>WindowsAccessBridge DLL</code> events
/// </summary>
public abstract class AccessBridgeEvents : IDisposable {
/// <summary>
/// Occurs when the caret location inside an accessible text component has changed.
/// </summary>
public abstract event CaretUpdateEventHandler CaretUpdate;
/// <summary>
/// Occurs when an accessible component has gained the input focus.
/// </summary>
public abstract event FocusGainedEventHandler FocusGained;
/// <summary>
/// Occurs when an accessible component has lost the input focus.
/// </summary>
public abstract event FocusLostEventHandler FocusLost;
/// <summary>
/// Occurs when a JVM has shutdown.
/// </summary>
public abstract event JavaShutdownEventHandler JavaShutdown;
public abstract event MenuCanceledEventHandler MenuCanceled;
public abstract event MenuDeselectedEventHandler MenuDeselected;
public abstract event MenuSelectedEventHandler MenuSelected;
/// <summary>
/// Occurs when the mouse button has been clicked on an accessible component.
/// </summary>
public abstract event MouseClickedEventHandler MouseClicked;
/// <summary>
/// Occurs when the mouse cursor has moved over the region of an accessible component.
/// </summary>
public abstract event MouseEnteredEventHandler MouseEntered;
/// <summary>
/// Occurs when the mouse cursor has exited the region of an accessible component.
/// </summary>
public abstract event MouseExitedEventHandler MouseExited;
/// <summary>
/// Occurs when the mouse button has been pressed of an accessible component.
/// </summary>
public abstract event MousePressedEventHandler MousePressed;
/// <summary>
/// Occurs when the mouse button has been released of an accessible component.
/// </summary>
public abstract event MouseReleasedEventHandler MouseReleased;
public abstract event PopupMenuCanceledEventHandler PopupMenuCanceled;
public abstract event PopupMenuWillBecomeInvisibleEventHandler PopupMenuWillBecomeInvisible;
public abstract event PopupMenuWillBecomeVisibleEventHandler PopupMenuWillBecomeVisible;
/// <summary>
/// Occurs the active/selected item of a tree/list/table has changed.
/// </summary>
public abstract event PropertyActiveDescendentChangeEventHandler PropertyActiveDescendentChange;
public abstract event PropertyCaretChangeEventHandler PropertyCaretChange;
/// <summary>
/// Unused.
/// </summary>
public abstract event PropertyChangeEventHandler PropertyChange;
public abstract event PropertyChildChangeEventHandler PropertyChildChange;
public abstract event PropertyDescriptionChangeEventHandler PropertyDescriptionChange;
public abstract event PropertyNameChangeEventHandler PropertyNameChange;
public abstract event PropertySelectionChangeEventHandler PropertySelectionChange;
public abstract event PropertyStateChangeEventHandler PropertyStateChange;
public abstract event PropertyTableModelChangeEventHandler PropertyTableModelChange;
public abstract event PropertyTextChangeEventHandler PropertyTextChange;
public abstract event PropertyValueChangeEventHandler PropertyValueChange;
public abstract event PropertyVisibleDataChangeEventHandler PropertyVisibleDataChange;
public abstract void Dispose();
}
#region Delegate types for events defined in AccessBridgeEvents
/// <summary>Delegate type for <code>CaretUpdate</code> event</summary>
public delegate void CaretUpdateEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>FocusGained</code> event</summary>
public delegate void FocusGainedEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>FocusLost</code> event</summary>
public delegate void FocusLostEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>JavaShutdown</code> event</summary>
public delegate void JavaShutdownEventHandler(int vmid);
/// <summary>Delegate type for <code>MenuCanceled</code> event</summary>
public delegate void MenuCanceledEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>MenuDeselected</code> event</summary>
public delegate void MenuDeselectedEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>MenuSelected</code> event</summary>
public delegate void MenuSelectedEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>MouseClicked</code> event</summary>
public delegate void MouseClickedEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>MouseEntered</code> event</summary>
public delegate void MouseEnteredEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>MouseExited</code> event</summary>
public delegate void MouseExitedEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>MousePressed</code> event</summary>
public delegate void MousePressedEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>MouseReleased</code> event</summary>
public delegate void MouseReleasedEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>PopupMenuCanceled</code> event</summary>
public delegate void PopupMenuCanceledEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>PopupMenuWillBecomeInvisible</code> event</summary>
public delegate void PopupMenuWillBecomeInvisibleEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>PopupMenuWillBecomeVisible</code> event</summary>
public delegate void PopupMenuWillBecomeVisibleEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>PropertyActiveDescendentChange</code> event</summary>
public delegate void PropertyActiveDescendentChangeEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source, JavaObjectHandle oldActiveDescendent, JavaObjectHandle newActiveDescendent);
/// <summary>Delegate type for <code>PropertyCaretChange</code> event</summary>
public delegate void PropertyCaretChangeEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source, int oldPosition, int newPosition);
/// <summary>Delegate type for <code>PropertyChange</code> event</summary>
public delegate void PropertyChangeEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source, string property, string oldValue, string newValue);
/// <summary>Delegate type for <code>PropertyChildChange</code> event</summary>
public delegate void PropertyChildChangeEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source, JavaObjectHandle oldChild, JavaObjectHandle newChild);
/// <summary>Delegate type for <code>PropertyDescriptionChange</code> event</summary>
public delegate void PropertyDescriptionChangeEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source, string oldDescription, string newDescription);
/// <summary>Delegate type for <code>PropertyNameChange</code> event</summary>
public delegate void PropertyNameChangeEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source, string oldName, string newName);
/// <summary>Delegate type for <code>PropertySelectionChange</code> event</summary>
public delegate void PropertySelectionChangeEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>PropertyStateChange</code> event</summary>
public delegate void PropertyStateChangeEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source, string oldState, string newState);
/// <summary>Delegate type for <code>PropertyTableModelChange</code> event</summary>
public delegate void PropertyTableModelChangeEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle src, string oldValue, string newValue);
/// <summary>Delegate type for <code>PropertyTextChange</code> event</summary>
public delegate void PropertyTextChangeEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
/// <summary>Delegate type for <code>PropertyValueChange</code> event</summary>
public delegate void PropertyValueChangeEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source, string oldValue, string newValue);
/// <summary>Delegate type for <code>PropertyVisibleDataChange</code> event</summary>
public delegate void PropertyVisibleDataChangeEventHandler(int vmid, JavaObjectHandle evt, JavaObjectHandle source);
#endregion
[Flags]
public enum AccessibleInterfaces {
cAccessibleValueInterface = 1,
cAccessibleActionInterface = 2,
cAccessibleComponentInterface = 4,
cAccessibleSelectionInterface = 8,
cAccessibleTableInterface = 16,
cAccessibleTextInterface = 32,
cAccessibleHypertextInterface = 64,
}
public enum AccessibleKeyCode : ushort {
ACCESSIBLE_VK_BACK_SPACE = 8,
ACCESSIBLE_VK_DELETE = 127,
ACCESSIBLE_VK_DOWN = 40,
ACCESSIBLE_VK_END = 35,
ACCESSIBLE_VK_HOME = 36,
ACCESSIBLE_VK_INSERT = 155,
ACCESSIBLE_VK_KP_DOWN = 225,
ACCESSIBLE_VK_KP_LEFT = 226,
ACCESSIBLE_VK_KP_RIGHT = 227,
ACCESSIBLE_VK_KP_UP = 224,
ACCESSIBLE_VK_LEFT = 37,
ACCESSIBLE_VK_PAGE_DOWN = 34,
ACCESSIBLE_VK_PAGE_UP = 33,
ACCESSIBLE_VK_RIGHT = 39,
ACCESSIBLE_VK_UP = 38,
}
[Flags]
public enum AccessibleModifiers {
ACCESSIBLE_SHIFT_KEYSTROKE = 1,
ACCESSIBLE_CONTROL_KEYSTROKE = 2,
ACCESSIBLE_META_KEYSTROKE = 4,
ACCESSIBLE_ALT_KEYSTROKE = 8,
ACCESSIBLE_ALT_GRAPH_KEYSTROKE = 16,
ACCESSIBLE_BUTTON1_KEYSTROKE = 32,
ACCESSIBLE_BUTTON2_KEYSTROKE = 64,
ACCESSIBLE_BUTTON3_KEYSTROKE = 128,
ACCESSIBLE_FKEY_KEYSTROKE = 256,
ACCESSIBLE_CONTROLCODE_KEYSTROKE = 512,
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct AccessBridgeVersionInfo {
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string VMversion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string bridgeJavaClassVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string bridgeJavaDLLVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string bridgeWinDLLVersion;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct AccessibleActionInfo {
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string name;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct AccessibleActionsToDo {
public int actionsCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public AccessibleActionInfo[] actions;
}
public struct AccessibleHyperlinkInfo {
public string text;
public int startIndex;
public int endIndex;
public JavaObjectHandle accessibleHyperlink;
}
public struct AccessibleHypertextInfo {
public int linkCount;
public AccessibleHyperlinkInfo[] links;
public JavaObjectHandle accessibleHypertext;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct AccessibleIconInfo {
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string description;
public int height;
public int width;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct AccessibleIcons {
public int iconsCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public AccessibleIconInfo[] iconInfo;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct AccessibleKeyBindingInfo {
public AccessibleKeyCode character;
public AccessibleModifiers modifiers;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct AccessibleKeyBindings {
public int keyBindingsCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public AccessibleKeyBindingInfo[] keyBindingInfo;
}
public struct AccessibleRelationInfo {
public string key;
public int targetCount;
public JavaObjectHandle[] targets;
}
public struct AccessibleRelationSetInfo {
public int relationCount;
public AccessibleRelationInfo[] relations;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct AccessibleTextInfo {
public int charCount;
public int caretIndex;
public int indexAtPoint;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct AccessibleTextItemsInfo {
public char letter;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string word;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
public string sentence;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct AccessibleTextRectInfo {
public int x;
public int y;
public int width;
public int height;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct AccessibleTextSelectionInfo {
public int selectionStartIndex;
public int selectionEndIndex;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
public string selectedText;
}
public struct VisibleChildrenInfo {
public int returnedChildrenCount;
public JavaObjectHandle[] children;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class AccessibleActions {
public int actionsCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public AccessibleActionInfo[] actionInfo;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class AccessibleContextInfo {
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
public string name;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
public string description;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string role;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string role_en_US;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string states;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string states_en_US;
public int indexInParent;
public int childrenCount;
public int x;
public int y;
public int width;
public int height;
public int accessibleComponent;
public int accessibleAction;
public int accessibleSelection;
public int accessibleText;
public AccessibleInterfaces accessibleInterfaces;
}
public class AccessibleTableCellInfo {
public JavaObjectHandle accessibleContext;
public int index;
public int row;
public int column;
public int rowExtent;
public int columnExtent;
public byte isSelected;
}
public class AccessibleTableInfo {
public JavaObjectHandle caption;
public JavaObjectHandle summary;
public int rowCount;
public int columnCount;
public JavaObjectHandle accessibleContext;
public JavaObjectHandle accessibleTable;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class AccessibleTextAttributesInfo {
public int bold;
public int italic;
public int underline;
public int strikethrough;
public int superscript;
public int subscript;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string backgroundColor;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string foregroundColor;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string fontFamily;
public int fontSize;
public int alignment;
public int bidiLevel;
public float firstLineIndent;
public float leftIndent;
public float rightIndent;
public float lineSpacing;
public float spaceAbove;
public float spaceBelow;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
public string fullAttributesString;
}
}
| |
namespace FakeItEasy.Specs
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using FakeItEasy.Configuration;
using FakeItEasy.Tests.TestHelpers;
using FluentAssertions;
using Xbehave;
using Xunit;
public static class ConfigurationSpecs
{
public interface IFoo
{
void Bar();
int Baz();
string Bas();
IFoo Bafoo();
IFoo Bafoo(out int i);
IFoo Wrap(IFoo wrappee);
Task BarAsync();
}
[SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "It's just used for testing.")]
public interface IInterface
{
}
[Scenario]
[InlineData(typeof(IInterface))]
[InlineData(typeof(AbstractClass))]
[InlineData(typeof(ClassWithProtectedConstructor))]
[InlineData(typeof(ClassWithInternalConstructorVisibleToDynamicProxy))]
[InlineData(typeof(InternalClassVisibleToDynamicProxy))]
public static void ConfigureToString(Type typeOfFake, object fake, string? stringResult)
{
"Given a fake"
.x(() => fake = Sdk.Create.Fake(typeOfFake));
"And I configure the fake's ToString method"
.x(() => A.CallTo(() => fake.ToString()).Returns("I configured " + typeOfFake + ".ToString()"));
"When I call the method"
.x(() => stringResult = fake.ToString());
"Then it returns the configured value"
.x(() => stringResult.Should().Be("I configured " + typeOfFake + ".ToString()"));
}
[Scenario]
public static void CallbackOnVoid(
IFoo fake,
bool wasCalled)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure a method to invoke an action when a void method is called"
.x(() => A.CallTo(() => fake.Bar()).Invokes(x => wasCalled = true));
"When I call the method"
.x(() => fake.Bar());
"Then it invokes the action"
.x(() => wasCalled.Should().BeTrue());
}
[Scenario]
public static void CallbackOnStringReturningMethod(
IFoo fake,
bool wasCalled,
string result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure a method to invoke an action when a string-returning method is called"
.x(() => A.CallTo(() => fake.Bas()).Invokes(x => wasCalled = true));
"When I call the method"
.x(() => result = fake.Bas());
"Then it invokes the action"
.x(() => wasCalled.Should().BeTrue());
"And a default value is returned"
.x(() => result.Should().BeEmpty());
}
[Scenario]
public static void MultipleCallbacks(
IFoo fake,
bool firstWasCalled,
bool secondWasCalled,
int returnValue)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure a method to invoke two actions and return a value"
.x(() =>
A.CallTo(() => fake.Baz())
.Invokes(x => firstWasCalled = true)
.Invokes(x => secondWasCalled = true)
.Returns(10));
"When I call the method"
.x(() => returnValue = fake.Baz());
"Then it calls the first callback"
.x(() => firstWasCalled.Should().BeTrue());
"And it calls the first callback"
.x(() => secondWasCalled.Should().BeTrue());
"And it returns the configured value"
.x(() => returnValue.Should().Be(10));
}
[Scenario]
public static void CallBaseMethod(
BaseClass fake,
int returnValue,
bool callbackWasInvoked)
{
"Given a fake"
.x(() => fake = A.Fake<BaseClass>());
"And I configure a method to invoke an action and call the base method"
.x(() =>
A.CallTo(() => fake.ReturnSomething())
.Invokes(x => callbackWasInvoked = true)
.CallsBaseMethod());
"When I call the method"
.x(() => returnValue = fake.ReturnSomething());
"Then it calls the base method"
.x(() => fake.WasCalled.Should().BeTrue());
"And it returns the value from base method"
.x(() => returnValue.Should().Be(10));
"And it invokes the callback"
.x(() => callbackWasInvoked.Should().BeTrue());
}
[Scenario]
public static void MultipleReturns(
IFoo fake,
IReturnValueArgumentValidationConfiguration<int> configuration,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure the return value for the method"
.x(() =>
{
configuration = A.CallTo(() => fake.Baz());
configuration.Returns(42);
});
"When I use the same configuration object to set the return value again"
.x(() => exception = Record.Exception(() => configuration.Returns(0)));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void ReturnThenThrow(
IFoo fake,
IReturnValueArgumentValidationConfiguration<int> configuration,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure the return value for the method"
.x(() =>
{
configuration = A.CallTo(() => fake.Baz());
configuration.Returns(42);
});
"When I use the same configuration object to have the method throw an exception"
.x(() => exception = Record.Exception(() => configuration.Throws<Exception>()));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void ReturnThenCallsBaseMethod(
IFoo fake,
IReturnValueArgumentValidationConfiguration<int> configuration,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure the return value for the method"
.x(() =>
{
configuration = A.CallTo(() => fake.Baz());
configuration.Returns(42);
});
"When I use the same configuration object to have the method call the base method"
.x(() => exception = Record.Exception(() => configuration.CallsBaseMethod()));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void MultipleThrows(
IFoo fake,
IReturnValueArgumentValidationConfiguration<int> configuration,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure the return method to throw an exception"
.x(() =>
{
configuration = A.CallTo(() => fake.Baz());
configuration.Throws<ArgumentNullException>();
});
"When I use the same configuration object to have the method throw an exception again"
.x(() => exception = Record.Exception(() => configuration.Throws<ArgumentException>()));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void CallToObjectOnNonFake(
BaseClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new BaseClass());
"When I start to configure the object"
.x(() => exception = Record.Exception(() => A.CallTo(notAFake)));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+BaseClass' of type FakeItEasy.Specs.ConfigurationSpecs+BaseClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToNonVirtualVoidOnNonFake(
BaseClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new BaseClass());
"When I start to configure a non-virtual void method on the object"
.x(() => exception = Record.Exception(() => A.CallTo(() => notAFake.DoSomethingNonVirtual())));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+BaseClass' of type FakeItEasy.Specs.ConfigurationSpecs+BaseClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToNonVirtualVoidOnFake(
BaseClass fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<BaseClass>());
"When I start to configure a non-virtual void method on the fake"
.x(() => exception = Record.Exception(() => A.CallTo(() => fake.DoSomethingNonVirtual())));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."));
}
[Scenario]
public static void CallToSealedVoidOnNonFake(
DerivedClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new DerivedClass());
"When I start to configure a sealed void method on the object"
.x(() => exception = Record.Exception(() => A.CallTo(() => notAFake.DoSomething())));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+DerivedClass' of type FakeItEasy.Specs.ConfigurationSpecs+DerivedClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToSealedVoidOnFake(
DerivedClass fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<DerivedClass>());
"When I start to configure a sealed void method on the fake"
.x(() => exception = Record.Exception(() => A.CallTo(() => fake.DoSomething())));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."));
}
[Scenario]
public static void CallToNonVirtualNonVoidOnNonFake(
BaseClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new BaseClass());
"When I start to configure a non-virtual non-void method on the object"
.x(() => exception = Record.Exception(() => A.CallTo(() => notAFake.ReturnSomethingNonVirtual())));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+BaseClass' of type FakeItEasy.Specs.ConfigurationSpecs+BaseClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToNonVirtualNonVoidOnFake(
BaseClass fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<BaseClass>());
"When I start to configure a non-virtual non-void method on the fake"
.x(() => exception = Record.Exception(() => A.CallTo(() => fake.ReturnSomethingNonVirtual())));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."));
}
[Scenario]
public static void CallToSealedNonVoidOnNonFake(
DerivedClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new DerivedClass());
"When I start to configure a sealed non-void method on the object"
.x(() => exception = Record.Exception(() => A.CallTo(() => notAFake.ReturnSomething())));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+DerivedClass' of type FakeItEasy.Specs.ConfigurationSpecs+DerivedClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToSealedNonVoidOnFake(
DerivedClass fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<DerivedClass>());
"When I start to configure a sealed non-void method on the fake"
.x(() => exception = Record.Exception(() => A.CallTo(() => fake.ReturnSomething())));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."));
}
[Scenario]
public static void CallToSetNonVirtualOnNonFake(
BaseClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new BaseClass());
"When I start to configure a non-virtual property setter on the object"
.x(() => exception = Record.Exception(() => A.CallToSet(() => notAFake.SomeNonVirtualProperty)));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+BaseClass' of type FakeItEasy.Specs.ConfigurationSpecs+BaseClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToSetNonVirtualOnFake(
BaseClass fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<BaseClass>());
"When I start to configure a non-virtual property setter on the fake"
.x(() => exception = Record.Exception(() => A.CallToSet(() => fake.SomeNonVirtualProperty)));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."));
}
[Scenario]
public static void CallToSetSealedOnNonFake(
DerivedClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new DerivedClass());
"When I start to configure a sealed property setter on the object"
.x(() => exception = Record.Exception(() => A.CallToSet(() => notAFake.SomeProperty)));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+DerivedClass' of type FakeItEasy.Specs.ConfigurationSpecs+DerivedClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToSetSealedOnFake(
DerivedClass fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<DerivedClass>());
"When I start to configure a sealed property setter on the fake"
.x(() => exception = Record.Exception(() => A.CallToSet(() => fake.SomeProperty)));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."));
}
[Scenario]
public static void DoesNothingAfterStrictVoidDoesNotThrow(
IFoo fake,
Exception exception)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure a void method to do nothing"
.x(() => A.CallTo(() => fake.Bar()).DoesNothing());
"When I call the method"
.x(() => exception = Record.Exception(() => fake.Bar()));
"Then it does not throw an exception"
.x(() => exception.Should().BeNull());
}
[Scenario]
public static void DoesNothingAfterStrictValueTypeKeepsDefaultReturnValue(
IFoo fake,
int result)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure all methods to do nothing"
.x(() => A.CallTo(fake).DoesNothing());
"When I call a value type method"
.x(() => result = fake.Baz());
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Baz()));
}
[Scenario]
public static void DoesNothingAfterStrictNonFakeableReferenceTypeKeepsDefaultReturnValue(
IFoo fake,
string result)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure all methods to do nothing"
.x(() => A.CallTo(fake).DoesNothing());
"When I call a non-fakeable reference type method"
.x(() => result = fake.Bas());
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Bas()));
}
[Scenario]
public static void DoesNothingAfterStrictFakeableReferenceTypeKeepsDefaultReturnValue(
IFoo fake,
IFoo result)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure all methods to do nothing"
.x(() => A.CallTo(fake).DoesNothing());
"When I call a fakeable reference type method"
.x(() => result = fake.Bafoo());
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Bafoo()));
}
[Scenario]
public static void ThrowsAndDoesNothingAppliedToSameACallTo(
IFoo fake,
IVoidArgumentValidationConfiguration callToBar,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I identify a method to configure"
.x(() => callToBar = A.CallTo(() => fake.Bar()));
"And I configure the method to throw an exception"
.x(() => callToBar.Throws<Exception>());
"When I configure the method to do nothing"
.x(() => exception = Record.Exception(() => callToBar.DoesNothing()));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void DoesNothingAndThrowsAppliedToSameACallTo(
IFoo fake,
IVoidArgumentValidationConfiguration callToBar,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I identify a method to configure"
.x(() => callToBar = A.CallTo(() => fake.Bar()));
"And I configure the method to do nothing"
.x(() => callToBar.DoesNothing());
"When I configure the method to throw an exception"
.x(() => exception = Record.Exception(() => callToBar.Throws<Exception>()));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void CallsBaseMethodAndDoesNothing(BaseClass fake)
{
"Given a fake"
.x(() => fake = A.Fake<BaseClass>());
"And I configure a method to call the base method"
.x(() => A.CallTo(() => fake.DoSomething()).CallsBaseMethod());
"And I configure the method to do nothing"
.x(() => A.CallTo(() => fake.DoSomething()).DoesNothing());
"When I call the method"
.x(() => fake.DoSomething());
"Then it does nothing"
.x(() => fake.WasCalled.Should().BeFalse());
}
[Scenario]
public static void CallsBaseMethodAndDoesNothingAppliedToSameACallTo(
BaseClass fake,
IVoidArgumentValidationConfiguration callToDoSomething,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<BaseClass>());
"And I identify a method to configure"
.x(() => callToDoSomething = A.CallTo(() => fake.DoSomething()));
"And I configure the method to call the base method"
.x(() => callToDoSomething.CallsBaseMethod());
"And I configure the method to do nothing"
.x(() => exception = Record.Exception(() => callToDoSomething.DoesNothing()));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void InvokesAfterStrictVoidDoesNotThrow(
IFoo fake,
Exception exception)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure a void method to invoke an action"
.x(() => A.CallTo(() => fake.Bar()).Invokes(() => { }));
"When I call the method"
.x(() => exception = Record.Exception(() => fake.Bar()));
"Then it does not throw an exception"
.x(() => exception.Should().BeNull());
}
[Scenario]
public static void InvokesAfterStrictValueTypeKeepsDefaultReturnValue(
IFoo fake,
int result)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure a value type method to invoke an action"
.x(() => A.CallTo(() => fake.Baz()).Invokes(() => { }));
"When I call the method"
.x(() => result = fake.Baz());
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Baz()));
}
[Scenario]
public static void InvokesAfterStrictNonFakeableReferenceTypeKeepsDefaultReturnValue(
IFoo fake,
string result)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure all methods to invoke an action"
.x(() => A.CallTo(fake).Invokes(() => { }));
"When I call a non-fakeable reference type method"
.x(() => result = fake.Bas());
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Bas()));
}
[Scenario]
public static void InvokesAfterStrictFakeableableReferenceTypeKeepsDefaultReturnValue(
IFoo fake,
IFoo result)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure all methods to invoke an action"
.x(() => A.CallTo(fake).Invokes(() => { }));
"When I call a fakeable reference type method"
.x(() => result = fake.Bafoo());
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Bafoo()));
}
[Scenario]
public static void AssignsOutAndRefParametersForAllMethodsKeepsDefaultReturnValue(
IFoo fake,
IFoo result,
int i)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure all methods to assign out and ref parameters"
.x(() => A.CallTo(fake).AssignsOutAndRefParameters(0));
"When I call a reference type method"
.x(() => result = fake.Bafoo(out i));
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Bafoo(out i)));
}
[Scenario]
public static void UnusedVoidCallSpec(
IFoo fake,
Exception exception)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(o => o.Strict()));
"When I specify a call to a void method without configuring its behavior"
.x(() => A.CallTo(() => fake.Bar()));
"And I make a call to that method"
.x(() => exception = Record.Exception(() => fake.Bar()));
"Then it throws an expectation exception"
.x(() => exception.Should().BeAnExceptionOfType<ExpectationException>());
}
[Scenario]
public static void UnusedNonVoidCallSpec(
IFoo fake,
Exception exception)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(o => o.Strict()));
"When I specify a call to a void method without configuring its behavior"
.x(() => A.CallTo(() => fake.Baz()));
"And I make a call to that method"
.x(() => exception = Record.Exception(() => fake.Baz()));
"Then it throws an expectation exception"
.x(() => exception.Should().BeAnExceptionOfType<ExpectationException>());
}
[Scenario]
public static void NestedCallThatIncludesArrayConstruction(
IFoo fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"When I specify a call and create a non-object array in the call configuration"
.x(() => exception = Record.Exception(() => A.CallTo(() => fake.Wrap(Foo.BuildFromArray(new[] { 1, 2, 3 })))));
"Then it doesn't throw"
.x(() => exception.Should().BeNull());
}
[Scenario]
public static void CallToExplicitInterfaceImplementation(
FooWithExplicitImplementationOfBaz fake,
Exception exception)
{
"Given a fake of a class that explicitly implements an interface method"
.x(() => fake = A.Fake<FooWithExplicitImplementationOfBaz>());
"When I start to configure the explicitly implemented interface method"
.x(() => exception = Record.Exception(() => A.CallTo(() => ((IFoo)fake).Baz())));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("The base type implements this interface method explicitly. In order to be able to intercept this method, the fake must specify that it implements this interface in the fake creation options."));
}
[Scenario]
public static void DoesNothingOnTaskReturningMethod(IFoo fake, Task result)
{
"Given a fake of a class with a task-returning method"
.x(() => fake = A.Fake<IFoo>());
"And the method is configured to return an failed task"
.x(() => A.CallTo(() => fake.BarAsync()).Returns(Task.FromException(new Exception("oops"))));
"When the method is configured to do nothing"
.x(() => A.CallTo(() => fake.BarAsync()).DoesNothing());
"And the method is called"
.x(() => result = fake.BarAsync());
"Then it returns a successfully completed task"
.x(() => result.Status.Should().Be(TaskStatus.RanToCompletion));
}
public class BaseClass
{
public bool WasCalled { get; private set; }
public string SomeNonVirtualProperty { get; set; } = string.Empty;
public virtual string SomeProperty { get; set; } = string.Empty;
public virtual void DoSomething()
{
this.WasCalled = true;
}
public void DoSomethingNonVirtual()
{
}
public virtual int ReturnSomething()
{
this.WasCalled = true;
return 10;
}
public int ReturnSomethingNonVirtual()
{
return 11;
}
}
public class DerivedClass : BaseClass
{
public sealed override string SomeProperty { get; set; } = string.Empty;
public sealed override void DoSomething()
{
}
public sealed override int ReturnSomething()
{
return 10;
}
}
public class Foo : IFoo
{
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "integers", Justification = "Required for testing.")]
public static IFoo BuildFromArray(int[] integers)
{
return new Foo();
}
public void Bar()
{
throw new NotSupportedException();
}
public int Baz()
{
throw new NotSupportedException();
}
public string Bas()
{
throw new NotSupportedException();
}
public IFoo Bafoo()
{
throw new NotSupportedException();
}
public IFoo Bafoo(out int i)
{
throw new NotSupportedException();
}
public IFoo Wrap(IFoo wrappee)
{
throw new NotImplementedException();
}
public Task BarAsync()
{
throw new NotImplementedException();
}
}
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Required for testing.")]
public class FooWithExplicitImplementationOfBaz : IFoo
{
int IFoo.Baz() => 123;
public IFoo Bafoo() => throw new NotImplementedException();
public IFoo Bafoo(out int i) => throw new NotImplementedException();
public void Bar() => throw new NotImplementedException();
public string Bas() => throw new NotImplementedException();
public IFoo Wrap(IFoo wrappee) => throw new NotImplementedException();
public Task BarAsync() => throw new NotImplementedException();
}
public class FooFactory : DummyFactory<IFoo>
{
public static IFoo Instance { get; } = new Foo();
protected override IFoo Create()
{
return Instance;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Xml.XPath;
namespace MS.Internal.Xml.Cache
{
/// <summary>
/// Implementation of a Node in the XPath/XQuery data model.
/// 1. All nodes are stored in variable-size pages (max 65536 nodes/page) of XPathNode structuSR.
/// 2. Pages are sequentially numbered. Nodes are allocated in strict document order.
/// 3. Node references take the form of a (page, index) pair.
/// 4. Each node explicitly stores a parent and a sibling reference.
/// 5. If a node has one or more attributes and/or non-collapsed content children, then its first
/// child is stored in the next slot. If the node is in the last slot of a page, then its first
/// child is stored in the first slot of the next page.
/// 6. Attributes are linked together at the start of the child list.
/// 7. Namespaces are allocated in totally separate pages. Elements are associated with
/// declared namespaces via a hashtable map in the document.
/// 8. Name parts are always non-null (string.Empty for nodes without names)
/// 9. XPathNodeInfoAtom contains all information that is common to many nodes in a
/// document, and therefore is atomized to save space. This includes the document, the name,
/// the child, sibling, parent, and value pages, and the schema type.
/// 10. The node structure is 20 bytes in length. Out-of-line overhead is typically 2-4 bytes per node.
/// </summary>
internal struct XPathNode
{
private XPathNodeInfoAtom _info; // Atomized node information
private ushort _idxSibling; // Page index of sibling node
private ushort _idxParent; // Page index of parent node
private ushort _idxSimilar; // Page index of next node in document order that has local name with same hashcode
private ushort _posOffset; // Line position offset of node (added to LinePositionBase)
private uint _props; // Node properties (broken down into bits below)
private string _value; // String value of node
private const uint NodeTypeMask = 0xF;
private const uint HasAttributeBit = 0x10;
private const uint HasContentChildBit = 0x20;
private const uint HasElementChildBit = 0x40;
private const uint HasCollapsedTextBit = 0x80;
private const uint AllowShortcutTagBit = 0x100; // True if this is an element that allows shortcut tag syntax
private const uint HasNmspDeclsBit = 0x200; // True if this is an element with namespace declarations declared on it
private const uint LineNumberMask = 0x00FFFC00; // 14 bits for line number offset (0 - 16K)
private const int LineNumberShift = 10;
private const int CollapsedPositionShift = 24; // 8 bits for collapsed text position offset (0 - 256)
#if DEBUG
public const int MaxLineNumberOffset = 0x20;
public const int MaxLinePositionOffset = 0x20;
public const int MaxCollapsedPositionOffset = 0x10;
#else
public const int MaxLineNumberOffset = 0x3FFF;
public const int MaxLinePositionOffset = 0xFFFF;
public const int MaxCollapsedPositionOffset = 0xFF;
#endif
/// <summary>
/// Returns the type of this node
/// </summary>
public XPathNodeType NodeType
{
get { return (XPathNodeType)(_props & NodeTypeMask); }
}
/// <summary>
/// Returns the namespace prefix of this node. If this node has no prefix, then the empty string
/// will be returned (never null).
/// </summary>
public string Prefix
{
get { return _info.Prefix; }
}
/// <summary>
/// Returns the local name of this node. If this node has no name, then the empty string
/// will be returned (never null).
/// </summary>
public string LocalName
{
get { return _info.LocalName; }
}
/// <summary>
/// Returns the name of this node. If this node has no name, then the empty string
/// will be returned (never null).
/// </summary>
public string Name
{
get
{
if (Prefix.Length == 0)
{
return LocalName;
}
else
{
return string.Concat(Prefix, ":", LocalName);
}
}
}
/// <summary>
/// Returns the namespace part of this node's name. If this node has no name, then the empty string
/// will be returned (never null).
/// </summary>
public string NamespaceUri
{
get { return _info.NamespaceUri; }
}
/// <summary>
/// Returns this node's document.
/// </summary>
public XPathDocument Document
{
get { return _info.Document; }
}
/// <summary>
/// Returns this node's base Uri. This is string.Empty for all node kinds except Element, Root, and PI.
/// </summary>
public string BaseUri
{
get { return _info.BaseUri; }
}
/// <summary>
/// Returns this node's source line number.
/// </summary>
public int LineNumber
{
get { return _info.LineNumberBase + (int)((_props & LineNumberMask) >> LineNumberShift); }
}
/// <summary>
/// Return this node's source line position.
/// </summary>
public int LinePosition
{
get { return _info.LinePositionBase + (int)_posOffset; }
}
/// <summary>
/// If this node is an element with collapsed text, then return the source line position of the node (the
/// source line number is the same as LineNumber).
/// </summary>
public int CollapsedLinePosition
{
get
{
Debug.Assert(HasCollapsedText, "Do not call CollapsedLinePosition unless HasCollapsedText is true.");
return LinePosition + (int)(_props >> CollapsedPositionShift);
}
}
/// <summary>
/// Returns information about the node page. Only the 0th node on each page has this property defined.
/// </summary>
public XPathNodePageInfo PageInfo
{
get { return _info.PageInfo; }
}
/// <summary>
/// Returns the root node of the current document. This always succeeds.
/// </summary>
public int GetRoot(out XPathNode[] pageNode)
{
return _info.Document.GetRootNode(out pageNode);
}
/// <summary>
/// Returns the parent of this node. If this node has no parent, then 0 is returned.
/// </summary>
public int GetParent(out XPathNode[] pageNode)
{
pageNode = _info.ParentPage;
return _idxParent;
}
/// <summary>
/// Returns the next sibling of this node. If this node has no next sibling, then 0 is returned.
/// </summary>
public int GetSibling(out XPathNode[] pageNode)
{
pageNode = _info.SiblingPage;
return _idxSibling;
}
/// <summary>
/// Returns the next element in document order that has the same local name hashcode as this element.
/// If there are no similar elements, then 0 is returned.
/// </summary>
public int GetSimilarElement(out XPathNode[] pageNode)
{
pageNode = _info.SimilarElementPage;
return _idxSimilar;
}
/// <summary>
/// Returns true if this node's name matches the specified localName and namespaceName. Assume
/// that localName has been atomized, but namespaceName has not.
/// </summary>
public bool NameMatch(string localName, string namespaceName)
{
Debug.Assert(localName == null || (object)Document.NameTable.Get(localName) == (object)localName, "localName must be atomized.");
return (object)_info.LocalName == (object)localName &&
_info.NamespaceUri == namespaceName;
}
/// <summary>
/// Returns true if this is an Element node with a name that matches the specified localName and
/// namespaceName. Assume that localName has been atomized, but namespaceName has not.
/// </summary>
public bool ElementMatch(string localName, string namespaceName)
{
Debug.Assert(localName == null || (object)Document.NameTable.Get(localName) == (object)localName, "localName must be atomized.");
return NodeType == XPathNodeType.Element &&
(object)_info.LocalName == (object)localName &&
_info.NamespaceUri == namespaceName;
}
/// <summary>
/// Return true if this node is an xmlns:xml node.
/// </summary>
public bool IsXmlNamespaceNode
{
get
{
string localName = _info.LocalName;
return NodeType == XPathNodeType.Namespace && localName.Length == 3 && localName == "xml";
}
}
/// <summary>
/// Returns true if this node has a sibling.
/// </summary>
public bool HasSibling
{
get { return _idxSibling != 0; }
}
/// <summary>
/// Returns true if this node has a collapsed text node as its only content-typed child.
/// </summary>
public bool HasCollapsedText
{
get { return (_props & HasCollapsedTextBit) != 0; }
}
/// <summary>
/// Returns true if this node has at least one attribute.
/// </summary>
public bool HasAttribute
{
get { return (_props & HasAttributeBit) != 0; }
}
/// <summary>
/// Returns true if this node has at least one content-typed child (attributes and namespaces
/// don't count).
/// </summary>
public bool HasContentChild
{
get { return (_props & HasContentChildBit) != 0; }
}
/// <summary>
/// Returns true if this node has at least one element child.
/// </summary>
public bool HasElementChild
{
get { return (_props & HasElementChildBit) != 0; }
}
/// <summary>
/// Returns true if this is an attribute or namespace node.
/// </summary>
public bool IsAttrNmsp
{
get
{
XPathNodeType xptyp = NodeType;
return xptyp == XPathNodeType.Attribute || xptyp == XPathNodeType.Namespace;
}
}
/// <summary>
/// Returns true if this is a text or whitespace node.
/// </summary>
public bool IsText
{
get { return XPathNavigator.IsText(NodeType); }
}
/// <summary>
/// Returns true if this node has local namespace declarations associated with it. Since all
/// namespace declarations are stored out-of-line in the owner Document, this property
/// can be consulted in order to avoid a lookup in the common case where this node has no
/// local namespace declarations.
/// </summary>
public bool HasNamespaceDecls
{
get { return (_props & HasNmspDeclsBit) != 0; }
set
{
if (value) _props |= HasNmspDeclsBit;
else unchecked { _props &= (byte)~((uint)HasNmspDeclsBit); }
}
}
/// <summary>
/// Returns true if this node is an empty element that allows shortcut tag syntax.
/// </summary>
public bool AllowShortcutTag
{
get { return (_props & AllowShortcutTagBit) != 0; }
}
/// <summary>
/// Cached hashcode computed over the local name of this element.
/// </summary>
public int LocalNameHashCode
{
get { return _info.LocalNameHashCode; }
}
/// <summary>
/// Return the precomputed String value of this node (null if no value exists, i.e. document node, element node with complex content, etc).
/// </summary>
public string Value
{
get { return _value; }
}
//-----------------------------------------------
// Node construction
//-----------------------------------------------
/// <summary>
/// Constructs the 0th XPathNode in each page, which contains only page information.
/// </summary>
public void Create(XPathNodePageInfo pageInfo)
{
_info = new XPathNodeInfoAtom(pageInfo);
}
/// <summary>
/// Constructs a XPathNode. Later, the idxSibling and value fields may be fixed up.
/// </summary>
public void Create(XPathNodeInfoAtom info, XPathNodeType xptyp, int idxParent)
{
Debug.Assert(info != null && idxParent <= ushort.MaxValue);
_info = info;
_props = (uint)xptyp;
_idxParent = (ushort)idxParent;
}
/// <summary>
/// Set this node's line number information.
/// </summary>
public void SetLineInfoOffsets(int lineNumOffset, int linePosOffset)
{
Debug.Assert(lineNumOffset >= 0 && lineNumOffset <= MaxLineNumberOffset, "Line number offset too large or small: " + lineNumOffset);
Debug.Assert(linePosOffset >= 0 && linePosOffset <= MaxLinePositionOffset, "Line position offset too large or small: " + linePosOffset);
_props |= ((uint)lineNumOffset << LineNumberShift);
_posOffset = (ushort)linePosOffset;
}
/// <summary>
/// Set the position offset of this element's collapsed text.
/// </summary>
public void SetCollapsedLineInfoOffset(int posOffset)
{
Debug.Assert(posOffset >= 0 && posOffset <= MaxCollapsedPositionOffset, "Collapsed text line position offset too large or small: " + posOffset);
_props |= ((uint)posOffset << CollapsedPositionShift);
}
/// <summary>
/// Set this node's value.
/// </summary>
public void SetValue(string value)
{
_value = value;
}
/// <summary>
/// Create an empty element value.
/// </summary>
public void SetEmptyValue(bool allowShortcutTag)
{
Debug.Assert(NodeType == XPathNodeType.Element);
_value = string.Empty;
if (allowShortcutTag)
_props |= AllowShortcutTagBit;
}
/// <summary>
/// Create a collapsed text node on this element having the specified value.
/// </summary>
public void SetCollapsedValue(string value)
{
Debug.Assert(NodeType == XPathNodeType.Element);
_value = value;
_props |= HasContentChildBit | HasCollapsedTextBit;
}
/// <summary>
/// This method is called when a new child is appended to this node's list of attributes and children.
/// The type of the new child is used to determine how various parent properties should be set.
/// </summary>
public void SetParentProperties(XPathNodeType xptyp)
{
if (xptyp == XPathNodeType.Attribute)
{
_props |= HasAttributeBit;
}
else
{
_props |= HasContentChildBit;
if (xptyp == XPathNodeType.Element)
_props |= HasElementChildBit;
}
}
/// <summary>
/// Link this node to its next sibling. If "pageSibling" is different than the one stored in the InfoAtom, re-atomize.
/// </summary>
public void SetSibling(XPathNodeInfoTable infoTable, XPathNode[] pageSibling, int idxSibling)
{
Debug.Assert(pageSibling != null && idxSibling != 0 && idxSibling <= ushort.MaxValue, "Bad argument");
Debug.Assert(_idxSibling == 0, "SetSibling should not be called more than once.");
_idxSibling = (ushort)idxSibling;
if (pageSibling != _info.SiblingPage)
{
// Re-atomize the InfoAtom
_info = infoTable.Create(_info.LocalName, _info.NamespaceUri, _info.Prefix, _info.BaseUri,
_info.ParentPage, pageSibling, _info.SimilarElementPage,
_info.Document, _info.LineNumberBase, _info.LinePositionBase);
}
}
/// <summary>
/// Link this element to the next element in document order that shares a local name having the same hash code.
/// If "pageSimilar" is different than the one stored in the InfoAtom, re-atomize.
/// </summary>
public void SetSimilarElement(XPathNodeInfoTable infoTable, XPathNode[] pageSimilar, int idxSimilar)
{
Debug.Assert(pageSimilar != null && idxSimilar != 0 && idxSimilar <= ushort.MaxValue, "Bad argument");
Debug.Assert(_idxSimilar == 0, "SetSimilarElement should not be called more than once.");
_idxSimilar = (ushort)idxSimilar;
if (pageSimilar != _info.SimilarElementPage)
{
// Re-atomize the InfoAtom
_info = infoTable.Create(_info.LocalName, _info.NamespaceUri, _info.Prefix, _info.BaseUri,
_info.ParentPage, _info.SiblingPage, pageSimilar,
_info.Document, _info.LineNumberBase, _info.LinePositionBase);
}
}
}
/// <summary>
/// A reference to a XPathNode is composed of two values: the page on which the node is located, and the node's
/// index in the page.
/// </summary>
internal struct XPathNodeRef
{
private readonly XPathNode[] _page;
private readonly int _idx;
public XPathNodeRef(XPathNode[] page, int idx)
{
_page = page;
_idx = idx;
}
public XPathNode[] Page
{
get { return _page; }
}
public int Index
{
get { return _idx; }
}
public override int GetHashCode()
{
return XPathNodeHelper.GetLocation(_page, _idx);
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticBeanstalk.Model
{
/// <summary>
/// Container for the parameters to the CreateConfigurationTemplate operation.
/// <para>Creates a configuration template. Templates are associated with a specific application and are used to deploy different versions of
/// the application with the same configuration settings.</para> <para>Related Topics</para>
/// <ul>
/// <li> DescribeConfigurationOptions </li>
/// <li> DescribeConfigurationSettings </li>
/// <li> ListAvailableSolutionStacks </li>
///
/// </ul>
/// </summary>
/// <seealso cref="Amazon.ElasticBeanstalk.AmazonElasticBeanstalk.CreateConfigurationTemplate"/>
public class CreateConfigurationTemplateRequest : AmazonWebServiceRequest
{
private string applicationName;
private string templateName;
private string solutionStackName;
private SourceConfiguration sourceConfiguration;
private string environmentId;
private string description;
private List<ConfigurationOptionSetting> optionSettings = new List<ConfigurationOptionSetting>();
/// <summary>
/// The name of the application to associate with this configuration template. If no application is found with this name, AWS Elastic Beanstalk
/// returns an <c>InvalidParameterValue</c> error.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 100</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string ApplicationName
{
get { return this.applicationName; }
set { this.applicationName = value; }
}
/// <summary>
/// Sets the ApplicationName property
/// </summary>
/// <param name="applicationName">The value to set for the ApplicationName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateConfigurationTemplateRequest WithApplicationName(string applicationName)
{
this.applicationName = applicationName;
return this;
}
// Check to see if ApplicationName property is set
internal bool IsSetApplicationName()
{
return this.applicationName != null;
}
/// <summary>
/// The name of the configuration template. Constraint: This name must be unique per application. Default: If a configuration template already
/// exists with this name, AWS Elastic Beanstalk returns an <c>InvalidParameterValue</c> error.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 100</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string TemplateName
{
get { return this.templateName; }
set { this.templateName = value; }
}
/// <summary>
/// Sets the TemplateName property
/// </summary>
/// <param name="templateName">The value to set for the TemplateName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateConfigurationTemplateRequest WithTemplateName(string templateName)
{
this.templateName = templateName;
return this;
}
// Check to see if TemplateName property is set
internal bool IsSetTemplateName()
{
return this.templateName != null;
}
/// <summary>
/// The name of the solution stack used by this configuration. The solution stack specifies the operating system, architecture, and application
/// server for a configuration template. It determines the set of configuration options as well as the possible and default values. Use
/// <a>ListAvailableSolutionStacks</a> to obtain a list of available solution stacks. Default: If the <c>SolutionStackName</c> is not specified
/// and the source configuration parameter is blank, AWS Elastic Beanstalk uses the default solution stack. If not specified and the source
/// configuration parameter is specified, AWS Elastic Beanstalk uses the same solution stack as the source configuration template.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 100</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string SolutionStackName
{
get { return this.solutionStackName; }
set { this.solutionStackName = value; }
}
/// <summary>
/// Sets the SolutionStackName property
/// </summary>
/// <param name="solutionStackName">The value to set for the SolutionStackName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateConfigurationTemplateRequest WithSolutionStackName(string solutionStackName)
{
this.solutionStackName = solutionStackName;
return this;
}
// Check to see if SolutionStackName property is set
internal bool IsSetSolutionStackName()
{
return this.solutionStackName != null;
}
/// <summary>
/// If specified, AWS Elastic Beanstalk uses the configuration values from the specified configuration template to create a new configuration.
/// Values specified in the <c>OptionSettings</c> parameter of this call overrides any values obtained from the <c>SourceConfiguration</c>. If
/// no configuration template is found, returns an <c>InvalidParameterValue</c> error. Constraint: If both the solution stack name parameter and
/// the source configuration parameters are specified, the solution stack of the source configuration template must match the specified solution
/// stack name or else AWS Elastic Beanstalk returns an <c>InvalidParameterCombination</c> error.
///
/// </summary>
public SourceConfiguration SourceConfiguration
{
get { return this.sourceConfiguration; }
set { this.sourceConfiguration = value; }
}
/// <summary>
/// Sets the SourceConfiguration property
/// </summary>
/// <param name="sourceConfiguration">The value to set for the SourceConfiguration property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateConfigurationTemplateRequest WithSourceConfiguration(SourceConfiguration sourceConfiguration)
{
this.sourceConfiguration = sourceConfiguration;
return this;
}
// Check to see if SourceConfiguration property is set
internal bool IsSetSourceConfiguration()
{
return this.sourceConfiguration != null;
}
/// <summary>
/// The ID of the environment used with this configuration template.
///
/// </summary>
public string EnvironmentId
{
get { return this.environmentId; }
set { this.environmentId = value; }
}
/// <summary>
/// Sets the EnvironmentId property
/// </summary>
/// <param name="environmentId">The value to set for the EnvironmentId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateConfigurationTemplateRequest WithEnvironmentId(string environmentId)
{
this.environmentId = environmentId;
return this;
}
// Check to see if EnvironmentId property is set
internal bool IsSetEnvironmentId()
{
return this.environmentId != null;
}
/// <summary>
/// Describes this configuration.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 200</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Description
{
get { return this.description; }
set { this.description = value; }
}
/// <summary>
/// Sets the Description property
/// </summary>
/// <param name="description">The value to set for the Description property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateConfigurationTemplateRequest WithDescription(string description)
{
this.description = description;
return this;
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this.description != null;
}
/// <summary>
/// If specified, AWS Elastic Beanstalk sets the specified configuration option to the requested value. The new value overrides the value
/// obtained from the solution stack or the source configuration template.
///
/// </summary>
public List<ConfigurationOptionSetting> OptionSettings
{
get { return this.optionSettings; }
set { this.optionSettings = value; }
}
/// <summary>
/// Adds elements to the OptionSettings collection
/// </summary>
/// <param name="optionSettings">The values to add to the OptionSettings collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateConfigurationTemplateRequest WithOptionSettings(params ConfigurationOptionSetting[] optionSettings)
{
foreach (ConfigurationOptionSetting element in optionSettings)
{
this.optionSettings.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the OptionSettings collection
/// </summary>
/// <param name="optionSettings">The values to add to the OptionSettings collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateConfigurationTemplateRequest WithOptionSettings(IEnumerable<ConfigurationOptionSetting> optionSettings)
{
foreach (ConfigurationOptionSetting element in optionSettings)
{
this.optionSettings.Add(element);
}
return this;
}
// Check to see if OptionSettings property is set
internal bool IsSetOptionSettings()
{
return this.optionSettings.Count > 0;
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MLifter.Generics;
namespace MLifterTest.Generics
{
/// <summary>
///This is a test class for MethodsTest and is intended
///to contain all MethodsTest Unit Tests
///</summary>
[TestClass()]
public class MethodsTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
#region ByteArrayToCompressedArrayString
/// <summary>
/// Test for ByteArrayToCompressedArrayString.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ByteArrayToCompressedArrayString01()
{
string s;
s = Methods.ByteArrayToCompressedArrayString((byte[])null);
}
/// <summary>
/// Test for ByteArrayToCompressedArrayString.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
public void ByteArrayToCompressedArrayString02()
{
string s;
byte[] bs = new byte[0];
s = Methods.ByteArrayToCompressedArrayString(bs);
Assert.AreEqual<string>("", s);
}
/// <summary>
/// Test for ByteArrayToCompressedArrayString.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
public void ByteArrayToCompressedArrayStringRandom()
{
for (int k = 0; k < 100; k++)
{
string input = TestInfrastructure.GetRandomString(TestInfrastructure.RandomGen.Next(2, 100));
byte[] bs = new byte[input.Length];
for (int i = 0; i < input.Length; i++)
bs[i] = (byte)input[i];
string step1 = Methods.ByteArrayToCompressedArrayString(bs);
byte[] bs2 = Methods.CompressedArrayStringToByteArray(step1, input.Length);
string step2 = String.Empty;
for (int i = 0; i < bs2.Length; i++)
step2 += (char)bs2[i];
Assert.AreEqual<string>(input, step2);
}
}
/// <summary>
/// Compares the length of random compressed array string and hex strings
/// to ensure the compressed array strings are shorter.
/// </summary>
/// <remarks>Documented by Dev09, 2009-02-18</remarks>
[TestMethod]
public void CompressedArrayStringHexStringLengthComparison()
{
for (int k = 0; k < 100; k++)
{
// generate the random string and corresponding byte array
string input = TestInfrastructure.GetRandomString(TestInfrastructure.RandomGen.Next(2, 100));
byte[] bs = new byte[input.Length];
for (int i = 0; i < input.Length; i++)
bs[i] = (byte)input[i];
// encode the byte array both as compressed string and hex string
string compressedStr = Methods.ByteArrayToCompressedArrayString(bs);
string hexStr = Methods.ByteArrayToHexString(bs);
Assert.IsTrue(compressedStr.Length <= hexStr.Length);
}
}
#endregion
#region CompressedArrayStringToByteArray
/// <summary>
/// Test for CompressedArrayStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CompressedArrayStringToByteArray01()
{
byte[] bs;
bs = Methods.CompressedArrayStringToByteArray("", int.MinValue);
}
/// <summary>
/// Test for CompressedArrayStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CompressedArrayStringToByteArray02()
{
byte[] bs;
bs = Methods.CompressedArrayStringToByteArray("", 0);
}
/// <summary>
/// Test for CompressedArrayStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CompressedArrayStringToByteArray03()
{
byte[] bs;
bs = Methods.CompressedArrayStringToByteArray((string)null, 2);
}
/// <summary>
/// Test for CompressedArrayStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
public void CompressedArrayStringToByteArray04()
{
byte[] bs;
bs = Methods.CompressedArrayStringToByteArray("", 1);
Assert.IsNotNull((object)bs);
Assert.AreEqual<int>(1, bs.Length);
Assert.AreEqual<byte>((byte)0, bs[0]);
}
/// <summary>
/// Test for CompressedArrayStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
public void CompressedArrayStringToByteArray05()
{
byte[] bs;
bs = Methods.CompressedArrayStringToByteArray("\0", 1);
Assert.IsNotNull((object)bs);
Assert.AreEqual<int>(1, bs.Length);
Assert.AreEqual<byte>((byte)0, bs[0]);
}
/// <summary>
/// Test for CompressedArrayStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
public void CompressedArrayStringToByteArray06()
{
byte[] bs;
bs = Methods.CompressedArrayStringToByteArray(new string('J', 62), 1);
Assert.IsNotNull((object)bs);
Assert.AreEqual<int>(1, bs.Length);
Assert.AreEqual<byte>((byte)132, bs[0]);
}
/// <summary>
/// Test for CompressedArrayStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
public void CompressedArrayStringToByteArray07()
{
byte[] bs;
bs = Methods.CompressedArrayStringToByteArray("JJ", 2);
Assert.IsNotNull((object)bs);
Assert.AreEqual<int>(2, bs.Length);
Assert.AreEqual<byte>((byte)132, bs[0]);
Assert.AreEqual<byte>((byte)0, bs[1]);
}
/// <summary>
/// Test for CompressedArrayStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
public void CompressedArrayStringToByteArray08()
{
byte[] bs;
bs = Methods.CompressedArrayStringToByteArray
("2222222222\022222222222\022222222222222\022222222", 2);
Assert.IsNotNull((object)bs);
Assert.AreEqual<int>(2, bs.Length);
Assert.AreEqual<byte>((byte)0, bs[0]);
Assert.AreEqual<byte>((byte)0, bs[1]);
}
/// <summary>
/// Test for CompressedArrayStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
public void CompressedArrayStringToByteArray09()
{
byte[] bs;
bs = Methods.CompressedArrayStringToByteArray(new string('2', 46), 3);
Assert.IsNotNull((object)bs);
Assert.AreEqual<int>(3, bs.Length);
Assert.AreEqual<byte>((byte)0, bs[0]);
Assert.AreEqual<byte>((byte)0, bs[1]);
Assert.AreEqual<byte>((byte)0, bs[2]);
}
#endregion
#region CreateLicenseKey
/// <summary>
/// Test for CreateLicenseKey.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CreateLicenseKeyNull()
{
string s;
s = Methods.CreateLicenseKey((string)null);
}
/// <summary>
/// Test for CreateLicenseKey.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CreateLicenseKeyInvalid01()
{
string s;
s = Methods.CreateLicenseKey(String.Empty);
}
/// <summary>
/// Test for CreateLicenseKey.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CreateLicenseKeyInvalid02()
{
string s;
s = Methods.CreateLicenseKey("other");
}
/// <summary>
/// Test for CreateLicenseKey.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
public void CreateLicenseKeyClient()
{
string s;
for (int i = 0; i < 100; i++)
{
s = Methods.CreateLicenseKey("client");
string[] blocks = s.Split(new char[] { '-' });
foreach (string block in blocks)
{
int sum = 0;
foreach (char c in block)
sum += (int)c;
Assert.IsFalse(sum % 2 == 0);
}
}
}
/// <summary>
/// Test for CreateLicenseKey.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
public void CreateLicenseKeyServer()
{
string s;
for (int i = 0; i < 100; i++)
{
s = Methods.CreateLicenseKey("server");
string[] blocks = s.Split(new char[] { '-' });
foreach (string block in blocks)
{
int sum = 0;
foreach (char c in block)
sum += (int)c;
Assert.IsTrue(sum % 2 == 0);
}
}
}
#endregion
#region IsEven
/// <summary>
/// Test for IsEven().
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void IsEven01()
{
bool b;
b = Methods.IsEven(-1);
}
/// <summary>
/// Test for IsEven().
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void IsEven02()
{
bool b;
b = Methods.IsEven(10000);
}
/// <summary>
/// Test for IsEven().
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-13</remarks>
[TestMethod]
public void IsEvenRandom()
{
for (int i = 0; i < 100; i++)
{
int val = TestInfrastructure.RandomGen.Next(0, 9999);
string block = val.ToString("0000");
int sum = 0;
foreach (char c in block)
sum += (int)c;
Assert.AreEqual<bool>(Methods.IsEven(val), (sum % 2 == 0));
}
}
#endregion
#region GenerateSymKey
/// <summary>
/// Tests for GenerateSymKey.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void GenerateSymKey01()
{
string s;
s = Methods.GenerateSymKey((string)null);
}
/// <summary>
/// Tests for GenerateSymKey.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
public void GenerateSymKey02()
{
string s;
s = Methods.GenerateSymKey("test");
Assert.AreEqual<string>("098f6bcd4621d373cade4e83", s);
}
#endregion
#region TDesDecryptBytes
/// <summary>
/// Test for TDesDecryptBytes.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TDesDecrypt01()
{
string s;
s = Methods.TDesDecrypt((string)null, "", false);
}
/// <summary>
/// Test for TDesDecryptBytes.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void TDesDecryptBytes01()
{
byte[] bs;
byte[] bs1 = new byte[0];
bs = Methods.TDesDecryptBytes(bs1, "", false);
}
/// <summary>
/// Test for TDesDecryptBytes.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TDesDecryptBytes02()
{
byte[] bs;
byte[] bs1 = new byte[0];
bs = Methods.TDesDecryptBytes(bs1, (string)null, false);
}
/// <summary>
/// Test for TDesDecryptBytes.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(CryptographicException))]
public void TDesDecryptBytes03()
{
byte[] bs;
byte[] bs1 = new byte[0];
bs = Methods.TDesDecryptBytes(bs1, "\0", false);
}
/// <summary>
/// Test for TDesDecryptBytes.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(CryptographicException))]
public void TDesDecryptBytes04()
{
byte[] bs;
byte[] bs1 = new byte[0];
bs = Methods.TDesDecryptBytes(bs1, "\0", true);
}
/// <summary>
/// Test for TDesDecryptBytes.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TDesDecryptBytes05()
{
byte[] bs;
bs = Methods.TDesDecryptBytes((byte[])null, "\0", false);
}
/// <summary>
/// Test for TDesDecryptBytes.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void TDesDecryptBytes06()
{
byte[] bs;
byte[] bs1 = new byte[0];
bs = Methods.TDesDecryptBytes(bs1, "\u3000", false);
}
/// <summary>
/// Test for TDesDecryptBytes.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(CryptographicException))]
public void TDesDecryptBytes07()
{
byte[] bs;
byte[] bs1 = new byte[0];
bs = Methods.TDesDecryptBytes(bs1, "\0\u1680", false);
}
/// <summary>
/// Test for TDesDecryptBytes.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(CryptographicException))]
public void TDesDecryptBytes08()
{
byte[] bs;
byte[] bs1 = new byte[0];
bs = Methods.TDesDecryptBytes(bs1, " \0", false);
}
/// <summary>
/// Test for TDesDecryptBytes.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void TDesDecryptBytes09()
{
byte[] bs;
byte[] bs1 = new byte[0];
bs = Methods.TDesDecryptBytes(bs1, "\u3000\u3000", false);
}
/// <summary>
/// Test for TDesDecryptBytes.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(CryptographicException))]
public void TDesDecryptBytes10()
{
byte[] bs;
byte[] bs1 = new byte[2];
bs = Methods.TDesDecryptBytes(bs1, "\0\u00a0\u2028", false);
}
#endregion
#region TDesEncryptBytes
/// <summary>
/// Test for TDesEncryptByte.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(CryptographicException))]
public void TDesEncryptBytes0101()
{
byte[] bs;
byte[] bs1 = new byte[0];
bs = Methods.TDesEncryptBytes(bs1, "", false);
}
/// <summary>
/// Test for TDesEncryptByte.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
public void TDesEncryptBytes0102()
{
byte[] bs;
byte[] bs1 = new byte[0];
bs = Methods.TDesEncryptBytes(bs1, "", true);
Assert.IsNotNull((object)bs);
Assert.AreEqual<int>(8, bs.Length);
Assert.AreEqual<byte>((byte)76, bs[0]);
Assert.AreEqual<byte>((byte)135, bs[1]);
Assert.AreEqual<byte>((byte)82, bs[2]);
Assert.AreEqual<byte>((byte)247, bs[3]);
Assert.AreEqual<byte>((byte)237, bs[4]);
Assert.AreEqual<byte>((byte)57, bs[5]);
Assert.AreEqual<byte>((byte)1, bs[6]);
Assert.AreEqual<byte>((byte)171, bs[7]);
}
/// <summary>
/// Test for TDesEncryptByte.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TDesEncryptBytes0103()
{
byte[] bs;
bs = Methods.TDesEncryptBytes((byte[])null, "", false);
}
/// <summary>
/// Test for TDesEncryptByte.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-16</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TDesEncryptBytes0104()
{
byte[] bs;
byte[] bs1 = new byte[0];
bs = Methods.TDesEncryptBytes(bs1, (string)null, false);
}
#endregion
#region EncryptDecryptDes
/// <summary>
/// Encrypts the decrypt des01.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
public void EncryptDecryptDes01()
{
string k = Methods.GenerateSymKey("testkey");
string input = "testdata";
string de = Methods.TDesEncrypt(input, k, false);
string output = Methods.TDesDecrypt(de, k, false);
Assert.AreEqual<string>(input, output);
}
/// <summary>
/// Encrypts the decrypt des02.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
public void EncryptDecryptDes02()
{
string k = Methods.GenerateSymKey("testkey");
string input = "testdata";
string de = Methods.TDesEncrypt(input, k, true);
string output = Methods.TDesDecrypt(de, k, true);
Assert.AreEqual<string>(input, output);
}
#endregion
#region ExtractPublicKey
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ExtractPublicKey01()
{
string s;
s = Methods.ExtractPublicKey((string)null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ExtractPublicKey02()
{
string s;
string key = "";
s = Methods.ExtractPublicKey(key);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ExtractPublicKey03()
{
string s;
string key = "<invalidxml>";
s = Methods.ExtractPublicKey(key);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ExtractPublicKey04()
{
string s;
string key = "<validxml></validxml>";
s = Methods.ExtractPublicKey(key);
}
[TestMethod]
public void ExtractPublicKey05()
{
string s;
MLifter.Generics.RSA rsa = new MLifter.Generics.RSA();
string key = rsa.GetPublicKey();
s = Methods.ExtractPublicKey(key);
Regex regex = new Regex(@"<Modulus>(?<modulus>.+)</Modulus>", RegexOptions.Multiline);
Match m = regex.Match(key);
string mod = String.Empty;
if (!m.Success)
{
Assert.Fail("Could not match modulus!");
}
else
{
mod = Methods.Base64ToHex(m.Groups["modulus"].Value);
}
Assert.AreEqual<string>(mod, s);
}
#endregion
#region ExtractExponent
/// <summary>
/// Tests ExtractExponent.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ExtractExponent01()
{
string s;
s = Methods.ExtractExponent((string)null);
}
/// <summary>
/// Tests ExtractExponent.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ExtractExponent02()
{
string s;
string key = "";
s = Methods.ExtractExponent(key);
}
/// <summary>
/// Tests ExtractExponent.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ExtractExponent03()
{
string s;
string key = "<invalidxml>";
s = Methods.ExtractExponent(key);
}
/// <summary>
/// Tests ExtractExponent.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ExtractExponent04()
{
string s;
string key = "<validxml></validxml>";
s = Methods.ExtractExponent(key);
}
/// <summary>
/// Tests ExtractExponent.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
public void ExtractExponent05()
{
string s;
MLifter.Generics.RSA rsa = new MLifter.Generics.RSA();
string key = rsa.GetPublicKey();
s = Methods.ExtractExponent(key);
Regex regex = new Regex(@"<Exponent>(?<exponent>.+)</Exponent>", RegexOptions.Multiline);
Match m = regex.Match(key);
string mod = String.Empty;
if (!m.Success)
{
Assert.Fail("Could not match exponent!");
}
else
{
mod = Methods.Base64ToHex(m.Groups["exponent"].Value);
}
Assert.AreEqual<string>(mod, s);
}
#endregion
#region Base64ToHex
/// <summary>
/// Tests Base64ToHex.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Base64ToHex01()
{
string s;
s = Methods.Base64ToHex((string)null);
}
/// <summary>
/// Tests Base64ToHex.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
public void Base64ToHex02()
{
string s;
s = Methods.Base64ToHex("");
Assert.AreEqual<string>("", s);
}
/// <summary>
/// Tests Base64ToHex.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
public void Base64ToHex03()
{
string input = "A test is a test is a test is a test!";
string s = Methods.Base64ToHex(Convert.ToBase64String(Encoding.ASCII.GetBytes(input)));
string reverse = Encoding.ASCII.GetString(Methods.HexStringToByteArray(s));
Assert.AreEqual<string>(input, reverse);
}
/// <summary>
/// Tests Base64ToHex.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
public void Base64ToHex04()
{
for (int i = 0; i <= 100; i++)
{
string input = TestInfrastructure.GetRandomString(TestInfrastructure.RandomGen.Next(15, 1000));
string s = Methods.Base64ToHex(Convert.ToBase64String(Encoding.ASCII.GetBytes(input)));
string reverse = Encoding.ASCII.GetString(Methods.HexStringToByteArray(s));
Assert.AreEqual<string>(input, reverse);
}
}
#endregion
#region ByteArrayToHexString
/// <summary>
/// Tests ByteArrayToHexString.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ByteArrayToHexString01()
{
string s;
s = Methods.ByteArrayToHexString((byte[])null);
}
/// <summary>
/// Tests ByteArrayToHexString.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
public void ByteArrayToHexString02()
{
string s;
byte[] bs = new byte[0];
s = Methods.ByteArrayToHexString(bs);
Assert.AreEqual<string>("", s);
}
/// <summary>
/// Tests ByteArrayToHexString.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
public void ByteArrayToHexString03()
{
string s;
byte[] bs = new byte[1];
s = Methods.ByteArrayToHexString(bs);
Assert.AreEqual<string>("00", s);
}
/// <summary>
/// Tests ByteArrayToHexString.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
public void ByteArrayToHexString04()
{
string s;
byte[] bs = new byte[2];
s = Methods.ByteArrayToHexString(bs);
Assert.AreEqual<string>("0000", s);
}
/// <summary>
/// Tests ByteArrayToHexString with sample known case.
/// </summary>
/// <remarks>Documented by Dev09, 2009-02-18</remarks>
[TestMethod]
public void ByteArrayToHexString05()
{
string s;
byte[] bs = new byte[4] { 170, 187, 204, 221 };
s = Methods.ByteArrayToHexString(bs);
Assert.AreEqual<string>("AABBCCDD", s);
}
#endregion
#region HexStringToByteArray
/// <summary>
/// Tests HexStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void HexStringToByteArray01()
{
byte[] bs;
bs = Methods.HexStringToByteArray((string)null);
}
/// <summary>
/// Tests HexStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void HexStringToByteArray02()
{
byte[] bs;
bs = Methods.HexStringToByteArray("\0"); //not a hex string
}
/// <summary>
/// Tests HexStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void HexStringToByteArray03()
{
byte[] bs;
bs = Methods.HexStringToByteArray("0a011"); //not a hex string
}
/// <summary>
/// Tests HexStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void HexStringToByteArray04()
{
byte[] bs;
bs = Methods.HexStringToByteArray("0a0H10"); //not a hex string
}
/// <summary>
/// Tests HexStringToByteArray.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
public void HexStringToByteArray05()
{
byte[] bs;
bs = Methods.HexStringToByteArray("");
Assert.IsNotNull((object)bs);
Assert.AreEqual<int>(0, bs.Length);
}
/// <summary>
/// Tests HexStringToByteArray with known value.
/// </summary>
/// <remarks>Documented by Dev09, 2009-02-18</remarks>
[TestMethod]
public void HexStringToByteArray06()
{
byte[] bs;
byte[] correctBs = new byte[4] { 170, 187, 204, 221 };
string s = "AABBCCDD";
bs = Methods.HexStringToByteArray(s);
Assert.AreEqual<int>(correctBs.Length, bs.Length);
for (int i = 0; i < correctBs.Length; i++)
{
Assert.AreEqual<byte>(correctBs[i], bs[i]);
}
}
#endregion
#region Right
/// <summary>
/// Tests Right.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void Right01()
{
string s;
s = Methods.Right("", 2);
}
/// <summary>
/// Tests Right.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
public void Right02()
{
string s;
s = Methods.Right("", 0);
Assert.AreEqual<string>("", s);
}
/// <summary>
/// Tests Right.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Right03()
{
string s;
s = Methods.Right((string)null, 2);
}
/// <summary>
/// Tests Right.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void Right04()
{
string s;
s = Methods.Right("", -262145);
}
[TestMethod]
public void Right05()
{
string s;
s = Methods.Right("This is a test string", 5);
Assert.AreEqual<string>("tring", s);
}
#endregion
/// <summary>
/// Tests Right.
/// </summary>
/// <remarks>Documented by Dev03, 2009-02-17</remarks>
[TestMethod]
public void GetMID01()
{
string before = String.Empty;
for (int i = 0; i < 10; i++)
{
string s;
s = Methods.GetMID();
if (i > 0)
Assert.AreEqual<string>(before, s);
before = s;
}
}
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript {
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices.Expando;
public class JSObject : ScriptObject, IEnumerable, IExpando{
private bool isASubClass;
private IReflect subClassIR;
private SimpleHashtable memberCache;
internal bool noExpando;
internal SimpleHashtable name_table;
protected ArrayList field_table;
internal JSObject outer_class_instance;
public JSObject()
: this(null, false){
this.noExpando = false;
}
internal JSObject(ScriptObject parent)
: this(parent, true) {
}
internal JSObject(ScriptObject parent, bool checkSubType)
: base(parent) {
this.memberCache = null;
this.isASubClass = false;
this.subClassIR = null;
if (checkSubType){
Type subType = Globals.TypeRefs.ToReferenceContext(this.GetType());
Debug.Assert(subType != Typeob.BuiltinFunction);
if (subType != Typeob.JSObject){
this.isASubClass = true;
this.subClassIR = TypeReflector.GetTypeReflectorFor(subType);
}
}else
Debug.Assert(Globals.TypeRefs.ToReferenceContext(this.GetType()) == Typeob.JSObject);
this.noExpando = this.isASubClass;
this.name_table = null;
this.field_table = null;
this.outer_class_instance = null;
}
internal JSObject(ScriptObject parent, Type subType)
: base(parent) {
this.memberCache = null;
this.isASubClass = false;
this.subClassIR = null;
Debug.Assert(subType == this.GetType() || this.GetType() == typeof(BuiltinFunction));
subType = Globals.TypeRefs.ToReferenceContext(subType);
if (subType != Typeob.JSObject){
this.isASubClass = true;
this.subClassIR = TypeReflector.GetTypeReflectorFor(subType);
}
this.noExpando = this.isASubClass;
this.name_table = null;
this.field_table = null;
}
public FieldInfo AddField(String name){
if (this.noExpando)
return null;
FieldInfo field = (FieldInfo)this.NameTable[name];
if (field == null){
field = new JSExpandoField(name);
this.name_table[name] = field;
this.field_table.Add(field);
}
return field;
}
MethodInfo IExpando.AddMethod(String name, Delegate method){
return null;
}
PropertyInfo IExpando.AddProperty(String name){
return null;
}
internal override bool DeleteMember(String name){
FieldInfo field = (FieldInfo)this.NameTable[name];
if (field != null){
if (field is JSExpandoField){
field.SetValue(this, Missing.Value);
this.name_table.Remove(name);
this.field_table.Remove(field);
return true;
}else if (field is JSPrototypeField){
field.SetValue(this, Missing.Value);
return true;
}else
return false;
}else if (this.parent != null)
return LateBinding.DeleteMember(this.parent, name);
else
return false;
}
internal virtual String GetClassName(){
return "Object";
}
#if !DEBUG
[DebuggerStepThroughAttribute]
[DebuggerHiddenAttribute]
#endif
internal override Object GetDefaultValue(PreferredType preferred_type){
if (preferred_type == PreferredType.String){
ScriptFunction toString = this.GetMemberValue("toString") as ScriptFunction;
if (toString != null){
Object result = toString.Call(new Object[0], this);
if (result == null) return result;
IConvertible ic = Convert.GetIConvertible(result);
if (ic != null && ic.GetTypeCode() != TypeCode.Object) return result;
}
ScriptFunction valueOf = this.GetMemberValue("valueOf") as ScriptFunction;
if (valueOf != null){
Object result = valueOf.Call(new Object[0], this);
if (result == null) return result;
IConvertible ic = Convert.GetIConvertible(result);
if (ic != null && ic.GetTypeCode() != TypeCode.Object) return result;
}
}else if (preferred_type == PreferredType.LocaleString){
ScriptFunction toLocaleString = this.GetMemberValue("toLocaleString") as ScriptFunction;
if (toLocaleString != null){
return toLocaleString.Call(new Object[0], this);
}
}else{
if (preferred_type == PreferredType.Either && this is DateObject)
return this.GetDefaultValue(PreferredType.String);
ScriptFunction valueOf = this.GetMemberValue("valueOf") as ScriptFunction;
if (valueOf != null){
Object result = valueOf.Call(new Object[0], this);
if (result == null) return result;
IConvertible ic = Convert.GetIConvertible(result);
if (ic != null && ic.GetTypeCode() != TypeCode.Object) return result;
}
ScriptFunction toString = this.GetMemberValue("toString") as ScriptFunction;
if (toString != null){
Object result = toString.Call(new Object[0], this);
if (result == null) return result;
IConvertible ic = Convert.GetIConvertible(result);
if (ic != null && ic.GetTypeCode() != TypeCode.Object) return result;
}
}
return this;
}
IEnumerator IEnumerable.GetEnumerator(){
return ForIn.JScriptGetEnumerator(this);
}
private static bool IsHiddenMember(MemberInfo mem) {
// Members that are declared in super classes of JSObject are hidden except for those
// in Object.
Type mtype = mem.DeclaringType;
if (mtype == Typeob.JSObject || mtype == Typeob.ScriptObject ||
(mtype == Typeob.ArrayWrapper && mem.Name != "length"))
return true;
return false;
}
private MemberInfo[] GetLocalMember(String name, BindingFlags bindingAttr, bool wrapMembers){
MemberInfo[] result = null;
FieldInfo field = this.name_table == null ? null : (FieldInfo)this.name_table[name];
if (field == null && this.isASubClass){
if (this.memberCache != null){
result = (MemberInfo[])this.memberCache[name];
if (result != null) return result;
}
bindingAttr &= ~BindingFlags.NonPublic; //Never expose non public fields of old style objects
result = this.subClassIR.GetMember(name, bindingAttr);
if (result.Length == 0)
result = this.subClassIR.GetMember(name, (bindingAttr&~BindingFlags.Instance)|BindingFlags.Static);
int n = result.Length;
if (n > 0){
//Suppress any members that are declared in JSObject or earlier. But keep the ones in Object.
int hiddenMembers = 0;
foreach (MemberInfo mem in result){
if (JSObject.IsHiddenMember(mem))
hiddenMembers++;
}
if (hiddenMembers > 0 && !(n == 1 && this is ObjectPrototype && name == "ToString")){
MemberInfo[] newResult = new MemberInfo[n-hiddenMembers];
int j = 0;
foreach (MemberInfo mem in result){
if (!JSObject.IsHiddenMember(mem))
newResult[j++] = mem;
}
result = newResult;
}
}
if ((result == null || result.Length == 0) && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0){
BindingFlags flags = (bindingAttr & BindingFlags.IgnoreCase) | BindingFlags.Public | BindingFlags.Instance;
if (this is StringObject)
result = TypeReflector.GetTypeReflectorFor(Typeob.String).GetMember(name, flags);
else if (this is NumberObject)
result = TypeReflector.GetTypeReflectorFor(((NumberObject)this).baseType).GetMember(name, flags);
else if (this is BooleanObject)
result = TypeReflector.GetTypeReflectorFor(Typeob.Boolean).GetMember(name, flags);
else if (this is StringConstructor)
result = TypeReflector.GetTypeReflectorFor(Typeob.String).GetMember(name, (flags|BindingFlags.Static)&~BindingFlags.Instance);
else if (this is BooleanConstructor)
result = TypeReflector.GetTypeReflectorFor(Typeob.Boolean).GetMember(name, (flags|BindingFlags.Static)&~BindingFlags.Instance);
else if (this is ArrayWrapper)
result = TypeReflector.GetTypeReflectorFor(Typeob.Array).GetMember(name, flags);
}
if (result != null && result.Length > 0){
if (wrapMembers)
result = ScriptObject.WrapMembers(result, this);
if (this.memberCache == null) this.memberCache = new SimpleHashtable(32);
this.memberCache[name] = result;
return result;
}
}
if ((bindingAttr&BindingFlags.IgnoreCase) != 0 && (result == null || result.Length == 0)){
result = null;
IDictionaryEnumerator e = this.name_table.GetEnumerator();
while (e.MoveNext()){
if (String.Compare(e.Key.ToString(), name, StringComparison.OrdinalIgnoreCase) == 0){
field = (FieldInfo)e.Value;
break;
}
}
}
if (field != null)
return new MemberInfo[]{field};
if (result == null) result = new MemberInfo[0];
return result;
}
public override MemberInfo[] GetMember(String name, BindingFlags bindingAttr){
return this.GetMember(name, bindingAttr, false);
}
private MemberInfo[] GetMember(String name, BindingFlags bindingAttr, bool wrapMembers){
MemberInfo[] members = this.GetLocalMember(name, bindingAttr, wrapMembers);
if (members.Length > 0) return members;
if (this.parent != null){
if (this.parent is JSObject){
members = ((JSObject)this.parent).GetMember(name, bindingAttr, true);
wrapMembers = false;
}else
members = this.parent.GetMember(name, bindingAttr);
foreach (MemberInfo mem in members){
if (mem.MemberType == MemberTypes.Field){
FieldInfo field = (FieldInfo)mem;
JSMemberField mfield = mem as JSMemberField;
if (mfield != null){ //This can only happen when running in the Evaluator
if (!mfield.IsStatic){
JSGlobalField gfield = new JSGlobalField(this, name, mfield.value, FieldAttributes.Public);
this.NameTable[name] = gfield;
this.field_table.Add(gfield);
field = mfield;
}
}else{
field = new JSPrototypeField(this.parent, (FieldInfo)mem);
if (!this.noExpando){
this.NameTable[name] = field;
this.field_table.Add(field);
}
}
return new MemberInfo[]{field};
}
if (!this.noExpando){
if (mem.MemberType == MemberTypes.Method){
FieldInfo field = new JSPrototypeField(this.parent,
new JSGlobalField(this, name,
LateBinding.GetMemberValue(this.parent, name, null, members),
FieldAttributes.Public|FieldAttributes.InitOnly));
this.NameTable[name] = field;
this.field_table.Add(field);
return new MemberInfo[]{field};
}
}
}
if (wrapMembers)
return ScriptObject.WrapMembers(members, this.parent);
else
return members;
}
return new MemberInfo[0];
}
public override MemberInfo[] GetMembers(BindingFlags bindingAttr){
MemberInfoList mems = new MemberInfoList();
SimpleHashtable uniqueMems = new SimpleHashtable(32);
if (!this.noExpando && this.field_table != null){ //Add any expando properties
IEnumerator enu = this.field_table.GetEnumerator();
while (enu.MoveNext()){
FieldInfo field = (FieldInfo)enu.Current;
mems.Add(field);
uniqueMems[field.Name] = field;
}
}
//Add the public members of the built-in objects if they don't already exist
if (this.isASubClass){
MemberInfo[] ilMembers = this.GetType().GetMembers(bindingAttr & ~BindingFlags.NonPublic); //Never expose non public members of old style objects
for (int i = 0, n = ilMembers.Length; i < n; i++){
MemberInfo ilMem = ilMembers[i];
//Hide any infrastructure stuff in JSObject
if (!ilMem.DeclaringType.IsAssignableFrom(Typeob.JSObject) && uniqueMems[ilMem.Name] == null){
MethodInfo method = ilMem as MethodInfo;
if (method == null || !method.IsSpecialName){
mems.Add(ilMem);
uniqueMems[ilMem.Name] = ilMem;
}
}
}
}
//Add parent members if they don't already exist
if (this.parent != null){
SimpleHashtable cache = this.parent.wrappedMemberCache;
if (cache == null)
cache = this.parent.wrappedMemberCache = new SimpleHashtable(8);
MemberInfo[] parentMems = ScriptObject.WrapMembers(((IReflect)this.parent).GetMembers(bindingAttr & ~BindingFlags.NonPublic), this.parent, cache);
for(int i = 0, n = parentMems.Length; i < n; i++){
MemberInfo parentMem = parentMems[i];
if(uniqueMems[parentMem.Name] == null){
mems.Add(parentMem);
//uniqueMems[parentMem.Name] = parentMem; //No need to add to lookup table - no one else will be looking.
}
}
}
return mems.ToArray();
}
internal override void GetPropertyEnumerator(ArrayList enums, ArrayList objects){
if (this.field_table == null) this.field_table = new ArrayList();
enums.Add(new ListEnumerator(this.field_table));
objects.Add(this);
if (this.parent != null)
this.parent.GetPropertyEnumerator(enums, objects);
}
internal override Object GetValueAtIndex(uint index){ //used by array functions
String name = System.Convert.ToString(index, CultureInfo.InvariantCulture);
//Do not defer to to routine below, since Array objects override it and could call back to this routine
FieldInfo field = (FieldInfo)(this.NameTable[name]);
if (field != null)
return field.GetValue(this);
else{
Object result = null;
if (this.parent != null)
result = this.parent.GetMemberValue(name);
else
result = Missing.Value;
if (this is StringObject && result == Missing.Value){
String str = ((StringObject)this).value;
if (index < str.Length)
return str[(int)index];
}
return result;
}
}
#if !DEBUG
[DebuggerStepThroughAttribute]
[DebuggerHiddenAttribute]
#endif
internal override Object GetMemberValue(String name){
FieldInfo field = (FieldInfo)this.NameTable[name];
if (field == null && this.isASubClass){
field = this.subClassIR.GetField(name, BindingFlags.Instance|BindingFlags.Static|BindingFlags.Public);
if (field != null){
if (field.DeclaringType == Typeob.ScriptObject) return Missing.Value;
}else{
PropertyInfo prop = this.subClassIR.GetProperty(name, BindingFlags.Instance|BindingFlags.Public);
if (prop != null && !prop.DeclaringType.IsAssignableFrom(Typeob.JSObject))
return JSProperty.GetGetMethod(prop, false).Invoke(this, BindingFlags.SuppressChangeType, null, null, null);
try{
MethodInfo method = this.subClassIR.GetMethod(name, BindingFlags.Public|BindingFlags.Static);
if (method != null){
Type dt = method.DeclaringType;
if (dt != Typeob.JSObject && dt != Typeob.ScriptObject && dt != Typeob.Object)
return new BuiltinFunction(this, method);
}
}catch(AmbiguousMatchException){}
}
}
if (field != null)
return field.GetValue(this);
if (this.parent != null)
return this.parent.GetMemberValue(name);
return Missing.Value;
}
internal SimpleHashtable NameTable{
get{
SimpleHashtable result = this.name_table;
if (result == null){
this.name_table = result = new SimpleHashtable(16);
this.field_table = new ArrayList();
}
return result;
}
}
void IExpando.RemoveMember(MemberInfo m){
this.DeleteMember(m.Name);
}
#if !DEBUG
[DebuggerStepThroughAttribute]
[DebuggerHiddenAttribute]
#endif
internal override void SetMemberValue(String name, Object value){
this.SetMemberValue2(name, value);
}
public void SetMemberValue2(String name, Object value){
FieldInfo field = (FieldInfo)this.NameTable[name];
if (field == null && this.isASubClass)
field = this.GetType().GetField(name);
if (field == null){
if (this.noExpando)
return;
field = new JSExpandoField(name);
this.name_table[name] = field;
this.field_table.Add(field);
}
if (!field.IsInitOnly && !field.IsLiteral)
field.SetValue(this, value);
}
internal override void SetValueAtIndex(uint index, Object value){
this.SetMemberValue(System.Convert.ToString(index, CultureInfo.InvariantCulture), value);
}
internal virtual void SwapValues(uint left, uint right){
String left_name = System.Convert.ToString(left, CultureInfo.InvariantCulture);
String right_name = System.Convert.ToString(right, CultureInfo.InvariantCulture);
FieldInfo left_field = (FieldInfo)(this.NameTable[left_name]);
FieldInfo right_field = (FieldInfo)(this.name_table[right_name]);
if (left_field == null)
if (right_field == null)
return;
else{
this.name_table[left_name] = right_field;
this.name_table.Remove(right_name);
}
else if (right_field == null){
this.name_table[right_name] = left_field;
this.name_table.Remove(left_name);
}else{
this.name_table[left_name] = right_field;
this.name_table[right_name] = left_field;
}
}
public override String ToString(){
return Convert.ToString(this);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.