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 log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Services.Interfaces;
using OpenSim.Services.UserProfilesService;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserProfilesModule")]
public class UserProfileModule : IProfileModule, INonSharedRegionModule
{
/// <summary>
/// Logging
/// </summary>
static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// The pair of Dictionaries are used to handle the switching of classified ads
// by maintaining a cache of classified id to creator id mappings and an interest
// count. The entries are removed when the interest count reaches 0.
Dictionary<UUID, UUID> m_classifiedCache = new Dictionary<UUID, UUID>();
Dictionary<UUID, int> m_classifiedInterest = new Dictionary<UUID, int>();
private JsonRpcRequestManager rpc = new JsonRpcRequestManager();
public Scene Scene
{
get; private set;
}
/// <summary>
/// Gets or sets the ConfigSource.
/// </summary>
/// <value>
/// The configuration
/// </value>
public IConfigSource Config {
get;
set;
}
/// <summary>
/// Gets or sets the URI to the profile server.
/// </summary>
/// <value>
/// The profile server URI.
/// </value>
public string ProfileServerUri {
get;
set;
}
IProfileModule ProfileModule
{
get; set;
}
IUserManagement UserManagementModule
{
get; set;
}
/// <summary>
/// Gets or sets a value indicating whether this
/// <see cref="OpenSim.Region.Coremodules.UserProfiles.UserProfileModule"/> is enabled.
/// </summary>
/// <value>
/// <c>true</c> if enabled; otherwise, <c>false</c>.
/// </value>
public bool Enabled {
get;
set;
}
#region IRegionModuleBase implementation
/// <summary>
/// This is called to initialize the region module. For shared modules, this is called exactly once, after
/// creating the single (shared) instance. For non-shared modules, this is called once on each instance, after
/// the instace for the region has been created.
/// </summary>
/// <param name='source'>
/// Source.
/// </param>
public void Initialise(IConfigSource source)
{
Config = source;
ReplaceableInterface = typeof(IProfileModule);
IConfig profileConfig = Config.Configs["UserProfiles"];
if (profileConfig == null)
{
m_log.Debug("[PROFILES]: UserProfiles disabled, no configuration");
Enabled = false;
return;
}
// If we find ProfileURL then we configure for FULL support
// else we setup for BASIC support
ProfileServerUri = profileConfig.GetString("ProfileServiceURL", "");
if (ProfileServerUri == "")
{
Enabled = false;
return;
}
m_log.Debug("[PROFILES]: Full Profiles Enabled");
ReplaceableInterface = null;
Enabled = true;
}
/// <summary>
/// Adds the region.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void AddRegion(Scene scene)
{
if(!Enabled)
return;
Scene = scene;
Scene.RegisterModuleInterface<IProfileModule>(this);
Scene.EventManager.OnNewClient += OnNewClient;
Scene.EventManager.OnMakeRootAgent += HandleOnMakeRootAgent;
UserManagementModule = Scene.RequestModuleInterface<IUserManagement>();
}
void HandleOnMakeRootAgent (ScenePresence obj)
{
if(obj.PresenceType == PresenceType.Npc)
return;
Util.FireAndForget(delegate
{
GetImageAssets(((IScenePresence)obj).UUID);
});
}
/// <summary>
/// Removes the region.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void RemoveRegion(Scene scene)
{
if(!Enabled)
return;
}
/// <summary>
/// This will be called once for every scene loaded. In a shared module this will be multiple times in one
/// instance, while a nonshared module instance will only be called once. This method is called after AddRegion
/// has been called in all modules for that scene, providing an opportunity to request another module's
/// interface, or hook an event from another module.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void RegionLoaded(Scene scene)
{
if(!Enabled)
return;
}
/// <summary>
/// If this returns non-null, it is the type of an interface that this module intends to register. This will
/// cause the loader to defer loading of this module until all other modules have been loaded. If no other
/// module has registered the interface by then, this module will be activated, else it will remain inactive,
/// letting the other module take over. This should return non-null ONLY in modules that are intended to be
/// easily replaceable, e.g. stub implementations that the developer expects to be replaced by third party
/// provided modules.
/// </summary>
/// <value>
/// The replaceable interface.
/// </value>
public Type ReplaceableInterface
{
get; private set;
}
/// <summary>
/// Called as the instance is closed.
/// </summary>
public void Close()
{
}
/// <value>
/// The name of the module
/// </value>
/// <summary>
/// Gets the module name.
/// </summary>
public string Name
{
get { return "UserProfileModule"; }
}
#endregion IRegionModuleBase implementation
#region Region Event Handlers
/// <summary>
/// Raises the new client event.
/// </summary>
/// <param name='client'>
/// Client.
/// </param>
void OnNewClient(IClientAPI client)
{
//Profile
client.OnRequestAvatarProperties += RequestAvatarProperties;
client.OnUpdateAvatarProperties += AvatarPropertiesUpdate;
client.OnAvatarInterestUpdate += AvatarInterestsUpdate;
// Classifieds
client.AddGenericPacketHandler("avatarclassifiedsrequest", ClassifiedsRequest);
client.OnClassifiedInfoUpdate += ClassifiedInfoUpdate;
client.OnClassifiedInfoRequest += ClassifiedInfoRequest;
client.OnClassifiedDelete += ClassifiedDelete;
// Picks
client.AddGenericPacketHandler("avatarpicksrequest", PicksRequest);
client.AddGenericPacketHandler("pickinforequest", PickInfoRequest);
client.OnPickInfoUpdate += PickInfoUpdate;
client.OnPickDelete += PickDelete;
// Notes
client.AddGenericPacketHandler("avatarnotesrequest", NotesRequest);
client.OnAvatarNotesUpdate += NotesUpdate;
// Preferences
client.OnUserInfoRequest += UserPreferencesRequest;
client.OnUpdateUserInfo += UpdateUserPreferences;
}
#endregion Region Event Handlers
#region Classified
///
/// <summary>
/// Handles the avatar classifieds request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void ClassifiedsRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID targetID;
UUID.TryParse(args[0], out targetID);
// Can't handle NPC yet...
ScenePresence p = FindPresence(targetID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
GetUserProfileServerURI(targetID, out serverURI);
UUID creatorId = UUID.Zero;
Dictionary<UUID, string> classifieds = new Dictionary<UUID, string>();
OSDMap parameters= new OSDMap();
UUID.TryParse(args[0], out creatorId);
parameters.Add("creatorId", OSD.FromUUID(creatorId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "avatarclassifiedsrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
return;
}
parameters = (OSDMap)Params;
OSDArray list = (OSDArray)parameters["result"];
foreach(OSD map in list)
{
OSDMap m = (OSDMap)map;
UUID cid = m["classifieduuid"].AsUUID();
string name = m["name"].AsString();
classifieds[cid] = name;
lock (m_classifiedCache)
{
if (!m_classifiedCache.ContainsKey(cid))
{
m_classifiedCache.Add(cid,creatorId);
m_classifiedInterest.Add(cid, 0);
}
m_classifiedInterest[cid]++;
}
}
remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
}
public void ClassifiedInfoRequest(UUID queryClassifiedID, IClientAPI remoteClient)
{
UUID target = remoteClient.AgentId;
UserClassifiedAdd ad = new UserClassifiedAdd();
ad.ClassifiedId = queryClassifiedID;
lock (m_classifiedCache)
{
if (m_classifiedCache.ContainsKey(queryClassifiedID))
{
target = m_classifiedCache[queryClassifiedID];
m_classifiedInterest[queryClassifiedID] --;
if (m_classifiedInterest[queryClassifiedID] == 0)
{
m_classifiedInterest.Remove(queryClassifiedID);
m_classifiedCache.Remove(queryClassifiedID);
}
}
}
string serverURI = string.Empty;
GetUserProfileServerURI(target, out serverURI);
object Ad = (object)ad;
if(!rpc.JsonRpcRequest(ref Ad, "classifieds_info_query", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error getting classified info", false);
return;
}
ad = (UserClassifiedAdd) Ad;
if(ad.CreatorId == UUID.Zero)
return;
Vector3 globalPos = new Vector3();
Vector3.TryParse(ad.GlobalPos, out globalPos);
remoteClient.SendClassifiedInfoReply(ad.ClassifiedId, ad.CreatorId, (uint)ad.CreationDate, (uint)ad.ExpirationDate,
(uint)ad.Category, ad.Name, ad.Description, ad.ParcelId, (uint)ad.ParentEstate,
ad.SnapshotId, ad.SimName, globalPos, ad.ParcelName, ad.Flags, ad.Price);
}
/// <summary>
/// Classifieds info update.
/// </summary>
/// <param name='queryclassifiedID'>
/// Queryclassified I.
/// </param>
/// <param name='queryCategory'>
/// Query category.
/// </param>
/// <param name='queryName'>
/// Query name.
/// </param>
/// <param name='queryDescription'>
/// Query description.
/// </param>
/// <param name='queryParcelID'>
/// Query parcel I.
/// </param>
/// <param name='queryParentEstate'>
/// Query parent estate.
/// </param>
/// <param name='querySnapshotID'>
/// Query snapshot I.
/// </param>
/// <param name='queryGlobalPos'>
/// Query global position.
/// </param>
/// <param name='queryclassifiedFlags'>
/// Queryclassified flags.
/// </param>
/// <param name='queryclassifiedPrice'>
/// Queryclassified price.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void ClassifiedInfoUpdate(UUID queryclassifiedID, uint queryCategory, string queryName, string queryDescription, UUID queryParcelID,
uint queryParentEstate, UUID querySnapshotID, Vector3 queryGlobalPos, byte queryclassifiedFlags,
int queryclassifiedPrice, IClientAPI remoteClient)
{
UserClassifiedAdd ad = new UserClassifiedAdd();
Scene s = (Scene) remoteClient.Scene;
Vector3 pos = remoteClient.SceneAgent.AbsolutePosition;
ILandObject land = s.LandChannel.GetLandObject(pos.X, pos.Y);
ScenePresence p = FindPresence(remoteClient.AgentId);
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
if (land == null)
{
ad.ParcelName = string.Empty;
}
else
{
ad.ParcelName = land.LandData.Name;
}
ad.CreatorId = remoteClient.AgentId;
ad.ClassifiedId = queryclassifiedID;
ad.Category = Convert.ToInt32(queryCategory);
ad.Name = queryName;
ad.Description = queryDescription;
ad.ParentEstate = Convert.ToInt32(queryParentEstate);
ad.SnapshotId = querySnapshotID;
ad.SimName = remoteClient.Scene.RegionInfo.RegionName;
ad.GlobalPos = queryGlobalPos.ToString ();
ad.Flags = queryclassifiedFlags;
ad.Price = queryclassifiedPrice;
ad.ParcelId = p.currentParcelUUID;
object Ad = ad;
OSD.SerializeMembers(Ad);
if(!rpc.JsonRpcRequest(ref Ad, "classified_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating classified", false);
}
}
/// <summary>
/// Classifieds delete.
/// </summary>
/// <param name='queryClassifiedID'>
/// Query classified I.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void ClassifiedDelete(UUID queryClassifiedID, IClientAPI remoteClient)
{
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
UUID classifiedId;
OSDMap parameters= new OSDMap();
UUID.TryParse(queryClassifiedID.ToString(), out classifiedId);
parameters.Add("classifiedId", OSD.FromUUID(classifiedId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "classified_delete", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error classified delete", false);
}
parameters = (OSDMap)Params;
}
#endregion Classified
#region Picks
/// <summary>
/// Handles the avatar picks request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void PicksRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID targetId;
UUID.TryParse(args[0], out targetId);
// Can't handle NPC yet...
ScenePresence p = FindPresence(targetId);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
GetUserProfileServerURI(targetId, out serverURI);
Dictionary<UUID, string> picks = new Dictionary<UUID, string>();
OSDMap parameters= new OSDMap();
parameters.Add("creatorId", OSD.FromUUID(targetId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "avatarpicksrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks);
return;
}
parameters = (OSDMap)Params;
OSDArray list = (OSDArray)parameters["result"];
foreach(OSD map in list)
{
OSDMap m = (OSDMap)map;
UUID cid = m["pickuuid"].AsUUID();
string name = m["name"].AsString();
m_log.DebugFormat("[PROFILES]: PicksRequest {0}", name);
picks[cid] = name;
}
remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks);
}
/// <summary>
/// Handles the pick info request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void PickInfoRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
UUID targetID;
UUID.TryParse(args[0], out targetID);
string serverURI = string.Empty;
GetUserProfileServerURI(targetID, out serverURI);
IClientAPI remoteClient = (IClientAPI)sender;
UserProfilePick pick = new UserProfilePick();
UUID.TryParse(args[0], out pick.CreatorId);
UUID.TryParse(args[1], out pick.PickId);
object Pick = (object)pick;
if(!rpc.JsonRpcRequest(ref Pick, "pickinforequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error selecting pick", false);
}
pick = (UserProfilePick) Pick;
Vector3 globalPos;
Vector3.TryParse(pick.GlobalPos,out globalPos);
m_log.DebugFormat("[PROFILES]: PickInfoRequest: {0} : {1}", pick.Name.ToString(), pick.SnapshotId.ToString());
remoteClient.SendPickInfoReply(pick.PickId,pick.CreatorId,pick.TopPick,pick.ParcelId,pick.Name,
pick.Desc,pick.SnapshotId,pick.User,pick.OriginalName,pick.SimName,
globalPos,pick.SortOrder,pick.Enabled);
}
/// <summary>
/// Updates the userpicks
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='pickID'>
/// Pick I.
/// </param>
/// <param name='creatorID'>
/// the creator of the pick
/// </param>
/// <param name='topPick'>
/// Top pick.
/// </param>
/// <param name='name'>
/// Name.
/// </param>
/// <param name='desc'>
/// Desc.
/// </param>
/// <param name='snapshotID'>
/// Snapshot I.
/// </param>
/// <param name='sortOrder'>
/// Sort order.
/// </param>
/// <param name='enabled'>
/// Enabled.
/// </param>
public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, UUID snapshotID, int sortOrder, bool enabled)
{
m_log.DebugFormat("[PROFILES]: Start PickInfoUpdate Name: {0} PickId: {1} SnapshotId: {2}", name, pickID.ToString(), snapshotID.ToString());
UserProfilePick pick = new UserProfilePick();
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
ScenePresence p = FindPresence(remoteClient.AgentId);
Vector3 avaPos = p.AbsolutePosition;
// Getting the global position for the Avatar
Vector3 posGlobal = new Vector3(remoteClient.Scene.RegionInfo.WorldLocX + avaPos.X,
remoteClient.Scene.RegionInfo.WorldLocY + avaPos.Y,
avaPos.Z);
string landOwnerName = string.Empty;
ILandObject land = p.Scene.LandChannel.GetLandObject(avaPos.X, avaPos.Y);
if (land != null)
{
if (land.LandData.IsGroupOwned)
{
IGroupsModule groupMod = p.Scene.RequestModuleInterface<IGroupsModule>();
UUID groupId = land.LandData.GroupID;
GroupRecord groupRecord = groupMod.GetGroupRecord(groupId);
landOwnerName = groupRecord.GroupName;
}
else
{
IUserAccountService accounts = p.Scene.RequestModuleInterface<IUserAccountService>();
UserAccount user = accounts.GetUserAccount(p.Scene.RegionInfo.ScopeID, land.LandData.OwnerID);
landOwnerName = user.Name;
}
}
else
{
m_log.WarnFormat(
"[PROFILES]: PickInfoUpdate found no parcel info at {0},{1} in {2}",
avaPos.X, avaPos.Y, p.Scene.Name);
}
pick.PickId = pickID;
pick.CreatorId = creatorID;
pick.TopPick = topPick;
pick.Name = name;
pick.Desc = desc;
pick.ParcelId = p.currentParcelUUID;
pick.SnapshotId = snapshotID;
pick.User = landOwnerName;
pick.SimName = remoteClient.Scene.RegionInfo.RegionName;
pick.GlobalPos = posGlobal.ToString();
pick.SortOrder = sortOrder;
pick.Enabled = enabled;
object Pick = (object)pick;
if(!rpc.JsonRpcRequest(ref Pick, "picks_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating pick", false);
}
m_log.DebugFormat("[PROFILES]: Finish PickInfoUpdate {0} {1}", pick.Name, pick.PickId.ToString());
}
/// <summary>
/// Delete a Pick
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='queryPickID'>
/// Query pick I.
/// </param>
public void PickDelete(IClientAPI remoteClient, UUID queryPickID)
{
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
OSDMap parameters= new OSDMap();
parameters.Add("pickId", OSD.FromUUID(queryPickID));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "picks_delete", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error picks delete", false);
}
}
#endregion Picks
#region Notes
/// <summary>
/// Handles the avatar notes request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void NotesRequest(Object sender, string method, List<String> args)
{
UserProfileNotes note = new UserProfileNotes();
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
note.UserId = remoteClient.AgentId;
UUID.TryParse(args[0], out note.TargetId);
object Note = (object)note;
if(!rpc.JsonRpcRequest(ref Note, "avatarnotesrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
return;
}
note = (UserProfileNotes) Note;
remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
}
/// <summary>
/// Avatars the notes update.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='queryTargetID'>
/// Query target I.
/// </param>
/// <param name='queryNotes'>
/// Query notes.
/// </param>
public void NotesUpdate(IClientAPI remoteClient, UUID queryTargetID, string queryNotes)
{
UserProfileNotes note = new UserProfileNotes();
note.UserId = remoteClient.AgentId;
note.TargetId = queryTargetID;
note.Notes = queryNotes;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Note = note;
if(!rpc.JsonRpcRequest(ref Note, "avatar_notes_update", serverURI, UUID.Random().ToString()))
{
return;
}
}
#endregion Notes
#region User Preferences
/// <summary>
/// Updates the user preferences.
/// </summary>
/// <param name='imViaEmail'>
/// Im via email.
/// </param>
/// <param name='visible'>
/// Visible.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void UpdateUserPreferences(bool imViaEmail, bool visible, IClientAPI remoteClient)
{
UserPreferences pref = new UserPreferences();
pref.UserId = remoteClient.AgentId;
pref.IMViaEmail = imViaEmail;
pref.Visible = visible;
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Pref = pref;
if(!rpc.JsonRpcRequest(ref Pref, "user_preferences_update", serverURI, UUID.Random().ToString()))
{
m_log.InfoFormat("[PROFILES]: UserPreferences update error");
remoteClient.SendAgentAlertMessage("Error updating preferences", false);
return;
}
}
/// <summary>
/// Users the preferences request.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void UserPreferencesRequest(IClientAPI remoteClient)
{
UserPreferences pref = new UserPreferences();
pref.UserId = remoteClient.AgentId;
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Pref = (object)pref;
if(!rpc.JsonRpcRequest(ref Pref, "user_preferences_request", serverURI, UUID.Random().ToString()))
{
m_log.InfoFormat("[PROFILES]: UserPreferences request error");
remoteClient.SendAgentAlertMessage("Error requesting preferences", false);
return;
}
pref = (UserPreferences) Pref;
remoteClient.SendUserInfoReply(pref.IMViaEmail, pref.Visible, pref.EMail);
}
#endregion User Preferences
#region Avatar Properties
/// <summary>
/// Update the avatars interests .
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='wantmask'>
/// Wantmask.
/// </param>
/// <param name='wanttext'>
/// Wanttext.
/// </param>
/// <param name='skillsmask'>
/// Skillsmask.
/// </param>
/// <param name='skillstext'>
/// Skillstext.
/// </param>
/// <param name='languages'>
/// Languages.
/// </param>
public void AvatarInterestsUpdate(IClientAPI remoteClient, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages)
{
UserProfileProperties prop = new UserProfileProperties();
prop.UserId = remoteClient.AgentId;
prop.WantToMask = (int)wantmask;
prop.WantToText = wanttext;
prop.SkillsMask = (int)skillsmask;
prop.SkillsText = skillstext;
prop.Language = languages;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Param = prop;
if(!rpc.JsonRpcRequest(ref Param, "avatar_interests_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating interests", false);
}
}
public void RequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
{
if (String.IsNullOrEmpty(avatarID.ToString()) || String.IsNullOrEmpty(remoteClient.AgentId.ToString()))
{
// Looking for a reason that some viewers are sending null Id's
m_log.DebugFormat("[PROFILES]: This should not happen remoteClient.AgentId {0} - avatarID {1}", remoteClient.AgentId, avatarID);
return;
}
// Can't handle NPC yet...
ScenePresence p = FindPresence(avatarID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(avatarID, out serverURI);
UserAccount account = null;
Dictionary<string,object> userInfo;
if (!foreign)
{
account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, avatarID);
}
else
{
userInfo = new Dictionary<string, object>();
}
Byte[] charterMember = new Byte[1];
string born = String.Empty;
uint flags = 0x00;
if (null != account)
{
if (account.UserTitle == "")
{
charterMember[0] = (Byte)((account.UserFlags & 0xf00) >> 8);
}
else
{
charterMember = Utils.StringToBytes(account.UserTitle);
}
born = Util.ToDateTime(account.Created).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
flags = (uint)(account.UserFlags & 0xff);
}
else
{
if (GetUserAccountData(avatarID, out userInfo) == true)
{
if ((string)userInfo["user_title"] == "")
{
charterMember[0] = (Byte)(((Byte)userInfo["user_flags"] & 0xf00) >> 8);
}
else
{
charterMember = Utils.StringToBytes((string)userInfo["user_title"]);
}
int val_born = (int)userInfo["user_created"];
born = Util.ToDateTime(val_born).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
// picky, picky
int val_flags = (int)userInfo["user_flags"];
flags = (uint)(val_flags & 0xff);
}
}
UserProfileProperties props = new UserProfileProperties();
string result = string.Empty;
props.UserId = avatarID;
if (!GetProfileData(ref props, foreign, out result))
{
m_log.DebugFormat("Error getting profile for {0}: {1}", avatarID, result);
return;
}
remoteClient.SendAvatarProperties(props.UserId, props.AboutText, born, charterMember , props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
remoteClient.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText, (uint)props.SkillsMask,
props.SkillsText, props.Language);
}
/// <summary>
/// Updates the avatar properties.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='newProfile'>
/// New profile.
/// </param>
public void AvatarPropertiesUpdate(IClientAPI remoteClient, UserProfileData newProfile)
{
if (remoteClient.AgentId == newProfile.ID)
{
UserProfileProperties prop = new UserProfileProperties();
prop.UserId = remoteClient.AgentId;
prop.WebUrl = newProfile.ProfileUrl;
prop.ImageId = newProfile.Image;
prop.AboutText = newProfile.AboutText;
prop.FirstLifeImageId = newProfile.FirstLifeImage;
prop.FirstLifeText = newProfile.FirstLifeAboutText;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Prop = prop;
if(!rpc.JsonRpcRequest(ref Prop, "avatar_properties_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating properties", false);
}
RequestAvatarProperties(remoteClient, newProfile.ID);
}
}
/// <summary>
/// Gets the profile data.
/// </summary>
/// <returns>
/// The profile data.
/// </returns>
bool GetProfileData(ref UserProfileProperties properties, bool foreign, out string message)
{
// Can't handle NPC yet...
ScenePresence p = FindPresence(properties.UserId);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
{
message = "Id points to NPC";
return false;
}
}
string serverURI = string.Empty;
GetUserProfileServerURI(properties.UserId, out serverURI);
// This is checking a friend on the home grid
// Not HG friend
if (String.IsNullOrEmpty(serverURI))
{
message = "No Presence - foreign friend";
return false;
}
object Prop = (object)properties;
if (!rpc.JsonRpcRequest(ref Prop, "avatar_properties_request", serverURI, UUID.Random().ToString()))
{
// If it's a foreign user then try again using OpenProfile, in case that's what the grid is using
bool secondChanceSuccess = false;
if (foreign)
{
try
{
OpenProfileClient client = new OpenProfileClient(serverURI);
if (client.RequestAvatarPropertiesUsingOpenProfile(ref properties))
secondChanceSuccess = true;
}
catch (Exception e)
{
m_log.Debug(string.Format("Request using the OpenProfile API to {0} failed", serverURI), e);
// Allow the return 'message' to say "JsonRpcRequest" and not "OpenProfile", because
// the most likely reason that OpenProfile failed is that the remote server
// doesn't support OpenProfile, and that's not very interesting.
}
}
if (!secondChanceSuccess)
{
message = string.Format("JsonRpcRequest to {0} failed", serverURI);
return false;
}
// else, continue below
}
properties = (UserProfileProperties)Prop;
message = "Success";
return true;
}
#endregion Avatar Properties
#region Utils
bool GetImageAssets(UUID avatarId)
{
string profileServerURI = string.Empty;
string assetServerURI = string.Empty;
bool foreign = GetUserProfileServerURI(avatarId, out profileServerURI);
if(!foreign)
return true;
assetServerURI = UserManagementModule.GetUserServerURL(avatarId, "AssetServerURI");
if(string.IsNullOrEmpty(profileServerURI) || string.IsNullOrEmpty(assetServerURI))
return false;
OSDMap parameters= new OSDMap();
parameters.Add("avatarId", OSD.FromUUID(avatarId));
OSD Params = (OSD)parameters;
try
{
if (!rpc.JsonRpcRequest(ref Params, "image_assets_request", profileServerURI, UUID.Random().ToString()))
{
return false;
}
parameters = (OSDMap)Params;
if (parameters.ContainsKey("result"))
{
OSDArray list = (OSDArray)parameters["result"];
foreach (OSD asset in list)
{
OSDString assetId = (OSDString)asset;
Scene.AssetService.Get(string.Format("{0}/{1}", assetServerURI, assetId.AsString()));
}
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
/// <summary>
/// Gets the user account data.
/// </summary>
/// <returns>
/// The user profile data.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user I.
/// </param>
/// <param name='userInfo'>
/// If set to <c>true</c> user info.
/// </param>
bool GetUserAccountData(UUID userID, out Dictionary<string, object> userInfo)
{
Dictionary<string,object> info = new Dictionary<string, object>();
if (UserManagementModule.IsLocalGridUser(userID))
{
// Is local
IUserAccountService uas = Scene.UserAccountService;
UserAccount account = uas.GetUserAccount(Scene.RegionInfo.ScopeID, userID);
info["user_flags"] = account.UserFlags;
info["user_created"] = account.Created;
if (!String.IsNullOrEmpty(account.UserTitle))
info["user_title"] = account.UserTitle;
else
info["user_title"] = "";
userInfo = info;
return false;
}
else
{
// Is Foreign
string home_url = UserManagementModule.GetUserServerURL(userID, "HomeURI");
if (String.IsNullOrEmpty(home_url))
{
info["user_flags"] = 0;
info["user_created"] = 0;
info["user_title"] = "Unavailable";
userInfo = info;
return true;
}
UserAgentServiceConnector uConn = new UserAgentServiceConnector(home_url);
Dictionary<string, object> account;
try
{
account = uConn.GetUserInfo(userID);
}
catch (Exception e)
{
m_log.Debug("[PROFILES]: GetUserInfo call failed ", e);
account = new Dictionary<string, object>();
}
if (account.Count > 0)
{
if (account.ContainsKey("user_flags"))
info["user_flags"] = account["user_flags"];
else
info["user_flags"] = "";
if (account.ContainsKey("user_created"))
info["user_created"] = account["user_created"];
else
info["user_created"] = "";
info["user_title"] = "HG Visitor";
}
else
{
info["user_flags"] = 0;
info["user_created"] = 0;
info["user_title"] = "HG Visitor";
}
userInfo = info;
return true;
}
}
/// <summary>
/// Gets the user profile server UR.
/// </summary>
/// <returns>
/// The user profile server UR.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user I.
/// </param>
/// <param name='serverURI'>
/// If set to <c>true</c> server UR.
/// </param>
bool GetUserProfileServerURI(UUID userID, out string serverURI)
{
bool local;
local = UserManagementModule.IsLocalGridUser(userID);
if (!local)
{
serverURI = UserManagementModule.GetUserServerURL(userID, "ProfileServerURI");
// Is Foreign
return true;
}
else
{
serverURI = ProfileServerUri;
// Is local
return false;
}
}
/// <summary>
/// Finds the presence.
/// </summary>
/// <returns>
/// The presence.
/// </returns>
/// <param name='clientID'>
/// Client I.
/// </param>
ScenePresence FindPresence(UUID clientID)
{
ScenePresence p;
p = Scene.GetScenePresence(clientID);
if (p != null && !p.IsChildAgent)
return p;
return null;
}
#endregion Util
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace mooftpserv
{
/// <summary>
/// FTP session/connection. Does all the heavy lifting of the FTP protocol.
/// Reads commands, sends replies, manages data connections, and so on.
/// Each session creates its own thread.
/// </summary>
class Session
{
// transfer data type, ascii or binary
enum DataType { ASCII, IMAGE };
// buffer size to use for reading commands from the control connection
private static int CMD_BUFFER_SIZE = 4096;
// version from AssemblyInfo
private static string LIB_VERSION = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(2);
// monthnames for LIST command, since DateTime returns localized names
private static string[] MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
// response text for initial response. preceeded by application name and version number.
private static string[] HELLO_TEXT = { "What can I do for you?", "Good day, sir or madam.", "Hey ho let's go!", "The poor man's FTP server." };
// response text for general ok messages
private static string[] OK_TEXT = { "Sounds good.", "Success!", "Alright, I'll do it...", "Consider it done." };
// Result for FEAT command
private static string[] FEATURES = { "MDTM", "PASV", "SIZE", "TVFS", "UTF8" };
// local EOL flavor
private static byte[] localEolBytes = Encoding.ASCII.GetBytes(Environment.NewLine);
// FTP-mandated EOL flavor (= CRLF)
private static byte[] remoteEolBytes = Encoding.ASCII.GetBytes("\r\n");
// on Windows, no ASCII conversion is necessary (CRLF == CRLF)
private static bool noAsciiConv = (localEolBytes == remoteEolBytes);
// socket for the control connection
private Socket controlSocket;
// buffer size to use for sending/receiving with data connections
private int dataBufferSize;
// auth handler, checks user credentials
private IAuthHandler authHandler;
// file system handler, implements file system access for the FTP commands
private IFileSystemHandler fsHandler;
// log handler, used for diagnostic logging output. can be null.
private ILogHandler logHandler;
// Session thread, the control and data connections are processed in this thread
private Thread thread;
// .NET CF does not have Thread.IsAlive, so this flag replaces it
private bool threadAlive = false;
// Random Number Generator for OK and HELLO texts
private Random randomTextIndex;
// flag for whether the user has successfully logged in
private bool loggedIn = false;
// name of the logged in user, also used to remember the username when waiting for the PASS command
private string loggedInUser = null;
// argument of pending RNFR command, when waiting for an RNTO command
private string renameFromPath = null;
// remote data port. null when PASV is used.
private IPEndPoint dataPort = null;
// socket for data connections
private Socket dataSocket = null;
// .NET CF does not have Socket.Bound, so this flag replaces it
private bool dataSocketBound = false;
// buffer for reading from the control connection
private byte[] cmdRcvBuffer;
// number of bytes in the cmdRcvBuffer
private int cmdRcvBytes;
// buffer for sending/receiving with data connections
private byte[] dataBuffer;
// data type of the session, can be changed by the client
private DataType transferDataType = DataType.ASCII;
/// <summary>
/// Creates a new session, which can afterwards be started with Start().
/// </summary>
public Session(Socket socket, int bufferSize, IAuthHandler authHandler, IFileSystemHandler fileSystemHandler, ILogHandler logHandler)
{
this.controlSocket = socket;
this.dataBufferSize = bufferSize;
this.authHandler = authHandler;
this.fsHandler = fileSystemHandler;
this.logHandler = logHandler;
this.cmdRcvBuffer = new byte[CMD_BUFFER_SIZE];
this.cmdRcvBytes = 0;
this.dataBuffer = new byte[dataBufferSize + 1]; // +1 for partial EOL
this.randomTextIndex = new Random();
this.thread = new Thread(new ThreadStart(this.Work));
}
/// <summary>
/// Indicates whether the session is still open
/// </summary>
public bool IsOpen
{
get { return threadAlive; }
}
/// <summary>
/// Start the session in a new thread
/// </summary>
public void Start()
{
if (!threadAlive) {
threadAlive = true;
this.thread.Start();
}
}
/// <summary>
/// Stop the session
/// </summary>
public void Stop()
{
if (threadAlive) {
threadAlive = false;
thread.Abort();
}
if (controlSocket.Connected)
controlSocket.Close();
if (dataSocket != null && dataSocket.Connected)
dataSocket.Close();
}
/// <summary>
/// Main method of the session thread.
/// Reads commands and executes them.
/// </summary>
private void Work()
{
if (logHandler != null)
logHandler.NewControlConnection();
try {
if (!authHandler.AllowControlConnection()) {
Respond(421, "Control connection refused.");
// first flush, then close
controlSocket.Shutdown(SocketShutdown.Both);
controlSocket.Close();
return;
}
Respond(220, String.Format("This is mooftpserv v{0}. {1}", LIB_VERSION, GetRandomText(HELLO_TEXT)));
// allow anonymous login?
if (authHandler.AllowLogin(null, null)) {
loggedIn = true;
}
while (controlSocket.Connected) {
string verb;
string args;
if (!ReadCommand(out verb, out args)) {
if (controlSocket.Connected) {
// assume clean disconnect if there are no buffered bytes
if (cmdRcvBytes != 0)
Respond(500, "Failed to read command, closing connection.");
controlSocket.Close();
}
break;
} else if (verb.Trim() == "") {
// ignore empty lines
continue;
}
try {
if (loggedIn)
ProcessCommand(verb, args);
else if (verb == "QUIT") { // QUIT should always be allowed
Respond(221, "Bye.");
// first flush, then close
controlSocket.Shutdown(SocketShutdown.Both);
controlSocket.Close();
} else {
HandleAuth(verb, args);
}
} catch (Exception ex) {
Respond(500, ex);
}
}
} catch (Exception) {
// catch any uncaught stuff, the server should not throw anything
} finally {
if (controlSocket.Connected)
controlSocket.Close();
if (logHandler != null)
logHandler.ClosedControlConnection();
threadAlive = false;
}
}
/// <summary>
/// Process an FTP command.
/// </summary>
private void ProcessCommand(string verb, string arguments)
{
switch (verb) {
case "SYST":
{
Respond(215, "UNIX emulated by mooftpserv");
break;
}
case "QUIT":
{
Respond(221, "Bye.");
// first flush, then close
controlSocket.Shutdown(SocketShutdown.Both);
controlSocket.Close();
break;
}
case "USER":
{
Respond(230, "You are already logged in.");
break;
}
case "PASS":
{
Respond(230, "You are already logged in.");
break;
}
case "FEAT":
{
Respond(211, "Features:\r\n " + String.Join("\r\n ", FEATURES), true);
Respond(211, "Features done.");
break;
}
case "OPTS":
{
// Windows Explorer uses lowercase args
if (arguments != null && arguments.ToUpper() == "UTF8 ON")
Respond(200, "Always in UTF8 mode.");
else
Respond(504, "Unknown option.");
break;
}
case "TYPE":
{
if (arguments == "A" || arguments == "A N") {
transferDataType = DataType.ASCII;
Respond(200, "Switching to ASCII mode.");
} else if (arguments == "I") {
transferDataType = DataType.IMAGE;
Respond(200, "Switching to BINARY mode.");
} else {
Respond(500, "Unknown TYPE arguments.");
}
break;
}
case "PORT":
{
IPEndPoint port = ParseAddress(arguments);
if (port == null) {
Respond(500, "Invalid host-port format.");
break;
}
if (!authHandler.AllowActiveDataConnection(port)) {
Respond(500, "PORT arguments refused.");
break;
}
dataPort = port;
CreateDataSocket(false);
Respond(200, GetRandomText(OK_TEXT));
break;
}
case "PASV":
{
dataPort = null;
try {
CreateDataSocket(true);
} catch (Exception ex) {
Respond(500, ex);
break;
}
string port = FormatAddress((IPEndPoint) dataSocket.LocalEndPoint);
Respond(227, String.Format("Switched to passive mode ({0})", port));
break;
}
case "XPWD":
case "PWD":
{
ResultOrError<string> ret = fsHandler.GetCurrentDirectory();
if (ret.HasError)
Respond(500, ret.Error);
else
Respond(257, EscapePath(ret.Result));
break;
}
case "XCWD":
case "CWD":
{
ResultOrError<string> ret = fsHandler.ChangeDirectory(arguments);
if (ret.HasError)
Respond(550, ret.Error);
else
Respond(200, GetRandomText(OK_TEXT));
break;
}
case "XCUP":
case "CDUP":
{
ResultOrError<string> ret = fsHandler.ChangeDirectory("..");
if (ret.HasError)
Respond(550, ret.Error);
else
Respond(200, GetRandomText(OK_TEXT));
break;
}
case "XMKD":
case "MKD":
{
ResultOrError<string> ret = fsHandler.CreateDirectory(arguments);
if (ret.HasError)
Respond(550, ret.Error);
else
Respond(257, EscapePath(ret.Result));
break;
}
case "XRMD":
case "RMD":
{
ResultOrError<bool> ret = fsHandler.RemoveDirectory(arguments);
if (ret.HasError)
Respond(550, ret.Error);
else
Respond(250, GetRandomText(OK_TEXT));
break;
}
case "RETR":
{
ResultOrError<Stream> ret = fsHandler.ReadFile(arguments);
if (ret.HasError) {
Respond(550, ret.Error);
break;
}
SendData(ret.Result);
break;
}
case "STOR":
{
ResultOrError<Stream> ret = fsHandler.WriteFile(arguments);
if (ret.HasError) {
Respond(550, ret.Error);
break;
}
ReceiveData(ret.Result);
break;
}
case "DELE":
{
ResultOrError<bool> ret = fsHandler.RemoveFile(arguments);
if (ret.HasError)
Respond(550, ret.Error);
else
Respond(250, GetRandomText(OK_TEXT));
break;
}
case "RNFR":
{
if (arguments == null || arguments.Trim() == "") {
Respond(500, "Empty path is invalid.");
break;
}
renameFromPath = arguments;
Respond(350, "Waiting for target path.");
break;
}
case "RNTO":
{
if (renameFromPath == null) {
Respond(503, "Use RNFR before RNTO.");
break;
}
ResultOrError<bool> ret = fsHandler.RenameFile(renameFromPath, arguments);
renameFromPath = null;
if (ret.HasError)
Respond(550, ret.Error);
else
Respond(250, GetRandomText(OK_TEXT));
break;
}
case "MDTM":
{
ResultOrError<DateTime> ret = fsHandler.GetLastModifiedTimeUtc(arguments);
if (ret.HasError)
Respond(550, ret.Error);
else
Respond(213, FormatTime(EnsureUnixTime(ret.Result)));
break;
}
case "SIZE":
{
ResultOrError<long> ret = fsHandler.GetFileSize(arguments);
if (ret.HasError)
Respond(550, ret.Error);
else
Respond(213, ret.Result.ToString());
break;
}
case "LIST":
{
// apparently browsers like to pass arguments to LIST
// assuming they are passed through to the UNIX ls command
arguments = RemoveLsArgs(arguments);
ResultOrError<FileSystemEntry[]> ret = fsHandler.ListEntries(arguments);
if (ret.HasError) {
Respond(500, ret.Error);
break;
}
SendData(MakeStream(FormatDirList(ret.Result)));
break;
}
case "STAT":
{
if (arguments == null || arguments.Trim() == "") {
Respond(504, "Not implemented for these arguments.");
break;
}
arguments = RemoveLsArgs(arguments);
ResultOrError<FileSystemEntry[]> ret = fsHandler.ListEntries(arguments);
if (ret.HasError) {
Respond(500, ret.Error);
break;
}
Respond(213, "Status:\r\n" + FormatDirList(ret.Result), true);
Respond(213, "Status done.");
break;
}
case "NLST":
{
// remove common arguments, we do not support any of them
arguments = RemoveLsArgs(arguments);
ResultOrError<FileSystemEntry[]> ret = fsHandler.ListEntries(arguments);
if (ret.HasError)
{
Respond(500, ret.Error);
break;
}
SendData(MakeStream(FormatNLST(ret.Result)));
break;
}
case "NOOP":
{
Respond(200, GetRandomText(OK_TEXT));
break;
}
default:
{
Respond(500, "Unknown command.");
break;
}
}
}
/// <summary>
/// Read a command from the control connection.
/// </summary>
/// <returns>
/// True if a command was read.
/// </returns>
/// <param name='verb'>
/// Will receive the verb of the command.
/// </param>
/// <param name='args'>
/// Will receive the arguments of the command, or null.
/// </param>
private bool ReadCommand(out string verb, out string args)
{
verb = null;
args = null;
int endPos = -1;
// can there already be a command in the buffer?
if (cmdRcvBytes > 0)
Array.IndexOf(cmdRcvBuffer, (byte)'\n', 0, cmdRcvBytes);
try {
// read data until a newline is found
do {
int freeBytes = cmdRcvBuffer.Length - cmdRcvBytes;
int bytes = controlSocket.Receive(cmdRcvBuffer, cmdRcvBytes, freeBytes, SocketFlags.None);
if (bytes <= 0)
break;
cmdRcvBytes += bytes;
// search \r\n
endPos = Array.IndexOf(cmdRcvBuffer, (byte)'\r', 0, cmdRcvBytes);
if (endPos != -1 && (cmdRcvBytes <= endPos + 1 || cmdRcvBuffer[endPos + 1] != (byte)'\n'))
endPos = -1;
} while (endPos == -1 && cmdRcvBytes < cmdRcvBuffer.Length);
} catch (SocketException) {
// in case the socket is closed or has some other error while reading
return false;
}
if (endPos == -1)
return false;
string command = DecodeString(cmdRcvBuffer, endPos);
// remove the command from the buffer
cmdRcvBytes -= (endPos + 2);
Array.Copy(cmdRcvBuffer, endPos + 2, cmdRcvBuffer, 0, cmdRcvBytes);
// CF is missing a limited String.Split
string[] tokens = command.Split(' ');
verb = tokens[0].ToUpper(); // commands are case insensitive
args = (tokens.Length > 1 ? String.Join(" ", tokens, 1, tokens.Length - 1) : null);
if (logHandler != null)
logHandler.ReceivedCommand(verb, args);
return true;
}
/// <summary>
/// Send a response on the control connection
/// </summary>
private void Respond(uint code, string desc, bool moreFollows)
{
string response = code.ToString();
if (desc != null)
response += (moreFollows ? '-' : ' ') + desc;
if (!response.EndsWith("\r\n"))
response += "\r\n";
byte[] sendBuffer = EncodeString(response);
controlSocket.Send(sendBuffer);
if (logHandler != null)
logHandler.SentResponse(code, desc);
}
/// <summary>
/// Send a response on the control connection
/// </summary>
private void Respond(uint code, string desc)
{
Respond(code, desc, false);
}
/// <summary>
/// Send a response on the control connection, with an exception as text
/// </summary>
private void Respond(uint code, Exception ex)
{
Respond(code, ex.Message.Replace(Environment.NewLine, " "));
}
/// <summary>
/// Process FTP commands when the user is not yet logged in.
/// Mostly handles the login commands USER and PASS.
/// </summary>
private void HandleAuth(string verb, string args)
{
if (verb == "USER" && args != null) {
if (authHandler.AllowLogin(args, null)) {
Respond(230, "Login successful.");
loggedIn = true;
} else {
loggedInUser = args;
Respond(331, "Password please.");
}
} else if (verb == "PASS") {
if (loggedInUser != null) {
if (authHandler.AllowLogin(loggedInUser, args)) {
Respond(230, "Login successful.");
loggedIn = true;
} else {
loggedInUser = null;
Respond(530, "Login failed, please try again.");
}
} else {
Respond(530, "No USER specified.");
}
} else {
Respond(530, "Please login first.");
}
}
/// <summary>
/// Read from the given stream and send the data over a data connection
/// </summary>
private void SendData(Stream stream)
{
try {
bool passive = (dataPort == null);
using (Socket socket = OpenDataConnection()) {
if (socket == null)
return;
IPEndPoint remote = (IPEndPoint) socket.RemoteEndPoint;
IPEndPoint local = (IPEndPoint) socket.LocalEndPoint;
if (logHandler != null)
logHandler.NewDataConnection(remote, local, passive);
try {
while (true) {
int bytes = stream.Read(dataBuffer, 0, dataBufferSize);
if (bytes <= 0) {
break;
}
if (transferDataType == DataType.IMAGE || noAsciiConv) {
// TYPE I -> just pass through
socket.Send(dataBuffer, bytes, SocketFlags.None);
} else {
// TYPE A -> convert local EOL style to CRLF
// if the buffer ends with a potential partial EOL,
// try to read the rest of the EOL
// (i assume that the EOL has max. two bytes)
if (localEolBytes.Length == 2 &&
dataBuffer[bytes - 1] == localEolBytes[0]) {
if (stream.Read(dataBuffer, bytes, 1) == 1)
++bytes;
}
byte[] convBuffer = null;
int convBytes = ConvertAsciiBytes(dataBuffer, bytes, true, out convBuffer);
socket.Send(convBuffer, convBytes, SocketFlags.None);
}
}
// flush socket before closing (done by using-statement)
socket.Shutdown(SocketShutdown.Send);
Respond(226, "Transfer complete.");
} catch (Exception ex) {
Respond(500, ex);
return;
} finally {
if (logHandler != null)
logHandler.ClosedDataConnection(remote, local, passive);
}
}
} finally {
stream.Close();
}
}
/// <summary>
/// Read from a data connection and write to the given stream
/// </summary>
private void ReceiveData(Stream stream)
{
try {
bool passive = (dataPort == null);
using (Socket socket = OpenDataConnection()) {
if (socket == null)
return;
IPEndPoint remote = (IPEndPoint) socket.RemoteEndPoint;
IPEndPoint local = (IPEndPoint) socket.LocalEndPoint;
if (logHandler != null)
logHandler.NewDataConnection(remote, local, passive);
try {
while (true) {
// fill up the in-memory buffer before writing to disk
int totalBytes = 0;
while (totalBytes < dataBufferSize) {
int freeBytes = dataBufferSize - totalBytes;
int newBytes = socket.Receive(dataBuffer, totalBytes, freeBytes, SocketFlags.None);
if (newBytes > 0) {
totalBytes += newBytes;
} else if (newBytes < 0) {
Respond(500, String.Format("Transfer failed: Receive() returned {0}", newBytes));
return;
} else {
// end of data
break;
}
}
// end of data
if (totalBytes == 0)
break;
if (transferDataType == DataType.IMAGE || noAsciiConv) {
// TYPE I -> just pass through
stream.Write(dataBuffer, 0, totalBytes);
} else {
// TYPE A -> convert CRLF to local EOL style
// if the buffer ends with a potential partial CRLF,
// try to read the LF
if (dataBuffer[totalBytes - 1] == remoteEolBytes[0]) {
if (socket.Receive(dataBuffer, totalBytes, 1, SocketFlags.None) == 1)
++totalBytes;
}
byte[] convBuffer = null;
int convBytes = ConvertAsciiBytes(dataBuffer, totalBytes, false, out convBuffer);
stream.Write(convBuffer, 0, convBytes);
}
}
socket.Shutdown(SocketShutdown.Receive);
Respond(226, "Transfer complete.");
} catch (Exception ex) {
Respond(500, ex);
return;
} finally {
if (logHandler != null)
logHandler.ClosedDataConnection(remote, local, passive);
}
}
} finally {
stream.Close();
}
}
/// <summary>
/// Create a socket for a data connection.
/// </summary>
/// <param name='listen'>
/// If true, the socket will be bound to a local port for the PASV command.
/// Otherwise the socket can be used for connecting to the address given in a PORT command.
/// </param>
private void CreateDataSocket(bool listen)
{
if (dataSocket != null)
dataSocket.Close();
dataSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
if (listen) {
IPAddress serverIP = ((IPEndPoint) controlSocket.LocalEndPoint).Address;
dataSocket.Bind(new IPEndPoint(serverIP, 0));
dataSocketBound = true; // CF is missing Socket.IsBound
dataSocket.Listen(1);
}
}
/// <summary>
/// Opens an active or passive data connection and returns the socket
/// or null if there was no preceding PORT or PASV command or in case or error.
/// </summary>
private Socket OpenDataConnection()
{
if (dataPort == null && !dataSocketBound) {
Respond(425, "No data port configured, use PORT or PASV.");
return null;
}
Respond(150, "Opening data connection.");
try {
if (dataPort != null) {
// active mode
dataSocket.Connect(dataPort);
dataPort = null;
return dataSocket;
} else {
// passive mode
Socket socket = dataSocket.Accept();
dataSocket.Close();
dataSocketBound = false;
return socket;
}
} catch (Exception ex) {
Respond(500, String.Format("Failed to open data connection: {0}", ex.Message.Replace(Environment.NewLine, " ")));
return null;
}
}
/// <summary>
/// Convert between different EOL flavors.
/// </summary>
/// <returns>
/// The number of bytes in the resultBuffer.
/// </returns>
/// <param name='buffer'>
/// The input buffer whose data will be converted.
/// </param>
/// <param name='len'>
/// The number of bytes in the input buffer.
/// </param>
/// <param name='localToRemote'>
/// If true, the conversion will be made from local to FTP flavor,
/// otherwise from FTP to local flavor.
/// </param>
/// <param name='resultBuffer'>
/// The resulting buffer with the converted text.
/// Can be the same reference as the input buffer if there is nothing to convert.
/// </param>
private int ConvertAsciiBytes(byte[] buffer, int len, bool localToRemote, out byte[] resultBuffer)
{
byte[] fromBytes = (localToRemote ? localEolBytes : remoteEolBytes);
byte[] toBytes = (localToRemote ? remoteEolBytes : localEolBytes);
resultBuffer = null;
int startIndex = 0;
int resultLen = 0;
int searchLen;
while ((searchLen = len - startIndex) > 0) {
// search for the first byte of the EOL sequence
int eolIndex = Array.IndexOf(buffer, fromBytes[0], startIndex, searchLen);
// shortcut if there is no EOL in the whole buffer
if (eolIndex == -1 && startIndex == 0) {
resultBuffer = buffer;
return len;
}
// allocate to worst-case size
if (resultBuffer == null)
resultBuffer = new byte[len * 2];
if (eolIndex == -1) {
Array.Copy(buffer, startIndex, resultBuffer, resultLen, searchLen);
resultLen += searchLen;
break;
} else {
// compare the rest of the EOL
int matchBytes = 1;
for (int i = 1; i < fromBytes.Length && eolIndex + i < len; ++i) {
if (buffer[eolIndex + i] == fromBytes[i])
++matchBytes;
}
if (matchBytes == fromBytes.Length) {
// found an EOL to convert
int copyLen = eolIndex - startIndex;
if (copyLen > 0) {
Array.Copy(buffer, startIndex, resultBuffer, resultLen, copyLen);
resultLen += copyLen;
}
Array.Copy(toBytes, 0, resultBuffer, resultLen, toBytes.Length);
resultLen += toBytes.Length;
startIndex += copyLen + fromBytes.Length;
} else {
int copyLen = (eolIndex - startIndex) + 1;
Array.Copy(buffer, startIndex, resultBuffer, resultLen, copyLen);
resultLen += copyLen;
startIndex += copyLen;
}
}
}
return resultLen;
}
/// <summary>
/// Parse the argument of a PORT command into an IPEndPoint
/// </summary>
private IPEndPoint ParseAddress(string address)
{
string[] tokens = address.Split(',');
byte[] bytes = new byte[tokens.Length];
for (int i = 0; i < tokens.Length; ++i) {
try {
// CF is missing TryParse
bytes[i] = byte.Parse(tokens[i]);
} catch (Exception) {
return null;
}
}
long ip = bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24;
int port = bytes[4] << 8 | bytes[5];
return new IPEndPoint(ip, port);
}
/// <summary>
/// Format an IPEndPoint so that it can be used in a response for a PASV command
/// </summary>
private string FormatAddress(IPEndPoint address)
{
byte[] ip = address.Address.GetAddressBytes();
int port = address.Port;
return String.Format("{0},{1},{2},{3},{4},{5}",
ip[0], ip[1], ip[2], ip[3],
(port & 0xFF00) >> 8, port & 0x00FF);
}
/// <summary>
/// Formats a list of file system entries for a response to a LIST or STAT command
/// </summary>
private string FormatDirList(FileSystemEntry[] list)
{
int maxSizeChars = 0;
foreach (FileSystemEntry entry in list) {
maxSizeChars = Math.Max(maxSizeChars, entry.Size.ToString().Length);
}
DateTime sixMonthsAgo = EnsureUnixTime(DateTime.Now.ToUniversalTime().AddMonths(-6));
StringBuilder result = new StringBuilder();
foreach (FileSystemEntry entry in list) {
char dirflag = (entry.IsDirectory ? 'd' : '-');
string size = entry.Size.ToString().PadLeft(maxSizeChars);
DateTime time = EnsureUnixTime(entry.LastModifiedTimeUtc);
string timestr = MONTHS[time.Month - 1];
if (time < sixMonthsAgo)
timestr += time.ToString(" dd yyyy");
else
timestr += time.ToString(" dd hh:mm");
result.AppendFormat("{0}rwxr--r-- 1 owner group {1} {2} {3}\r\n",
dirflag, size, timestr, entry.Name);
}
return result.ToString();
}
/// <summary>
/// Formats a list of file system entries for a response to an NLST command
/// </summary>
private string FormatNLST(FileSystemEntry[] list)
{
StringBuilder sb = new StringBuilder();
foreach (FileSystemEntry entry in list) {
sb.Append(entry.Name);
sb.Append("\r\n");
}
return sb.ToString();
}
/// <summary>
/// Format a timestamp for a reponse to a MDTM command
/// </summary>
private string FormatTime(DateTime time)
{
return time.ToString("yyyyMMddHHmmss");
}
/// <summary>
/// Restrict the year in a timestamp to >= 1970
/// </summary>
private DateTime EnsureUnixTime(DateTime time)
{
// the server claims to be UNIX, so there should be
// no timestamps before 1970.
// e.g. FileZilla does not handle them correctly.
int yearDiff = time.Year - 1970;
if (yearDiff < 0)
return time.AddYears(-yearDiff);
else
return time;
}
/// <summary>
/// Escape a path for a response to a PWD command
/// </summary>
private string EscapePath(string path)
{
// double-quotes in paths are escaped by doubling them
return '"' + path.Replace("\"", "\"\"") + '"';
}
/// <summary>
/// Remove "-a" or "-l" from the arguments for a LIST or STAT command
/// </summary>
private string RemoveLsArgs(string args)
{
if (args != null && (args.StartsWith("-a") || args.StartsWith("-l"))) {
if (args.Length == 2)
return null;
else if (args.Length > 3 && args[2] == ' ')
return args.Substring(3);
}
return args;
}
/// <summary>
/// Convert a string to a list of UTF8 bytes
/// </summary>
private byte[] EncodeString(string data)
{
return Encoding.UTF8.GetBytes(data);
}
/// <summary>
/// Convert a list of UTF8 bytes to a string
/// </summary>
private string DecodeString(byte[] data, int len)
{
return Encoding.UTF8.GetString(data, 0, len);
}
/// <summary>
/// Convert a list of UTF8 bytes to a string
/// </summary>
private string DecodeString(byte[] data)
{
return DecodeString(data, data.Length);
}
/// <summary>
/// Fill a stream with the given string as UTF8 bytes
/// </summary>
private Stream MakeStream(string data)
{
return new MemoryStream(EncodeString(data));
}
/// <summary>
/// Return a randomly selected text from the given list
/// </summary>
private string GetRandomText(string[] texts)
{
int index = randomTextIndex.Next(0, texts.Length);
return texts[index];
}
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
namespace Net.Pkcs11Interop.HighLevelAPI.MechanismParams
{
/// <summary>
/// Parameters for the CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE and the CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE mechanisms
/// </summary>
public class CkWtlsKeyMatParams : IMechanismParams, IDisposable
{
/// <summary>
/// Flag indicating whether instance has been disposed
/// </summary>
private bool _disposed = false;
/// <summary>
/// Platform specific CkWtlsKeyMatParams
/// </summary>
private HighLevelAPI40.MechanismParams.CkWtlsKeyMatParams _params40 = null;
/// <summary>
/// Platform specific CkWtlsKeyMatParams
/// </summary>
private HighLevelAPI41.MechanismParams.CkWtlsKeyMatParams _params41 = null;
/// <summary>
/// Platform specific CkWtlsKeyMatParams
/// </summary>
private HighLevelAPI80.MechanismParams.CkWtlsKeyMatParams _params80 = null;
/// <summary>
/// Platform specific CkWtlsKeyMatParams
/// </summary>
private HighLevelAPI81.MechanismParams.CkWtlsKeyMatParams _params81 = null;
/// <summary>
/// Flag indicating whether object with returned key material has left this instance
/// </summary>
private bool _returnedKeyMaterialLeftInstance = false;
/// <summary>
/// Resulting key handles and initialization vector after performing a DeriveKey method
/// </summary>
private CkWtlsKeyMatOut _returnedKeyMaterial = null;
/// <summary>
/// Resulting key handles and initialization vector after performing a DeriveKey method
/// </summary>
public CkWtlsKeyMatOut ReturnedKeyMaterial
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
if (_returnedKeyMaterial == null)
{
if (Platform.UnmanagedLongSize == 4)
_returnedKeyMaterial = (Platform.StructPackingSize == 0) ? new CkWtlsKeyMatOut(_params40.ReturnedKeyMaterial) : new CkWtlsKeyMatOut(_params41.ReturnedKeyMaterial);
else
_returnedKeyMaterial = (Platform.StructPackingSize == 0) ? new CkWtlsKeyMatOut(_params80.ReturnedKeyMaterial) : new CkWtlsKeyMatOut(_params81.ReturnedKeyMaterial);
// Since now it is the caller's responsibility to dispose returned key material
_returnedKeyMaterialLeftInstance = true;
}
return _returnedKeyMaterial;
}
}
/// <summary>
/// Client's and server's random data information
/// </summary>
private CkWtlsRandomData _randomInfo = null;
/// <summary>
/// Initializes a new instance of the CkWtlsKeyMatParams class.
/// </summary>
/// <param name='digestMechanism'>The digest mechanism to be used (CKM)</param>
/// <param name='macSizeInBits'>The length (in bits) of the MACing key agreed upon during the protocol handshake phase</param>
/// <param name='keySizeInBits'>The length (in bits) of the secret key agreed upon during the handshake phase</param>
/// <param name='ivSizeInBits'>The length (in bits) of the IV agreed upon during the handshake phase or if no IV is required, the length should be set to 0</param>
/// <param name='sequenceNumber'>The current sequence number used for records sent by the client and server respectively</param>
/// <param name='isExport'>Flag indicating whether the keys have to be derived for an export version of the protocol</param>
/// <param name='randomInfo'>Client's and server's random data information</param>
public CkWtlsKeyMatParams(ulong digestMechanism, ulong macSizeInBits, ulong keySizeInBits, ulong ivSizeInBits, ulong sequenceNumber, bool isExport, CkWtlsRandomData randomInfo)
{
if (randomInfo == null)
throw new ArgumentNullException("randomInfo");
// Keep reference to randomInfo so GC will not free it while this object exists
_randomInfo = randomInfo;
if (Platform.UnmanagedLongSize == 4)
{
if (Platform.StructPackingSize == 0)
_params40 = new HighLevelAPI40.MechanismParams.CkWtlsKeyMatParams(Convert.ToUInt32(digestMechanism), Convert.ToUInt32(macSizeInBits), Convert.ToUInt32(keySizeInBits), Convert.ToUInt32(ivSizeInBits), Convert.ToUInt32(sequenceNumber), isExport, _randomInfo._params40);
else
_params41 = new HighLevelAPI41.MechanismParams.CkWtlsKeyMatParams(Convert.ToUInt32(digestMechanism), Convert.ToUInt32(macSizeInBits), Convert.ToUInt32(keySizeInBits), Convert.ToUInt32(ivSizeInBits), Convert.ToUInt32(sequenceNumber), isExport, _randomInfo._params41);
}
else
{
if (Platform.StructPackingSize == 0)
_params80 = new HighLevelAPI80.MechanismParams.CkWtlsKeyMatParams(digestMechanism, macSizeInBits, keySizeInBits, ivSizeInBits, sequenceNumber, isExport, _randomInfo._params80);
else
_params81 = new HighLevelAPI81.MechanismParams.CkWtlsKeyMatParams(digestMechanism, macSizeInBits, keySizeInBits, ivSizeInBits, sequenceNumber, isExport, _randomInfo._params81);
}
}
#region IMechanismParams
/// <summary>
/// Returns managed object that can be marshaled to an unmanaged block of memory
/// </summary>
/// <returns>A managed object holding the data to be marshaled. This object must be an instance of a formatted class.</returns>
public object ToMarshalableStructure()
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
if (Platform.UnmanagedLongSize == 4)
return (Platform.StructPackingSize == 0) ? _params40.ToMarshalableStructure() : _params41.ToMarshalableStructure();
else
return (Platform.StructPackingSize == 0) ? _params80.ToMarshalableStructure() : _params81.ToMarshalableStructure();
}
#endregion
#region IDisposable
/// <summary>
/// Disposes object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes object
/// </summary>
/// <param name="disposing">Flag indicating whether managed resources should be disposed</param>
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// Dispose managed objects
if (_params40 != null)
{
_params40.Dispose();
_params40 = null;
}
if (_params41 != null)
{
_params41.Dispose();
_params41 = null;
}
if (_params80 != null)
{
_params80.Dispose();
_params80 = null;
}
if (_params81 != null)
{
_params81.Dispose();
_params81 = null;
}
if (_returnedKeyMaterialLeftInstance == false)
{
if (_returnedKeyMaterial != null)
{
_returnedKeyMaterial.Dispose();
_returnedKeyMaterial = null;
}
}
}
// Dispose unmanaged objects
_disposed = true;
}
}
/// <summary>
/// Class destructor that disposes object if caller forgot to do so
/// </summary>
~CkWtlsKeyMatParams()
{
Dispose(false);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AverageByte()
{
var test = new SimpleBinaryOpTest__AverageByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AverageByte
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Byte);
private const int Op2ElementCount = VectorSize / sizeof(Byte);
private const int RetElementCount = VectorSize / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector256<Byte> _clsVar1;
private static Vector256<Byte> _clsVar2;
private Vector256<Byte> _fld1;
private Vector256<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable;
static SimpleBinaryOpTest__AverageByte()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AverageByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.Average(
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.Average(
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.Average(
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Average), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Average), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Average), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.Average(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr);
var result = Avx2.Average(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx2.Average(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx2.Average(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AverageByte();
var result = Avx2.Average(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Average(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Byte> left, Vector256<Byte> right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
if ((byte)((left[0] + right[0] + 1) >> 1) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((byte)((left[i] + right[i] + 1) >> 1) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Average)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
namespace NServiceKit.ServiceHost
{
/// <summary>Bitfield of flags for specifying EndpointAttributes.</summary>
[Flags]
public enum EndpointAttributes : long
{
/// <summary>A binary constant representing the none flag.</summary>
None = 0,
/// <summary>A binary constant representing any flag.</summary>
Any = AnyNetworkAccessType | AnySecurityMode | AnyHttpMethod | AnyCallStyle | AnyFormat,
/// <summary>A binary constant representing any network access type flag.</summary>
AnyNetworkAccessType = External | Localhost | LocalSubnet,
/// <summary>A binary constant representing any security mode flag.</summary>
AnySecurityMode = Secure | InSecure,
/// <summary>A binary constant representing any HTTP method flag.</summary>
AnyHttpMethod = HttpHead | HttpGet | HttpPost | HttpPut | HttpDelete | HttpOther,
/// <summary>A binary constant representing any call style flag.</summary>
AnyCallStyle = OneWay | Reply,
/// <summary>A binary constant representing any format flag.</summary>
AnyFormat = Soap11 | Soap12 | Xml | Json | Jsv | Html | ProtoBuf | Csv | MsgPack | Yaml | FormatOther,
/// <summary>A binary constant representing any endpoint flag.</summary>
AnyEndpoint = Http | MessageQueue | Tcp | EndpointOther,
/// <summary>A binary constant representing the internal network access flag.</summary>
InternalNetworkAccess = Localhost | LocalSubnet,
/// <summary>Whether it came from an Internal or External address</summary>
Localhost = 1 << 0,
/// <summary>A binary constant representing the local subnet flag.</summary>
LocalSubnet = 1 << 1,
/// <summary>A binary constant representing the external flag.</summary>
External = 1 << 2,
/// <summary>A binary constant representing the secure flag.</summary>
Secure = 1 << 3,
/// <summary>A binary constant representing the in secure flag.</summary>
InSecure = 1 << 4,
//HTTP request type
/// <summary>A binary constant representing the HTTP head flag.</summary>
HttpHead = 1 << 5,
/// <summary>A binary constant representing the HTTP get flag.</summary>
HttpGet = 1 << 6,
/// <summary>A binary constant representing the HTTP post flag.</summary>
HttpPost = 1 << 7,
/// <summary>A binary constant representing the HTTP put flag.</summary>
HttpPut = 1 << 8,
/// <summary>A binary constant representing the HTTP delete flag.</summary>
HttpDelete = 1 << 9,
/// <summary>A binary constant representing the HTTP patch flag.</summary>
HttpPatch = 1 << 10,
/// <summary>A binary constant representing the HTTP options flag.</summary>
HttpOptions = 1 << 11,
/// <summary>A binary constant representing the HTTP other flag.</summary>
HttpOther = 1 << 12,
//Call Styles
/// <summary>An enum constant representing the one way option.</summary>
OneWay = 1 << 13,
/// <summary>A binary constant representing the reply flag.</summary>
Reply = 1 << 14,
/// <summary>An enum constant representing the SOAP 11 option.</summary>
Soap11 = 1 << 15,
/// <summary>A binary constant representing the SOAP 12 flag.</summary>
Soap12 = 1 << 16,
/// <summary>An enum constant representing the XML option.</summary>
Xml = 1 << 17,
/// <summary>An enum constant representing the JSON option.</summary>
Json = 1 << 18,
/// <summary>An enum constant representing the jsv option.</summary>
Jsv = 1 << 19,
/// <summary>An enum constant representing the prototype buffer option.</summary>
ProtoBuf = 1 << 20,
/// <summary>An enum constant representing the CSV option.</summary>
Csv = 1 << 21,
/// <summary>An enum constant representing the HTML option.</summary>
Html = 1 << 22,
/// <summary>An enum constant representing the yaml option.</summary>
Yaml = 1 << 23,
/// <summary>An enum constant representing the message pack option.</summary>
MsgPack = 1 << 24,
/// <summary>An enum constant representing the format other option.</summary>
FormatOther = 1 << 25,
/// <summary>An enum constant representing the HTTP option.</summary>
Http = 1 << 26,
/// <summary>An enum constant representing the message queue option.</summary>
MessageQueue = 1 << 27,
/// <summary>An enum constant representing the TCP option.</summary>
Tcp = 1 << 28,
/// <summary>An enum constant representing the endpoint other option.</summary>
EndpointOther = 1 << 29,
}
/// <summary>Values that represent Network.</summary>
public enum Network : long
{
/// <summary>An enum constant representing the localhost option.</summary>
Localhost = 1 << 0,
/// <summary>An enum constant representing the local subnet option.</summary>
LocalSubnet = 1 << 1,
/// <summary>An enum constant representing the external option.</summary>
External = 1 << 2,
}
/// <summary>Values that represent Security.</summary>
public enum Security : long
{
/// <summary>An enum constant representing the secure option.</summary>
Secure = 1 << 3,
/// <summary>An enum constant representing the in secure option.</summary>
InSecure = 1 << 4,
}
/// <summary>Values that represent Http.</summary>
public enum Http : long
{
/// <summary>An enum constant representing the head option.</summary>
Head = 1 << 5,
/// <summary>An enum constant representing the get option.</summary>
Get = 1 << 6,
/// <summary>An enum constant representing the post option.</summary>
Post = 1 << 7,
/// <summary>An enum constant representing the put option.</summary>
Put = 1 << 8,
/// <summary>An enum constant representing the delete option.</summary>
Delete = 1 << 9,
/// <summary>An enum constant representing the patch option.</summary>
Patch = 1 << 10,
/// <summary>An enum constant representing the options option.</summary>
Options = 1 << 11,
/// <summary>An enum constant representing the other option.</summary>
Other = 1 << 12,
}
/// <summary>Values that represent CallStyle.</summary>
public enum CallStyle : long
{
/// <summary>An enum constant representing the one way option.</summary>
OneWay = 1 << 13,
/// <summary>An enum constant representing the reply option.</summary>
Reply = 1 << 14,
}
/// <summary>Values that represent Format.</summary>
public enum Format : long
{
/// <summary>An enum constant representing the SOAP 11 option.</summary>
Soap11 = 1 << 15,
/// <summary>An enum constant representing the SOAP 12 option.</summary>
Soap12 = 1 << 16,
/// <summary>An enum constant representing the XML option.</summary>
Xml = 1 << 17,
/// <summary>An enum constant representing the JSON option.</summary>
Json = 1 << 18,
/// <summary>An enum constant representing the jsv option.</summary>
Jsv = 1 << 19,
/// <summary>An enum constant representing the prototype buffer option.</summary>
ProtoBuf = 1 << 20,
/// <summary>An enum constant representing the CSV option.</summary>
Csv = 1 << 21,
/// <summary>An enum constant representing the HTML option.</summary>
Html = 1 << 22,
/// <summary>An enum constant representing the yaml option.</summary>
Yaml = 1 << 23,
/// <summary>An enum constant representing the message pack option.</summary>
MsgPack = 1 << 24,
/// <summary>An enum constant representing the other option.</summary>
Other = 1 << 25,
}
/// <summary>Values that represent Endpoint.</summary>
public enum Endpoint : long
{
/// <summary>An enum constant representing the HTTP option.</summary>
Http = 1 << 26,
/// <summary>An enum constant representing the message queue option.</summary>
MessageQueue = 1 << 27,
/// <summary>An enum constant representing the TCP option.</summary>
Tcp = 1 << 28,
/// <summary>An enum constant representing the other option.</summary>
Other = 1 << 29,
}
/// <summary>An endpoint attributes extensions.</summary>
public static class EndpointAttributesExtensions
{
/// <summary>The EndpointAttributes extension method that query if 'attrs' is localhost.</summary>
///
/// <param name="attrs">The attrs to act on.</param>
///
/// <returns>true if localhost, false if not.</returns>
public static bool IsLocalhost(this EndpointAttributes attrs)
{
return (EndpointAttributes.Localhost & attrs) == EndpointAttributes.Localhost;
}
/// <summary>The EndpointAttributes extension method that query if 'attrs' is local subnet.</summary>
///
/// <param name="attrs">The attrs to act on.</param>
///
/// <returns>true if local subnet, false if not.</returns>
public static bool IsLocalSubnet(this EndpointAttributes attrs)
{
return (EndpointAttributes.LocalSubnet & attrs) == EndpointAttributes.LocalSubnet;
}
/// <summary>The EndpointAttributes extension method that query if 'attrs' is external.</summary>
///
/// <param name="attrs">The attrs to act on.</param>
///
/// <returns>true if external, false if not.</returns>
public static bool IsExternal(this EndpointAttributes attrs)
{
return (EndpointAttributes.External & attrs) == EndpointAttributes.External;
}
/// <summary>A Feature extension method that converts a feature to a format.</summary>
///
/// <param name="format">The format to act on.</param>
///
/// <returns>feature as a Format.</returns>
public static Format ToFormat(this string format)
{
try
{
return (Format)Enum.Parse(typeof(Format), format.ToUpper().Replace("X-", ""), true);
}
catch (Exception)
{
return Format.Other;
}
}
/// <summary>A Format extension method that initializes this object from the given from format.</summary>
///
/// <param name="format">The format to act on.</param>
///
/// <returns>A string.</returns>
public static string FromFormat(this Format format)
{
var formatStr = format.ToString().ToLower();
if (format == Format.ProtoBuf || format == Format.MsgPack)
return "x-" + formatStr;
return formatStr;
}
/// <summary>A Feature extension method that converts a feature to a format.</summary>
///
/// <param name="feature">The feature to act on.</param>
///
/// <returns>feature as a Format.</returns>
public static Format ToFormat(this Feature feature)
{
switch (feature)
{
case Feature.Xml:
return Format.Xml;
case Feature.Json:
return Format.Json;
case Feature.Jsv:
return Format.Jsv;
case Feature.Csv:
return Format.Csv;
case Feature.Html:
return Format.Html;
case Feature.MsgPack:
return Format.MsgPack;
case Feature.ProtoBuf:
return Format.ProtoBuf;
case Feature.Soap11:
return Format.Soap11;
case Feature.Soap12:
return Format.Soap12;
}
return Format.Other;
}
/// <summary>A Format extension method that converts a format to a feature.</summary>
///
/// <param name="format">The format to act on.</param>
///
/// <returns>format as a Feature.</returns>
public static Feature ToFeature(this Format format)
{
switch (format)
{
case Format.Xml:
return Feature.Xml;
case Format.Json:
return Feature.Json;
case Format.Jsv:
return Feature.Jsv;
case Format.Csv:
return Feature.Csv;
case Format.Html:
return Feature.Html;
case Format.MsgPack:
return Feature.MsgPack;
case Format.ProtoBuf:
return Feature.ProtoBuf;
case Format.Soap11:
return Feature.Soap11;
case Format.Soap12:
return Feature.Soap12;
}
return Feature.CustomFormat;
}
/// <summary>The EndpointAttributes extension method that converts the attributes to a SOAP feature.</summary>
///
/// <param name="attributes">The attributes to act on.</param>
///
/// <returns>attributes as a Feature.</returns>
public static Feature ToSoapFeature(this EndpointAttributes attributes)
{
if ((EndpointAttributes.Soap11 & attributes) == EndpointAttributes.Soap11)
return Feature.Soap11;
if ((EndpointAttributes.Soap12 & attributes) == EndpointAttributes.Soap12)
return Feature.Soap12;
return Feature.None;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Untech.SharePoint.Common.CodeAnnotations;
using Untech.SharePoint.Common.Data.QueryModels;
using Untech.SharePoint.Common.Extensions;
using Untech.SharePoint.Common.MetaModels;
using Untech.SharePoint.Common.Utils;
using Untech.SharePoint.Common.Utils.Reflection;
namespace Untech.SharePoint.Common.Data.Mapper
{
/// <summary>
/// Represents class that can map SP List item to Entity.
/// </summary>
/// <typeparam name="TSPItem">Exact type of SP list item, i.e. SPListItem for SSOM, ListItem for CSOM.</typeparam>
[PublicAPI]
public abstract class TypeMapper<TSPItem>
{
/// <summary>
/// Initializes a new instance of the <see cref="TypeMapper{TSPItem}"/> for the specified SP ContentType.
/// </summary>
/// <param name="contentType">ContentType to map.</param>
/// <exception cref="ArgumentNullException"><paramref name="contentType"/> is null.</exception>
protected TypeMapper([NotNull]MetaContentType contentType)
{
Guard.CheckNotNull(nameof(contentType), contentType);
ContentType = contentType;
TypeCreator = InstanceCreationUtility.GetCreator<object>(contentType.EntityType);
}
/// <summary>
/// Gets assocaited SP ContentType metadata.
/// </summary>
[NotNull]
public MetaContentType ContentType { get; }
/// <summary>
/// Gets .NET type creator.
/// </summary>
[NotNull]
public Func<object> TypeCreator { get; }
/// <summary>
/// Maps source entity to SP list item.
/// </summary>
/// <param name="source">Source object.</param>
/// <param name="dest">Destination SP list item.</param>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="dest"/> is null.</exception>
public void Map([NotNull]object source, [NotNull]TSPItem dest)
{
Guard.CheckNotNull(nameof(source), source);
Guard.CheckNotNull(nameof(dest), dest);
foreach (var mapper in GetMappers())
{
mapper.Map(source, dest);
}
if (ContentType.List.IsExternal)
{
return;
}
SetContentType(dest);
}
/// <summary>
/// Maps source entity to dictionary with CAML values.
/// </summary>
/// <param name="source">Source object.</param>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
public IReadOnlyDictionary<string, string> MapToCaml([NotNull] object source)
{
Guard.CheckNotNull(nameof(source), source);
var fields = new Dictionary<string, string>();
var mappers = GetMappers()
.Where(n => n.StoreAccessor.CanSetValue || n.Field.InternalName.In(new[] { Fields.Id, Fields.BdcIdentity }));
foreach (var mapper in mappers)
{
fields[mapper.Field.InternalName] = mapper.MapToCaml(source);
}
if (ContentType.List.IsExternal)
{
return fields;
}
fields[Fields.ContentTypeId] = ContentType.Id;
return fields;
}
/// <summary>
/// Maps SP list item to destination entity.
/// </summary>
/// <param name="source">Souce SP list item to map.</param>
/// <param name="dest">Destination object.</param>
/// <param name="viewFields">Collection of fields internal names that should be mapped.</param>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="dest"/> is null.</exception>
public void Map([NotNull]TSPItem source, [NotNull]object dest, IReadOnlyCollection<MemberRefModel> viewFields = null)
{
Guard.CheckNotNull(nameof(source), source);
Guard.CheckNotNull(nameof(dest), dest);
foreach (var mapper in GetMappers(viewFields))
{
mapper.Map(source, dest);
}
}
/// <summary>
/// Creates and maps SP list item to .NET entity.
/// </summary>
/// <param name="source">Souce SP list item to map.</param>
/// <param name="viewFields">Collection of fields internal names that should be mapped.</param>
/// <returns>New .NET entity.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
public object CreateAndMap([NotNull]TSPItem source, IReadOnlyCollection<MemberRefModel> viewFields = null)
{
Guard.CheckNotNull(nameof(source), source);
var item = TypeCreator();
Map(source, item, viewFields);
return item;
}
/// <summary>
/// Creates and maps SP list items to .NET entities.
/// </summary>
/// <param name="source">Souce SP list items to map.</param>
/// <param name="viewFields">Collection of fields internal names that should be mapped.</param>
/// <returns>New .NET entities.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
public IEnumerable<T> CreateAndMap<T>([NotNull]IEnumerable<TSPItem> source, IReadOnlyCollection<MemberRefModel> viewFields = null)
{
Guard.CheckNotNull(nameof(source), source);
var mappers = GetMappers(viewFields).ToList();
foreach (var spItem in source)
{
var item = TypeCreator();
foreach (var mapper in mappers)
{
mapper.Map(spItem, item);
}
yield return (T)item;
}
}
/// <summary>
/// Sets current contnet type id for the specified SP list item.
/// </summary>
/// <param name="spItem">SP list item</param>
protected abstract void SetContentType([NotNull]TSPItem spItem);
/// <summary>
/// Gets collection of field mappers associated with current <see cref="ContentType"/>.
/// </summary>
/// <returns>Collection of field mappers.</returns>
[NotNull]
protected IEnumerable<FieldMapper<TSPItem>> GetMappers()
{
foreach(var field in (IEnumerable<MetaField>)ContentType.Fields)
{
yield return field.GetMapper<TSPItem>();
}
}
/// <summary>
/// Gets collection of field mappers associated with current <see cref="ContentType"/> and filtered in according to list of selectable fields.
/// </summary>
/// <returns>Collection of field mappers for fields that should be mapped.</returns>
[NotNull]
protected IEnumerable<FieldMapper<TSPItem>> GetMappers([CanBeNull]IReadOnlyCollection<MemberRefModel> viewFields)
{
if (viewFields.IsNullOrEmpty())
{
return GetMappers();
}
return GetMappers(viewFields.Select(n => n.Member).ToList());
}
private IEnumerable<FieldMapper<TSPItem>> GetMappers([NotNull]IReadOnlyCollection<MemberInfo> viewMembers)
{
foreach (var field in (IEnumerable<MetaField>)ContentType.Fields)
{
if (viewMembers.Contains(field.Member, MemberInfoComparer.Default))
{
yield return field.GetMapper<TSPItem>();
}
}
}
}
}
| |
/*
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.Security;
using System.Security.Permissions;
using log4net;
using FluorineFx.Exceptions;
using FluorineFx.Messaging;
using FluorineFx.Messaging.Messages;
using FluorineFx.Messaging.Services.Messaging;
using FluorineFx.Data.Messages;
using FluorineFx.Context;
namespace FluorineFx.Data
{
//http://livedocs.adobe.com/flex/2/fds2javadoc/flex/data/DataServiceTransaction.html
/// <summary>
/// Describes the current state of the DataServiceTransaction
/// </summary>
public enum TransactionState
{
/// <summary>
/// Transactions in this state are waiting to be committed or rolled back.
/// </summary>
Active,
/// <summary>
/// Transactions in this state have been committed.
/// </summary>
Committed,
/// <summary>
/// Transactions in this state have been rolled back.
/// </summary>
RolledBack
}
/// <summary>
/// A DataServiceTransaction instance is created for each operation that modifies the state of
/// objects managed by Data Management Services. You can use this class from server-side code to
/// push changes to managed data stored on clients as long as they have the autoSyncEnabled
/// property set to true.
/// </summary>
public class DataServiceTransaction
{
private static readonly ILog log = LogManager.GetLogger(typeof(DataServiceTransaction));
sealed class RefreshFillData
{
string _destination;
IList _parameters;
public RefreshFillData(string destination, IList parameters)
{
_destination = destination;
_parameters = parameters;
}
public string Destination { get { return _destination; } }
public IList Parameters { get { return _parameters; } }
}
DataService _dataService;
bool _sendMessagesToPeers;
bool _rollbackOnly;
string _clientId;
string _correlationId;
TransactionState _transactionState;
ArrayList _refreshFills;
ArrayList _processedMessageBatches;
Hashtable _updateCollectionMessages;
Hashtable _clientUpdateCollectionMessages;
ArrayList _outgoingMessages;
ArrayList _pushMessages;
static int _idCounter;
private DataServiceTransaction(DataService dataService)
{
_transactionState = TransactionState.Active;
_dataService = dataService;
_sendMessagesToPeers = true;
_rollbackOnly = false;
_outgoingMessages = new ArrayList();
_processedMessageBatches = new ArrayList(1);
#if (NET_1_1)
_updateCollectionMessages = new Hashtable(new ListHashCodeProvider(), new ListComparer());
_clientUpdateCollectionMessages = new Hashtable(new ListHashCodeProvider(), new ListComparer());
#else
_updateCollectionMessages = new Hashtable(new ListHashCodeProvider());
_clientUpdateCollectionMessages = new Hashtable(new ListHashCodeProvider());
#endif
}
/// <summary>
/// Gets the current state of the DataServiceTransaction.
/// </summary>
public TransactionState TransactionState
{
get{ return _transactionState; }
}
internal string ClientId
{
get{ return _clientId; }
set{ _clientId = value; }
}
internal string CorrelationId
{
get{ return _correlationId; }
set{ _correlationId = value; }
}
/// <summary>
/// Gets the current DataServiceTransaction if one has been associated with the current thread.
/// When you begin a DataServiceTransaction, it is automatically associated with your thread.
/// If you want to add changes while in an adapter/assembler's sync method, you can use this
/// method to get a reference to the existing DataServiceTransaction.
/// In this case, you can call updateItem, createItem, deleteItem, and so forth, but you do not
/// call commit or rollback yourself as this is done by the data services code when the
/// sync method completes.
/// </summary>
/// <value>The current DataServiceTransaction or null if there is no transaction currently associated with the current thread.</value>
public static DataServiceTransaction CurrentDataServiceTransaction
{
get
{
return FluorineWebSafeCallContext.GetData(FluorineContext.FluorineDataServiceTransaction) as DataServiceTransaction;
}
}
private static void SetCurrentDataServiceTransaction(DataServiceTransaction dataServiceTransaction)
{
FluorineWebSafeCallContext.SetData(FluorineContext.FluorineDataServiceTransaction, dataServiceTransaction);
}
/// <summary>
/// Starts a DataServiceTransaction that you can use to send changes to clients. Use this method when
/// you want to push changes to clients when you are not in the midst of an adapter/assembler's method.
/// If you are being called from within the context of an assembler method (or if you are not
/// sure), you should call the CurrentDataServiceTransaction property. If that returns null, you can then
/// use this method to start one.
/// If you call this method, you must either call commit or rollback to complete the transaction.
/// You should make sure that this commit or rollback occurs no matter what else happens - it almost
/// always must be in a finally block in your code.
/// If you are in an assembler method, you should not commit or rollback the transaction as that
/// happens in the data services code when it completes. Instead, if you want to rollback the
/// transaction, call SetRollbackOnly.
/// </summary>
/// <param name="serverId">Identifies the MessageBroker that created the Data Management Services destination you want to manipulate using this api. Typically there is only one MessageBroker for each web application and in this case, you can pass in null.</param>
/// <returns></returns>
public static DataServiceTransaction Begin(string serverId)
{
if( DataServiceTransaction.CurrentDataServiceTransaction == null )
{
MessageBroker messageBroker = MessageBroker.GetMessageBroker(serverId);
DataService dataService = messageBroker.GetServiceByMessageType("flex.data.messages.DataMessage") as DataService;
return Begin(dataService);
}
else
return DataServiceTransaction.CurrentDataServiceTransaction;
}
/// <summary>
/// This version of the Begin method uses the default MessageBroker.
/// </summary>
/// <returns></returns>
public static DataServiceTransaction Begin()
{
return Begin((string)null);
}
internal static DataServiceTransaction Begin(DataService dataService)
{
DataServiceTransaction dataServiceTransaction = new DataServiceTransaction(dataService);
SetCurrentDataServiceTransaction(dataServiceTransaction);
return dataServiceTransaction;
}
/// <summary>
/// Marks the DataServiceTransaction so we rollback the transaction instead of committing it when it completes.
/// </summary>
public void SetRollbackOnly()
{
_rollbackOnly = true;
}
private void ProcessRefreshFills()
{
for (int i = 0; _refreshFills != null && i < _refreshFills.Count; i++)
{
RefreshFillData refreshFill = _refreshFills[i] as RefreshFillData;
DataDestination dataDestination = _dataService.GetDestination(refreshFill.Destination) as DataDestination;
if (dataDestination == null)
throw new FluorineException(__Res.GetString(__Res.Destination_NotFound, refreshFill.Destination));
ICollection sequences = dataDestination.SequenceManager.GetSequences(refreshFill.Parameters);
if (sequences != null)
{
lock (dataDestination.SequenceManager.SyncRoot)
{
foreach (Sequence sequence in sequences)
{
DataMessage dataMessage = new DataMessage();
dataMessage.operation = DataMessage.FillOperation;
if (sequence.Parameters != null)
dataMessage.body = sequence.Parameters;
else
dataMessage.body = new object[0];
if (_clientId != null)
dataMessage.clientId = _clientId;
else
dataMessage.clientId = "srv:" + Guid.NewGuid().ToString("D");
IList result = dataDestination.ServiceAdapter.Invoke(dataMessage) as IList;
if (result.Count > 0)
{
Sequence sequenceTmp = dataDestination.SequenceManager.CreateSequence(dataMessage.clientId as string, result, sequence.Parameters, this);
}
}
}
}
}
}
/// <summary>
/// Clients can call this method to commit the transaction. You should only use this method if
/// you used the begin method to create the DataServiceTransaction.
/// Otherwise, the gateway will commit or rollback the transaction as necessary.
/// </summary>
public void Commit()
{
if( _rollbackOnly )
{
Rollback();
return;
}
try
{
ProcessRefreshFills();
_pushMessages = new ArrayList();
for(int i = 0; i < _processedMessageBatches.Count; i++)
{
MessageBatch messageBatch = _processedMessageBatches[i] as MessageBatch;
if( messageBatch.Messages != null && messageBatch.Messages.Count > 0 )
{
DataDestination dataDestination = _dataService.GetDestination(messageBatch.IncomingMessage) as DataDestination;
try
{
dataDestination.SequenceManager.ManageMessageBatch(messageBatch, this);
}
catch(Exception ex)
{
MessageException messageException = new MessageException(ex);
ErrorMessage errorMessage = messageException.GetErrorMessage();
errorMessage.correlationId = messageBatch.IncomingMessage.messageId;
errorMessage.destination = messageBatch.IncomingMessage.destination;
messageBatch.Messages.Clear();
messageBatch.Messages.Add(errorMessage);
}
for(int j = 0; j < messageBatch.Messages.Count; j++)
{
IMessage message = messageBatch.Messages[j] as IMessage;
if( !(message is ErrorMessage) )
_pushMessages.Add(message);
}
}
_outgoingMessages.AddRange(messageBatch.Messages);
}
for(int i = 0; i < _pushMessages.Count; i++)
{
IMessage message = _pushMessages[i] as IMessage;
DataMessage dataMessage = message as DataMessage;
if( dataMessage != null )
PushMessage(GetSubscribers(message), message);
}
foreach(DictionaryEntry entry in _clientUpdateCollectionMessages)
{
UpdateCollectionMessage updateCollectionMessage = entry.Value as UpdateCollectionMessage;
_outgoingMessages.Add(updateCollectionMessage);
PushMessage(GetSubscribers(updateCollectionMessage), updateCollectionMessage);
}
foreach(DictionaryEntry entry in _updateCollectionMessages)
{
UpdateCollectionMessage updateCollectionMessage = entry.Value as UpdateCollectionMessage;
_outgoingMessages.Add(updateCollectionMessage);
PushMessage(GetSubscribers(updateCollectionMessage), updateCollectionMessage);
}
}
finally
{
_transactionState = TransactionState.Committed;
}
}
ICollection GetSubscribers(IMessage message)
{
MessageDestination destination = _dataService.GetDestination(message) as MessageDestination;
SubscriptionManager subscriptionManager = destination.SubscriptionManager;
IList subscribers = subscriptionManager.GetSubscribers();
subscribers.Remove(message.clientId);
return subscribers;
}
private void PushMessage(ICollection subscribers, IMessage message)
{
//Get subscribers here
_dataService.PushMessageToClients(subscribers, message);
}
internal IList GetOutgoingMessages()
{
return _outgoingMessages;
}
/// <summary>
/// Rollsback this transaction.
/// You should only use this method if you created the DataServiceTransaction with the Begin method.
/// </summary>
public void Rollback()
{
try
{
}
finally
{
_transactionState = TransactionState.RolledBack;
}
}
/// <summary>
/// Send an update event to clients subscribed to this message. Note that this method does not send
/// the change to the adapter/assembler - it assumes that the changes have already been applied
/// or are being applied. It only updates the clients with the new version of this data.
///
/// You must supply a destination parameter and a new version of the object. If you supply a
/// non-null previous version, this object is used to detect conflicts on the client in case
/// the client's version of the data does not match the previous version. You may also supply
/// a list of property names that have changed as a hint to the client to indicate which properties
/// should be checked for conflicts and updated. If you supply null for the changes, all
/// properties on the client are updated. These property names do not accept any kind of dot
/// notation to specify that a property of a property has changed. Only top level property
/// names are allowed.
/// </summary>
/// <param name="destination">Name of the Data Management Services destination that is managing the item you want to update.</param>
/// <param name="newVersion">New version of the item to update. The identity of the item is used to determine which item to update.</param>
/// <param name="previousVersion">If not null, this contains a version of the item you intend to update. The client can detect a conflict if its version does not match the previousVersion. If you specify the value as null, a conflict is only detected if the client has pending changes for the item being updated.</param>
/// <param name="changes">Array of property names which are to be updated. You can provide a null value to indicate that all property values may have changed.</param>
public void UpdateItem(string destination, object newVersion, object previousVersion, string[] changes)
{
DataMessage dataMessage = new DataMessage();
DataDestination dataDestination = _dataService.GetDestination(destination) as DataDestination;
object[] body = new object[3];
body[0] = changes;
body[2] = newVersion;
body[1] = previousVersion;
dataMessage.operation = DataMessage.UpdateOperation;
dataMessage.body = body;
dataMessage.destination = destination;
if (_clientId != null)
dataMessage.clientId = _clientId;
else
dataMessage.clientId = "srv:" + Guid.NewGuid().ToString("D");
dataMessage.identity = Identity.GetIdentity(newVersion, dataDestination);
dataMessage.messageId = "srv:" + Guid.NewGuid().ToString("D") + ":" + _idCounter.ToString();
System.Threading.Interlocked.Increment(ref _idCounter);
ArrayList messages = new ArrayList(1);
messages.Add(dataMessage);
MessageBatch messageBatch = new MessageBatch(dataMessage, messages);
_processedMessageBatches.Add(messageBatch);
}
/// <summary>
/// You use this method to indicate to to the Data Management Service that a new item has been created.
/// The Data Management Service goes through all sequences currently being managed by clients and
/// determine whether this item belongs in each sequence. Usually it re-evaluates each fill method
/// to make this determination (though you can control how this is done for each fill method).
/// When it finds a sequence that contains this item, it then sends a create message for this
/// item to each client subscribed for that sequence.
///
/// Note that this method does not send a create message to the adapter/assembler for this item.
/// It assumes that your backend database has already been updated with the data or is being
/// updated in this transaction. If this transaction is rolled back, no changes are applied.
/// </summary>
/// <param name="destination">Name of the destination that is to be managing this newly created item.</param>
/// <param name="item">New item to create.</param>
public void CreateItem(string destination, object item)
{
DataMessage dataMessage = new DataMessage();
DataDestination dataDestination = _dataService.GetDestination(destination) as DataDestination;
dataMessage.operation = DataMessage.CreateOperation;
dataMessage.body = item;
dataMessage.destination = destination;
if (_clientId != null)
dataMessage.clientId = _clientId;
else
dataMessage.clientId = "srv:" + Guid.NewGuid().ToString("D");
dataMessage.identity = Identity.GetIdentity(item, dataDestination);
dataMessage.messageId = "srv:" + Guid.NewGuid().ToString("D") + ":" + _idCounter.ToString();
System.Threading.Interlocked.Increment(ref _idCounter);
ArrayList messages = new ArrayList(1);
messages.Add(dataMessage);
MessageBatch messageBatch = new MessageBatch(dataMessage, messages);
AddProcessedMessageBatch(messageBatch);
}
/// <summary>
/// Sends a deleteItem method to the clients that are sync'd to sequences that contain this item.
/// It does not send a delete message to the adapter/assembler but instead assumes that this
/// item is already have been deleted from the database or is being deleted in this transaction.
/// If you rollback the transaction, this message is also rolled back.
///
/// This version of the delete method causes clients to generate a conflict if they have a version
/// of the item that does not match the version of the item specified. You can use the
/// DeleteItemWithId method to unconditionally delete an item on the client if you do not have
/// the original version.
/// </summary>
/// <param name="destination">Name of the destination containing the item to be deleted.</param>
/// <param name="item">Version of the item to delete. Clients can detect a conflict if this version of the item does not match the version they are currently managing.</param>
public void DeleteItem(string destination, object item)
{
DataMessage dataMessage = new DataMessage();
DataDestination dataDestination = _dataService.GetDestination(destination) as DataDestination;
dataMessage.operation = DataMessage.DeleteOperation;
dataMessage.body = item;
dataMessage.destination = destination;
if (_clientId != null)
dataMessage.clientId = _clientId;
else
dataMessage.clientId = "srv:" + Guid.NewGuid().ToString("D");
dataMessage.identity = Identity.GetIdentity(item, dataDestination);
dataMessage.messageId = "srv:" + Guid.NewGuid().ToString("D") + ":" + _idCounter.ToString();
System.Threading.Interlocked.Increment(ref _idCounter);
ArrayList messages = new ArrayList(1);
messages.Add(dataMessage);
MessageBatch messageBatch = new MessageBatch(dataMessage, messages);
AddProcessedMessageBatch(messageBatch);
}
/// <summary>
/// This version of the deleteItem method does not provide for conflict detection if the item has been modified before the delete occurs; it is deleted.
/// </summary>
/// <param name="destination">Name of the destination containing the item to be deleted.</param>
/// <param name="identity">A Hashtable containing entries for each of the id properties for this item (the key is the id property name, the value is its value).</param>
public void DeleteItemWithId(string destination, Hashtable identity)
{
DataMessage dataMessage = new DataMessage();
DataDestination dataDestination = _dataService.GetDestination(destination) as DataDestination;
dataMessage.operation = DataMessage.DeleteOperation;
dataMessage.body = null;
dataMessage.destination = destination;
if (_clientId != null)
dataMessage.clientId = _clientId;
else
dataMessage.clientId = "srv:" + Guid.NewGuid().ToString("D");
dataMessage.identity = identity;
dataMessage.messageId = "srv:" + Guid.NewGuid().ToString("D") + ":" + _idCounter.ToString();
System.Threading.Interlocked.Increment(ref _idCounter);
ArrayList messages = new ArrayList(1);
messages.Add(dataMessage);
MessageBatch messageBatch = new MessageBatch(dataMessage, messages);
AddProcessedMessageBatch(messageBatch);
}
/// <summary>
/// For a matching list of auto-sync'd fills, re-executes the fill method, compares the identities
/// of the items returned to the those returned the last time we executed it with
/// AutoSyncEnabled=true. It builds an update collection events for any fills that have changed.
/// This contains the items that have been added to or removed from the list but does not look
/// for changes made to the properties of those items. This update collection message is sent to
/// clients along with the other messages in this transaction when you commit. If the transaction
/// is rolled back, the fills are not updated.
///
/// If you want to update the property values of items, you'll need to use updateItem on the individual items that have changed.
///
/// If you provide null for the fill parameters argument, all auto-sync'd fills are refreshed.
/// If you provide a list of fill parameters, we match that list of fill parameters against the
/// list provided by the clients when they executed the fills. If the fill parameters match, that
/// fill is refreshed. The matching algorithm works as follows. If you provide a value for a given
/// fill parameter, the equals method is used on it to compare against the fill parameter value
/// that the client used when it executed the fill. If you provide a null parameter value,
/// it matches that slot for all fills.
/// </summary>
/// <param name="destination">Destination on which the desired fills were created against.</param>
/// <param name="fillParameters">Fill parameter pattern that defines the fills to be refreshed.</param>
public void RefreshFill(string destination, IList fillParameters)
{
if (_refreshFills == null)
_refreshFills = new ArrayList(1);
_refreshFills.Add(new RefreshFillData(destination, fillParameters));
}
/// <summary>
/// When you call the updateItem, createItem, and the deleteItem methods, normally these messages
/// are sent to other peers in the cluster so they are distributed by those nodes to clients
/// connected to them. If your code is arranging to send these updates from each instance in
/// the cluster, set SendMessagesToPeers=false before you call the updateItem, createItem method,
/// and so forth.
/// </summary>
public bool SendMessagesToPeers
{
get{ return _sendMessagesToPeers; }
set{ _sendMessagesToPeers = value; }
}
internal void AddProcessedMessageBatch(MessageBatch messageBatch)
{
_processedMessageBatches.Add(messageBatch);
}
internal void AddClientUpdateCollection(UpdateCollectionMessage updateCollectionMessage)
{
_clientUpdateCollectionMessages[updateCollectionMessage.collectionId] = updateCollectionMessage;
}
internal void GenerateUpdateCollectionMessage(int updateType, DataDestination dataDestination, Sequence sequence, int position, Identity identity)
{
UpdateCollectionMessage updateCollectionMessage = CreateUpdateCollectionMessage(dataDestination, sequence);
updateCollectionMessage.AddItemIdentityChange(updateType, position, identity);
if (updateCollectionMessage.collectionId != null)
_updateCollectionMessages[updateCollectionMessage.collectionId] = updateCollectionMessage;
else
{
//without fill parameters
_updateCollectionMessages[new object[0]] = updateCollectionMessage;
}
}
private UpdateCollectionMessage CreateUpdateCollectionMessage(DataDestination dataDestination, Sequence sequence)
{
UpdateCollectionMessage updateCollectionMessage = new UpdateCollectionMessage();
updateCollectionMessage.clientId = this.ClientId;
updateCollectionMessage.updateMode = UpdateCollectionMessage.ServerUpdate;
// The unique identifier for the collection that was updated. For a collection filled with the
// DataService.fill() method this contains an Array of the parameters specified.
updateCollectionMessage.collectionId = sequence.Parameters;
updateCollectionMessage.destination = dataDestination.Id;
updateCollectionMessage.correlationId = this.CorrelationId;
updateCollectionMessage.messageId = "srv:" + Guid.NewGuid().ToString("D") + ":" + _idCounter.ToString();
System.Threading.Interlocked.Increment(ref _idCounter);
return updateCollectionMessage;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace Xero.Bus
{
/// <summary>
/// Defines the Xero bus.
/// </summary>
[ContractClass(typeof(ContractForIBus))]
public interface IBus
{
/// <summary>
/// Gets the list of key/value pairs that will be in the header of
/// messages being sent by the same thread.
/// This value will be cleared when a thread receives a message.
/// </summary>
IDictionary<string, string> OutgoingHeaders { get; }
/// <summary>
/// Gets the message context containing the Id, return address, and headers of the message currently being handled on
/// this thread.
/// </summary>
IMessageContext CurrentMessageContext { get; }
/// <summary>
/// Publish the event to subscribers.
/// </summary>
void Publish<T>() where T : IEvent;
/// <summary>
/// Publish the event to subscribers.
/// </summary>
void Publish<T>(T @event) where T : IEvent;
/// <summary>
/// Instantiates a event of type T and publishes it.
/// </summary>
/// <typeparam name="T">The type of event, usually an interface</typeparam>
/// <param name="eventConstructor">An action which initializes properties of the event</param>
void Publish<T>(Action<T> eventConstructor) where T : IEvent;
// /// <summary>
// /// Subcribes to receive published messages of the specified type.
// /// This method is only necessary if you turned off auto-subscribe.
// /// </summary>
// /// <param name="messageType">The type of message to subscribe to.</param>
// void Subscribe(Type messageType);
/// <summary>
/// Subscribes to receive published messages of type T.
/// This method is only necessary if you turned off auto-subscribe.
/// </summary>
/// <typeparam name="T">The type of message to subscribe to.</typeparam>
void Subscribe<T>() where T : IEvent;
// /// <summary>
// /// Unsubscribes from receiving published messages of the specified type.
// /// </summary>
// /// <param name="messageType">The type of message to subscribe to.</param>
// void Unsubscribe(Type messageType);
/// <summary>
/// Unsubscribes from receiving published messages of the specified type.
/// </summary>
/// <typeparam name="T">The type of message to unsubscribe from.</typeparam>
void Unsubscribe<T>() where T : IEvent;
/// <summary>
/// Sends the command back to the current bus.
/// </summary>
/// <param name="command"></param>
/// <remarks>
/// The Xero Bus deliberately prevents the request/response pattern, therefore no callbacks (as per the standard
/// NServiceBus API) are provided.
/// </remarks>
void SendLocal<T>(T command) where T : class, ICommand;
/// <summary>
/// Instantiates a command of type T and sends it back to the current bus.
/// </summary>
/// <typeparam name="T">The type of command.</typeparam>
/// <param name="commandConstructor">An action which initializes properties of the message</param>
/// <remarks>
/// The Xero Bus deliberately prevents the request/response pattern, therefore no callbacks (as per the standard
/// NServiceBus API) are provided.
/// </remarks>
void SendLocal<T>(Action<T> commandConstructor) where T : class, ICommand;
/// <summary>
/// Sends the provided command.
/// </summary>
/// <param name="command">The command to send.</param>
/// <remarks>
/// The commands will be sent to the destination configured for T.
/// The Xero Bus deliberately prevents the request/response pattern, therefore no callbacks (as per the standard
/// NServiceBus API) are provided.
/// </remarks>
void Send<T>(T command) where T : class, ICommand;
/// <summary>
/// Instantiates a command of type T and sends it.
/// </summary>
/// <typeparam name="T">The type of command.</typeparam>
/// <param name="commandConstructor">An action which initializes properties of the command</param>
/// <remarks>
/// The command will be sent to the destination configured for T.
/// The Xero Bus deliberately prevents the request/response pattern, therefore no callbacks (as per the standard
/// NServiceBus API) are provided.
/// </remarks>
void Send<T>(Action<T> commandConstructor) where T : class, ICommand;
// /// <summary>
// /// Sends the list of provided messages.
// /// </summary>
// /// <param name="destination">
// /// The address of the destination to which the messages will be sent.
// /// </param>
// /// <param name="messages">The list of messages to send.</param>
// ICallback Send(string destination, params object[] messages);
//
// /// <summary>
// /// Sends the list of provided messages.
// /// </summary>
// /// <param name="address">
// /// The address to which the messages will be sent.
// /// </param>
// /// <param name="messages">The list of messages to send.</param>
// ICallback Send(Address address, params object[] messages);
//
// /// <summary>
// /// Instantiates a message of type T and sends it to the given destination.
// /// </summary>
// /// <typeparam name="T">The type of message, usually an interface</typeparam>
// /// <param name="destination">The destination to which the message will be sent.</param>
// /// <param name="messageConstructor">An action which initializes properties of the message</param>
// /// <returns></returns>
// ICallback Send<T>(string destination, Action<T> messageConstructor);
//
// /// <summary>
// /// Instantiates a message of type T and sends it to the given address.
// /// </summary>
// /// <typeparam name="T">The type of message, usually an interface</typeparam>
// /// <param name="address">The address to which the message will be sent.</param>
// /// <param name="messageConstructor">An action which initializes properties of the message</param>
// /// <returns></returns>
// ICallback Send<T>(Address address, Action<T> messageConstructor);
//
// /// <summary>
// /// Sends the messages to the destination as well as identifying this
// /// as a response to a message containing the Id found in correlationId.
// /// </summary>
// /// <param name="destination"></param>
// /// <param name="correlationId"></param>
// /// <param name="messages"></param>
// ICallback Send(string destination, string correlationId, params object[] messages);
//
// /// <summary>
// /// Sends the messages to the given address as well as identifying this
// /// as a response to a message containing the Id found in correlationId.
// /// </summary>
// /// <param name="address"></param>
// /// <param name="correlationId"></param>
// /// <param name="messages"></param>
// ICallback Send(Address address, string correlationId, params object[] messages);
//
// /// <summary>
// /// Instantiates a message of the type T using the given messageConstructor,
// /// and sends it to the destination identifying it as a response to a message
// /// containing the Id found in correlationId.
// /// </summary>
// /// <typeparam name="T"></typeparam>
// /// <param name="destination"></param>
// /// <param name="correlationId"></param>
// /// <param name="messageConstructor"></param>
// ICallback Send<T>(string destination, string correlationId, Action<T> messageConstructor);
//
// /// <summary>
// /// Instantiates a message of the type T using the given messageConstructor,
// /// and sends it to the given address identifying it as a response to a message
// /// containing the Id found in correlationId.
// /// </summary>
// /// <typeparam name="T"></typeparam>
// /// <param name="address"></param>
// /// <param name="correlationId"></param>
// /// <param name="messageConstructor"></param>
// ICallback Send<T>(Address address, string correlationId, Action<T> messageConstructor);
//
// /// <summary>
// /// Sends the messages to all sites with matching site keys registered with the gateway.
// /// The gateway is assumed to be located at the master node.
// /// </summary>
// /// <param name="siteKeys"></param>
// /// <param name="messages"></param>
// /// <returns></returns>
// ICallback SendToSites(IEnumerable<string> siteKeys, params object[] messages);
//
//
// /// <summary>
// /// Defers the processing of the messages for the given delay. This feature is using the timeout manager so make sure that you enable timeouts
// /// </summary>
// /// <param name="delay"></param>
// /// <param name="messages"></param>
// /// <returns></returns>
// ICallback Defer(TimeSpan delay, params object[] messages);
//
//
// /// <summary>
// /// Defers the processing of the messages until the specified time. This feature is using the timeout manager so make sure that you enable timeouts
// /// </summary>
// /// <param name="processAt"></param>
// /// <param name="messages"></param>
// /// <returns></returns>
// ICallback Defer(DateTime processAt, params object[] messages);
//
// /// <summary>
// /// Sends all messages to the endpoint which sent the message currently being handled on this thread.
// /// </summary>
// /// <param name="messages">The messages to send.</param>
// void Reply(params object[] messages);
//
// /// <summary>
// /// Instantiates a message of type T and performs a regular <see cref="Reply" />.
// /// </summary>
// /// <typeparam name="T">The type of message, usually an interface</typeparam>
// /// <param name="messageConstructor">An action which initializes properties of the message</param>
// void Reply<T>(Action<T> messageConstructor) where T : IMessage;
/// <summary>
/// Moves the message being handled to the back of the list of available
/// messages so it can be handled later.
/// </summary>
void HandleCurrentMessageLater();
//
// /// <summary>
// /// Forwards the current message being handled to the destination maintaining
// /// all of its transport-level properties and headers.
// /// </summary>
// /// <param name="destination"></param>
// void ForwardCurrentMessageTo(string destination);
/// <summary>
/// Tells the bus to stop dispatching the current message to additional
/// handlers.
/// </summary>
void DoNotContinueDispatchingCurrentMessageToHandlers();
}
[ContractClassFor(typeof(IBus))]
internal abstract class ContractForIBus : IBus
{
public IMessageContext CurrentMessageContext { get; set; }
public T CreateInstance<T>() where T : IEvent {
return default(T);
}
public T CreateInstance<T>(Action<T> action) where T : IEvent {
Contract.Requires(action != null);
return default(T);
}
public void Publish<T>() where T : IEvent {
}
public void Publish<T>(T @event) where T : IEvent {
// ReSharper disable once CompareNonConstrainedGenericWithNull
Contract.Requires(@event != null);
}
public void Publish<T>(Action<T> eventConstructor) where T : IEvent {
Contract.Requires(eventConstructor != null);
}
public void Subscribe<T>() where T : IEvent {
}
public void Unsubscribe<T>() where T : IEvent {
}
public void Send<T>(T command) where T : class, ICommand {
Contract.Requires(command != null);
}
public void Send<T>(Action<T> commandConstructor) where T : class, ICommand {
Contract.Requires(commandConstructor != null);
}
public void SendLocal<T>(T command) where T : class, ICommand {
Contract.Requires(command != null);
}
public void SendLocal<T>(Action<T> commandConstructor) where T : class, ICommand {
Contract.Requires(commandConstructor != null);
}
public void HandleCurrentMessageLater() {
}
public void DoNotContinueDispatchingCurrentMessageToHandlers() {
}
public IDictionary<string, string> OutgoingHeaders { get; set; }
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: route_guide.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Routeguide {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class RouteGuide {
#region Descriptor
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static RouteGuide() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChFyb3V0ZV9ndWlkZS5wcm90bxIKcm91dGVndWlkZSIsCgVQb2ludBIQCghs",
"YXRpdHVkZRgBIAEoBRIRCglsb25naXR1ZGUYAiABKAUiSQoJUmVjdGFuZ2xl",
"Eh0KAmxvGAEgASgLMhEucm91dGVndWlkZS5Qb2ludBIdCgJoaRgCIAEoCzIR",
"LnJvdXRlZ3VpZGUuUG9pbnQiPAoHRmVhdHVyZRIMCgRuYW1lGAEgASgJEiMK",
"CGxvY2F0aW9uGAIgASgLMhEucm91dGVndWlkZS5Qb2ludCJBCglSb3V0ZU5v",
"dGUSIwoIbG9jYXRpb24YASABKAsyES5yb3V0ZWd1aWRlLlBvaW50Eg8KB21l",
"c3NhZ2UYAiABKAkiYgoMUm91dGVTdW1tYXJ5EhMKC3BvaW50X2NvdW50GAEg",
"ASgFEhUKDWZlYXR1cmVfY291bnQYAiABKAUSEAoIZGlzdGFuY2UYAyABKAUS",
"FAoMZWxhcHNlZF90aW1lGAQgASgFMoUCCgpSb3V0ZUd1aWRlEjYKCkdldEZl",
"YXR1cmUSES5yb3V0ZWd1aWRlLlBvaW50GhMucm91dGVndWlkZS5GZWF0dXJl",
"IgASPgoMTGlzdEZlYXR1cmVzEhUucm91dGVndWlkZS5SZWN0YW5nbGUaEy5y",
"b3V0ZWd1aWRlLkZlYXR1cmUiADABEj4KC1JlY29yZFJvdXRlEhEucm91dGVn",
"dWlkZS5Qb2ludBoYLnJvdXRlZ3VpZGUuUm91dGVTdW1tYXJ5IgAoARI/CglS",
"b3V0ZUNoYXQSFS5yb3V0ZWd1aWRlLlJvdXRlTm90ZRoVLnJvdXRlZ3VpZGUu",
"Um91dGVOb3RlIgAoATABQg8KB2V4LmdycGOiAgNSVEdiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Routeguide.Point), new[]{ "Latitude", "Longitude" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Routeguide.Rectangle), new[]{ "Lo", "Hi" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Routeguide.Feature), new[]{ "Name", "Location" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Routeguide.RouteNote), new[]{ "Location", "Message" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Routeguide.RouteSummary), new[]{ "PointCount", "FeatureCount", "Distance", "ElapsedTime" }, null, null, null)
}));
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Point : pb::IMessage<Point> {
private static readonly pb::MessageParser<Point> _parser = new pb::MessageParser<Point>(() => new Point());
public static pb::MessageParser<Point> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Routeguide.Proto.RouteGuide.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Point() {
OnConstruction();
}
partial void OnConstruction();
public Point(Point other) : this() {
latitude_ = other.latitude_;
longitude_ = other.longitude_;
}
public Point Clone() {
return new Point(this);
}
public const int LatitudeFieldNumber = 1;
private int latitude_;
public int Latitude {
get { return latitude_; }
set {
latitude_ = value;
}
}
public const int LongitudeFieldNumber = 2;
private int longitude_;
public int Longitude {
get { return longitude_; }
set {
longitude_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as Point);
}
public bool Equals(Point other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Latitude != other.Latitude) return false;
if (Longitude != other.Longitude) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Latitude != 0) hash ^= Latitude.GetHashCode();
if (Longitude != 0) hash ^= Longitude.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Latitude != 0) {
output.WriteRawTag(8);
output.WriteInt32(Latitude);
}
if (Longitude != 0) {
output.WriteRawTag(16);
output.WriteInt32(Longitude);
}
}
public int CalculateSize() {
int size = 0;
if (Latitude != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Latitude);
}
if (Longitude != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Longitude);
}
return size;
}
public void MergeFrom(Point other) {
if (other == null) {
return;
}
if (other.Latitude != 0) {
Latitude = other.Latitude;
}
if (other.Longitude != 0) {
Longitude = other.Longitude;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Latitude = input.ReadInt32();
break;
}
case 16: {
Longitude = input.ReadInt32();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Rectangle : pb::IMessage<Rectangle> {
private static readonly pb::MessageParser<Rectangle> _parser = new pb::MessageParser<Rectangle>(() => new Rectangle());
public static pb::MessageParser<Rectangle> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Routeguide.Proto.RouteGuide.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Rectangle() {
OnConstruction();
}
partial void OnConstruction();
public Rectangle(Rectangle other) : this() {
Lo = other.lo_ != null ? other.Lo.Clone() : null;
Hi = other.hi_ != null ? other.Hi.Clone() : null;
}
public Rectangle Clone() {
return new Rectangle(this);
}
public const int LoFieldNumber = 1;
private global::Routeguide.Point lo_;
public global::Routeguide.Point Lo {
get { return lo_; }
set {
lo_ = value;
}
}
public const int HiFieldNumber = 2;
private global::Routeguide.Point hi_;
public global::Routeguide.Point Hi {
get { return hi_; }
set {
hi_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as Rectangle);
}
public bool Equals(Rectangle other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Lo, other.Lo)) return false;
if (!object.Equals(Hi, other.Hi)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (lo_ != null) hash ^= Lo.GetHashCode();
if (hi_ != null) hash ^= Hi.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (lo_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Lo);
}
if (hi_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Hi);
}
}
public int CalculateSize() {
int size = 0;
if (lo_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Lo);
}
if (hi_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Hi);
}
return size;
}
public void MergeFrom(Rectangle other) {
if (other == null) {
return;
}
if (other.lo_ != null) {
if (lo_ == null) {
lo_ = new global::Routeguide.Point();
}
Lo.MergeFrom(other.Lo);
}
if (other.hi_ != null) {
if (hi_ == null) {
hi_ = new global::Routeguide.Point();
}
Hi.MergeFrom(other.Hi);
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (lo_ == null) {
lo_ = new global::Routeguide.Point();
}
input.ReadMessage(lo_);
break;
}
case 18: {
if (hi_ == null) {
hi_ = new global::Routeguide.Point();
}
input.ReadMessage(hi_);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Feature : pb::IMessage<Feature> {
private static readonly pb::MessageParser<Feature> _parser = new pb::MessageParser<Feature>(() => new Feature());
public static pb::MessageParser<Feature> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Routeguide.Proto.RouteGuide.Descriptor.MessageTypes[2]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Feature() {
OnConstruction();
}
partial void OnConstruction();
public Feature(Feature other) : this() {
name_ = other.name_;
Location = other.location_ != null ? other.Location.Clone() : null;
}
public Feature Clone() {
return new Feature(this);
}
public const int NameFieldNumber = 1;
private string name_ = "";
public string Name {
get { return name_; }
set {
name_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public const int LocationFieldNumber = 2;
private global::Routeguide.Point location_;
public global::Routeguide.Point Location {
get { return location_; }
set {
location_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as Feature);
}
public bool Equals(Feature other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (!object.Equals(Location, other.Location)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (location_ != null) hash ^= Location.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (location_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Location);
}
}
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (location_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Location);
}
return size;
}
public void MergeFrom(Feature other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.location_ != null) {
if (location_ == null) {
location_ = new global::Routeguide.Point();
}
Location.MergeFrom(other.Location);
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
if (location_ == null) {
location_ = new global::Routeguide.Point();
}
input.ReadMessage(location_);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class RouteNote : pb::IMessage<RouteNote> {
private static readonly pb::MessageParser<RouteNote> _parser = new pb::MessageParser<RouteNote>(() => new RouteNote());
public static pb::MessageParser<RouteNote> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Routeguide.Proto.RouteGuide.Descriptor.MessageTypes[3]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public RouteNote() {
OnConstruction();
}
partial void OnConstruction();
public RouteNote(RouteNote other) : this() {
Location = other.location_ != null ? other.Location.Clone() : null;
message_ = other.message_;
}
public RouteNote Clone() {
return new RouteNote(this);
}
public const int LocationFieldNumber = 1;
private global::Routeguide.Point location_;
public global::Routeguide.Point Location {
get { return location_; }
set {
location_ = value;
}
}
public const int MessageFieldNumber = 2;
private string message_ = "";
public string Message {
get { return message_; }
set {
message_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as RouteNote);
}
public bool Equals(RouteNote other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Location, other.Location)) return false;
if (Message != other.Message) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (location_ != null) hash ^= Location.GetHashCode();
if (Message.Length != 0) hash ^= Message.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (location_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Location);
}
if (Message.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Message);
}
}
public int CalculateSize() {
int size = 0;
if (location_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Location);
}
if (Message.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Message);
}
return size;
}
public void MergeFrom(RouteNote other) {
if (other == null) {
return;
}
if (other.location_ != null) {
if (location_ == null) {
location_ = new global::Routeguide.Point();
}
Location.MergeFrom(other.Location);
}
if (other.Message.Length != 0) {
Message = other.Message;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (location_ == null) {
location_ = new global::Routeguide.Point();
}
input.ReadMessage(location_);
break;
}
case 18: {
Message = input.ReadString();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class RouteSummary : pb::IMessage<RouteSummary> {
private static readonly pb::MessageParser<RouteSummary> _parser = new pb::MessageParser<RouteSummary>(() => new RouteSummary());
public static pb::MessageParser<RouteSummary> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Routeguide.Proto.RouteGuide.Descriptor.MessageTypes[4]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public RouteSummary() {
OnConstruction();
}
partial void OnConstruction();
public RouteSummary(RouteSummary other) : this() {
pointCount_ = other.pointCount_;
featureCount_ = other.featureCount_;
distance_ = other.distance_;
elapsedTime_ = other.elapsedTime_;
}
public RouteSummary Clone() {
return new RouteSummary(this);
}
public const int PointCountFieldNumber = 1;
private int pointCount_;
public int PointCount {
get { return pointCount_; }
set {
pointCount_ = value;
}
}
public const int FeatureCountFieldNumber = 2;
private int featureCount_;
public int FeatureCount {
get { return featureCount_; }
set {
featureCount_ = value;
}
}
public const int DistanceFieldNumber = 3;
private int distance_;
public int Distance {
get { return distance_; }
set {
distance_ = value;
}
}
public const int ElapsedTimeFieldNumber = 4;
private int elapsedTime_;
public int ElapsedTime {
get { return elapsedTime_; }
set {
elapsedTime_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as RouteSummary);
}
public bool Equals(RouteSummary other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (PointCount != other.PointCount) return false;
if (FeatureCount != other.FeatureCount) return false;
if (Distance != other.Distance) return false;
if (ElapsedTime != other.ElapsedTime) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (PointCount != 0) hash ^= PointCount.GetHashCode();
if (FeatureCount != 0) hash ^= FeatureCount.GetHashCode();
if (Distance != 0) hash ^= Distance.GetHashCode();
if (ElapsedTime != 0) hash ^= ElapsedTime.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (PointCount != 0) {
output.WriteRawTag(8);
output.WriteInt32(PointCount);
}
if (FeatureCount != 0) {
output.WriteRawTag(16);
output.WriteInt32(FeatureCount);
}
if (Distance != 0) {
output.WriteRawTag(24);
output.WriteInt32(Distance);
}
if (ElapsedTime != 0) {
output.WriteRawTag(32);
output.WriteInt32(ElapsedTime);
}
}
public int CalculateSize() {
int size = 0;
if (PointCount != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PointCount);
}
if (FeatureCount != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(FeatureCount);
}
if (Distance != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Distance);
}
if (ElapsedTime != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(ElapsedTime);
}
return size;
}
public void MergeFrom(RouteSummary other) {
if (other == null) {
return;
}
if (other.PointCount != 0) {
PointCount = other.PointCount;
}
if (other.FeatureCount != 0) {
FeatureCount = other.FeatureCount;
}
if (other.Distance != 0) {
Distance = other.Distance;
}
if (other.ElapsedTime != 0) {
ElapsedTime = other.ElapsedTime;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
PointCount = input.ReadInt32();
break;
}
case 16: {
FeatureCount = input.ReadInt32();
break;
}
case 24: {
Distance = input.ReadInt32();
break;
}
case 32: {
ElapsedTime = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/* Copyright (c) 2006-2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Change history
* Oct 13 2008 Joe Feser joseph.feser@gmail.com
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Xml;
using Google.GData.Client;
namespace Google.GData.Extensions {
/// <summary>
/// GData schema extension describing a nested entry link.
/// </summary>
public class EntryLink : IExtensionElementFactory
{
/// <summary>holds the href property of the EntryLink element</summary>
private string href;
/// <summary>holds the readOnlySet property of the EntryLink element</summary>
private bool readOnly;
/// <summary>holds the AtomEntry property of the EntryLink element</summary>
private AtomEntry entry;
/// <summary>holds the rel attribute of the EntyrLink element</summary>
private string rel;
private bool readOnlySet;
/// <summary>
/// Entry URI
/// </summary>
public string Href
{
get { return href; }
set { href = value; }
}
/// <summary>
/// Read only flag.
/// </summary>
public bool ReadOnly
{
get { return this.readOnly; }
set { this.readOnly = value; this.readOnlySet = true; }
}
/// <summary>
/// Nested entry (optional).
/// </summary>
public AtomEntry Entry
{
get { return entry; }
set { entry = value; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string Rel</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Rel
{
get {return this.rel;}
set {this.rel = value;}
}
/////////////////////////////////////////////////////////////////////////////
#region EntryLink Parser
//////////////////////////////////////////////////////////////////////
/// <summary>parses an xml node to create an EntryLink object</summary>
/// <param name="node">entrylink node</param>
/// <param name="parser">AtomFeedParser to use</param>
/// <returns> the created EntryLink object</returns>
//////////////////////////////////////////////////////////////////////
public static EntryLink ParseEntryLink(XmlNode node, AtomFeedParser parser)
{
Tracing.TraceCall();
EntryLink link = null;
Tracing.Assert(node != null, "node should not be null");
if (node == null)
{
throw new ArgumentNullException("node");
}
object localname = node.LocalName;
if (localname.Equals(GDataParserNameTable.XmlEntryLinkElement))
{
link = new EntryLink();
if (node.Attributes != null)
{
if (node.Attributes[GDataParserNameTable.XmlAttributeHref] != null)
{
link.Href = node.Attributes[GDataParserNameTable.XmlAttributeHref].Value;
}
if (node.Attributes[GDataParserNameTable.XmlAttributeReadOnly] != null)
{
link.ReadOnly = node.Attributes[GDataParserNameTable.XmlAttributeReadOnly].Value.Equals(Utilities.XSDTrue);
}
if (node.Attributes[GDataParserNameTable.XmlAttributeRel] != null)
{
link.Rel = node.Attributes[GDataParserNameTable.XmlAttributeRel].Value;
}
}
if (node.HasChildNodes)
{
XmlNode entryChild = node.FirstChild;
while (entryChild != null && entryChild is XmlElement)
{
if (entryChild.LocalName == AtomParserNameTable.XmlAtomEntryElement &&
entryChild.NamespaceURI == BaseNameTable.NSAtom)
{
if (link.Entry == null)
{
XmlReader reader = new XmlNodeReader(entryChild);
// move the reader to the first node
reader.Read();
AtomFeedParser p = new AtomFeedParser();
p.NewAtomEntry += new FeedParserEventHandler(link.OnParsedNewEntry);
p.ParseEntry(reader);
}
else
{
throw new ArgumentException("Only one entry is allowed inside the g:entryLink");
}
}
entryChild = entryChild.NextSibling;
}
}
}
return link;
}
//////////////////////////////////////////////////////////////////////
/// <summary>Event chaining. We catch this from the AtomFeedParser
/// we want to set this to our property, and do not add the entry to the collection
/// </summary>
/// <param name="sender"> the object which send the event</param>
/// <param name="e">FeedParserEventArguments, holds the feed entry</param>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
internal void OnParsedNewEntry(object sender, FeedParserEventArgs e)
{
// by default, if our event chain is not hooked, add it to the collection
Tracing.TraceCall("received new item notification");
Tracing.Assert(e != null, "e should not be null");
if (e == null)
{
throw new ArgumentNullException("e");
}
if (!e.CreatingEntry)
{
if (e.Entry != null)
{
// add it to the collection
Tracing.TraceMsg("\t new EventEntry found");
this.Entry = e.Entry;
e.DiscardEntry = true;
}
}
}
/////////////////////////////////////////////////////////////////////////////
#endregion
#region overloaded for persistence
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public static string XmlName
{
get { return GDataParserNameTable.XmlEntryLinkElement; }
}
/// <summary>
/// Used to save the EntryLink instance into the passed in xmlwriter
/// </summary>
/// <param name="writer">the XmlWriter to write into</param>
public void Save(XmlWriter writer)
{
if (Utilities.IsPersistable(this.Href) ||
this.readOnlySet ||
this.entry != null)
{
writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace);
if (Utilities.IsPersistable(this.Href))
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeHref, this.Href);
}
if (Utilities.IsPersistable(this.Rel))
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeRel, this.Rel);
}
if (this.readOnlySet)
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeReadOnly,
Utilities.ConvertBooleanToXSDString(this.ReadOnly));
}
if (entry != null)
{
entry.SaveToXml(writer);
}
writer.WriteEndElement();
}
}
#endregion
#region IExtensionElementFactory Members
/// <summary>
/// returns the xml local name for this element
/// </summary>
string IExtensionElementFactory.XmlName
{
get
{
return XmlName;
}
}
/// <summary>
/// returns the xml namespace for this element
/// </summary>
public string XmlNameSpace
{
get
{
return BaseNameTable.gNamespace;
}
}
/// <summary>
/// returns the xml prefix to be used for this element
/// </summary>
public string XmlPrefix
{
get
{
return BaseNameTable.gDataPrefix;
}
}
/// <summary>
/// factory method to create an instance of a batchinterrupt during parsing
/// </summary>
/// <param name="node">the xmlnode that is going to be parsed</param>
/// <param name="parser">the feedparser that is used right now</param>
/// <returns></returns>
public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser)
{
return EntryLink.ParseEntryLink(node, parser);
}
#endregion
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Catapult.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region File Information
//-----------------------------------------------------------------------------
// Animation.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Devices;
using System.Xml.Linq;
#endregion
namespace CatapultGame
{
#region Catapult states definition enum
[Flags]
public enum CatapultState
{
Idle = 0x0,
Aiming = 0x1,
Firing = 0x2,
ProjectileFlying = 0x4,
ProjectileHit = 0x8,
HitKill = 0x10,
HitDamage = 0x15,
Reset = 0x20,
Stalling = 0x40
}
#endregion
public class Catapult : DrawableGameComponent
{
#region Variables/Fields and Properties
// Hold what the game to which the catapult belongs
CatapultGame curGame = null;
SpriteBatch spriteBatch;
Random random;
public bool AnimationRunning { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
// In some cases the game need to start second animation while first animation is still running;
// this variable define at which frame the second animation should start
Dictionary<string, int> splitFrames;
Texture2D idleTexture;
Dictionary<string, Animation> animations;
SpriteEffects spriteEffects;
// Projectile
Projectile projectile;
string idleTextureName;
bool isAI;
// Game constants
const float gravity = 500f;
// State of the catapult during its last update
CatapultState lastUpdateState = CatapultState.Idle;
// Used to stall animations
int stallUpdateCycles;
// Current state of the Catapult
CatapultState currentState;
public CatapultState CurrentState
{
get { return currentState; }
set { currentState = value; }
}
float wind;
public float Wind
{
set
{
wind = value;
}
}
Player enemy;
internal Player Enemy
{
set
{
enemy = value;
}
}
Player self;
internal Player Self
{
set
{
self = value;
}
}
Vector2 catapultPosition;
public Vector2 Position
{
get
{
return catapultPosition;
}
}
/// <summary>
/// Describes how powerful the current shot being fired is. The more powerful
/// the shot, the further it goes. 0 is the weakest, 1 is the strongest.
/// </summary>
public float ShotStrength { get; set; }
public float ShotVelocity { get; set; }
/// <summary>
/// Used to determine whether or not the game is over
/// </summary>
public bool GameOver { get; set; }
const int winScore = 5;
#endregion
#region Initialization
public Catapult(Game game)
: base(game)
{
curGame = (CatapultGame)game;
}
public Catapult(Game game, SpriteBatch screenSpriteBatch,
string IdleTexture,
Vector2 CatapultPosition, SpriteEffects SpriteEffect, bool IsAI)
: this(game)
{
idleTextureName = IdleTexture;
catapultPosition = CatapultPosition;
spriteEffects = SpriteEffect;
spriteBatch = screenSpriteBatch;
isAI = IsAI;
splitFrames = new Dictionary<string, int>();
animations = new Dictionary<string, Animation>();
}
/// <summary>
/// Function initializes the catapult instance and loads the animations from XML definition sheet
/// </summary>
public override void Initialize()
{
// Define initial state of the catapult
IsActive = true;
AnimationRunning = false;
currentState = CatapultState.Idle;
stallUpdateCycles = 0;
// Load multiple animations form XML definition
XDocument doc = XDocument.Load("Content/Textures/Catapults/AnimationsDef.xml");
XName name = XName.Get("Definition");
var definitions = doc.Document.Descendants(name);
// Loop over all definitions in XML
foreach (var animationDefinition in definitions)
{
bool? toLoad = null;
bool val;
if (bool.TryParse(animationDefinition.Attribute("IsAI").Value, out val))
toLoad = val;
// Check if the animation definition need to be loaded for current catapult
if (toLoad == isAI || null == toLoad)
{
// Get a name of the animation
string animatonAlias = animationDefinition.Attribute("Alias").Value;
Texture2D texture =
curGame.Content.Load<Texture2D>(animationDefinition.Attribute("SheetName").Value);
// Get the frame size (width & height)
Point frameSize = new Point();
frameSize.X = int.Parse(animationDefinition.Attribute("FrameWidth").Value);
frameSize.Y = int.Parse(animationDefinition.Attribute("FrameHeight").Value);
// Get the frames sheet dimensions
Point sheetSize = new Point();
sheetSize.X = int.Parse(animationDefinition.Attribute("SheetColumns").Value);
sheetSize.Y = int.Parse(animationDefinition.Attribute("SheetRows").Value);
// If definition has a "SplitFrame" - means that other animation should start here - load it
if (null != animationDefinition.Attribute("SplitFrame"))
splitFrames.Add(animatonAlias,
int.Parse(animationDefinition.Attribute("SplitFrame").Value));
// Defing animation speed
TimeSpan frameInterval = TimeSpan.FromSeconds((float)1 /
int.Parse(animationDefinition.Attribute("Speed").Value));
Animation animation = new Animation(texture, frameSize, sheetSize);
// If definition has an offset defined - means that it should be rendered relatively
// to some element/other animation - load it
if (null != animationDefinition.Attribute("OffsetX") &&
null != animationDefinition.Attribute("OffsetY"))
{
animation.Offset = new Vector2(int.Parse(animationDefinition.Attribute("OffsetX").Value),
int.Parse(animationDefinition.Attribute("OffsetY").Value));
}
animations.Add(animatonAlias, animation);
}
}
// Load the textures
idleTexture = curGame.Content.Load<Texture2D>(idleTextureName);
// Initialize the projectile
Vector2 projectileStartPosition;
if (isAI)
projectileStartPosition = new Vector2(630, 340);
else
projectileStartPosition = new Vector2(175, 340);
projectile = new Projectile(curGame, spriteBatch, "Textures/Ammo/rock_ammo",
projectileStartPosition, animations["Fire"].FrameSize.Y, isAI, gravity);
projectile.Initialize();
// Initialize randomizer
random = new Random();
base.Initialize();
}
#endregion
#region Update and Render
public override void Update(GameTime gameTime)
{
bool isGroundHit;
bool startStall;
CatapultState postUpdateStateChange = 0;
if (gameTime == null)
throw new ArgumentNullException("gameTime");
// The catapult is inactive, so there is nothing to update
if (!IsActive)
{
base.Update(gameTime);
return;
}
switch (currentState)
{
case CatapultState.Idle:
// Nothing to do
break;
case CatapultState.Aiming:
if (lastUpdateState != CatapultState.Aiming)
{
AudioManager.PlaySound("ropeStretch", true);
AnimationRunning = true;
if (isAI == true)
{
animations["Aim"].PlayFromFrameIndex(0);
stallUpdateCycles = 20;
startStall = false;
}
}
// Progress Aiming "animation"
if (isAI == false)
{
UpdateAimAccordingToShotStrength();
}
else
{
animations["Aim"].Update();
startStall = AimReachedShotStrength();
currentState = (startStall) ?
CatapultState.Stalling : CatapultState.Aiming;
}
break;
case CatapultState.Stalling:
if (stallUpdateCycles-- <= 0)
{
// We've finished stalling, fire the projectile
Fire(ShotVelocity);
postUpdateStateChange = CatapultState.Firing;
}
break;
case CatapultState.Firing:
// Progress Fire animation
if (lastUpdateState != CatapultState.Firing)
{
AudioManager.StopSound("ropeStretch");
AudioManager.PlaySound("catapultFire");
StartFiringFromLastAimPosition();
}
animations["Fire"].Update();
// If in the "split" point of the animation start
// projectile fire sequence
if (animations["Fire"].FrameIndex == splitFrames["Fire"])
{
postUpdateStateChange =
currentState | CatapultState.ProjectileFlying;
projectile.ProjectilePosition =
projectile.ProjectileStartPosition;
}
break;
case CatapultState.Firing | CatapultState.ProjectileFlying:
// Progress Fire animation
animations["Fire"].Update();
// Update projectile velocity & position in flight
projectile.UpdateProjectileFlightData(gameTime, wind,
gravity, out isGroundHit);
if (isGroundHit)
{
// Start hit sequence
postUpdateStateChange = CatapultState.ProjectileHit;
animations["fireMiss"].PlayFromFrameIndex(0);
}
break;
case CatapultState.ProjectileFlying:
// Update projectile velocity & position in flight
projectile.UpdateProjectileFlightData(gameTime, wind,
gravity, out isGroundHit);
if (isGroundHit)
{
// Start hit sequence
postUpdateStateChange = CatapultState.ProjectileHit;
animations["fireMiss"].PlayFromFrameIndex(0);
}
break;
case CatapultState.ProjectileHit:
// Check hit on ground impact
if (!CheckHit())
{
if (lastUpdateState != CatapultState.ProjectileHit)
{
VibrateController.Default.Start(
TimeSpan.FromMilliseconds(100));
// Play hit sound only on a missed hit,
// a direct hit will trigger the explosion sound
AudioManager.PlaySound("boulderHit");
}
// Hit animation finished playing
if (animations["fireMiss"].IsActive == false)
{
postUpdateStateChange = CatapultState.Reset;
}
animations["fireMiss"].Update();
}
else
{
// Catapult hit - start longer vibration on any catapult hit
// Remember that the call to "CheckHit" updates the catapult's
// state to "Hit"
VibrateController.Default.Start(
TimeSpan.FromMilliseconds(500));
}
break;
case CatapultState.HitDamage:
if (animations["hitSmoke"].IsActive == false)
postUpdateStateChange = CatapultState.Reset;
animations["hitSmoke"].Update();
break;
case CatapultState.HitKill:
// Progress hit animation
if ((animations["Destroyed"].IsActive == false) &&
(animations["hitSmoke"].IsActive == false))
{
if (enemy.Score >= winScore)
{
GameOver = true;
break;
}
self.Health = 100;
postUpdateStateChange = CatapultState.Reset;
}
animations["Destroyed"].Update();
animations["hitSmoke"].Update();
break;
case CatapultState.Reset:
AnimationRunning = false;
break;
default:
break;
}
lastUpdateState = currentState;
if (postUpdateStateChange != 0)
{
currentState = postUpdateStateChange;
}
base.Update(gameTime);
}
/// <summary>
/// Used to check if the current aim animation frame represents the shot
/// strength set for the catapult.
/// </summary>
/// <returns>True if the current frame represents the shot strength,
/// false otherwise.</returns>
private bool AimReachedShotStrength()
{
return (animations["Aim"].FrameIndex ==
(Convert.ToInt32(animations["Aim"].FrameCount * ShotStrength) - 1));
}
private void UpdateAimAccordingToShotStrength()
{
var aimAnimation = animations["Aim"];
int frameToDisplay =
Convert.ToInt32(aimAnimation.FrameCount * ShotStrength);
aimAnimation.FrameIndex = frameToDisplay;
}
/// <summary>
/// Calculates the frame from which to start the firing animation,
/// and activates it.
/// </summary>
private void StartFiringFromLastAimPosition()
{
int startFrame = animations["Aim"].FrameCount -
animations["Aim"].FrameIndex;
animations["Fire"].PlayFromFrameIndex(startFrame);
}
public override void Draw(GameTime gameTime)
{
if (gameTime == null)
throw new ArgumentNullException("gameTime");
// Using the last update state makes sure we do not draw
// before updating animations properly
switch (lastUpdateState)
{
case CatapultState.Idle:
DrawIdleCatapult();
break;
case CatapultState.Aiming:
case CatapultState.Stalling:
animations["Aim"].Draw(spriteBatch, catapultPosition,
spriteEffects);
break;
case CatapultState.Firing:
animations["Fire"].Draw(spriteBatch, catapultPosition,
spriteEffects);
break;
case CatapultState.Firing | CatapultState.ProjectileFlying:
case CatapultState.ProjectileFlying:
animations["Fire"].Draw(spriteBatch, catapultPosition,
spriteEffects);
projectile.Draw(gameTime);
break;
case CatapultState.ProjectileHit:
// Draw the catapult
DrawIdleCatapult();
// Projectile Hit animation
animations["fireMiss"].Draw(spriteBatch,
projectile.ProjectileHitPosition, spriteEffects);
break;
case CatapultState.HitDamage:
// Draw the catapult
DrawIdleCatapult();
// Projectile smoke animation
animations["hitSmoke"].Draw(spriteBatch, catapultPosition,
spriteEffects);
break;
case CatapultState.HitKill:
// Catapult hit animation
animations["Destroyed"].Draw(spriteBatch, catapultPosition,
spriteEffects);
// Projectile smoke animation
animations["hitSmoke"].Draw(spriteBatch, catapultPosition,
spriteEffects);
break;
case CatapultState.Reset:
DrawIdleCatapult();
break;
default:
break;
}
base.Draw(gameTime);
}
#endregion
#region Hit
/// <summary>
/// Start Hit sequence on catapult - could be executed on self or from enemy in case of hit
/// </summary>
public void Hit(bool isKilled)
{
AnimationRunning = true;
if (isKilled)
animations["Destroyed"].PlayFromFrameIndex(0);
animations["hitSmoke"].PlayFromFrameIndex(0);
if (isKilled)
currentState = CatapultState.HitKill;
else
currentState = CatapultState.HitDamage;
}
#endregion
public void Fire(float velocity)
{
projectile.Fire(velocity, velocity);
}
#region Helper Functions
/// <summary>
/// Check if projectile hit some catapult. The possibilities are:
/// Nothing hit, Hit enemy, Hit self
/// </summary>
/// <returns></returns>
private bool CheckHit()
{
bool bRes = false;
// Build a sphere around a projectile
Vector3 center = new Vector3(projectile.ProjectilePosition, 0);
BoundingSphere sphere = new BoundingSphere(center,
Math.Max(projectile.ProjectileTexture.Width / 2,
projectile.ProjectileTexture.Height / 2));
// Check Self-Hit - create a bounding box around self
Vector3 min = new Vector3(catapultPosition, 0);
Vector3 max = new Vector3(catapultPosition +
new Vector2(animations["Fire"].FrameSize.X,
animations["Fire"].FrameSize.Y), 0);
BoundingBox selfBox = new BoundingBox(min, max);
// Check enemy - create a bounding box around the enemy
min = new Vector3(enemy.Catapult.Position, 0);
max = new Vector3(enemy.Catapult.Position +
new Vector2(animations["Fire"].FrameSize.X,
animations["Fire"].FrameSize.Y), 0);
BoundingBox enemyBox = new BoundingBox(min, max);
// Check self hit
if (sphere.Intersects(selfBox) && currentState != CatapultState.HitKill)
{
AudioManager.PlaySound("catapultExplosion");
// Launch hit animation sequence on self
UpdateHealth(self, sphere, selfBox);
if (self.Health <= 0)
{
Hit(true);
enemy.Score++;
bRes = true;
}
}
// Check if enemy was hit
else if (sphere.Intersects(enemyBox)
&& enemy.Catapult.CurrentState != CatapultState.HitKill
&& enemy.Catapult.CurrentState != CatapultState.Reset)
{
AudioManager.PlaySound("catapultExplosion");
// Launch enemy hit animaton
UpdateHealth(enemy, sphere, enemyBox);
if (enemy.Health <= 0)
{
enemy.Catapult.Hit(true);
self.Score++;
bRes = true;
}
currentState = CatapultState.Reset;
}
return bRes;
}
/// <summary>
/// Updates the health status of the player based on hit area
/// </summary>
/// <param name="enemy"></param>
private void UpdateHealth(Player player, BoundingSphere projectile, BoundingBox catapult)
{
bool isHit = false;
float midPoint = (catapult.Max.X - catapult.Min.X) / 2;
BoundingBox catapultCenter = new BoundingBox(
new Vector3(catapult.Min.X + midPoint - projectile.Radius, projectile.Center.Y - projectile.Radius, 0),
new Vector3(catapult.Min.X + midPoint + projectile.Radius, projectile.Center.Y + projectile.Radius, 0));
BoundingBox catapultLeft = new BoundingBox(
new Vector3(catapult.Min.X, projectile.Center.Y - projectile.Radius, 0),
new Vector3(catapult.Min.X + midPoint - projectile.Radius, projectile.Center.Y + projectile.Radius, 0));
BoundingBox catapultRight = new BoundingBox(
new Vector3(catapult.Min.X + midPoint + projectile.Radius, projectile.Center.Y - projectile.Radius, 0),
new Vector3(catapult.Max.X, projectile.Center.Y + projectile.Radius, 0));
if (projectile.Intersects(catapultCenter))
{
player.Health -= 75;
isHit = true;
}
else if (projectile.Intersects(catapultLeft))
{
player.Health -= isAI ? 50 : 25;
isHit = true;
}
else if (projectile.Intersects(catapultRight))
{
player.Health -= isAI ? 25 : 50;
isHit = true;
}
if (isHit)
{
player.Catapult.Hit(false);
// Catapult hit - start longer vibration on any catapult hit
VibrateController.Default.Start(
TimeSpan.FromMilliseconds(250));
}
}
/// <summary>
/// Draw catapult in Idle state
/// </summary>
private void DrawIdleCatapult()
{
spriteBatch.Draw(idleTexture, catapultPosition, null, Color.White,
0.0f, Vector2.Zero, 1.0f,
spriteEffects, 0);
}
#endregion
}
}
| |
//
// redis-sharp.cs: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Miguel de Icaza (miguel@gnome.org)
//
// Copyright 2010 Novell, Inc.
//
// Licensed under the same terms of Redis: new BSD license.
//
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using NServiceKit.Text;
namespace NServiceKit.Redis
{
public partial class RedisNativeClient
{
private void Connect()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) {
SendTimeout = SendTimeout
};
try
{
socket.Connect(Host, Port);
if (!socket.Connected)
{
socket.Close();
socket = null;
return;
}
Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);
if (Password != null)
SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
db = 0;
var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
lastCommand = null;
lastSocketException = null;
LastConnectedAtTimestamp = Stopwatch.GetTimestamp();
if (isPreVersion1_26 == null)
{
isPreVersion1_26 = this.ServerVersion.CompareTo("1.2.6") <= 0;
//force version reload
log.DebugFormat("redis-server Version: {0}", isPreVersion1_26);
}
}
catch (SocketException ex)
{
HadExceptions = true;
var throwEx = new InvalidOperationException("could not connect to redis Instance at " + Host + ":" + Port, ex);
log.Error(throwEx.Message, ex);
throw throwEx;
}
}
protected string ReadLine()
{
var sb = new StringBuilder();
int c;
while ((c = Bstream.ReadByte()) != -1)
{
if (c == '\r')
continue;
if (c == '\n')
break;
sb.Append((char)c);
}
return sb.ToString();
}
private bool AssertConnectedSocket()
{
if (LastConnectedAtTimestamp > 0)
{
var now = Stopwatch.GetTimestamp();
var elapsedSecs = (now - LastConnectedAtTimestamp) / Stopwatch.Frequency;
if (elapsedSecs > IdleTimeOutSecs && !socket.IsConnected())
{
return Reconnect();
}
LastConnectedAtTimestamp = now;
}
if (socket == null)
{
var previousDb = db;
Connect();
if (previousDb != DefaultDb) this.Db = previousDb;
}
var isConnected = socket != null;
return isConnected;
}
private bool Reconnect()
{
var previousDb = db;
SafeConnectionClose();
Connect(); //sets db to 0
if (previousDb != DefaultDb) this.Db = previousDb;
return socket != null;
}
private bool HandleSocketException(SocketException ex)
{
HadExceptions = true;
log.Error("SocketException: ", ex);
lastSocketException = ex;
// timeout?
socket.Close();
socket = null;
return false;
}
private RedisResponseException CreateResponseError(string error)
{
HadExceptions = true;
var throwEx = new RedisResponseException(
string.Format("{0}, sPort: {1}, LastCommand: {2}",
error, clientPort, lastCommand));
log.Error(throwEx.Message);
throw throwEx;
}
private Exception CreateConnectionError()
{
HadExceptions = true;
var throwEx = new Exception(
string.Format("Unable to Connect: sPort: {0}",
clientPort), lastSocketException);
log.Error(throwEx.Message);
throw throwEx;
}
private static byte[] GetCmdBytes(char cmdPrefix, int noOfLines)
{
var strLines = noOfLines.ToString();
var strLinesLength = strLines.Length;
var cmdBytes = new byte[1 + strLinesLength + 2];
cmdBytes[0] = (byte)cmdPrefix;
for (var i = 0; i < strLinesLength; i++)
cmdBytes[i + 1] = (byte)strLines[i];
cmdBytes[1 + strLinesLength] = 0x0D; // \r
cmdBytes[2 + strLinesLength] = 0x0A; // \n
return cmdBytes;
}
/// <summary>
/// Command to set multuple binary safe arguments
/// </summary>
/// <param name="cmdWithBinaryArgs"></param>
/// <returns></returns>
protected bool SendCommand(params byte[][] cmdWithBinaryArgs)
{
if (!AssertConnectedSocket()) return false;
try
{
CmdLog(cmdWithBinaryArgs);
//Total command lines count
WriteAllToSendBuffer(cmdWithBinaryArgs);
FlushSendBuffer();
}
catch (SocketException ex)
{
cmdBufferIndex = 0;
return HandleSocketException(ex);
}
return true;
}
public void WriteAllToSendBuffer(params byte[][] cmdWithBinaryArgs)
{
WriteToSendBuffer(GetCmdBytes('*', cmdWithBinaryArgs.Length));
foreach (var safeBinaryValue in cmdWithBinaryArgs)
{
WriteToSendBuffer(GetCmdBytes('$', safeBinaryValue.Length));
WriteToSendBuffer(safeBinaryValue);
WriteToSendBuffer(endData);
}
}
byte[] cmdBuffer = new byte[32 * 1024];
int cmdBufferIndex = 0;
public void WriteToSendBuffer(byte[] cmdBytes)
{
if ((cmdBufferIndex + cmdBytes.Length) > cmdBuffer.Length)
{
const int breathingSpaceToReduceReallocations = (32 * 1024);
var newLargerBuffer = new byte[cmdBufferIndex + cmdBytes.Length + breathingSpaceToReduceReallocations];
Buffer.BlockCopy(cmdBuffer, 0, newLargerBuffer, 0, cmdBuffer.Length);
cmdBuffer = newLargerBuffer;
}
Buffer.BlockCopy(cmdBytes, 0, cmdBuffer, cmdBufferIndex, cmdBytes.Length);
cmdBufferIndex += cmdBytes.Length;
}
public void FlushSendBuffer()
{
socket.Send(cmdBuffer, cmdBufferIndex, SocketFlags.None);
cmdBufferIndex = 0;
}
private int SafeReadByte()
{
return Bstream.ReadByte();
}
private void SendExpectSuccess(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (this.CurrentTransaction != null)
{
this.CurrentTransaction.CompleteVoidQueuedCommand(ExpectSuccess);
ExpectQueued();
return;
}
ExpectSuccess();
}
private int SendExpectInt(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (this.CurrentTransaction != null)
{
this.CurrentTransaction.CompleteIntQueuedCommand(ReadInt);
ExpectQueued();
return default(int);
}
return ReadInt();
}
private byte[] SendExpectData(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (this.CurrentTransaction != null)
{
this.CurrentTransaction.CompleteBytesQueuedCommand(ReadData);
ExpectQueued();
return null;
}
return ReadData();
}
private string SendExpectString(params byte[][] cmdWithBinaryArgs)
{
var bytes = SendExpectData(cmdWithBinaryArgs);
return bytes.FromUtf8Bytes();
}
private double SendExpectDouble(params byte[][] cmdWithBinaryArgs)
{
return parseDouble( SendExpectData(cmdWithBinaryArgs) );
}
private double parseDouble(byte[] doubleBytes)
{
var doubleString = Encoding.UTF8.GetString(doubleBytes);
double d;
double.TryParse(doubleString, out d);
return d;
}
private string SendExpectCode(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (this.CurrentTransaction != null)
{
this.CurrentTransaction.CompleteBytesQueuedCommand(ReadData);
ExpectQueued();
return null;
}
return ExpectCode();
}
private byte[][] SendExpectMultiData(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (this.CurrentTransaction != null)
{
this.CurrentTransaction.CompleteMultiBytesQueuedCommand(ReadMultiData);
ExpectQueued();
return new byte[0][];
}
return ReadMultiData();
}
[Conditional("DEBUG")]
protected void Log(string fmt, params object[] args)
{
log.DebugFormat("{0}", string.Format(fmt, args).Trim());
}
[Conditional("DEBUG")]
protected void CmdLog(byte[][] args)
{
var sb = new StringBuilder();
foreach (var arg in args)
{
if (sb.Length > 0)
sb.Append(" ");
sb.Append(arg.FromUtf8Bytes());
}
this.lastCommand = sb.ToString();
if (this.lastCommand.Length > 100)
{
this.lastCommand = this.lastCommand.Substring(0, 100) + "...";
}
log.Debug("S: " + this.lastCommand);
}
protected void ExpectSuccess()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log((char)c + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") && s.Length >= 4 ? s.Substring(4) : s);
}
private void ExpectWord(string word)
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log((char)c + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (s != word)
throw CreateResponseError(string.Format("Expected '{0}' got '{1}'", word, s));
}
private string ExpectCode()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log((char)c + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
return s;
}
protected void ExpectOk()
{
ExpectWord("OK");
}
protected void ExpectQueued()
{
ExpectWord("QUEUED");
}
public int ReadInt()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == ':' || c == '$')//really strange why ZRANK needs the '$' here
{
int i;
if (int.TryParse(s, out i))
return i;
}
throw CreateResponseError("Unknown reply on integer response: " + c + s);
}
private byte[] ReadData()
{
string r = ReadLine();
Log("R: {0}", r);
if (r.Length == 0)
throw CreateResponseError("Zero length respose");
char c = r[0];
if (c == '-')
throw CreateResponseError(r.StartsWith("-ERR") ? r.Substring(5) : r.Substring(1));
if (c == '$')
{
if (r == "$-1")
return null;
int count;
if (Int32.TryParse(r.Substring(1), out count))
{
var retbuf = new byte[count];
var offset = 0;
while (count > 0)
{
var readCount = Bstream.Read(retbuf, offset, count);
if (readCount <= 0)
throw CreateResponseError("Unexpected end of Stream");
offset += readCount;
count -= readCount;
}
if (Bstream.ReadByte() != '\r' || Bstream.ReadByte() != '\n')
throw CreateResponseError("Invalid termination");
return retbuf;
}
throw CreateResponseError("Invalid length");
}
if (c == ':')
{
//match the return value
return r.Substring(1).ToUtf8Bytes();
}
throw CreateResponseError("Unexpected reply: " + r);
}
private byte[][] ReadMultiData()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == '*')
{
int count;
if (int.TryParse(s, out count))
{
if (count == -1)
{
//redis is in an invalid state
return new byte[0][];
}
var result = new byte[count][];
for (int i = 0; i < count; i++)
result[i] = ReadData();
return result;
}
}
throw CreateResponseError("Unknown reply on multi-request: " + c + s);
}
private int ReadMultiDataResultCount()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == '*')
{
int count;
if (int.TryParse(s, out count))
{
return count;
}
}
throw CreateResponseError("Unknown reply on multi-request: " + c + s);
}
private static void AssertListIdAndValue(string listId, byte[] value)
{
if (listId == null)
throw new ArgumentNullException("listId");
if (value == null)
throw new ArgumentNullException("value");
}
private static byte[][] MergeCommandWithKeysAndValues(byte[] cmd, byte[][] keys, byte[][] values)
{
var firstParams = new[] { cmd };
return MergeCommandWithKeysAndValues(firstParams, keys, values);
}
private static byte[][] MergeCommandWithKeysAndValues(byte[] cmd, byte[] firstArg, byte[][] keys, byte[][] values)
{
var firstParams = new[] { cmd, firstArg };
return MergeCommandWithKeysAndValues(firstParams, keys, values);
}
private static byte[][] MergeCommandWithKeysAndValues(byte[][] firstParams,
byte[][] keys, byte[][] values)
{
if (keys == null || keys.Length == 0)
throw new ArgumentNullException("keys");
if (values == null || values.Length == 0)
throw new ArgumentNullException("values");
if (keys.Length != values.Length)
throw new ArgumentException("The number of values must be equal to the number of keys");
var keyValueStartIndex = (firstParams != null) ? firstParams.Length : 0;
var keysAndValuesLength = keys.Length * 2 + keyValueStartIndex;
var keysAndValues = new byte[keysAndValuesLength][];
for (var i = 0; i < keyValueStartIndex; i++)
{
keysAndValues[i] = firstParams[i];
}
var j = 0;
for (var i = keyValueStartIndex; i < keysAndValuesLength; i += 2)
{
keysAndValues[i] = keys[j];
keysAndValues[i + 1] = values[j];
j++;
}
return keysAndValues;
}
private static byte[][] MergeCommandWithArgs(byte[] cmd, params string[] args)
{
var mergedBytes = new byte[1 + args.Length][];
mergedBytes[0] = cmd;
for (var i = 0; i < args.Length; i++)
{
mergedBytes[i + 1] = args[i].ToUtf8Bytes();
}
return mergedBytes;
}
private static byte[][] MergeCommandWithArgs(byte[] cmd, byte[] firstArg, params byte[][] args)
{
var mergedBytes = new byte[2 + args.Length][];
mergedBytes[0] = cmd;
mergedBytes[1] = firstArg;
for (var i = 0; i < args.Length; i++)
{
mergedBytes[i + 2] = args[i];
}
return mergedBytes;
}
protected byte[][] ConvertToBytes(string[] keys)
{
var keyBytes = new byte[keys.Length][];
for (var i = 0; i < keys.Length; i++)
{
var key = keys[i];
keyBytes[i] = key != null ? key.ToUtf8Bytes() : new byte[0];
}
return keyBytes;
}
}
}
| |
// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using Lucene.Net.Diagnostics;
using Lucene.Net.Util;
using Lucene.Net.Util.Fst;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Lucene.Net.Analysis.CharFilters
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Simplistic <see cref="CharFilter"/> that applies the mappings
/// contained in a <see cref="NormalizeCharMap"/> to the character
/// stream, and correcting the resulting changes to the
/// offsets. Matching is greedy (longest pattern matching at
/// a given point wins). Replacement is allowed to be the
/// empty string.
/// </summary>
public class MappingCharFilter : BaseCharFilter
{
private readonly Outputs<CharsRef> outputs = CharSequenceOutputs.Singleton;
private readonly FST<CharsRef> map;
private readonly FST.BytesReader fstReader;
private readonly RollingCharBuffer buffer = new RollingCharBuffer();
private readonly FST.Arc<CharsRef> scratchArc = new FST.Arc<CharsRef>();
private readonly IDictionary<char?, FST.Arc<CharsRef>> cachedRootArcs;
private CharsRef replacement;
private int replacementPointer;
private int inputOff;
/// <summary>
/// LUCENENET specific support to buffer the reader.
/// </summary>
private readonly BufferedCharFilter _input;
/// <summary>
/// Default constructor that takes a <see cref="TextReader"/>. </summary>
public MappingCharFilter(NormalizeCharMap normMap, TextReader @in)
: base(@in)
{
//LUCENENET support to reset the reader.
_input = GetBufferedReader(@in);
_input.Mark(BufferedCharFilter.DEFAULT_CHAR_BUFFER_SIZE);
buffer.Reset(_input);
//buffer.Reset(@in);
map = normMap.map;
cachedRootArcs = normMap.cachedRootArcs;
if (map != null)
{
fstReader = map.GetBytesReader();
}
else
{
fstReader = null;
}
}
/// <summary>
/// LUCENENET: Copied this method from the <see cref="WordlistLoader"/> class - this class requires readers
/// with a Reset() method (which .NET readers don't support). So, we use the <see cref="BufferedCharFilter"/>
/// (which is similar to Java BufferedReader) as a wrapper for whatever reader the user passes
/// (unless it is already a <see cref="BufferedCharFilter"/>).
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static BufferedCharFilter GetBufferedReader(TextReader reader)
{
return (reader is BufferedCharFilter) ? (BufferedCharFilter)reader : new BufferedCharFilter(reader);
}
public override void Reset()
{
// LUCENENET: reset the BufferedCharFilter.
_input.Reset();
buffer.Reset(_input);
replacement = null;
inputOff = 0;
}
public override int Read()
{
//System.out.println("\nread");
while (true)
{
if (replacement != null && replacementPointer < replacement.Length)
{
//System.out.println(" return repl[" + replacementPointer + "]=" + replacement.chars[replacement.offset + replacementPointer]);
return replacement.Chars[replacement.Offset + replacementPointer++];
}
// TODO: a more efficient approach would be Aho/Corasick's
// algorithm
// (http://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_string_matching_algorithm)
// or this generalizatio: www.cis.uni-muenchen.de/people/Schulz/Pub/dictle5.ps
//
// I think this would be (almost?) equivalent to 1) adding
// epsilon arcs from all final nodes back to the init
// node in the FST, 2) adding a .* (skip any char)
// loop on the initial node, and 3) determinizing
// that. Then we would not have to Restart matching
// at each position.
int lastMatchLen = -1;
CharsRef lastMatch = null;
int firstCH = buffer.Get(inputOff);
if (firstCH != -1)
{
// LUCENENET fix: Check the dictionary to ensure it contains a key before reading it.
char key = Convert.ToChar((char)firstCH);
if (cachedRootArcs.TryGetValue(key, out FST.Arc<CharsRef> arc) && arc != null)
{
if (!FST.TargetHasArcs(arc))
{
// Fast pass for single character match:
if (Debugging.AssertsEnabled) Debugging.Assert(arc.IsFinal);
lastMatchLen = 1;
lastMatch = arc.Output;
}
else
{
int lookahead = 0;
CharsRef output = arc.Output;
while (true)
{
lookahead++;
if (arc.IsFinal)
{
// Match! (to node is final)
lastMatchLen = lookahead;
lastMatch = outputs.Add(output, arc.NextFinalOutput);
// Greedy: keep searching to see if there's a
// longer match...
}
if (!FST.TargetHasArcs(arc))
{
break;
}
int ch = buffer.Get(inputOff + lookahead);
if (ch == -1)
{
break;
}
if ((arc = map.FindTargetArc(ch, arc, scratchArc, fstReader)) == null)
{
// Dead end
break;
}
output = outputs.Add(output, arc.Output);
}
}
}
}
if (lastMatch != null)
{
inputOff += lastMatchLen;
//System.out.println(" match! len=" + lastMatchLen + " repl=" + lastMatch);
int diff = lastMatchLen - lastMatch.Length;
if (diff != 0)
{
int prevCumulativeDiff = LastCumulativeDiff;
if (diff > 0)
{
// Replacement is shorter than matched input:
AddOffCorrectMap(inputOff - diff - prevCumulativeDiff, prevCumulativeDiff + diff);
}
else
{
// Replacement is longer than matched input: remap
// the "extra" chars all back to the same input
// offset:
int outputStart = inputOff - prevCumulativeDiff;
for (int extraIDX = 0; extraIDX < -diff; extraIDX++)
{
AddOffCorrectMap(outputStart + extraIDX, prevCumulativeDiff - extraIDX - 1);
}
}
}
replacement = lastMatch;
replacementPointer = 0;
}
else
{
int ret = buffer.Get(inputOff);
if (ret != -1)
{
inputOff++;
buffer.FreeBefore(inputOff);
}
return ret;
}
}
}
public override int Read(char[] cbuf, int off, int len)
{
int numRead = 0;
for (int i = off; i < off + len; i++)
{
int c = Read();
if (c == -1)
{
break;
}
cbuf[i] = (char)c;
numRead++;
}
return numRead == 0 ? -1 : numRead;
}
}
}
| |
using UnityEngine;
using Pathfinding.Serialization;
namespace Pathfinding {
/** Base class for GridNode and LevelGridNode */
public abstract class GridNodeBase : GraphNode {
protected GridNodeBase (AstarPath astar) : base(astar) {
}
const int GridFlagsWalkableErosionOffset = 8;
const int GridFlagsWalkableErosionMask = 1 << GridFlagsWalkableErosionOffset;
const int GridFlagsWalkableTmpOffset = 9;
const int GridFlagsWalkableTmpMask = 1 << GridFlagsWalkableTmpOffset;
protected const int NodeInGridIndexLayerOffset = 24;
protected const int NodeInGridIndexMask = 0xFFFFFF;
/** Bitfield containing the x and z coordinates of the node as well as the layer (for layered grid graphs).
* \see NodeInGridIndex
*/
protected int nodeInGridIndex;
protected ushort gridFlags;
#if !ASTAR_GRID_NO_CUSTOM_CONNECTIONS
public Connection[] connections;
#endif
/** The index of the node in the grid.
* This is x + z*graph.width
* So you can get the X and Z indices using
* \code
* int index = node.NodeInGridIndex;
* int x = index % graph.width;
* int z = index / graph.width;
* // where graph is GridNode.GetGridGraph (node.graphIndex), i.e the graph the nodes are contained in.
* \endcode
*/
public int NodeInGridIndex { get { return nodeInGridIndex & NodeInGridIndexMask; } set { nodeInGridIndex = (nodeInGridIndex & ~NodeInGridIndexMask) | value; } }
/** X coordinate of the node in the grid.
* The node in the bottom left corner has (x,z) = (0,0) and the one in the opposite
* corner has (x,z) = (width-1, depth-1)
* \see ZCoordInGrid
* \see NodeInGridIndex
*/
public int XCoordinateInGrid {
get {
return NodeInGridIndex % GridNode.GetGridGraph(GraphIndex).width;
}
}
/** Z coordinate of the node in the grid.
* The node in the bottom left corner has (x,z) = (0,0) and the one in the opposite
* corner has (x,z) = (width-1, depth-1)
* \see XCoordInGrid
* \see NodeInGridIndex
*/
public int ZCoordinateInGrid {
get {
return NodeInGridIndex / GridNode.GetGridGraph(GraphIndex).width;
}
}
/** Stores walkability before erosion is applied.
* Used internally when updating the graph.
*/
public bool WalkableErosion {
get {
return (gridFlags & GridFlagsWalkableErosionMask) != 0;
}
set {
unchecked { gridFlags = (ushort)(gridFlags & ~GridFlagsWalkableErosionMask | (value ? (ushort)GridFlagsWalkableErosionMask : (ushort)0)); }
}
}
/** Temporary variable used internally when updating the graph. */
public bool TmpWalkable {
get {
return (gridFlags & GridFlagsWalkableTmpMask) != 0;
}
set {
unchecked { gridFlags = (ushort)(gridFlags & ~GridFlagsWalkableTmpMask | (value ? (ushort)GridFlagsWalkableTmpMask : (ushort)0)); }
}
}
/** True if the node has grid connections to all its 8 neighbours.
* \note This will always return false if GridGraph.neighbours is set to anything other than Eight.
* \see GetNeighbourAlongDirection
*/
public abstract bool HasConnectionsToAllEightNeighbours { get; }
public override float SurfaceArea () {
GridGraph gg = GridNode.GetGridGraph(GraphIndex);
return gg.nodeSize*gg.nodeSize;
}
public override Vector3 RandomPointOnSurface () {
GridGraph gg = GridNode.GetGridGraph(GraphIndex);
var graphSpacePosition = gg.transform.InverseTransform((Vector3)position);
return gg.transform.Transform(graphSpacePosition + new Vector3(Random.value - 0.5f, 0, Random.value - 0.5f));
}
public override int GetGizmoHashCode () {
var hash = base.GetGizmoHashCode();
#if !ASTAR_GRID_NO_CUSTOM_CONNECTIONS
if (connections != null) {
for (int i = 0; i < connections.Length; i++) {
hash ^= 17 * connections[i].GetHashCode();
}
}
#endif
hash ^= 109 * gridFlags;
return hash;
}
/** Adjacent grid node in the specified direction.
* This will return null if the node does not have a connection to a node
* in that direction.
*
* The dir parameter corresponds to directions in the grid as:
* \code
* Z
* |
* |
*
* 6 2 5
* \ | /
* -- 3 - X - 1 ----- X
* / | \
* 7 0 4
*
* |
* |
* \endcode
*
* \see GetConnections
*/
public abstract GridNodeBase GetNeighbourAlongDirection (int direction);
public override bool ContainsConnection (GraphNode node) {
#if !ASTAR_GRID_NO_CUSTOM_CONNECTIONS
if (connections != null) {
for (int i = 0; i < connections.Length; i++) {
if (connections[i].node == node) {
return true;
}
}
}
#endif
for (int i = 0; i < 8; i++) {
if (node == GetNeighbourAlongDirection(i)) {
return true;
}
}
return false;
}
#if ASTAR_GRID_NO_CUSTOM_CONNECTIONS
public override void AddConnection (GraphNode node, uint cost) {
throw new System.NotImplementedException("GridNodes do not have support for adding manual connections with your current settings."+
"\nPlease disable ASTAR_GRID_NO_CUSTOM_CONNECTIONS in the Optimizations tab in the A* Inspector");
}
public override void RemoveConnection (GraphNode node) {
throw new System.NotImplementedException("GridNodes do not have support for adding manual connections with your current settings."+
"\nPlease disable ASTAR_GRID_NO_CUSTOM_CONNECTIONS in the Optimizations tab in the A* Inspector");
}
#else
public override void FloodFill (System.Collections.Generic.Stack<GraphNode> stack, uint region) {
if (connections != null) for (int i = 0; i < connections.Length; i++) {
GraphNode other = connections[i].node;
if (other.Area != region) {
other.Area = region;
stack.Push(other);
}
}
}
public override void ClearConnections (bool alsoReverse) {
if (alsoReverse) {
if (connections != null) for (int i = 0; i < connections.Length; i++) connections[i].node.RemoveConnection(this);
}
connections = null;
}
public override void GetConnections (System.Action<GraphNode> action) {
if (connections != null) for (int i = 0; i < connections.Length; i++) action(connections[i].node);
}
public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
ushort pid = handler.PathID;
if (connections != null) for (int i = 0; i < connections.Length; i++) {
GraphNode other = connections[i].node;
PathNode otherPN = handler.GetPathNode(other);
if (otherPN.parent == pathNode && otherPN.pathID == pid) other.UpdateRecursiveG(path, otherPN, handler);
}
}
public override void Open (Path path, PathNode pathNode, PathHandler handler) {
ushort pid = handler.PathID;
if (connections != null) for (int i = 0; i < connections.Length; i++) {
GraphNode other = connections[i].node;
if (!path.CanTraverse(other)) continue;
PathNode otherPN = handler.GetPathNode(other);
uint tmpCost = connections[i].cost;
if (otherPN.pathID != pid) {
otherPN.parent = pathNode;
otherPN.pathID = pid;
otherPN.cost = tmpCost;
otherPN.H = path.CalculateHScore(other);
other.UpdateG(path, otherPN);
//Debug.Log ("G " + otherPN.G + " F " + otherPN.F);
handler.heap.Add(otherPN);
//Debug.DrawRay ((Vector3)otherPN.node.Position, Vector3.up,Color.blue);
} else {
// Sorry for the huge number of #ifs
//If not we can test if the path from the current node to this one is a better one then the one already used
#if ASTAR_NO_TRAVERSAL_COST
if (pathNode.G+tmpCost < otherPN.G)
#else
if (pathNode.G+tmpCost+path.GetTraversalCost(other) < otherPN.G)
#endif
{
//Debug.Log ("Path better from " + NodeIndex + " to " + otherPN.node.NodeIndex + " " + (pathNode.G+tmpCost+path.GetTraversalCost(other)) + " < " + otherPN.G);
otherPN.cost = tmpCost;
otherPN.parent = pathNode;
other.UpdateRecursiveG(path, otherPN, handler);
//Or if the path from this node ("other") to the current ("current") is better
}
#if ASTAR_NO_TRAVERSAL_COST
else if (otherPN.G+tmpCost < pathNode.G && other.ContainsConnection(this))
#else
else if (otherPN.G+tmpCost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection(this))
#endif
{
//Debug.Log ("Path better from " + otherPN.node.NodeIndex + " to " + NodeIndex + " " + (otherPN.G+tmpCost+path.GetTraversalCost (this)) + " < " + pathNode.G);
pathNode.parent = otherPN;
pathNode.cost = tmpCost;
UpdateRecursiveG(path, pathNode, handler);
}
}
}
}
/** Add a connection from this node to the specified node.
* If the connection already exists, the cost will simply be updated and
* no extra connection added.
*
* \note Only adds a one-way connection. Consider calling the same function on the other node
* to get a two-way connection.
*/
public override void AddConnection (GraphNode node, uint cost) {
if (node == null) throw new System.ArgumentNullException();
if (connections != null) {
for (int i = 0; i < connections.Length; i++) {
if (connections[i].node == node) {
connections[i].cost = cost;
return;
}
}
}
int connLength = connections != null ? connections.Length : 0;
var newconns = new Connection[connLength+1];
for (int i = 0; i < connLength; i++) {
newconns[i] = connections[i];
}
newconns[connLength] = new Connection {
node = node,
cost = cost
};
connections = newconns;
}
/** Removes any connection from this node to the specified node.
* If no such connection exists, nothing will be done.
*
* \note This only removes the connection from this node to the other node.
* You may want to call the same function on the other node to remove its eventual connection
* to this node.
*/
public override void RemoveConnection (GraphNode node) {
if (connections == null) return;
for (int i = 0; i < connections.Length; i++) {
if (connections[i].node == node) {
int connLength = connections.Length;
var newconns = new Connection[connLength-1];
for (int j = 0; j < i; j++) {
newconns[j] = connections[j];
}
for (int j = i+1; j < connLength; j++) {
newconns[j-1] = connections[j];
}
connections = newconns;
return;
}
}
}
public override void SerializeReferences (GraphSerializationContext ctx) {
// TODO: Deduplicate code
if (connections == null) {
ctx.writer.Write(-1);
} else {
ctx.writer.Write(connections.Length);
for (int i = 0; i < connections.Length; i++) {
ctx.SerializeNodeReference(connections[i].node);
ctx.writer.Write(connections[i].cost);
}
}
}
/** Cached to avoid allocations */
static readonly System.Version VERSION_3_8_3 = new System.Version(3, 8, 3);
public override void DeserializeReferences (GraphSerializationContext ctx) {
// Grid nodes didn't serialize references before 3.8.3
if (ctx.meta.version < VERSION_3_8_3)
return;
int count = ctx.reader.ReadInt32();
if (count == -1) {
connections = null;
} else {
connections = new Connection[count];
for (int i = 0; i < count; i++) {
connections[i] = new Connection {
node = ctx.DeserializeNodeReference(),
cost = ctx.reader.ReadUInt32()
};
}
}
}
#endif
}
}
| |
using System;
using System.Threading.Tasks;
using MonoTouch.Dialog;
using Foundation;
using MediaPlayer;
using UIKit;
using Xamarin.Media;
namespace MediaPickerSample
{
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
readonly MediaPicker mediaPicker = new MediaPicker();
readonly TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
private MediaPickerController mediaPickerController;
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
pickPhoto = new StringElement ("Pick Photo");
pickPhoto.Tapped += () => {
mediaPickerController = mediaPicker.GetPickPhotoUI();
dialogController.PresentViewController (mediaPickerController, true, null);
mediaPickerController.GetResultAsync().ContinueWith (t => {
// We need to dismiss the controller ourselves
dialogController.DismissViewController (true, () => {
// User canceled or something went wrong
if (t.IsCanceled || t.IsFaulted)
return;
// We get back a MediaFile
MediaFile media = t.Result;
ShowPhoto (media);
});
}, uiScheduler); // Make sure we use the UI thread to show our photo.
};
takePhoto = new StringElement ("Take Photo");
takePhoto.Tapped += () => {
// Make sure we actually have a camera
if (!mediaPicker.IsCameraAvailable) {
ShowUnsupported();
return;
}
// When capturing new media, we can specify it's name and location
mediaPickerController = mediaPicker.GetTakePhotoUI (new StoreCameraMediaOptions {
Name = "test.jpg",
Directory = "MediaPickerSample"
});
dialogController.PresentViewController (mediaPickerController, true, null);
mediaPickerController.GetResultAsync().ContinueWith (t => {
// We need to dismiss the controller ourselves
dialogController.DismissViewController (true, () => {
// User canceled or something went wrong
if (t.IsCanceled || t.IsFaulted)
return;
// We get back a MediaFile
MediaFile media = t.Result;
ShowPhoto (media);
});
}, uiScheduler); // Make sure we use the UI thread to show our photo.
};
takeVideo = new StringElement ("Take Video");
takeVideo.Tapped += () => {
// Make sure video is supported and a camera is available
if (!mediaPicker.VideosSupported || !mediaPicker.IsCameraAvailable) {
ShowUnsupported();
return;
}
// When capturing video, we can hint at the desired quality and length.
// DesiredLength is only a hint, however, and the resulting video may
// be longer than desired.
mediaPickerController = mediaPicker.GetTakeVideoUI (new StoreVideoOptions {
Quality = VideoQuality.Medium,
DesiredLength = TimeSpan.FromSeconds (10),
Directory = "MediaPickerSample",
Name = "test.mp4"
});
dialogController.PresentViewController (mediaPickerController, true, null);
mediaPickerController.GetResultAsync().ContinueWith (t => {
// We need to dismiss the controller ourselves
dialogController.DismissViewController (true, () => {
// User canceled or something went wrong
if (t.IsCanceled || t.IsFaulted)
return;
// We get back a MediaFile
MediaFile media = t.Result;
ShowVideo (media);
});
}, uiScheduler); // Make sure we use the UI thread to show our video.
};
pickVideo = new StringElement ("Pick Video");
pickVideo.Tapped += () => {
if (!mediaPicker.VideosSupported) {
ShowUnsupported();
return;
}
mediaPickerController = mediaPicker.GetPickVideoUI();
dialogController.PresentViewController (mediaPickerController, true, null);
mediaPickerController.GetResultAsync().ContinueWith (t => {
// We need to dismiss the controller ourselves
dialogController.DismissViewController (true, () => {
// User canceled or something went wrong
if (t.IsCanceled || t.IsFaulted)
return;
// We get back a MediaFile
MediaFile media = t.Result;
ShowVideo (media);
});
}, uiScheduler); // Make sure we use the UI thread to show our video.
};
var root = new RootElement("Xamarin.Media Sample") {
new Section ("Picking media") { pickPhoto, pickVideo },
new Section ("Capturing media") { takePhoto, takeVideo }
};
dialogController = new DisposingMediaViewController (root);
viewController = new UINavigationController (dialogController);
window = new UIWindow (UIScreen.MainScreen.Bounds);
window.RootViewController = viewController;
window.MakeKeyAndVisible ();
return true;
}
private void ShowVideo (MediaFile media)
{
dialogController.Media = media;
moviePlayerView = new MPMoviePlayerViewController (NSUrl.FromFilename (media.Path));
viewController.PresentMoviePlayerViewController (moviePlayerView);
}
private void ShowPhoto (MediaFile media)
{
dialogController.Media = media;
image = new UIImageView (dialogController.View.Bounds);
image.ContentMode = UIViewContentMode.ScaleAspectFit;
image.Image = UIImage.FromFile (media.Path);
mediaController = new UIViewController();
mediaController.View.AddSubview (image);
mediaController.NavigationItem.LeftBarButtonItem =
new UIBarButtonItem (UIBarButtonSystemItem.Done, (s, e) => viewController.PopViewController (true));
viewController.PushViewController (mediaController, true);
}
private class DisposingMediaViewController : DialogViewController
{
public DisposingMediaViewController (RootElement root)
: base (root)
{
}
public MediaFile Media
{
get;
set;
}
public override void ViewDidAppear (bool animated)
{
// When we're done viewing the media, we should clean it up
if (Media != null) {
Media.Dispose();
Media = null;
}
base.ViewDidAppear (animated);
}
}
private UIAlertView errorAlert;
private void ShowUnsupported()
{
if (this.errorAlert != null)
this.errorAlert.Dispose();
this.errorAlert = new UIAlertView ("Device unsupported", "Your device does not support this feature",
new UIAlertViewDelegate(), "OK");
this.errorAlert.Show();
}
MPMoviePlayerController moviePlayer;
MPMoviePlayerViewController moviePlayerView;
UIViewController mediaController;
UIImageView image;
UIWindow window;
UINavigationController viewController;
DisposingMediaViewController dialogController;
StringElement pickPhoto, pickVideo, takePhoto, takeVideo;
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.Securities
{
/// <summary>
/// Represents the market hours under normal conditions for an exchange and a specific day of the week in terms of local time
/// </summary>
public class LocalMarketHours
{
private readonly bool _hasPreMarket;
private readonly bool _hasPostMarket;
private readonly MarketHoursSegment[] _segments;
/// <summary>
/// Gets whether or not this exchange is closed all day
/// </summary>
public bool IsClosedAllDay { get; }
/// <summary>
/// Gets whether or not this exchange is closed all day
/// </summary>
public bool IsOpenAllDay { get; }
/// <summary>
/// Gets the day of week these hours apply to
/// </summary>
public DayOfWeek DayOfWeek { get; }
/// <summary>
/// Gets the tradable time during the market day.
/// For a normal US equity trading day this is 6.5 hours.
/// This does NOT account for extended market hours and only
/// considers <see cref="MarketHoursState.Market"/>
/// </summary>
public TimeSpan MarketDuration { get; }
/// <summary>
/// Gets the individual market hours segments that define the hours of operation for this day
/// </summary>
public IEnumerable<MarketHoursSegment> Segments => _segments;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMarketHours"/> class
/// </summary>
/// <param name="day">The day of the week these hours are applicable</param>
/// <param name="segments">The open/close segments defining the market hours for one day</param>
public LocalMarketHours(DayOfWeek day, params MarketHoursSegment[] segments)
: this(day, (IEnumerable<MarketHoursSegment>) segments)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LocalMarketHours"/> class
/// </summary>
/// <param name="day">The day of the week these hours are applicable</param>
/// <param name="segments">The open/close segments defining the market hours for one day</param>
public LocalMarketHours(DayOfWeek day, IEnumerable<MarketHoursSegment> segments)
{
DayOfWeek = day;
// filter out the closed states, we'll assume closed if no segment exists
_segments = (segments ?? Enumerable.Empty<MarketHoursSegment>()).Where(x => x.State != MarketHoursState.Closed).ToArray();
IsClosedAllDay = _segments.Length == 0;
IsOpenAllDay = _segments.Length == 1
&& _segments[0].Start == TimeSpan.Zero
&& _segments[0].End == Time.OneDay
&& _segments[0].State == MarketHoursState.Market;
foreach (var segment in _segments)
{
if (segment.State == MarketHoursState.PreMarket)
{
_hasPreMarket = true;
}
if (segment.State == MarketHoursState.PostMarket)
{
_hasPostMarket = true;
}
if (segment.State == MarketHoursState.Market)
{
MarketDuration += segment.End - segment.Start;
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="LocalMarketHours"/> class from the specified open/close times
/// </summary>
/// <param name="day">The day of week these hours apply to</param>
/// <param name="extendedMarketOpen">The extended market open time</param>
/// <param name="marketOpen">The regular market open time, must be greater than or equal to the extended market open time</param>
/// <param name="marketClose">The regular market close time, must be greater than the regular market open time</param>
/// <param name="extendedMarketClose">The extended market close time, must be greater than or equal to the regular market close time</param>
public LocalMarketHours(DayOfWeek day, TimeSpan extendedMarketOpen, TimeSpan marketOpen, TimeSpan marketClose, TimeSpan extendedMarketClose)
: this(day, MarketHoursSegment.GetMarketHoursSegments(extendedMarketOpen, marketOpen, marketClose, extendedMarketClose))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LocalMarketHours"/> class from the specified open/close times
/// using the market open as the extended market open and the market close as the extended market close, effectively
/// removing any 'extended' session from these exchange hours
/// </summary>
/// <param name="day">The day of week these hours apply to</param>
/// <param name="marketOpen">The regular market open time</param>
/// <param name="marketClose">The regular market close time, must be greater than the regular market open time</param>
public LocalMarketHours(DayOfWeek day, TimeSpan marketOpen, TimeSpan marketClose)
: this(day, marketOpen, marketOpen, marketClose, marketClose)
{
}
/// <summary>
/// Gets the market opening time of day
/// </summary>
/// <param name="time">The reference time, the open returned will be the first open after the specified time if there are multiple market open segments</param>
/// <param name="extendedMarket">True to include extended market hours, false for regular market hours</param>
/// <returns>The market's opening time of day</returns>
public TimeSpan? GetMarketOpen(TimeSpan time, bool extendedMarket)
{
foreach (var segment in _segments)
{
if (segment.State == MarketHoursState.Closed || segment.End <= time)
{
continue;
}
if (extendedMarket && _hasPreMarket)
{
if (segment.State == MarketHoursState.PreMarket)
{
return segment.Start;
}
}
else if (segment.State == MarketHoursState.Market)
{
return segment.Start;
}
}
// we couldn't locate an open segment after the specified time
return null;
}
/// <summary>
/// Gets the market closing time of day
/// </summary>
/// <param name="time">The reference time, the close returned will be the first close after the specified time if there are multiple market open segments</param>
/// <param name="extendedMarket">True to include extended market hours, false for regular market hours</param>
/// <returns>The market's closing time of day</returns>
public TimeSpan? GetMarketClose(TimeSpan time, bool extendedMarket)
{
foreach (var segment in _segments)
{
if (segment.State == MarketHoursState.Closed || segment.End <= time)
{
continue;
}
if (extendedMarket && _hasPostMarket)
{
if (segment.State == MarketHoursState.PostMarket)
{
return segment.End;
}
}
else if (segment.State == MarketHoursState.Market)
{
return segment.End;
}
}
// we couldn't locate an open segment after the specified time
return null;
}
/// <summary>
/// Determines if the exchange is open at the specified time
/// </summary>
/// <param name="time">The time of day to check</param>
/// <param name="extendedMarket">True to check exended market hours, false to check regular market hours</param>
/// <returns>True if the exchange is considered open, false otherwise</returns>
public bool IsOpen(TimeSpan time, bool extendedMarket)
{
foreach (var segment in _segments)
{
if (segment.State == MarketHoursState.Closed)
{
continue;
}
if (segment.Contains(time))
{
return extendedMarket || segment.State == MarketHoursState.Market;
}
}
// if we didn't find a segment then we're closed
return false;
}
/// <summary>
/// Determines if the exchange is open during the specified interval
/// </summary>
/// <param name="start">The start time of the interval</param>
/// <param name="end">The end time of the interval</param>
/// <param name="extendedMarket">True to check exended market hours, false to check regular market hours</param>
/// <returns>True if the exchange is considered open, false otherwise</returns>
public bool IsOpen(TimeSpan start, TimeSpan end, bool extendedMarket)
{
if (start == end)
{
return IsOpen(start, extendedMarket);
}
foreach (var segment in _segments)
{
if (segment.State == MarketHoursState.Closed)
{
continue;
}
if (extendedMarket || segment.State == MarketHoursState.Market)
{
if (segment.Overlaps(start, end))
{
return true;
}
}
}
// if we didn't find a segment then we're closed
return false;
}
/// <summary>
/// Gets a <see cref="LocalMarketHours"/> instance that is always closed
/// </summary>
/// <param name="dayOfWeek">The day of week</param>
/// <returns>A <see cref="LocalMarketHours"/> instance that is always closed</returns>
public static LocalMarketHours ClosedAllDay(DayOfWeek dayOfWeek)
{
return new LocalMarketHours(dayOfWeek);
}
/// <summary>
/// Gets a <see cref="LocalMarketHours"/> instance that is always open
/// </summary>
/// <param name="dayOfWeek">The day of week</param>
/// <returns>A <see cref="LocalMarketHours"/> instance that is always open</returns>
public static LocalMarketHours OpenAllDay(DayOfWeek dayOfWeek)
{
return new LocalMarketHours(dayOfWeek, new MarketHoursSegment(MarketHoursState.Market, TimeSpan.Zero, Time.OneDay));
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
if (IsClosedAllDay)
{
return "Closed All Day";
}
if (IsOpenAllDay)
{
return "Open All Day";
}
return DayOfWeek + ": " + string.Join(" | ", (IEnumerable<MarketHoursSegment>) _segments);
}
}
}
| |
//
// AppleDeviceTrackInfo.cs
//
// Author:
// Alan McGovern <amcgovern@novell.com>
//
// Copyright (c) 2010 Moonlight Team
//
// 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 Banshee.Base;
using Banshee.Streaming;
using Banshee.Collection;
using Banshee.Collection.Database;
using Hyena;
namespace Banshee.Dap.AppleDevice
{
public class AppleDeviceTrackInfo : DatabaseTrackInfo
{
internal GPod.Track IpodTrack {
get; set;
}
private string mimetype;
private string description; // Only used for podcasts.
public AppleDeviceTrackInfo (GPod.Track track)
{
IpodTrack = track;
LoadFromIpodTrack ();
CanSaveToDatabase = true;
}
public AppleDeviceTrackInfo (TrackInfo track)
{
CanSaveToDatabase = true;
if (track is AppleDeviceTrackInfo) {
IpodTrack = ((AppleDeviceTrackInfo)track).IpodTrack;
LoadFromIpodTrack ();
} else {
UpdateInfo (track);
}
}
public void UpdateInfo (TrackInfo track)
{
if (track is AppleDeviceTrackInfo) {
throw new ArgumentException ("Shouldn't update an AppleDeviceTrackInfo from an AppleDeviceTrackInfo");
}
IsCompilation = track.IsCompilation ;
AlbumArtist = track.AlbumArtist;
AlbumTitle = track.AlbumTitle;
ArtistName = track.ArtistName;
BitRate = track.BitRate;
SampleRate = track.SampleRate;
Bpm = track.Bpm;
Comment = track.Comment;
Composer = track.Composer;
Conductor = track.Conductor;
Copyright = track.Copyright;
DateAdded = track.DateAdded;
DiscCount = track.DiscCount;
DiscNumber = track.DiscNumber;
Duration = track.Duration;
FileSize = track.FileSize;
Genre = track.Genre;
Grouping = track.Grouping;
LastPlayed = track.LastPlayed;
LastSkipped = track.LastSkipped;
PlayCount = track.PlayCount;
Rating = track.Rating;
ReleaseDate = track.ReleaseDate;
SkipCount = track.SkipCount;
TrackCount = track.TrackCount;
TrackNumber = track.TrackNumber;
TrackTitle = track.TrackTitle;
Year = track.Year;
MediaAttributes = track.MediaAttributes;
ArtistNameSort = track.ArtistNameSort;
AlbumTitleSort = track.AlbumTitleSort;
AlbumArtistSort = track.AlbumArtistSort;
TrackTitleSort = track.TrackTitleSort;
var podcast_info = track.ExternalObject as IPodcastInfo;
if (podcast_info != null) {
description = podcast_info.Description;
ReleaseDate = podcast_info.ReleaseDate;
}
mimetype = track.MimeType;
}
private void LoadFromIpodTrack ()
{
var track = IpodTrack;
try {
Uri = new SafeUri (System.IO.Path.Combine (track.ITDB.Mountpoint, track.IpodPath.Replace (":", System.IO.Path.DirectorySeparatorChar.ToString ()).Substring (1)));
} catch (Exception ex) {
Log.Exception (ex);
Uri = null;
}
ExternalId = (long) track.DBID;
IsCompilation = track.Compilation;
AlbumArtist = track.AlbumArtist;
AlbumTitle = String.IsNullOrEmpty (track.Album) ? null : track.Album;
ArtistName = String.IsNullOrEmpty (track.Artist) ? null : track.Artist;
BitRate = track.Bitrate;
SampleRate = track.Samplerate;
Bpm = (int)track.BPM;
Comment = track.Comment;
Composer = track.Composer;
DateAdded = track.TimeAdded;
DiscCount = track.CDs;
DiscNumber = track.CDNumber;
Duration = TimeSpan.FromMilliseconds (track.TrackLength);
FileSize = track.Size;
Genre = String.IsNullOrEmpty (track.Genre) ? null : track.Genre;
Grouping = track.Grouping;
LastPlayed = track.TimePlayed;
PlayCount = (int) track.PlayCount;
TrackCount = track.Tracks;
TrackNumber = track.TrackNumber;
TrackTitle = String.IsNullOrEmpty (track.Title) ? null : track.Title;
Year = track.Year;
description = track.Description;
ReleaseDate = track.TimeReleased;
ArtistNameSort = track.SortArtist;
AlbumTitleSort = track.SortAlbum;
AlbumArtistSort = track.SortAlbumArtist;
TrackTitleSort = track.SortTitle;
rating = track.Rating > 5 ? 0 : (int) track.Rating;
if (track.DRMUserID > 0) {
PlaybackError = StreamPlaybackError.Drm;
}
MediaAttributes = TrackMediaAttributes.AudioStream;
switch (track.MediaType) {
case GPod.MediaType.Audio:
MediaAttributes |= TrackMediaAttributes.Music;
break;
// This seems to cause audio files to show up in Banshee in the Videos section
/*case GPod.MediaType.AudioVideo:
MediaAttributes |= TrackMediaAttributes.VideoStream;
break;*/
case GPod.MediaType.MusicVideo:
MediaAttributes |= TrackMediaAttributes.Music | TrackMediaAttributes.VideoStream;
break;
case GPod.MediaType.Movie:
MediaAttributes |= TrackMediaAttributes.VideoStream | TrackMediaAttributes.Movie;
break;
case GPod.MediaType.TVShow:
MediaAttributes |= TrackMediaAttributes.VideoStream | TrackMediaAttributes.TvShow;
break;
case GPod.MediaType.Podcast:
MediaAttributes |= TrackMediaAttributes.Podcast;
// FIXME: persist URL on the track (track.PodcastUrl)
break;
case GPod.MediaType.Audiobook:
MediaAttributes |= TrackMediaAttributes.AudioBook;
break;
case GPod.MediaType.MusicTVShow:
MediaAttributes |= TrackMediaAttributes.Music | TrackMediaAttributes.VideoStream | TrackMediaAttributes.TvShow;
break;
}
// If it's just AudioStream, add Music to it as well so it'll show up in Music
if (MediaAttributes == TrackMediaAttributes.AudioStream) {
MediaAttributes |= TrackMediaAttributes.Music;
}
}
public void CommitToIpod (GPod.ITDB database)
{
bool addTrack = IpodTrack == null;
if (IpodTrack == null) {
IpodTrack = new GPod.Track ();
}
var track = IpodTrack;
track.Compilation = IsCompilation;
track.AlbumArtist = AlbumArtist;
track.Bitrate = BitRate;
track.Samplerate= (ushort)SampleRate;
track.BPM = (short)Bpm;
track.Comment = Comment;
track.Composer = Composer;
track.TimeAdded = DateTime.Now;
track.CDs = DiscCount;
track.CDNumber = DiscNumber;
track.TrackLength = (int) Duration.TotalMilliseconds;
track.Size = (int)FileSize;
track.Grouping = Grouping;
try {
track.TimePlayed = LastPlayed;
} catch {
Hyena.Log.InformationFormat ("Couldn't set TimePlayed to '{0}'", LastPlayed);
}
track.PlayCount = (uint) PlayCount;
track.Tracks = TrackCount;
track.TrackNumber = TrackNumber;
track.Year = Year;
try {
track.TimeReleased = ReleaseDate;
} catch {
Hyena.Log.InformationFormat ("Couldn't set TimeReleased to '{0}'", ReleaseDate);
}
track.Album = AlbumTitle;
track.Artist = ArtistName;
track.Title = TrackTitle;
track.Genre = Genre;
track.SortArtist = ArtistNameSort;
track.SortAlbum = AlbumTitleSort;
track.SortAlbumArtist = AlbumArtistSort;
track.SortTitle = TrackTitleSort;
track.Rating = ((Rating >= 1) && (Rating <= 5)) ? (uint)Rating : 0;
if (HasAttribute (TrackMediaAttributes.Podcast)) {
track.Description = description;
track.RememberPlaybackPosition = true;
track.SkipWhenShuffling = true;
track.Flag4 = (byte)1;
track.MarkUnplayed = (track.PlayCount == 0);
}
track.MediaType = GPod.MediaType.Audio;
if (HasAttribute (TrackMediaAttributes.VideoStream)) {
if (HasAttribute (TrackMediaAttributes.Podcast)) {
track.MediaType = GPod.MediaType.Podcast | GPod.MediaType.Movie;
} else if (HasAttribute (TrackMediaAttributes.Music)) {
if (HasAttribute (TrackMediaAttributes.TvShow)) {
track.MediaType = GPod.MediaType.MusicTVShow;
} else {
track.MediaType = GPod.MediaType.MusicVideo;
}
} else if (HasAttribute (TrackMediaAttributes.Movie)) {
track.MediaType = GPod.MediaType.Movie;
} else if (HasAttribute (TrackMediaAttributes.TvShow)) {
track.MediaType = GPod.MediaType.TVShow;
} else {
// I dont' think AudioVideo should be used here; upon loading the tracks
// into Banshee, audio files often have AudioVideo (aka MediaType == 0) too.
//track.MediaType = GPod.MediaType.AudioVideo;
track.MediaType = GPod.MediaType.Movie;
}
} else {
if (HasAttribute (TrackMediaAttributes.Podcast)) {
track.MediaType = GPod.MediaType.Podcast;
} else if (HasAttribute (TrackMediaAttributes.AudioBook)) {
track.MediaType = GPod.MediaType.Audiobook;
} else if (HasAttribute (TrackMediaAttributes.Music)) {
track.MediaType = GPod.MediaType.Audio;
} else {
track.MediaType = GPod.MediaType.Audio;
}
}
if (addTrack) {
track.Filetype = mimetype;
database.Tracks.Add (IpodTrack);
database.MasterPlaylist.Tracks.Add (IpodTrack);
if (HasAttribute (TrackMediaAttributes.Podcast) && database.Device.SupportsPodcast) {
database.PodcastsPlaylist.Tracks.Add (IpodTrack);
}
database.CopyTrackToIPod (track, Uri.LocalPath);
Uri = new SafeUri (GPod.ITDB.GetLocalPath (database.Device, track));
ExternalId = (long) IpodTrack.DBID;
}
if (CoverArtSpec.CoverExists (ArtworkId)) {
string path = CoverArtSpec.GetPath (ArtworkId);
if (!track.ThumbnailsSet (path)) {
Log.Error (String.Format ("Could not set cover art for {0}.", path));
}
} else {
track.ThumbnailsRemoveAll ();
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssetsHelper.cs" company="Itransition">
// Itransition (c) Copyright. All right reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Core.Framework.Plugins.Constants;
using Core.Framework.Plugins.Web;
using Framework.Core.Helpers.Yaml;
using Yahoo.Yui.Compressor;
using Environment = Framework.Core.Configuration.Environment;
namespace Framework.Mvc.Helpers
{
/// <summary>
/// Provides helper functionality for resources packaging.
/// </summary>
public static class AssetsHelper
{
#region Constants
/// <summary>
/// Default assets configuration application relative path.
/// </summary>
public static readonly String DefaultConfigPath = "Config/asset_packages.yml";
private const String CssPackageNameTemplate = "{0}_packed.css";
private const String JavascriptPackageNameTemplate = "{0}_packed.js";
private const String CssVirtualPath = "{0}";
private const String PhysicalDelimeter = "\\";
private const String VirtualDelimeter = "/";
private const String UrlRegex = @"url\(\s*[""']?([\.\.\/]+)?([^""']+)[""']?\s*\)";
private const String UrlPattern = "url('{0}{1}')";
#endregion
private static dynamic assetsConfig;
/// <summary>
/// Reads assets config from <see name="DefaultConfigPath"/>.
/// </summary>
/// <remarks>
/// If <paramref name="environment"/> equals to <see cref="Environment.Development"/> configuration will be read on each call;
/// otherwise configuration will be read only on first call.
/// </remarks>
/// <param name="environment">The environment.</param>
/// <returns>Assets configuration.</returns>
public static dynamic GetAssetsConfig(Environment environment)
{
return GetAssetsConfig(environment, DefaultConfigPath);
}
/// <summary>
/// Reads assets config from <paramref name="configPath"/>.
/// </summary>
/// <param name="environment">The environment.</param>
/// <param name="configPath">The configuration path.</param>
/// <returns>Assets configuration.</returns>
/// <remarks>
/// If <paramref name="environment"/> equals to <see cref="Environment.Development"/> configuration will be read on each call;
/// otherwise configuration will be read only on first call.
/// </remarks>
public static dynamic GetAssetsConfig(Environment environment, String configPath)
{
if (Environment.Development.Equals(environment) || assetsConfig == null)
{
assetsConfig = YamlDocument.FromFile(configPath);
}
return assetsConfig;
}
/// <summary>
/// Gets list of files included in css package specified in <see name="DefaultConfigPath"/>.
/// </summary>
/// <param name="environment">The environment.</param>
/// <param name="packageName">Name of the package.</param>
/// <returns>List of files relative to css directory.</returns>
public static IEnumerable<String> GetCssPackFiles(Environment environment, String packageName)
{
return GetCssPackFiles(environment, packageName, DefaultConfigPath);
}
/// <summary>
/// Gets list of files included in css package specified in <paramref name="configPath"/>.
/// </summary>
/// <param name="environment">The environment.</param>
/// <param name="packageName">Name of the package.</param>
/// <param name="configPath">The configuration path.</param>
/// <returns>List of files relative to css directory.</returns>
public static IEnumerable<String> GetCssPackFiles(Environment environment, String packageName, String configPath)
{
dynamic config = GetAssetsConfig(environment, configPath);
var files = new List<String>();
foreach (var file in config.stylesheets[packageName])
{
files.Add(file);
}
return files;
}
/// <summary>
/// Gets list of files included in javascript package specified in <see name="DefaultConfigPath"/>.
/// </summary>
/// <param name="environment">The environment.</param>
/// <param name="packageName">Name of the package.</param>
/// <returns>List of files relative to javascript directory.</returns>
public static IEnumerable<String> GetJavascriptPackFiles(Environment environment, String packageName)
{
return GetJavascriptPackFiles(environment, packageName, DefaultConfigPath);
}
/// <summary>
/// Gets list of files included in javascript package specified in <paramref name="configPath"/>.
/// </summary>
/// <param name="environment">The environment.</param>
/// <param name="packageName">Name of the package.</param>
/// <param name="configPath">The configuration path.</param>
/// <returns>
/// List of files relative to javascript directory.
/// </returns>
public static IEnumerable<String> GetJavascriptPackFiles(Environment environment, String packageName, String configPath)
{
dynamic config = GetAssetsConfig(environment, configPath);
var files = new List<String>();
foreach (var file in config.javascripts[packageName])
{
files.Add(file);
}
return files;
}
/// <summary>
/// Builds the css package file specified in <see name="DefaultConfigPath"/>.
/// </summary>
/// <remarks>
/// If package file already exists it will be rebuilt according with files access time.
/// </remarks>
/// <param name="environment">The environment.</param>
/// <param name="packageName">Name of the package.</param>
/// <param name="cssPath">The css directory server path.</param>
/// <returns>Generated package file name.</returns>
public static String BuildCssPack(Environment environment, String packageName, String cssPath)
{
return BuildCssPack(environment, packageName, cssPath, DefaultConfigPath);
}
/// <summary>
/// Builds the css package file specified in <paramref name="configPath"/>.
/// </summary>
/// <remarks>
/// If package file already exists it will be rebuilt according with files access time.
/// </remarks>
/// <param name="environment">The environment.</param>
/// <param name="packageName">Name of the package.</param>
/// <param name="cssPath">The css directory server path.</param>
/// <param name="configPath">Assets config path.</param>
/// <returns>Generated package file name.</returns>
public static String BuildCssPack(Environment environment, String packageName, String cssPath, String configPath)
{
var packageFileName = String.Format(CssPackageNameTemplate, packageName);
var packagePath = Path.Combine(cssPath, packageFileName);
var files = GetCssPackFiles(environment, packageName, configPath);
if (!File.Exists(packagePath) || File.GetLastWriteTimeUtc(packagePath) < GetMaxLastModifyDate(cssPath, files))
{
var output = new StringBuilder();
foreach (var file in files)
{
using (var reader = new StreamReader(Path.Combine(cssPath, file)))
{
var temp = reader.ReadToEnd();
if (!String.IsNullOrEmpty(temp))
{
output.Append(CssCompressor.Compress(temp));
}
}
}
using (var writer = new StreamWriter(File.Create(packagePath)))
{
writer.Write(output.ToString());
}
}
return packageFileName;
}
/// <summary>
/// Builds the javascript package file specified in <see name="DefaultConfigPath"/>.
/// </summary>
/// <remarks>
/// If package file already exists it will be rebuilt according with files access time.
/// </remarks>
/// <param name="environment">The environment.</param>
/// <param name="packageName">Name of the package.</param>
/// <param name="javascriptPath">The javascript directory server path.</param>
/// <returns>Generated package file name.</returns>
public static String BuildJavascriptPack(Environment environment, String packageName, String javascriptPath)
{
return BuildJavascriptPack(environment, packageName, javascriptPath, DefaultConfigPath);
}
/// <summary>
/// Builds the javascript package file specified in <paramref name="configPath"/>.
/// </summary>
/// <remarks>
/// If package file already exists it will be rebuilt according with files access time.
/// </remarks>
/// <param name="environment">The environment.</param>
/// <param name="packageName">Name of the package.</param>
/// <param name="javascriptPath">The javascript directory server path.</param>
/// <param name="configPath">Assets config path.</param>
/// <returns>Generated package file name.</returns>
public static String BuildJavascriptPack(Environment environment, String packageName, String javascriptPath, String configPath)
{
var packageFileName = String.Format(JavascriptPackageNameTemplate, packageName);
var packagePath = Path.Combine(javascriptPath, packageFileName);
var files = GetJavascriptPackFiles(environment, packageName, configPath);
if (!File.Exists(packagePath) || File.GetLastWriteTimeUtc(packagePath) < GetMaxLastModifyDate(javascriptPath, files))
{
var output = new StringBuilder();
foreach (var file in files)
{
using (var reader = new StreamReader(Path.Combine(javascriptPath, file)))
{
var temp = reader.ReadToEnd();
if (!String.IsNullOrEmpty(temp))
{
output.Append(JavaScriptCompressor.Compress(temp));
}
}
}
using (var writer = new StreamWriter(File.Create(packagePath)))
{
writer.Write(output.ToString());
}
}
return packageFileName;
}
/// <summary>
/// Builds the plugin CSS pack.
/// </summary>
/// <param name="corePlugin">The core plugin.</param>
/// <param name="applicationServerPath">The application server path.</param>
/// <returns>
/// Return Html CSS links.
/// </returns>
public static String BuildPluginCssPack(ICorePlugin corePlugin, String applicationServerPath)
{
if (String.IsNullOrEmpty(corePlugin.CssJsConfigPath) || String.IsNullOrEmpty(corePlugin.CssPath) || String.IsNullOrEmpty(corePlugin.CssPack))
{
return String.Empty;
}
var pluginCssServerPath = Path.Combine(corePlugin.PluginDirectory, corePlugin.CssPath);
var pluginPackageCssServerPath = Path.Combine(pluginCssServerPath, Constants.PluginCssPackage);
var configPath = Path.Combine(corePlugin.PluginDirectory, corePlugin.CssJsConfigPath);
var files = GetPluginCssPackFiles(corePlugin.CssPack, configPath);
if (!File.Exists(pluginPackageCssServerPath) || File.GetLastWriteTimeUtc(pluginPackageCssServerPath) < GetMaxLastModifyDate(Path.Combine(corePlugin.PluginDirectory, corePlugin.CssPath), files))
{
var outputCss = new StringBuilder();
foreach (var file in files)
{
using (var reader = new StreamReader(Path.Combine(pluginCssServerPath, file)))
{
var temp = reader.ReadToEnd();
if (!String.IsNullOrEmpty(temp))
{
temp = ReplaceCssUrls(temp, MakeVirtualCssPath(corePlugin, applicationServerPath));
outputCss.Append(CssCompressor.Compress(temp));
}
}
}
using (var writer = new StreamWriter(File.Create(pluginPackageCssServerPath)))
{
writer.Write(outputCss.ToString());
}
}
return pluginPackageCssServerPath;
}
/// <summary>
/// Gets list of files included in plugin css package specified in <paramref name="configPath"/>.
/// </summary>
/// <param name="packageName">Name of the package.</param>
/// <param name="configPath">The configuration path.</param>
/// <returns>List of files relative to css directory.</returns>
public static IEnumerable<String> GetPluginCssPackFiles(String packageName, String configPath)
{
dynamic config = GetPluginAssetsConfig(configPath);
var files = new List<String>();
foreach (var file in config.stylesheets[packageName])
{
files.Add(file);
}
return files;
}
/// <summary>
/// Gets list of files included in plugin js package specified in <paramref name="configPath"/>.
/// </summary>
/// <param name="packageName">Name of the package.</param>
/// <param name="configPath">The configuration path.</param>
/// <param name="scriptType">The type of script (internal/external).</param>
/// <returns>List of files relative to js directory.</returns>
public static IEnumerable<String> GetPluginJsPackFiles(String packageName, String configPath, String scriptType)
{
dynamic config = GetPluginAssetsConfig(configPath);
var files = new List<String>();
if (config.javascripts != null && config.javascripts[packageName] != null && config.javascripts[packageName][scriptType] != null)
{
foreach (dynamic file in config.javascripts[packageName][scriptType])
{
files.Add(file);
}
}
return files;
}
/// <summary>
/// Gets the plugin inner js path.
/// </summary>
/// <param name="corePlugin">The core plugin.</param>
/// <param name="applicationVirtualPath">The application virtual path.</param>
/// <param name="applicationServerPath">The application server path.</param>
/// <returns>Returns javascript package virtual path.</returns>
public static String GetPluginInnerJsVirtualPath(ICorePlugin corePlugin, String applicationVirtualPath, String applicationServerPath)
{
var pluginPackageJsServerPath = GetPluginInnerJsPath(corePlugin);
if (!String.IsNullOrEmpty(pluginPackageJsServerPath))
{
// get javascript package virtual path
pluginPackageJsServerPath = pluginPackageJsServerPath.Replace(applicationServerPath.ToLower(), applicationVirtualPath).Replace("\\", "/");
}
return pluginPackageJsServerPath;
}
/// <summary>
/// Gets the plugin inner js path.
/// </summary>
/// <param name="corePlugin">The core plugin.</param>
/// <returns>Returns javascript package path.</returns>
public static String GetPluginInnerJsPath(ICorePlugin corePlugin)
{
if (String.IsNullOrEmpty(corePlugin.CssJsConfigPath) || String.IsNullOrEmpty(corePlugin.JsPath) || String.IsNullOrEmpty(corePlugin.JsPack))
{
return String.Empty;
}
var pluginJsServerPath = Path.Combine(corePlugin.PluginDirectory, corePlugin.JsPath);
var pluginPackageJsServerPath = Path.Combine(pluginJsServerPath, Constants.PluginJsPackage).ToLower();
var configPath = Path.Combine(corePlugin.PluginDirectory, corePlugin.CssJsConfigPath);
var files = GetPluginJsPackFiles(corePlugin.JsPack, configPath, Constants.InnerJsTypeName);
if (!File.Exists(pluginPackageJsServerPath) || File.GetLastWriteTimeUtc(pluginPackageJsServerPath) < GetMaxLastModifyDate(Path.Combine(corePlugin.PluginDirectory, corePlugin.JsPath), files))
{
var outputJs = new StringBuilder();
foreach (var file in files)
{
if (File.Exists(Path.Combine(pluginJsServerPath, file)))
{
using (var reader = new StreamReader(Path.Combine(pluginJsServerPath, file)))
{
String content = reader.ReadToEnd();
if (!String.IsNullOrEmpty(content))
{
outputJs.Append(JavaScriptCompressor.Compress(content));
}
}
}
}
using (var writer = new StreamWriter(File.Create(pluginPackageJsServerPath)))
{
writer.Write(outputJs.ToString());
}
}
return pluginPackageJsServerPath;
}
/// <summary>
/// Reads plugin assets config from <paramref name="configPath"/>.
/// </summary>
/// <param name="configPath">The configuration path.</param>
/// <returns>Plugin assets configuration.</returns>
/// <remarks>
/// </remarks>
public static dynamic GetPluginAssetsConfig(String configPath)
{
return YamlDocument.FromFile(configPath);
}
/// <summary>
/// Builds the plugins CSS pack.
/// </summary>
/// <param name="corePlugins">The core widgets.</param>
/// <param name="applicationServerPath">The application server path.</param>
/// <param name="cssServerPath">The CSS server path.</param>
/// <param name="fileName">Name of the file.</param>
/// <returns>Return Html CSS links.</returns>
public static String BuildPluginsCssPack(IEnumerable<ICorePlugin> corePlugins, String applicationServerPath, String cssServerPath, String fileName)
{
var packageFileName = fileName;
var packagePath = Path.Combine(cssServerPath, packageFileName);
if (!File.Exists(packagePath))
{
if (!Directory.Exists(cssServerPath))
{
Directory.CreateDirectory(cssServerPath);
}
var output = new StringBuilder();
foreach (var plugin in corePlugins)
{
if (String.IsNullOrEmpty(plugin.CssJsConfigPath) || String.IsNullOrEmpty(plugin.CssPath) || String.IsNullOrEmpty(plugin.CssPack))
{
continue;
}
var pluginPackageCssServerPath = Path.Combine(plugin.PluginDirectory, plugin.CssPath, Constants.PluginCssPackage);
var configPath = Path.Combine(plugin.PluginDirectory, plugin.CssJsConfigPath);
var files = GetPluginCssPackFiles(plugin.CssPack, configPath);
if (!File.Exists(pluginPackageCssServerPath) || File.GetLastWriteTimeUtc(pluginPackageCssServerPath) < GetMaxLastModifyDate(Path.Combine(plugin.PluginDirectory, plugin.CssPath), files))
{
BuildPluginCssPack(plugin, applicationServerPath);
}
using (var reader = new StreamReader(pluginPackageCssServerPath))
{
var temp = reader.ReadToEnd();
if (!String.IsNullOrEmpty(temp))
{
output.Append(CssCompressor.Compress(temp));
}
}
}
using (var writer = new StreamWriter(File.Create(packagePath)))
{
writer.Write(output.ToString());
}
}
return packagePath;
}
private static DateTime GetMaxLastModifyDate(String baseDirectory, IEnumerable<String> files)
{
var maxModifyDate = DateTime.MinValue;
foreach (var file in files)
{
var modifyDate = File.GetLastWriteTimeUtc(Path.Combine(baseDirectory, file));
if (modifyDate > maxModifyDate)
{
maxModifyDate = modifyDate;
}
}
return maxModifyDate;
}
/// <summary>
/// Replaces the CSS urls.
/// </summary>
/// <param name="cssContent">Content of the CSS.</param>
/// <param name="imagePluginPath">The image plugin path.</param>
/// <returns>Return content Css with replaced urls.</returns>
private static String ReplaceCssUrls(String cssContent, String imagePluginPath)
{
var regex = new System.Text.RegularExpressions.Regex(UrlRegex);
var vals = regex.Matches(cssContent).Cast<Match>().ToDictionary(mathe => mathe.Index.ToString(),
mathe => mathe.Groups[2].Value);
return regex.Replace(cssContent,
match => String.Format(UrlPattern, imagePluginPath, vals[match.Index.ToString()]));
}
/// <summary>
/// Makes the virtual CSS path.
/// </summary>
/// <param name="coreWidget">The core widget.</param>
/// <param name="serverPath">The server path.</param>
/// <returns>Return virtual Url.</returns>
private static String MakeVirtualCssPath(ICorePlugin coreWidget, String serverPath)
{
var physicalContentPath = Path.Combine(coreWidget.PluginDirectory, coreWidget.ImagesPath);
var partPhysicalPluginPath = physicalContentPath.ToLower().Replace(serverPath.ToLower(), String.Empty);
var virtualPluginPath = partPhysicalPluginPath.Replace(PhysicalDelimeter, VirtualDelimeter);
return String.Format(CssVirtualPath, virtualPluginPath);
}
}
}
| |
/********************************************************************
*
* PropertyBag.cs
* --------------
* Derived from PropertyBag.cs by Tony Allowatt
* CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp
* Last Update: 04/05/2005
*
********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Reflection;
using CslaGenerator.Attributes;
using System.Configuration;
using CslaGenerator.Metadata;
using System.Diagnostics;
namespace CslaGenerator.Util.PropertyBags
{
#region PropertySpec class
/// <summary>
/// Summary description for PropertySpec.
/// </summary>
public class PropertySpec
{
private Attribute[] attributes;
private string name;
private string category;
private string description;
private object defaultValue;
private string type;
private string editor;
private string typeConverter;
private Type targetClass;
private object targetObject = null;
private string targetProperty = "";
private string helpTopic = "";
private bool isReadonly = false;
private bool isBrowsable = true;
private string designerTypename = "";
private bool isBindable = true;
//public PropertySpec(string name, object type, object typeconverter, string category, string description, object defaultValue, object tarObject, string tarProperty, string helptopic)
public PropertySpec(string name, string type, string category, string description, object defaultValue, string editor, string typeConverter, object tarObject, string tarProperty, string helptopic, bool isreadonly, bool isbrowsable, string designertypename, bool isbindable)
{
this.Name = name;
this.TypeName = type;
if (this.TypeName == "")
throw new Exception("Unable to determine PropertySpec type.");
this.category = category;
this.description = description;
this.defaultValue = defaultValue;
this.editor = editor;
this.typeConverter = typeConverter;
this.targetObject = tarObject;
this.targetProperty = tarProperty;
this.helpTopic = helptopic;
this.isReadonly = isreadonly;
this.isBrowsable = isbrowsable;
this.designerTypename = designertypename;
this.isBindable = isbindable;
}
#region properties
/// <summary>
/// Gets or sets a collection of additional Attributes for this property. This can
/// be used to specify attributes beyond those supported intrinsically by the
/// PropertySpec class, such as ReadOnly and Browsable.
/// </summary>
public Attribute[] Attributes
{
get { return attributes; }
set { attributes = value; }
}
/// <summary>
/// Gets or sets the category name of this property.
/// </summary>
public string Category
{
get { return category; }
set { category = value; }
}
/// <summary>
/// Gets or sets the fully qualified name of the type converter
/// type for this property (as string).
/// </summary>
public string ConverterTypeName
{
get { return typeConverter; }
set { typeConverter = value; }
}
/// <summary>
/// Gets or sets the default value of this property.
/// </summary>
public object DefaultValue
{
get { return defaultValue; }
set { defaultValue = value; }
}
/// <summary>
/// Gets or sets the help text description of this property.
/// </summary>
public string Description
{
get { return description; }
set { description = value; }
}
/// <summary>
/// Gets or sets the fully qualified name of the editor type for
/// this property (as string).
/// </summary>
public string EditorTypeName
{
get { return editor; }
set { editor = value; }
}
/// <summary>
/// Gets or sets the name of this property.
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// Gets or sets the fully qualfied name of the type of this
/// property (as string).
/// </summary>
public string TypeName
{
get { return type; }
set { type = value; }
}
/// <summary>
/// Gets or sets the boolean flag indicating if this property
/// is readonly
/// </summary>
public bool ReadOnly
{
get { return isReadonly; }
set { isReadonly = value; }
}
/// <summary>
/// Gets or sets the boolean flag indicating if this property
/// is browsable (i.e. visible in PropertyGrid
/// </summary>
public bool Browsable
{
get { return isBrowsable; }
set { isBrowsable = value; }
}
/// <summary>
/// Gets or sets the boolean flag indicating if this property
/// is bindable
/// </summary>
public bool Bindable
{
get { return isBindable; }
set { isBindable = value; }
}
/// <summary>
/// Test
///
/// </summary>
public Type TargetClass
{
get { return targetClass; }
set { targetClass = value; }
}
/// <summary>
/// Gets or sets the target object which is the owner of the
/// properties displayed in the PropertyGrid
/// </summary>
public object TargetObject
{
get { return targetObject; }
set { targetObject = value; }
}
/// <summary>
/// Gets or sets the target property in the target object
/// associated with the PropertyGrid item
/// </summary>
public string TargetProperty
{
get { return targetProperty; }
set { targetProperty = value; }
}
/// <summary>
/// Gets or sets the help topic key associated with this
/// PropertyGrid item
/// </summary>
public string HelpTopic
{
get { return helpTopic; }
set { helpTopic = value; }
}
}
#endregion
/// <summary>
/// Provides data for the GetValue and SetValue events of the PropertyBag class.
/// </summary>
public class PropertySpecEventArgs : EventArgs
{
private PropertySpec property;
private object val;
/// <summary>
/// Initializes a new instance of the PropertySpecEventArgs class.
/// </summary>
/// <param name="property">The PropertySpec that represents the property whose
/// value is being requested or set.</param>
/// <param name="val">The current value of the property.</param>
public PropertySpecEventArgs(PropertySpec property, object val)
{
this.property = property;
this.val = val;
}
/// <summary>
/// Gets the PropertySpec that represents the property whose value is being
/// requested or set.
/// </summary>
public PropertySpec Property
{
get { return property; }
}
/// <summary>
/// Gets or sets the current value of the property.
/// </summary>
public object Value
{
get { return val; }
set { val = value; }
}
}
/// <summary>
/// Represents the method that will handle the GetValue and SetValue events of the
/// PropertyBag class.
/// </summary>
public delegate void PropertySpecEventHandler(object sender, PropertySpecEventArgs e);
#endregion
/// <summary>
/// Represents a collection of custom properties that can be selected into a
/// PropertyGrid to provide functionality beyond that of the simple reflection
/// normally used to query an object's properties.
/// </summary>
public class PropertyBag : ICustomTypeDescriptor
{
#region PropertySpecCollection class definition
/// <summary>
/// Encapsulates a collection of PropertySpec objects.
/// </summary>
[Serializable]
public class PropertySpecCollection : IList
{
private ArrayList innerArray;
/// <summary>
/// Initializes a new instance of the PropertySpecCollection class.
/// </summary>
public PropertySpecCollection()
{
innerArray = new ArrayList();
}
/// <summary>
/// Gets the number of elements in the PropertySpecCollection.
/// </summary>
/// <value>
/// The number of elements contained in the PropertySpecCollection.
/// </value>
public int Count
{
get { return innerArray.Count; }
}
/// <summary>
/// Gets a value indicating whether the PropertySpecCollection has a fixed size.
/// </summary>
/// <value>
/// true if the PropertySpecCollection has a fixed size; otherwise, false.
/// </value>
public bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the PropertySpecCollection is read-only.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <value>
/// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false.
/// </value>
public bool IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
/// <value>
/// An object that can be used to synchronize access to the collection.
/// </value>
object ICollection.SyncRoot
{
get { return null; }
}
/// <summary>
/// Gets or sets the element at the specified index.
/// In C#, this property is the indexer for the PropertySpecCollection class.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <value>
/// The element at the specified index.
/// </value>
public PropertySpec this[int index]
{
get { return (PropertySpec)innerArray[index]; }
set { innerArray[index] = value; }
}
/// <summary>
/// Adds a PropertySpec to the end of the PropertySpecCollection.
/// </summary>
/// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param>
/// <returns>The PropertySpecCollection index at which the value has been added.</returns>
public int Add(PropertySpec value)
{
int index = innerArray.Add(value);
return index;
}
/// <summary>
/// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection.
/// </summary>
/// <param name="array">The PropertySpec array whose elements should be added to the end of the
/// PropertySpecCollection.</param>
public void AddRange(PropertySpec[] array)
{
innerArray.AddRange(array);
}
/// <summary>
/// Removes all elements from the PropertySpecCollection.
/// </summary>
public void Clear()
{
innerArray.Clear();
}
/// <summary>
/// Determines whether a PropertySpec is in the PropertySpecCollection.
/// </summary>
/// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate
/// can be a null reference (Nothing in Visual Basic).</param>
/// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns>
public bool Contains(PropertySpec item)
{
return innerArray.Contains(item);
}
/// <summary>
/// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns>
public bool Contains(string name)
{
foreach (PropertySpec spec in innerArray)
if (spec.Name == name)
return true;
return false;
}
/// <summary>
/// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the
/// beginning of the target array.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied
/// from PropertySpecCollection. The Array must have zero-based indexing.</param>
public void CopyTo(PropertySpec[] array)
{
innerArray.CopyTo(array);
}
/// <summary>
/// Copies the PropertySpecCollection or a portion of it to a one-dimensional array.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied
/// from the collection.</param>
/// <param name="index">The zero-based index in array at which copying begins.</param>
public void CopyTo(PropertySpec[] array, int index)
{
innerArray.CopyTo(array, index);
}
/// <summary>
/// Returns an enumerator that can iterate through the PropertySpecCollection.
/// </summary>
/// <returns>An IEnumerator for the entire PropertySpecCollection.</returns>
public IEnumerator GetEnumerator()
{
return innerArray.GetEnumerator();
}
/// <summary>
/// Searches for the specified PropertySpec and returns the zero-based index of the first
/// occurrence within the entire PropertySpecCollection.
/// </summary>
/// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection,
/// if found; otherwise, -1.</returns>
public int IndexOf(PropertySpec value)
{
return innerArray.IndexOf(value);
}
/// <summary>
/// Searches for the PropertySpec with the specified name and returns the zero-based index of
/// the first occurrence within the entire PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection,
/// if found; otherwise, -1.</returns>
public int IndexOf(string name)
{
int i = 0;
foreach (PropertySpec spec in innerArray)
{
//if (spec.Name == name)
if (spec.TargetProperty == name)
return i;
i++;
}
return -1;
}
/// <summary>
/// Inserts a PropertySpec object into the PropertySpecCollection at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which value should be inserted.</param>
/// <param name="value">The PropertySpec to insert.</param>
public void Insert(int index, PropertySpec value)
{
innerArray.Insert(index, value);
}
/// <summary>
/// Removes the first occurrence of a specific object from the PropertySpecCollection.
/// </summary>
/// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param>
public void Remove(PropertySpec obj)
{
innerArray.Remove(obj);
}
/// <summary>
/// Removes the property with the specified name from the PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param>
public void Remove(string name)
{
int index = IndexOf(name);
RemoveAt(index);
}
/// <summary>
/// Removes the object at the specified index of the PropertySpecCollection.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
public void RemoveAt(int index)
{
innerArray.RemoveAt(index);
}
/// <summary>
/// Copies the elements of the PropertySpecCollection to a new PropertySpec array.
/// </summary>
/// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns>
public PropertySpec[] ToArray()
{
return (PropertySpec[])innerArray.ToArray(typeof(PropertySpec));
}
#region Explicit interface implementations for ICollection and IList
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void ICollection.CopyTo(Array array, int index)
{
CopyTo((PropertySpec[])array, index);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
int IList.Add(object value)
{
return Add((PropertySpec)value);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
bool IList.Contains(object obj)
{
return Contains((PropertySpec)obj);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
object IList.this[int index]
{
get
{
return ((PropertySpecCollection)this)[index];
}
set
{
((PropertySpecCollection)this)[index] = (PropertySpec)value;
}
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
int IList.IndexOf(object obj)
{
return IndexOf((PropertySpec)obj);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void IList.Insert(int index, object value)
{
Insert(index, (PropertySpec)value);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void IList.Remove(object value)
{
Remove((PropertySpec)value);
}
#endregion
}
#endregion
#region PropertySpecDescriptor class definition
private class PropertySpecDescriptor : PropertyDescriptor
{
private PropertyBag bag;
private PropertySpec item;
public PropertySpecDescriptor(PropertySpec item, PropertyBag bag, string name, Attribute[] attrs)
:
base(name, attrs)
{
this.bag = bag;
this.item = item;
}
public override Type ComponentType
{
get { return item.GetType(); }
}
public override bool IsReadOnly
{
get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); }
}
public override Type PropertyType
{
get { return Type.GetType(item.TypeName); }
}
public override bool CanResetValue(object component)
{
if (item.DefaultValue == null)
return false;
else
return !this.GetValue(component).Equals(item.DefaultValue);
}
public override object GetValue(object component)
{
// Have the property bag raise an event to get the current value
// of the property.
PropertySpecEventArgs e = new PropertySpecEventArgs(item, null);
bag.OnGetValue(e);
return e.Value;
}
public override void ResetValue(object component)
{
SetValue(component, item.DefaultValue);
}
public override void SetValue(object component, object value)
{
// Have the property bag raise an event to set the current value
// of the property.
PropertySpecEventArgs e = new PropertySpecEventArgs(item, value);
bag.OnSetValue(e);
}
public override bool ShouldSerializeValue(object component)
{
object val = this.GetValue(component);
if (item.DefaultValue == null && val == null)
return false;
else
return !val.Equals(item.DefaultValue);
}
}
#endregion
#region properties and events
private string defaultProperty;
private PropertySpecCollection properties;
private CslaObjectInfo[] mSelectedObject;
private PropertyContext propertyContext;
/// <summary>
/// Initializes a new instance of the PropertyBag class.
/// </summary>
public PropertyBag()
{
defaultProperty = null;
properties = new PropertySpecCollection();
}
public PropertyBag(CslaObjectInfo obj)
: this(new CslaObjectInfo[] { obj })
{ }
public PropertyBag(CslaObjectInfo[] obj)
{
defaultProperty = null;
properties = new PropertySpecCollection();
mSelectedObject = obj;
InitPropertyBag();
}
public PropertyBag(CslaObjectInfo obj, PropertyContext context)
: this(new CslaObjectInfo[] { obj }, context)
{ }
public PropertyBag(CslaObjectInfo[] obj, PropertyContext context)
{
defaultProperty = "ObjectName";
properties = new PropertySpecCollection();
mSelectedObject = obj;
propertyContext = context;
InitPropertyBag();
}
/// <summary>
/// Gets or sets the name of the default property in the collection.
/// </summary>
public string DefaultProperty
{
get { return defaultProperty; }
set { defaultProperty = value; }
}
/// <summary>
/// Gets or sets the name of the default property in the collection.
/// </summary>
public CslaObjectInfo[] SelectedObject
{
get { return mSelectedObject; }
set
{
mSelectedObject = value;
InitPropertyBag();
}
}
/// <summary>
/// Gets or sets the property context.
/// </summary>
public PropertyContext PropertyContext
{
get { return propertyContext; }
set
{
propertyContext = value;
}
}
/// <summary>
/// Gets the collection of properties contained within this PropertyBag.
/// </summary>
public PropertySpecCollection Properties
{
get { return properties; }
}
/// <summary>
/// Occurs when a PropertyGrid requests the value of a property.
/// </summary>
public event PropertySpecEventHandler GetValue;
/// <summary>
/// Occurs when the user changes the value of a property in a PropertyGrid.
/// </summary>
public event PropertySpecEventHandler SetValue;
/// <summary>
/// Raises the GetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
protected virtual void OnGetValue(PropertySpecEventArgs e)
{
if (e.Value != null)
GetValue(this, e);
e.Value = getProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue);
}
/// <summary>
/// Raises the SetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
protected virtual void OnSetValue(PropertySpecEventArgs e)
{
if (SetValue != null)
SetValue(this, e);
setProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value);
}
#endregion
#region Initialize Propertybag
private void InitPropertyBag()
{
PropertyInfo pi;
Type t = typeof(CslaObjectInfo);// mSelectedObject.GetType();
PropertyInfo[] props = t.GetProperties();
// Display information for all properties.
for (int i = 0; i < props.Length; i++)
{
pi = (PropertyInfo)props[i];
Object[] myAttributes = pi.GetCustomAttributes(true);
string category = "";
string description = "";
bool isreadonly = false;
bool isbrowsable = true;
object defaultvalue = null;
string defaultproperty = "";
string userfriendlyname = "";
string typeconverter = "";
string designertypename = "";
string helptopic = "";
bool bindable = true;
string editor = "";
for (int n = 0; n < myAttributes.Length; n++)
{
Attribute a = (Attribute)myAttributes[n];
switch (a.GetType().ToString())
{
case "System.ComponentModel.CategoryAttribute":
category = ((CategoryAttribute)a).Category;
break;
case "System.ComponentModel.DescriptionAttribute":
description = ((DescriptionAttribute)a).Description;
break;
case "System.ComponentModel.ReadOnlyAttribute":
isreadonly = ((ReadOnlyAttribute)a).IsReadOnly;
break;
case "System.ComponentModel.BrowsableAttribute":
isbrowsable = ((BrowsableAttribute)a).Browsable;
break;
case "System.ComponentModel.DefaultValueAttribute":
defaultvalue = ((DefaultValueAttribute)a).Value;
break;
case "System.ComponentModel.DefaultPropertyAttribute":
defaultproperty = ((DefaultPropertyAttribute)a).Name;
break;
case "CslaGenerator.Attributes.UserFriendlyNameAttribute":
userfriendlyname = ((UserFriendlyNameAttribute)a).UserFriendlyName;
break;
case "CslaGenerator.Attributes.HelpTopicAttribute":
helptopic = ((HelpTopicAttribute)a).HelpTopic;
break;
case "System.ComponentModel.TypeConverterAttribute":
typeconverter = ((TypeConverterAttribute)a).ConverterTypeName;
break;
case "System.ComponentModel.DesignerAttribute":
designertypename = ((DesignerAttribute)a).DesignerTypeName;
break;
case "System.ComponentModel.BindableAttribute":
bindable = ((BindableAttribute)a).Bindable;
break;
case "System.ComponentModel.EditorAttribute":
editor = ((EditorAttribute)a).EditorTypeName;
break;
}
}
userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : pi.Name;
List<string> types = new List<string>();
foreach (CslaObjectInfo obj in mSelectedObject)
{
if (!types.Contains(obj.ObjectType.ToString()))
types.Add(obj.ObjectType.ToString());
}
// here get rid of ComponentName and Parent
bool IsValidProperty = (pi.Name != "Properties" && pi.Name != "ComponentName" && pi.Name != "Parent");
if (IsValidProperty && IsBrowsable(types.ToArray(), pi.Name))
{
// CR added missing parameters
//this.Properties.Add(new PropertySpec(userfriendlyname,pi.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, mSelectedObject, pi.Name,helptopic));
this.Properties.Add(new PropertySpec(userfriendlyname, pi.PropertyType.AssemblyQualifiedName, category, description, defaultvalue, editor, typeconverter, mSelectedObject, pi.Name, helptopic, isreadonly, isbrowsable, designertypename, bindable));
}
}
}
#endregion
Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>();
PropertyInfo GetPropertyInfoCache(string propertyName)
{
if (!propertyInfoCache.ContainsKey(propertyName))
{
propertyInfoCache.Add(propertyName, typeof(CslaObjectInfo).GetProperty(propertyName));
}
return propertyInfoCache[propertyName];
}
bool IsEnumerable(PropertyInfo prop)
{
if (prop.PropertyType == typeof(string))
return false;
Type[] interfaces = prop.PropertyType.GetInterfaces();
foreach (Type typ in interfaces)
if (typ.Name.Contains("IEnumerable"))
return true;
return false;
}
#region IsBrowsable map objecttype:propertyname -> true | false
private bool IsBrowsable(string[] objectType, string propertyName)
{
try
{
// Use PropertyContext class to determine if the combination
// objectType + propertyName should be shown in propertygrid
// else defalut to true (show it)
// objectType + propertyName --> true | false
if (propertyContext != null)
{
foreach (string typ in objectType)
{
if (!propertyContext.ShowProperty(typ, propertyName))
return false;
if (!GeneratorController.Current.CurrentUnit.GenerationParams.ActiveObjects &&
(propertyName == "PublishToChannel" || propertyName == "SubscribeToChannel"))
return false;
if (((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == Authorization.None ||
GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == Authorization.PropertyLevel)) &&
(propertyName == "NewRoles" ||
propertyName == "GetRoles" ||
propertyName == "UpdateRoles" ||
propertyName == "DeleteRoles"))
return false;
if (GeneratorController.Current.CurrentUnit.GenerationParams.TargetFramework == TargetFramework.CSLA40 &&
(propertyName == "AddParentReference" ||
propertyName == "HashcodeProperty" ||
propertyName == "EqualsProperty" ||
propertyName == "DeleteProcedureName"))
return false;
if (GeneratorController.Current.CurrentUnit.GenerationParams.TargetFramework == TargetFramework.CSLA40 &&
(propertyName == "LazyLoad"))
return false;
}
if (mSelectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName)))
return false;
return true;
}
else
return true;
}
catch //(Exception e)
{
Debug.WriteLine(objectType + ":" + propertyName);
return true;
}
}
#endregion
#region reflection functions
private object getField(Type t, string name, object target)
{
object obj = null;
Type tx;
FieldInfo[] fields;
//fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
fields = target.GetType().GetFields(BindingFlags.Public);
tx = target.GetType();
obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] { });
return obj;
}
private object setField(Type t, string name, object value, object target)
{
object obj;
obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new object[] { value });
return obj;
}
bool setProperty(object obj, string propertyName, object val)
{
try
{
// get a reference to the PropertyInfo, exit if no property with that
// name
PropertyInfo pi = typeof(CslaObjectInfo).GetProperty(propertyName);
if (pi == null)
return false;
// convert the value to the expected type
val = Convert.ChangeType(val, pi.PropertyType);
// attempt the assignment
foreach (CslaObjectInfo bo in (CslaObjectInfo[])obj)
pi.SetValue(bo, val, null);
return true;
}
catch
{
return false;
}
}
object getProperty(object obj, string propertyName, object defaultValue)
{
try
{
PropertyInfo pi = GetPropertyInfoCache(propertyName);
if (!(pi == null))
{
CslaObjectInfo[] objs = (CslaObjectInfo[])obj;
ArrayList valueList = new ArrayList();
foreach (CslaObjectInfo bo in objs)
{
object value = pi.GetValue(bo, null);
if (!valueList.Contains(value))
{
valueList.Add(value);
}
}
switch (valueList.Count)
{
case 1:
return valueList[0];
default:
return string.Empty;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// if property doesn't exist or throws
return defaultValue;
}
#endregion
#region ICustomTypeDescriptor explicit interface definitions
// Most of the functions required by the ICustomTypeDescriptor are
// merely pssed on to the default TypeDescriptor for this type,
// which will do something appropriate. The exceptions are noted
// below.
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
string ICustomTypeDescriptor.GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
string ICustomTypeDescriptor.GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
// This function searches the property list for the property
// with the same name as the DefaultProperty specified, and
// returns a property descriptor for it. If no property is
// found that matches DefaultProperty, a null reference is
// returned instead.
PropertySpec propertySpec = null;
if (defaultProperty != null)
{
int index = properties.IndexOf(defaultProperty);
propertySpec = properties[index];
}
if (propertySpec != null)
return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null);
else
return null;
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor)this).GetProperties(new Attribute[0]);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
// Rather than passing this function on to the default TypeDescriptor,
// which would return the actual properties of PropertyBag, I construct
// a list here that contains property descriptors for the elements of the
// Properties list in the bag.
ArrayList props = new ArrayList();
foreach (PropertySpec property in properties)
{
ArrayList attrs = new ArrayList();
// If a category, description, editor, or type converter are specified
// in the PropertySpec, create attributes to define that relationship.
if (property.Category != null)
attrs.Add(new CategoryAttribute(property.Category));
if (property.Description != null)
attrs.Add(new DescriptionAttribute(property.Description));
if (property.EditorTypeName != null)
attrs.Add(new EditorAttribute(property.EditorTypeName, typeof(UITypeEditor)));
if (property.ConverterTypeName != null)
attrs.Add(new TypeConverterAttribute(property.ConverterTypeName));
// Additionally, append the custom attributes associated with the
// PropertySpec, if any.
if (property.Attributes != null)
attrs.AddRange(property.Attributes);
if (property.DefaultValue != null)
attrs.Add(new DefaultValueAttribute(property.DefaultValue));
attrs.Add(new BrowsableAttribute(property.Browsable));
attrs.Add(new ReadOnlyAttribute(property.ReadOnly));
attrs.Add(new BindableAttribute(property.Bindable));
Attribute[] attrArray = (Attribute[])attrs.ToArray(typeof(Attribute));
// Create a new property descriptor for the property item, and add
// it to the list.
PropertySpecDescriptor pd = new PropertySpecDescriptor(property,
this, property.Name, attrArray);
props.Add(pd);
}
// Convert the list of PropertyDescriptors to a collection that the
// ICustomTypeDescriptor can use, and return it.
PropertyDescriptor[] propArray = (PropertyDescriptor[])props.ToArray(
typeof(PropertyDescriptor));
return new PropertyDescriptorCollection(propArray);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Linq.Expressions;
namespace Wax
{
/// <summary>
/// Extensions for runtime expansion of expressions.
/// </summary>
public static class Wax
{
/// <summary>
/// Inject a constant directly into the query.
/// </summary>
/// <typeparam name="TValue">
/// The type of the result.
/// </typeparam>
/// <param name="value">
/// The value to inject. It must not rely on
/// parameters local to the query.
/// </param>
/// <returns>
/// If this method is executed outside of an expression,
/// it will throw an instance of <see cref="NotImplementedException"/>.
/// </returns>
[ConstantValueMethod]
public static TValue Constant<TValue>(this TValue value)
{
throw new NotImplementedException();
}
/// <summary>
/// Invoke an expression with a single parameter.
/// </summary>
/// <typeparam name="TParameter">
/// The type of the parameter.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the expression.
/// </typeparam>
/// <param name="expression">
/// The expression to invoke.
/// </param>
/// <param name="parameter">
/// The parameter to pass to the expression.
/// </param>
/// <returns>
/// The result of the expression.
/// </returns>
/// <remarks>
/// When used in an expression, this call can be unwrapped.
/// This method should not be used outside of an unwrapped expression.
/// </remarks>
[UnwrappableMethod]
public static TResult Expand<TParameter, TResult>(
this Expression<Func<TParameter, TResult>> expression,
TParameter parameter)
{
throw new InvalidOperationException();
}
/// <summary>
/// Invoke an expression with two parameters.
/// </summary>
/// <typeparam name="TParam1">
/// The first parameter type.
/// </typeparam>
/// <typeparam name="TParam2">
/// The second parameter type.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the expression.
/// </typeparam>
/// <param name="expression">
/// The expression to invoke.
/// </param>
/// <param name="param1">
/// The first parameter.
/// </param>
/// <param name="param2">
/// The second parameter.
/// </param>
/// <returns>
/// The result of the expression.
/// </returns>
/// <remarks>
/// When used in an expression, this call can be unwrapped.
/// This method should not be used outside of an unwrapped expression.
/// </remarks>
[UnwrappableMethod]
public static TResult Expand<TParam1, TParam2, TResult>(
this Expression<Func<TParam1, TParam2, TResult>> expression,
TParam1 param1,
TParam2 param2)
{
throw new InvalidOperationException();
}
/// <summary>
/// Unwraps any <see cref="Expand{TParameter, TResult}(Expression{Func{TParameter, TResult}}, TParameter)"/>
/// calls
/// within the given expression.
/// </summary>
/// <typeparam name="TParam">
/// The first parameter type.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the expression.
/// </typeparam>
/// <param name="expression">
/// The expression to unwrap.
/// </param>
/// <returns>
/// The unwrapped expression.
/// </returns>
public static Expression<Func<TParam, TResult>> Unwrap<TParam, TResult>(
this Expression<Func<TParam, TResult>> expression)
{
return new UnwrapVisitor()
.Visit(expression)
as Expression<Func<TParam, TResult>>;
}
/// <summary>
/// Combines a call to <see cref="Unwrap{TParam, TResult}(Expression{Func{TParam, TResult}})"/>
/// with a call to
/// <see cref="System.Linq.Queryable.Select{TSource, TResult}(IQueryable{TSource}, Expression{Func{TSource, TResult}})"/>.
/// </summary>
/// <typeparam name="TSource">
/// The type of the source of elements.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the projected value.
/// </typeparam>
/// <param name="source">
/// The source of elements.
/// </param>
/// <param name="expression">
/// The projector.
/// </param>
/// <returns>
/// A collection.
/// </returns>
/// <remarks>
/// Can be useful for anonymously typed objects.
/// </remarks>
public static IQueryable<TResult> UnwrappedSelect<TSource, TResult>(
this IQueryable<TSource> source,
Expression<Func<TSource, TResult>> expression)
{
return source.Select(expression.Unwrap());
}
/// <summary>
/// Combines a call to <see cref="Unwrap{TParam, TResult}(Expression{Func{TParam, TResult}})"/>
/// with a call to
/// <see cref="System.Linq.Queryable.Where{TSource}(IQueryable{TSource}, Expression{Func{TSource, Boolean}})"/>.
/// </summary>
/// <typeparam name="TSource">
/// The type of the source of elements.
/// </typeparam>
/// <param name="source">
/// The source of elements.
/// </param>
/// <param name="filter">
/// The filter.
/// </param>
/// <returns>
/// A collection.
/// </returns>
/// <remarks>
/// Can be useful for anonymously typed objects.
/// </remarks>
public static IQueryable<TSource> UnwrappedWhere<TSource>(
this IQueryable<TSource> source,
Expression<Func<TSource, bool>> filter)
{
return source.Where(filter.Unwrap());
}
/// <summary>
/// Unwraps any <see cref="Expand{TParameter, TResult}(Expression{Func{TParameter, TResult}}, TParameter)"/>
/// calls
/// within the given expression.
/// </summary>
/// <typeparam name="TParam1">
/// The first parameter type.
/// </typeparam>
/// <typeparam name="TParam2">
/// The second parameter type.
/// </typeparam>
/// <typeparam name="TValue">
/// The return type of the expression.
/// </typeparam>
/// <param name="expression">
/// The expression to unwrap.
/// </param>
/// <returns>
/// The unwrapped expression.
/// </returns>
public static Expression<Func<TParam1, TParam2, TValue>> Unwrap<TParam1, TParam2, TValue>(
this Expression<Func<TParam1, TParam2, TValue>> expression)
{
return new UnwrapVisitor()
.Visit(expression)
as Expression<Func<TParam1, TParam2, TValue>>;
}
/// <summary>
/// An expression that simply returns false.
/// </summary>
/// <typeparam name="TParam">
/// The type of the parameter.
/// </typeparam>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> False<TParam>()
{
return model => false;
}
/// <summary>
/// An expression that simply returns true.
/// </summary>
/// <typeparam name="TParam">
/// The type of the parameter.
/// </typeparam>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> True<TParam>()
{
return model => true;
}
/// <summary>
/// Combine two predicates with boolean OR logic.
/// </summary>
/// <typeparam name="TParam">
/// The type of parameter for each expression.
/// </typeparam>
/// <param name="expression">
/// The first expression.
/// </param>
/// <param name="condition">
/// The second expression, only evaluated if the
/// first returns false.
/// </param>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> Or<TParam>(
this Expression<Func<TParam, bool>> expression,
Expression<Func<TParam, bool>> condition)
{
var replaced = new ReplaceVisitor(
condition.Parameters[0],
expression.Parameters[0])
.Visit(condition.Body);
return Expression.Lambda<Func<TParam, bool>>(
Expression.OrElse(
expression.Body,
replaced),
expression.Parameters);
}
/// <summary>
/// Combine two predicates with boolean AND logic.
/// </summary>
/// <typeparam name="TParam">
/// The type of parameter for each expression.
/// </typeparam>
/// <param name="expression">
/// The first expression.
/// </param>
/// <param name="condition">
/// The second expression, not evaluated if the
/// first returns false.
/// </param>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> And<TParam>(
this Expression<Func<TParam, bool>> expression,
Expression<Func<TParam, bool>> condition)
{
var replaced = new ReplaceVisitor(
condition.Parameters[0],
expression.Parameters[0])
.Visit(condition.Body);
return Expression.Lambda<Func<TParam, bool>>(
Expression.AndAlso(
expression.Body,
replaced),
expression.Parameters);
}
/// <summary>
/// Combine a series of expressions with boolean AND logic.
/// </summary>
/// <typeparam name="TParam">
/// The type of parameter for every expression.
/// </typeparam>
/// <param name="expressions">
/// The expressions.
/// </param>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> All<TParam>(
params Expression<Func<TParam, bool>>[] expressions)
{
var head = expressions.First();
var tail = expressions.Skip(1);
foreach (var expression in tail)
head = head.And(expression);
return head;
}
/// <summary>
/// Combine a series of expressions with boolean OR logic.
/// </summary>
/// <typeparam name="TParam">
/// The type of parameter for every expression.
/// </typeparam>
/// <param name="expressions">
/// The expressions.
/// </param>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> Any<TParam>(
params Expression<Func<TParam, bool>>[] expressions)
{
var head = expressions.First();
var tail = expressions.Skip(1);
foreach (var expression in tail)
head = head.Or(expression);
return head;
}
/// <summary>
/// Invert a boolean expression.
/// </summary>
/// <typeparam name="TParam">
/// The type of parameter for the expression.
/// </typeparam>
/// <param name="predicate">
/// The expression.
/// </param>
/// <returns>
/// An expression.
/// </returns>
public static Expression<Func<TParam, bool>> Inverse<TParam>(
this Expression<Func<TParam, bool>> predicate)
{
return Expression.Lambda<Func<TParam, bool>>(
new InvertVisitor().Visit(predicate.Body),
predicate.Parameters);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Graph.RBAC;
using Microsoft.Azure.Graph.RBAC.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Graph.RBAC
{
/// <summary>
/// Operations for working with Users in Azure Active Directory Graph API.
/// (see http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx for
/// more information)
/// </summary>
internal partial class UserOperations : IServiceOperations<GraphRbacManagementClient>, IUserOperations
{
/// <summary>
/// Initializes a new instance of the UserOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal UserOperations(GraphRbacManagementClient client)
{
this._client = client;
}
private GraphRbacManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Graph.RBAC.GraphRbacManagementClient.
/// </summary>
public GraphRbacManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a new user. (see
/// http://msdn.microsoft.com/en-us/library/azure/dn130117.aspx for
/// more information)
/// </summary>
/// <param name='parameters'>
/// Required. Parameters to create a user.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Server response for Get user information API call
/// </returns>
public async Task<UserGetResult> CreateAsync(UserCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.DisplayName == null)
{
throw new ArgumentNullException("parameters.DisplayName");
}
if (parameters.MailNickname == null)
{
throw new ArgumentNullException("parameters.MailNickname");
}
if (parameters.PasswordProfileSettings == null)
{
throw new ArgumentNullException("parameters.PasswordProfileSettings");
}
if (parameters.PasswordProfileSettings.Password == null)
{
throw new ArgumentNullException("parameters.PasswordProfileSettings.Password");
}
if (parameters.UserPrincipalName == null)
{
throw new ArgumentNullException("parameters.UserPrincipalName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.TenantID);
url = url + "/users";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.6-internal");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject userCreateParametersValue = new JObject();
requestDoc = userCreateParametersValue;
userCreateParametersValue["userPrincipalName"] = parameters.UserPrincipalName;
userCreateParametersValue["accountEnabled"] = parameters.AccountEnabled;
userCreateParametersValue["displayName"] = parameters.DisplayName;
userCreateParametersValue["mailNickname"] = parameters.MailNickname;
JObject passwordProfileValue = new JObject();
userCreateParametersValue["passwordProfile"] = passwordProfileValue;
passwordProfileValue["password"] = parameters.PasswordProfileSettings.Password;
passwordProfileValue["forceChangePasswordNextLogin"] = parameters.PasswordProfileSettings.ForceChangePasswordNextLogin;
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
UserGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new UserGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
User userInstance = new User();
result.User = userInstance;
JToken objectIdValue = responseDoc["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
string objectIdInstance = ((string)objectIdValue);
userInstance.ObjectId = objectIdInstance;
}
JToken objectTypeValue = responseDoc["objectType"];
if (objectTypeValue != null && objectTypeValue.Type != JTokenType.Null)
{
string objectTypeInstance = ((string)objectTypeValue);
userInstance.ObjectType = objectTypeInstance;
}
JToken userPrincipalNameValue = responseDoc["userPrincipalName"];
if (userPrincipalNameValue != null && userPrincipalNameValue.Type != JTokenType.Null)
{
string userPrincipalNameInstance = ((string)userPrincipalNameValue);
userInstance.UserPrincipalName = userPrincipalNameInstance;
}
JToken displayNameValue = responseDoc["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
userInstance.DisplayName = displayNameInstance;
}
JToken mailValue = responseDoc["mail"];
if (mailValue != null && mailValue.Type != JTokenType.Null)
{
string mailInstance = ((string)mailValue);
userInstance.Mail = mailInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete a user. (see
/// http://msdn.microsoft.com/en-us/library/azure/dn151676.aspx for
/// more information)
/// </summary>
/// <param name='user'>
/// Required. user object id or user principal name
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string user, CancellationToken cancellationToken)
{
// Validate
if (user == null)
{
throw new ArgumentNullException("user");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("user", user);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.TenantID);
url = url + "/users/";
url = url + user;
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.6-internal");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets user information from the directory. (see
/// http://msdn.microsoft.com/en-us/library/azure/dn151678.aspx for
/// more information)
/// </summary>
/// <param name='upnOrObjectId'>
/// Required. User object Id or user principal name to get user
/// information.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Server response for Get user information API call
/// </returns>
public async Task<UserGetResult> GetAsync(string upnOrObjectId, CancellationToken cancellationToken)
{
// Validate
if (upnOrObjectId == null)
{
throw new ArgumentNullException("upnOrObjectId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("upnOrObjectId", upnOrObjectId);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.TenantID);
url = url + "/users/";
url = url + upnOrObjectId;
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.6-internal");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
UserGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new UserGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
User userInstance = new User();
result.User = userInstance;
JToken objectIdValue = responseDoc["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
string objectIdInstance = ((string)objectIdValue);
userInstance.ObjectId = objectIdInstance;
}
JToken objectTypeValue = responseDoc["objectType"];
if (objectTypeValue != null && objectTypeValue.Type != JTokenType.Null)
{
string objectTypeInstance = ((string)objectTypeValue);
userInstance.ObjectType = objectTypeInstance;
}
JToken userPrincipalNameValue = responseDoc["userPrincipalName"];
if (userPrincipalNameValue != null && userPrincipalNameValue.Type != JTokenType.Null)
{
string userPrincipalNameInstance = ((string)userPrincipalNameValue);
userInstance.UserPrincipalName = userPrincipalNameInstance;
}
JToken displayNameValue = responseDoc["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
userInstance.DisplayName = displayNameInstance;
}
JToken mailValue = responseDoc["mail"];
if (mailValue != null && mailValue.Type != JTokenType.Null)
{
string mailInstance = ((string)mailValue);
userInstance.Mail = mailInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets user information from the directory.
/// </summary>
/// <param name='userPrincipalName'>
/// Required. Filter based on userPrincipalName. This works well with
/// guest users upn.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Server response for Get tenant users API call
/// </returns>
public async Task<UserListResult> GetByUserPrincipalNameAsync(string userPrincipalName, CancellationToken cancellationToken)
{
// Validate
if (userPrincipalName == null)
{
throw new ArgumentNullException("userPrincipalName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("userPrincipalName", userPrincipalName);
TracingAdapter.Enter(invocationId, this, "GetByUserPrincipalNameAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.TenantID);
url = url + "/users";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
odataFilter.Add("userPrincipalName eq '" + Uri.EscapeDataString(userPrincipalName) + "'");
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
queryParameters.Add("api-version=1.6-internal");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
UserListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new UserListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
User userInstance = new User();
result.Users.Add(userInstance);
JToken objectIdValue = valueValue["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
string objectIdInstance = ((string)objectIdValue);
userInstance.ObjectId = objectIdInstance;
}
JToken objectTypeValue = valueValue["objectType"];
if (objectTypeValue != null && objectTypeValue.Type != JTokenType.Null)
{
string objectTypeInstance = ((string)objectTypeValue);
userInstance.ObjectType = objectTypeInstance;
}
JToken userPrincipalNameValue = valueValue["userPrincipalName"];
if (userPrincipalNameValue != null && userPrincipalNameValue.Type != JTokenType.Null)
{
string userPrincipalNameInstance = ((string)userPrincipalNameValue);
userInstance.UserPrincipalName = userPrincipalNameInstance;
}
JToken displayNameValue = valueValue["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
userInstance.DisplayName = displayNameInstance;
}
JToken mailValue = valueValue["mail"];
if (mailValue != null && mailValue.Type != JTokenType.Null)
{
string mailInstance = ((string)mailValue);
userInstance.Mail = mailInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a collection that contains the Object IDs of the groups of
/// which the user is a member.
/// </summary>
/// <param name='parameters'>
/// Required. User filtering parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Server response for GetMemberGroups API call
/// </returns>
public async Task<UserGetMemberGroupsResult> GetMemberGroupsAsync(UserGetMemberGroupsParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.ObjectId == null)
{
throw new ArgumentNullException("parameters.ObjectId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "GetMemberGroupsAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.TenantID);
url = url + "/users/";
url = url + parameters.ObjectId;
url = url + "/getMemberGroups";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.6-internal");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject userGetMemberGroupsParametersValue = new JObject();
requestDoc = userGetMemberGroupsParametersValue;
userGetMemberGroupsParametersValue["securityEnabledOnly"] = parameters.SecurityEnabledOnly;
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
UserGetMemberGroupsResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new UserGetMemberGroupsResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
result.ObjectIds.Add(((string)valueValue));
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets list of users for the current tenant.
/// </summary>
/// <param name='mail'>
/// Optional. Email to filter results.
/// </param>
/// <param name='displayNameStartsWith'>
/// Optional. Display name to filter results.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Server response for Get tenant users API call
/// </returns>
public async Task<UserListResult> ListAsync(string mail, string displayNameStartsWith, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("mail", mail);
tracingParameters.Add("displayNameStartsWith", displayNameStartsWith);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.TenantID);
url = url + "/users";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
if (mail != null)
{
odataFilter.Add("mail eq '" + Uri.EscapeDataString(mail) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
List<string> odataFilter2 = new List<string>();
if (displayNameStartsWith != null)
{
odataFilter2.Add("startswith(displayName,'" + Uri.EscapeDataString(displayNameStartsWith) + "')");
}
if (odataFilter2.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter2));
}
queryParameters.Add("api-version=1.6-internal");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
UserListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new UserListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
User userInstance = new User();
result.Users.Add(userInstance);
JToken objectIdValue = valueValue["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
string objectIdInstance = ((string)objectIdValue);
userInstance.ObjectId = objectIdInstance;
}
JToken objectTypeValue = valueValue["objectType"];
if (objectTypeValue != null && objectTypeValue.Type != JTokenType.Null)
{
string objectTypeInstance = ((string)objectTypeValue);
userInstance.ObjectType = objectTypeInstance;
}
JToken userPrincipalNameValue = valueValue["userPrincipalName"];
if (userPrincipalNameValue != null && userPrincipalNameValue.Type != JTokenType.Null)
{
string userPrincipalNameInstance = ((string)userPrincipalNameValue);
userInstance.UserPrincipalName = userPrincipalNameInstance;
}
JToken displayNameValue = valueValue["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
userInstance.DisplayName = displayNameInstance;
}
JToken mailValue = valueValue["mail"];
if (mailValue != null && mailValue.Type != JTokenType.Null)
{
string mailInstance = ((string)mailValue);
userInstance.Mail = mailInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets list of users for the current tenant.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Server response for Get tenant users API call
/// </returns>
public async Task<UserListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.TenantID);
url = url + "/";
url = url + nextLink;
url = url + "&api-version=1.6-internal";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
UserListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new UserListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
User userInstance = new User();
result.Users.Add(userInstance);
JToken objectIdValue = valueValue["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
string objectIdInstance = ((string)objectIdValue);
userInstance.ObjectId = objectIdInstance;
}
JToken objectTypeValue = valueValue["objectType"];
if (objectTypeValue != null && objectTypeValue.Type != JTokenType.Null)
{
string objectTypeInstance = ((string)objectTypeValue);
userInstance.ObjectType = objectTypeInstance;
}
JToken userPrincipalNameValue = valueValue["userPrincipalName"];
if (userPrincipalNameValue != null && userPrincipalNameValue.Type != JTokenType.Null)
{
string userPrincipalNameInstance = ((string)userPrincipalNameValue);
userInstance.UserPrincipalName = userPrincipalNameInstance;
}
JToken displayNameValue = valueValue["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
userInstance.DisplayName = displayNameInstance;
}
JToken mailValue = valueValue["mail"];
if (mailValue != null && mailValue.Type != JTokenType.Null)
{
string mailInstance = ((string)mailValue);
userInstance.Mail = mailInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
namespace AreaImportExportTool
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.txtTeamProject = new System.Windows.Forms.TextBox();
this.txtCollectionUri = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.chkIterationStructure = new System.Windows.Forms.CheckBox();
this.chkAreaStructure = new System.Windows.Forms.CheckBox();
this.label3 = new System.Windows.Forms.Label();
this.cmdExport = new System.Windows.Forms.Button();
this.cmdImport = new System.Windows.Forms.Button();
this.cmdClose = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.txtTeamProject);
this.groupBox1.Controls.Add(this.txtCollectionUri);
this.groupBox1.Location = new System.Drawing.Point(14, 15);
this.groupBox1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Padding = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBox1.Size = new System.Drawing.Size(385, 116);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "General";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(7, 70);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(79, 15);
this.label2.TabIndex = 2;
this.label2.Text = "Team &Project:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(7, 34);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(107, 15);
this.label1.TabIndex = 0;
this.label1.Text = "TFS Collection URI:";
//
// txtTeamProject
//
this.txtTeamProject.Location = new System.Drawing.Point(125, 66);
this.txtTeamProject.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.txtTeamProject.Name = "txtTeamProject";
this.txtTeamProject.Size = new System.Drawing.Size(249, 23);
this.txtTeamProject.TabIndex = 3;
this.txtTeamProject.TextChanged += new System.EventHandler(this.chkIterationStructure_CheckedChanged);
//
// txtCollectionUri
//
this.txtCollectionUri.Location = new System.Drawing.Point(125, 30);
this.txtCollectionUri.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.txtCollectionUri.Name = "txtCollectionUri";
this.txtCollectionUri.Size = new System.Drawing.Size(249, 23);
this.txtCollectionUri.TabIndex = 1;
this.txtCollectionUri.TextChanged += new System.EventHandler(this.chkIterationStructure_CheckedChanged);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.chkIterationStructure);
this.groupBox2.Controls.Add(this.chkAreaStructure);
this.groupBox2.Location = new System.Drawing.Point(14, 139);
this.groupBox2.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Padding = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBox2.Size = new System.Drawing.Size(385, 116);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Choose items to im-/export";
//
// chkIterationStructure
//
this.chkIterationStructure.AutoSize = true;
this.chkIterationStructure.Checked = true;
this.chkIterationStructure.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkIterationStructure.Location = new System.Drawing.Point(10, 68);
this.chkIterationStructure.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.chkIterationStructure.Name = "chkIterationStructure";
this.chkIterationStructure.Size = new System.Drawing.Size(120, 19);
this.chkIterationStructure.TabIndex = 1;
this.chkIterationStructure.Text = "&Iteration structure";
this.chkIterationStructure.UseVisualStyleBackColor = true;
this.chkIterationStructure.CheckedChanged += new System.EventHandler(this.chkIterationStructure_CheckedChanged);
//
// chkAreaStructure
//
this.chkAreaStructure.AutoSize = true;
this.chkAreaStructure.Checked = true;
this.chkAreaStructure.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkAreaStructure.Location = new System.Drawing.Point(10, 34);
this.chkAreaStructure.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.chkAreaStructure.Name = "chkAreaStructure";
this.chkAreaStructure.Size = new System.Drawing.Size(100, 19);
this.chkAreaStructure.TabIndex = 0;
this.chkAreaStructure.Text = "&Area structure";
this.chkAreaStructure.UseVisualStyleBackColor = true;
this.chkAreaStructure.CheckedChanged += new System.EventHandler(this.chkIterationStructure_CheckedChanged);
//
// label3
//
this.label3.Location = new System.Drawing.Point(21, 270);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(378, 55);
this.label3.TabIndex = 2;
this.label3.Text = "Note: This tool does not im-/export permissions that might be assigned to areas o" +
"r iterations.";
//
// cmdExport
//
this.cmdExport.Location = new System.Drawing.Point(24, 329);
this.cmdExport.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.cmdExport.Name = "cmdExport";
this.cmdExport.Size = new System.Drawing.Size(87, 29);
this.cmdExport.TabIndex = 3;
this.cmdExport.Text = "&Export...";
this.cmdExport.UseVisualStyleBackColor = true;
this.cmdExport.Click += new System.EventHandler(this.cmdExport_Click);
//
// cmdImport
//
this.cmdImport.Location = new System.Drawing.Point(119, 329);
this.cmdImport.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.cmdImport.Name = "cmdImport";
this.cmdImport.Size = new System.Drawing.Size(87, 29);
this.cmdImport.TabIndex = 4;
this.cmdImport.Text = "&Import...";
this.cmdImport.UseVisualStyleBackColor = true;
this.cmdImport.Click += new System.EventHandler(this.cmdImport_Click);
//
// cmdClose
//
this.cmdClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cmdClose.Location = new System.Drawing.Point(213, 329);
this.cmdClose.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.cmdClose.Name = "cmdClose";
this.cmdClose.Size = new System.Drawing.Size(87, 29);
this.cmdClose.TabIndex = 5;
this.cmdClose.Text = "&Close";
this.cmdClose.UseVisualStyleBackColor = true;
this.cmdClose.Click += new System.EventHandler(this.cmdClose_Click);
//
// MainForm
//
this.AcceptButton = this.cmdExport;
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.cmdClose;
this.ClientSize = new System.Drawing.Size(420, 375);
this.Controls.Add(this.cmdClose);
this.Controls.Add(this.cmdImport);
this.Controls.Add(this.cmdExport);
this.Controls.Add(this.label3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Area Import/Export Tool (for TFS 2010)";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtCollectionUri;
private System.Windows.Forms.TextBox txtTeamProject;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.CheckBox chkIterationStructure;
private System.Windows.Forms.CheckBox chkAreaStructure;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button cmdExport;
private System.Windows.Forms.Button cmdImport;
private System.Windows.Forms.Button cmdClose;
}
}
| |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*/
// To disabled special debugging features, simply uncomment this line.
// #undef DEBUG
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Reflection;
namespace CKFinder.Connector
{
/// <summary>
/// The class handles all requests sent to the CKFinder connector file,
/// connector.aspx.
/// </summary>
public class Connector : Page
{
/// <summary>
/// The "ConfigFile" object, is the instance of config.ascx, present in
/// the connector.aspx file. It makes it possible to configure CKFinder
/// whithout having to compile it.
/// </summary>
public Settings.ConfigFile ConfigFile;
public CKFinderPlugin[] Plugins;
public List<string> JavascriptPlugins;
public CKFinderEvent CKFinderEvent = new CKFinderEvent();
#region Disable ASP.NET features
/// <summary>
/// Theming is disabled as it interferes in the connector response data.
/// </summary>
public override bool EnableTheming
{
get { return false; }
set { /* Ignore it with no error */ }
}
/// <summary>
/// Master Page is disabled as it interferes in the connector response data.
/// </summary>
public override string MasterPageFile
{
get { return null; }
set { /* Ignore it with no error */ }
}
/// <summary>
/// Theming is disabled as it interferes in the connector response data.
/// </summary>
public override string Theme
{
get { return ""; }
set { /* Ignore it with no error */ }
}
/// <summary>
/// Theming is disabled as it interferes in the connector response data.
/// </summary>
public override string StyleSheetTheme
{
get { return ""; }
set { /* Ignore it with no error */ }
}
#endregion
protected void LoadPlugins()
{
Config _Config = Config.Current;
if ( _Config.Plugins == null || _Config.Plugins.Length == 0 )
return;
Plugins = new CKFinderPlugin[_Config.Plugins.Length];
JavascriptPlugins = new List<string>();
for ( int i = 0; i < _Config.Plugins.Length; i++ )
{
int j = 0;
if ( _Config.Plugins[i].IndexOf( "," ) != -1 )
{
this.Plugins[j] = (CKFinderPlugin)Activator.CreateInstance( Type.GetType( _Config.Plugins[i] ) );
this.Plugins[j].Init( CKFinderEvent );
if ( this.Plugins[j].JavascriptPlugins.Length > 0 )
{
this.JavascriptPlugins.Add( this.Plugins[j].JavascriptPlugins );
}
j++;
}
else
{
this.JavascriptPlugins.Add( _Config.Plugins[i] );
}
}
}
protected override void OnLoad( EventArgs e )
{
// Set the config file instance as the current one (to avoid singleton issues).
ConfigFile.SetCurrent();
// Load the config file settings.
ConfigFile.SetConfig();
// Load plugins.
LoadPlugins();
#if (DEBUG)
// For testing purposes, we may force the user to get the Admin role.
// Session[ "CKFinder_UserRole" ] = "Admin";
// Simulate slow connections.
// System.Threading.Thread.Sleep( 2000 );
#endif
CommandHandlers.CommandHandlerBase commandHandler = null;
try
{
// Take the desired command from the querystring.
string command = Request.QueryString["command"];
if ( command == null )
ConnectorException.Throw( Errors.InvalidCommand );
else
{
CKFinderEvent.ActivateEvent( CKFinderEvent.Hooks.BeforeExecuteCommand, command, Response );
// Create an instance of the class that handles the
// requested command.
switch ( command )
{
case "Init":
commandHandler = new CommandHandlers.InitCommandHandler();
break;
case "LoadCookies":
commandHandler = new CommandHandlers.LoadCookiesCommandHandler();
break;
case "GetFolders":
commandHandler = new CommandHandlers.GetFoldersCommandHandler();
break;
case "GetFiles":
commandHandler = new CommandHandlers.GetFilesCommandHandler();
break;
case "Thumbnail":
commandHandler = new CommandHandlers.ThumbnailCommandHandler();
break;
case "CreateFolder":
commandHandler = new CommandHandlers.CreateFolderCommandHandler();
break;
case "RenameFolder":
commandHandler = new CommandHandlers.RenameFolderCommandHandler();
break;
case "DeleteFolder":
commandHandler = new CommandHandlers.DeleteFolderCommandHandler();
break;
case "FileUpload":
commandHandler = new CommandHandlers.FileUploadCommandHandler();
break;
case "QuickUpload":
commandHandler = new CommandHandlers.QuickUploadCommandHandler();
break;
case "DownloadFile":
commandHandler = new CommandHandlers.DownloadFileCommandHandler();
break;
case "RenameFile":
commandHandler = new CommandHandlers.RenameFileCommandHandler();
break;
case "DeleteFiles":
commandHandler = new CommandHandlers.DeleteFilesCommandHandler();
break;
case "CopyFiles":
commandHandler = new CommandHandlers.CopyFilesCommandHandler();
break;
case "MoveFiles":
commandHandler = new CommandHandlers.MoveFilesCommandHandler();
break;
default:
ConnectorException.Throw( Errors.InvalidCommand );
break;
}
}
// Send the appropriate response.
if ( commandHandler != null )
commandHandler.SendResponse( Response );
}
catch ( ConnectorException connectorException )
{
#if DEBUG
// While debugging, throwing the error gives us more useful
// information.
throw connectorException;
#else
commandHandler = new CommandHandlers.ErrorCommandHandler( connectorException );
commandHandler.SendResponse( Response );
#endif
}
}
public static bool CheckFolderName(string folderName)
{
Config _Config = Config.Current;
if ( _Config.DisallowUnsafeCharacters && folderName.Contains(".") )
return false;
return Connector.CheckFileName(folderName);
}
public static bool CheckFileName( string fileName )
{
if ( fileName == null || fileName.Length == 0 || fileName.StartsWith( "." ) || fileName.EndsWith( "." ) || fileName.Contains( ".." ) )
return false;
if ( Regex.IsMatch( fileName, @"[/\\:\*\?""\<\>\|\p{C}]" ) )
return false;
Config _Config = Config.Current;
if ( _Config.DisallowUnsafeCharacters && fileName.Contains(";") )
return false;
return true;
}
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************
using System;
using System.Collections;
using NUnit.Core;
using NUnit.Framework;
namespace NUnit.Util.Tests
{
[TestFixture]
public class EventDispatcherTests
{
private TestEventDispatcher dispatcher;
private TestEventCatcher catcher;
private TestInfo test;
private TestResult result;
private Exception exception;
private readonly string FILENAME = "MyTestFileName";
private readonly string TESTNAME = "MyTestName";
private readonly string MESSAGE = "My message!";
private readonly string RSLTNAME = "MyResult";
[SetUp]
public void SetUp()
{
dispatcher = new TestEventDispatcher();
catcher = new TestEventCatcher( dispatcher );
test = new TestInfo( new TestSuite( TESTNAME ) );
result = new TestSuiteResult( test, RSLTNAME );
exception = new Exception( MESSAGE );
}
[Test]
public void ProjectLoading()
{
dispatcher.FireProjectLoading( FILENAME );
CheckEvent( TestAction.ProjectLoading, FILENAME );
}
[Test]
public void ProjectLoaded()
{
dispatcher.FireProjectLoaded( FILENAME );
CheckEvent( TestAction.ProjectLoaded, FILENAME );
}
[Test]
public void ProjectLoadFailed()
{
dispatcher.FireProjectLoadFailed( FILENAME, exception );
CheckEvent( TestAction.ProjectLoadFailed, FILENAME, exception );
}
[Test]
public void ProjectUnloading()
{
dispatcher.FireProjectUnloading( FILENAME );
CheckEvent( TestAction.ProjectUnloading, FILENAME );
}
[Test]
public void ProjectUnloaded()
{
dispatcher.FireProjectUnloaded( FILENAME );
CheckEvent( TestAction.ProjectUnloaded, FILENAME );
}
[Test]
public void ProjectUnloadFailed()
{
dispatcher.FireProjectUnloadFailed( FILENAME, exception );
CheckEvent( TestAction.ProjectUnloadFailed, FILENAME, exception );
}
[Test]
public void TestLoading()
{
dispatcher.FireTestLoading( FILENAME );
CheckEvent( TestAction.TestLoading, FILENAME );
}
[Test]
public void TestLoaded()
{
dispatcher.FireTestLoaded( FILENAME, test );
CheckEvent( TestAction.TestLoaded, FILENAME, test );
}
[Test]
public void TestLoadFailed()
{
dispatcher.FireTestLoadFailed( FILENAME, exception );
CheckEvent( TestAction.TestLoadFailed, FILENAME, exception );
}
[Test]
public void TestUnloading()
{
dispatcher.FireTestUnloading( FILENAME );
CheckEvent( TestAction.TestUnloading, FILENAME );
}
[Test]
public void TestUnloaded()
{
dispatcher.FireTestUnloaded( FILENAME );
CheckEvent( TestAction.TestUnloaded, FILENAME );
}
[Test]
public void TestUnloadFailed()
{
dispatcher.FireTestUnloadFailed( FILENAME, exception );
CheckEvent( TestAction.TestUnloadFailed, FILENAME, exception );
}
[Test]
public void TestReloading()
{
dispatcher.FireTestReloading( FILENAME );
CheckEvent( TestAction.TestReloading, FILENAME );
}
[Test]
public void TestReloaded()
{
dispatcher.FireTestReloaded( FILENAME, test );
CheckEvent( TestAction.TestReloaded, FILENAME, test );
}
[Test]
public void TestReloadFailed()
{
dispatcher.FireTestReloadFailed( FILENAME, exception );
CheckEvent( TestAction.TestReloadFailed, FILENAME, exception );
}
[Test]
public void RunStarting()
{
dispatcher.FireRunStarting( test.TestName.FullName, test.TestCount );
CheckEvent( TestAction.RunStarting, test.TestName.FullName, test.TestCount );
}
[Test]
public void RunFinished()
{
dispatcher.FireRunFinished( result );
CheckEvent( TestAction.RunFinished, result );
}
[Test]
public void RunFailed()
{
dispatcher.FireRunFinished( exception );
CheckEvent( TestAction.RunFinished, exception );
}
[Test]
public void SuiteStarting()
{
dispatcher.FireSuiteStarting( test.TestName );
CheckEvent( TestAction.SuiteStarting, test.TestName );
}
[Test]
public void SuiteFinished()
{
dispatcher.FireSuiteFinished( result );
CheckEvent( TestAction.SuiteFinished, result );
}
[Test]
public void TestStarting()
{
dispatcher.FireTestStarting( test.TestName );
CheckEvent( TestAction.TestStarting, test.TestName );
}
[Test]
public void TestFinished()
{
dispatcher.FireTestFinished( result );
CheckEvent( TestAction.TestFinished, result );
}
private void CheckEvent( TestAction action )
{
Assert.AreEqual( 1, catcher.Events.Count );
Assert.AreEqual( action, ((TestEventArgs)catcher.Events[0]).Action );
}
private void CheckEvent( TestAction action, string fileName )
{
CheckEvent( action );
Assert.AreEqual( fileName, ((TestEventArgs)catcher.Events[0]).Name );
}
private void CheckEvent( TestAction action, string fileName, int testCount )
{
CheckEvent( action, fileName );
Assert.AreEqual( testCount, ((TestEventArgs)catcher.Events[0]).TestCount );
}
private void CheckEvent( TestAction action, string fileName, TestInfo test )
{
CheckEvent( action, fileName );
Assert.AreEqual( TESTNAME, ((TestEventArgs)catcher.Events[0]).Test.TestName.Name );
}
private void CheckEvent( TestAction action, string fileName, Exception exception )
{
CheckEvent( action, fileName );
Assert.AreEqual( MESSAGE, ((TestEventArgs)catcher.Events[0]).Exception.Message );
}
private void CheckEvent( TestAction action, TestName testName )
{
CheckEvent( action );
Assert.AreEqual( TESTNAME, ((TestEventArgs)catcher.Events[0]).TestName.Name );
}
private void CheckEvent( TestAction action, TestResult result )
{
CheckEvent( action );
Assert.AreEqual( RSLTNAME, result.Name );
}
private void CheckEvent( TestAction action, Exception exception )
{
CheckEvent( TestAction.RunFinished );
Assert.AreEqual( MESSAGE, ((TestEventArgs)catcher.Events[0]).Exception.Message );
}
}
}
| |
// 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.Web.Command;
using System.Collections;
using Alachisoft.NCache.Common.Protobuf;
using Alachisoft.NCache.Common.DataStructures;
using Alachisoft.NCache.Runtime.Exceptions;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Common.Stats;
using Common = Alachisoft.NCache.Common;
namespace Alachisoft.NCache.Web.Communication
{
internal class Request
{
private long _requestId = -1;
private bool _isAsync = false;
private bool _isBulk = false;
private bool _isAsyncCallbackSpecified = false;
private string _name;
private CommandResponse _finalResponse = null;
private object _responseMutex = new object();
private Alachisoft.NCache.Common.Protobuf.Response.Type _type;
private Dictionary<Common.Net.Address, ResponseList> _responses = new Dictionary<Common.Net.Address, ResponseList>();
private Dictionary<Common.Net.Address, CommandBase> _commands = new Dictionary<Common.Net.Address, CommandBase>();
private Dictionary<Common.Net.Address, EnumerationDataChunk> _chunks = new Dictionary<Common.Net.Address, EnumerationDataChunk>();
private long _timeout = 90000;
private bool _isrequestTimeoutReset = false;
private bool _resend = false;
private Common.Net.Address _reRoutedAddress = null;
public Request(bool isBulk, long timeout)
{
_isBulk = isBulk;
_timeout = timeout;
}
internal bool IsRequestTimeoutReset
{
get { return _isrequestTimeoutReset; }
set { _isrequestTimeoutReset = value; }
}
internal bool IsResendReuest
{
get { return _resend; }
set { _resend = value; }
}
internal long RequestTimeout
{
get { return _timeout; }
set { _timeout = value; }
}
internal string Name
{
get { return _name; }
set { _name = value; }
}
internal bool IsAyncCallbackSpecified
{
get { return _isAsyncCallbackSpecified; }
set { _isAsyncCallbackSpecified = value; }
}
internal bool IsAsync
{
get { return _isAsync; }
set { _isAsync = value; }
}
internal Common.Net.Address ReRoutedAddress
{
get { return _reRoutedAddress; }
set { _reRoutedAddress = value; }
}
internal bool IsBulk
{
get { return _commands.Count > 1 || _isBulk; }
}
internal RequestType CommandRequestType
{
get
{
foreach (CommandBase command in _commands.Values)
{
return command.CommandRequestType;
}
return RequestType.InternalCommand;
}
}
internal bool IsDedicated(long viewId)
{
foreach (CommandBase command in _commands.Values)
{
return command.clientLastViewId == viewId;
}
return false;
}
internal long RequestId
{
get { return _requestId; }
set
{
_requestId = value;
foreach (CommandBase command in _commands.Values)
{
command.RequestId = value;
}
}
}
internal Dictionary<Common.Net.Address, CommandBase> Commands
{
get { return _commands; }
}
internal int NumberOfCompleteResponses
{
get
{
int count = 0;
lock (_responseMutex)
{
foreach (ResponseList responseList in _responses.Values)
{
if (responseList.IsComplete)
count++;
}
}
return count;
}
}
internal string TimeoutMessage
{
get
{
StringBuilder sb = new StringBuilder("Operation timed out. No response from the server(s)." );
sb.Append(" [");
lock (_responseMutex)
{
foreach (Common.Net.Address ip in Commands.Keys)
{
if (!_responses.ContainsKey(ip))
{
sb.Append(ip + ", ");
}
else
{
ResponseList response = _responses[ip];
if (!response.IsComplete)
{
sb.Append(ip + ", ");
}
}
}
}
sb.Remove(sb.Length - 2, 2);
sb.Append("]");
return sb.ToString();
}
}
internal CommandResponse Response
{
get
{
lock (_responseMutex)
{
foreach (KeyValuePair<Common.Net.Address, ResponseList> responses in _responses)
{
foreach (CommandResponse rsp in responses.Value.Responses.Values)
{
//in case exception is not thrown from 1st server.
if (!string.IsNullOrEmpty(rsp.ExceptionMsg) && rsp.ExceptionType != Alachisoft.NCache.Common.Enum.ExceptionType.STATE_TRANSFER_EXCEPTION
&& rsp.ExceptionType != Alachisoft.NCache.Common.Enum.ExceptionType.ATTRIBUTE_INDEX_NOT_FOUND
&& rsp.ExceptionType != Alachisoft.NCache.Common.Enum.ExceptionType.TYPE_INDEX_NOT_FOUND)
{
_finalResponse = rsp;
return _finalResponse;
}
MergeResponse(responses.Key, rsp);
}
}
}
return _finalResponse;
}
}
internal bool Responses
{
get
{
return NumberOfCompleteResponses == _commands.Count;
}
}
internal void AddCommand(Common.Net.Address address, CommandBase command)
{
_name = command.CommandName;
command.Parent = this;
if (!_commands.ContainsKey(address))
_commands.Add(address, command);
}
internal void AddResponse(Common.Net.Address address, CommandResponse response)
{
_type = response.Type;
lock (_responseMutex)
{
if (_responses.ContainsKey(address))
{
ResponseList responseList = _responses[address];
if (!responseList.IsComplete)
{
responseList.AddResponse(response);
}
else
{
if (_reRoutedAddress != null && !_reRoutedAddress.Equals(address))
{
if (!_responses.ContainsKey(_reRoutedAddress))
{
ResponseList rspList = new ResponseList();
if (!rspList.IsComplete)
{
rspList.AddResponse(response);
}
_responses.Add(_reRoutedAddress, rspList);
}
else
{
responseList = _responses[_reRoutedAddress];
if (!responseList.IsComplete)
{
responseList.AddResponse(response);
}
}
}
}
}
}
}
internal void InitializeResponse(Common.Net.Address address)
{
lock (_responseMutex)
{
if (!_responses.ContainsKey(address))
{
_responses.Add(address, new ResponseList());
}
}
}
internal bool RemoveResponse(Common.Net.Address address)
{
lock (_responseMutex)
{
_responses.Remove(address);
bool removeRequestFromTable = _responses.Count == 0;
return removeRequestFromTable;
}
}
internal bool ExpectingResponseFrom(Common.Net.Address address)
{
lock (_responseMutex)
{
bool result = _responses.ContainsKey(address);
return result;
}
}
internal void Reset(Common.Net.Address ip)
{
lock (_responseMutex)
{
if (_responses.ContainsKey(ip))
{
ResponseList responseList = _responses[ip];
responseList.Clear();
responseList.AddResponse(new CommandResponse(true, ip));
_responses[ip] = responseList;
}
}
}
internal void ResetFailedResponse(Common.Net.Address ip)
{
lock (_responseMutex)
{
if (_responses.ContainsKey(ip))
{
ResponseList responseList = _responses[ip];
responseList.Clear();
responseList.AddResponse(new CommandResponse(true, ip));
}
}
}
internal void ResetResponseNodeForShutDown(Common.Net.Address ip)
{
lock (_responseMutex)
{
if (_responses.ContainsKey(ip))
{
ResponseList responseList = _responses[ip];
responseList.Clear();
responseList.AddResponse(new CommandResponse(false, ip));
_resend = true;
}
}
}
internal void SetAggregateFunctionResult()
{
switch (_finalResponse.ResultSet.AggregateFunctionType)
{
case Alachisoft.NCache.Common.Enum.AggregateFunctionType.MAX:
_finalResponse.ResultSet.AggregateFunctionResult = new DictionaryEntry(AggregateFunctionType.MAX, _finalResponse.ResultSet.AggregateFunctionResult.Value);
break;
case Alachisoft.NCache.Common.Enum.AggregateFunctionType.MIN:
_finalResponse.ResultSet.AggregateFunctionResult = new DictionaryEntry(AggregateFunctionType.MIN, _finalResponse.ResultSet.AggregateFunctionResult.Value);
break;
case Alachisoft.NCache.Common.Enum.AggregateFunctionType.COUNT:
_finalResponse.ResultSet.AggregateFunctionResult = new DictionaryEntry(AggregateFunctionType.COUNT, _finalResponse.ResultSet.AggregateFunctionResult.Value);
break;
case Alachisoft.NCache.Common.Enum.AggregateFunctionType.SUM:
_finalResponse.ResultSet.AggregateFunctionResult = new DictionaryEntry(AggregateFunctionType.SUM, _finalResponse.ResultSet.AggregateFunctionResult.Value);
break;
case Alachisoft.NCache.Common.Enum.AggregateFunctionType.AVG:
_finalResponse.ResultSet.AggregateFunctionResult = new DictionaryEntry(AggregateFunctionType.AVG, _finalResponse.ResultSet.AggregateFunctionResult.Value);
break;
}
}
internal void MergeResponse(Common.Net.Address address, CommandResponse response)
{
if (_finalResponse == null && response.Type != Alachisoft.NCache.Common.Protobuf.Response.Type.GET_NEXT_CHUNK)
{
_finalResponse = response;
if (response.IsBrokerReset)
{
MergeFailedResponse(response);
}
}
else
{
if (response.IsBrokerReset)
{
MergeFailedResponse(response);
}
else
{
IDictionaryEnumerator ide = null;
switch (response.Type)
{
case Alachisoft.NCache.Common.Protobuf.Response.Type.ADD_BULK:
case Alachisoft.NCache.Common.Protobuf.Response.Type.INSERT_BULK:
case Alachisoft.NCache.Common.Protobuf.Response.Type.GET_BULK:
case Alachisoft.NCache.Common.Protobuf.Response.Type.REMOVE_BULK:
ide = response.KeyValueDic.GetEnumerator();
while (ide.MoveNext())
{
_finalResponse.KeyValueDic[ide.Key] = ide.Value;
}
break;
case Alachisoft.NCache.Common.Protobuf.Response.Type.SEARCH:
if ((_finalResponse.ExceptionType == Alachisoft.NCache.Common.Enum.ExceptionType.TYPE_INDEX_NOT_FOUND)
|| (_finalResponse.ExceptionType == Alachisoft.NCache.Common.Enum.ExceptionType.ATTRIBUTE_INDEX_NOT_FOUND))
{
_finalResponse = response;
break;
}
switch (response.ResultSet.AggregateFunctionType)
{
case Alachisoft.NCache.Common.Enum.AggregateFunctionType.NOTAPPLICABLE:
_finalResponse.KeyList.AddRange(response.KeyList);
break;
default:
if (!_finalResponse.ResultSet.IsInitialized)
{
SetAggregateFunctionResult();
_finalResponse.ResultSet.Initialize(_finalResponse.ResultSet);
}
_finalResponse.ResultSet.Compile(response.ResultSet);
break;
}
break;
case Alachisoft.NCache.Common.Protobuf.Response.Type.SEARCH_ENTRIES:
if ((_finalResponse.ExceptionType == Alachisoft.NCache.Common.Enum.ExceptionType.TYPE_INDEX_NOT_FOUND)
|| (_finalResponse.ExceptionType == Alachisoft.NCache.Common.Enum.ExceptionType.ATTRIBUTE_INDEX_NOT_FOUND))
{
_finalResponse = response;
break;
}
switch (response.ResultSet.AggregateFunctionType)
{
case Alachisoft.NCache.Common.Enum.AggregateFunctionType.NOTAPPLICABLE:
ide = response.KeyValueDic.GetEnumerator();
while (ide.MoveNext())
{
_finalResponse.KeyValueDic[ide.Key] = ide.Value;
}
break;
default:
if (!_finalResponse.ResultSet.IsInitialized)
{
SetAggregateFunctionResult();
_finalResponse.ResultSet.Initialize(_finalResponse.ResultSet);
}
_finalResponse.ResultSet.Compile(response.ResultSet);
break;
}
break;
case Alachisoft.NCache.Common.Protobuf.Response.Type.GET_NEXT_CHUNK:
if (_finalResponse == null)
_finalResponse = response;
EnumerationDataChunk chunk = null;
if (_chunks.ContainsKey(address))
{
chunk = _chunks[address];
}
else
{
chunk = new EnumerationDataChunk();
chunk.Data = new List<string>();
_chunks.Add(address, chunk);
}
for (int i = 0; i < response.NextChunk.Count; i++)
{
chunk.Data.AddRange(response.NextChunk[i].Data);
chunk.Pointer = response.NextChunk[i].Pointer;
if (chunk.Pointer.NodeIpAddress==null)
chunk.Pointer.NodeIpAddress = address;
}
_finalResponse.NextChunk = new List<EnumerationDataChunk>(_chunks.Values);
break;
case Alachisoft.NCache.Common.Protobuf.Response.Type.EXCEPTION:
if (response.ExceptionType == Common.Enum.ExceptionType.STATE_TRANSFER_EXCEPTION)
{
_finalResponse = response;
}
break;
default:
break;
}
}
}
}
private void MergeFailedResponse(CommandResponse response)
{
CommandBase command;
_commands.TryGetValue(response.ResetConnectionIP, out command);
switch (_type)
{
case Alachisoft.NCache.Common.Protobuf.Response.Type.ADD_BULK:
case Alachisoft.NCache.Common.Protobuf.Response.Type.INSERT_BULK:
case Alachisoft.NCache.Common.Protobuf.Response.Type.GET_BULK:
case Alachisoft.NCache.Common.Protobuf.Response.Type.REMOVE_BULK:
string key;
for (int index = 0; index < command.BulkKeys.Length; index++)
{
key = command.BulkKeys[index];
_finalResponse.KeyValueDic[key] = new ConnectionException("Connection with server lost [" + response.ResetConnectionIP + "]");
}
_finalResponse.SetBroker = false;
break;
case Alachisoft.NCache.Common.Protobuf.Response.Type.SEARCH:
case Alachisoft.NCache.Common.Protobuf.Response.Type.SEARCH_ENTRIES:
_finalResponse.SetBroker = true;
_finalResponse.ResetConnectionIP = response.ResetConnectionIP;
break;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Threading
{
// ManualResetEventSlim wraps a manual-reset event internally with a little bit of
// spinning. When an event will be set imminently, it is often advantageous to avoid
// a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to
// a brief amount of spinning that should, on the average, make using the slim event
// cheaper than using Win32 events directly. This can be reset manually, much like
// a Win32 manual-reset would be.
//
// Notes:
// We lazily allocate the Win32 event internally. Therefore, the caller should
// always call Dispose to clean it up, just in case. This API is a no-op of the
// event wasn't allocated, but if it was, ensures that the event goes away
// eagerly, instead of waiting for finalization.
/// <summary>
/// Provides a slimmed down version of <see cref="System.Threading.ManualResetEvent"/>.
/// </summary>
/// <remarks>
/// All public and protected members of <see cref="ManualResetEventSlim"/> are thread-safe and may be used
/// concurrently from multiple threads, with the exception of Dispose, which
/// must only be used when all other operations on the <see cref="ManualResetEventSlim"/> have
/// completed, and Reset, which should only be used when no other threads are
/// accessing the event.
/// </remarks>
[DebuggerDisplay("Set = {IsSet}")]
public class ManualResetEventSlim : IDisposable
{
// These are the default spin counts we use on single-proc and MP machines.
private const int DEFAULT_SPIN_SP = 1;
private volatile object? m_lock;
// A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated()
private volatile ManualResetEvent? m_eventObj; // A true Win32 event used for waiting.
// -- State -- //
// For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant.
private volatile int m_combinedState; // ie a uint. Used for the state items listed below.
// 1-bit for signalled state
private const int SignalledState_BitMask = unchecked((int)0x80000000); // 1000 0000 0000 0000 0000 0000 0000 0000
private const int SignalledState_ShiftCount = 31;
// 1-bit for disposed state
private const int Dispose_BitMask = unchecked((int)0x40000000); // 0100 0000 0000 0000 0000 0000 0000 0000
// 11-bits for m_spinCount
private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); // 0011 1111 1111 1000 0000 0000 0000 0000
private const int SpinCountState_ShiftCount = 19;
private const int SpinCountState_MaxValue = (1 << 11) - 1; // 2047
// 19-bits for m_waiters. This allows support of 512K threads waiting which should be ample
private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111
private const int NumWaitersState_ShiftCount = 0;
private const int NumWaitersState_MaxValue = (1 << 19) - 1; // 512K-1
// ----------- //
/// <summary>
/// Gets the underlying <see cref="System.Threading.WaitHandle"/> object for this <see
/// cref="ManualResetEventSlim"/>.
/// </summary>
/// <value>The underlying <see cref="System.Threading.WaitHandle"/> event object fore this <see
/// cref="ManualResetEventSlim"/>.</value>
/// <remarks>
/// Accessing this property forces initialization of an underlying event object if one hasn't
/// already been created. To simply wait on this <see cref="ManualResetEventSlim"/>,
/// the public Wait methods should be preferred.
/// </remarks>
public WaitHandle WaitHandle
{
get
{
ThrowIfDisposed();
if (m_eventObj == null)
{
// Lazily initialize the event object if needed.
LazyInitializeEvent();
Debug.Assert(m_eventObj != null);
}
return m_eventObj;
}
}
/// <summary>
/// Gets whether the event is set.
/// </summary>
/// <value>true if the event has is set; otherwise, false.</value>
public bool IsSet
{
get => 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask);
private set => UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask);
}
/// <summary>
/// Gets the number of spin waits that will be occur before falling back to a true wait.
/// </summary>
public int SpinCount
{
get => ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount);
private set
{
Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
// Don't worry about thread safety because it's set one time from the constructor
m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount);
}
}
/// <summary>
/// How many threads are waiting.
/// </summary>
private int Waiters
{
get => ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount);
set
{
// setting to <0 would indicate an internal flaw, hence Assert is appropriate.
Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
// it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here.
if (value >= NumWaitersState_MaxValue)
throw new InvalidOperationException(SR.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue));
UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask);
}
}
//-----------------------------------------------------------------------------------
// Constructs a new event, optionally specifying the initial state and spin count.
// The defaults are that the event is unsignaled and some reasonable default spin.
//
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with an initial state of nonsignaled.
/// </summary>
public ManualResetEventSlim()
: this(false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with a boolean value indicating whether to set the initial state to signaled.
/// </summary>
/// <param name="initialState">true to set the initial state signaled; false to set the initial state
/// to nonsignaled.</param>
public ManualResetEventSlim(bool initialState)
{
// Specify the default spin count, and use default spin if we're
// on a multi-processor machine. Otherwise, we won't.
Initialize(initialState, SpinWait.SpinCountforSpinBeforeWait);
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with a Boolean value indicating whether to set the initial state to signaled and a specified
/// spin count.
/// </summary>
/// <param name="initialState">true to set the initial state to signaled; false to set the initial state
/// to nonsignaled.</param>
/// <param name="spinCount">The number of spin waits that will occur before falling back to a true
/// wait.</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="spinCount"/> is less than
/// 0 or greater than the maximum allowed value.</exception>
public ManualResetEventSlim(bool initialState, int spinCount)
{
if (spinCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(spinCount));
}
if (spinCount > SpinCountState_MaxValue)
{
throw new ArgumentOutOfRangeException(
nameof(spinCount),
SR.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue));
}
// We will suppress default spin because the user specified a count.
Initialize(initialState, spinCount);
}
/// <summary>
/// Initializes the internal state of the event.
/// </summary>
/// <param name="initialState">Whether the event is set initially or not.</param>
/// <param name="spinCount">The spin count that decides when the event will block.</param>
private void Initialize(bool initialState, int spinCount)
{
m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0;
// the spinCount argument has been validated by the ctors.
// but we now sanity check our predefined constants.
Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
SpinCount = Environment.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount;
}
/// <summary>
/// Helper to ensure the lock object is created before first use.
/// </summary>
private void EnsureLockObjectCreated()
{
if (m_lock != null)
return;
object newObj = new object();
Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign. Someone else set the value.
}
/// <summary>
/// This method lazily initializes the event object. It uses CAS to guarantee that
/// many threads racing to call this at once don't result in more than one event
/// being stored and used. The event will be signaled or unsignaled depending on
/// the state of the thin-event itself, with synchronization taken into account.
/// </summary>
private void LazyInitializeEvent()
{
bool preInitializeIsSet = IsSet;
ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet);
// We have to CAS this in case we are racing with another thread. We must
// guarantee only one event is actually stored in this field.
if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null)
{
// Someone else set the value due to a race condition. Destroy the garbage event.
newEventObj.Dispose();
}
else
{
// Now that the event is published, verify that the state hasn't changed since
// we snapped the preInitializeState. Another thread could have done that
// between our initial observation above and here. The barrier incurred from
// the CAS above (in addition to m_state being volatile) prevents this read
// from moving earlier and being collapsed with our original one.
bool currentIsSet = IsSet;
if (currentIsSet != preInitializeIsSet)
{
Debug.Assert(currentIsSet,
"The only safe concurrent transition is from unset->set: detected set->unset.");
// We saw it as unsignaled, but it has since become set.
lock (newEventObj)
{
// If our event hasn't already been disposed of, we must set it.
if (m_eventObj == newEventObj)
{
newEventObj.Set();
}
}
}
}
}
/// <summary>
/// Sets the state of the event to signaled, which allows one or more threads waiting on the event to
/// proceed.
/// </summary>
public void Set()
{
Set(false);
}
/// <summary>
/// Private helper to actually perform the Set.
/// </summary>
/// <param name="duringCancellation">Indicates whether we are calling Set() during cancellation.</param>
/// <exception cref="System.OperationCanceledException">The object has been canceled.</exception>
private void Set(bool duringCancellation)
{
// We need to ensure that IsSet=true does not get reordered past the read of m_eventObj
// This would be a legal movement according to the .NET memory model.
// The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier.
IsSet = true;
// If there are waiting threads, we need to pulse them.
if (Waiters > 0)
{
Debug.Assert(m_lock != null); // if waiters>0, then m_lock has already been created.
lock (m_lock)
{
Monitor.PulseAll(m_lock);
}
}
ManualResetEvent? eventObj = m_eventObj;
// Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly
// It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic
if (eventObj != null && !duringCancellation)
{
// We must surround this call to Set in a lock. The reason is fairly subtle.
// Sometimes a thread will issue a Wait and wake up after we have set m_state,
// but before we have gotten around to setting m_eventObj (just below). That's
// because Wait first checks m_state and will only access the event if absolutely
// necessary. However, the coding pattern { event.Wait(); event.Dispose() } is
// quite common, and we must support it. If the waiter woke up and disposed of
// the event object before the setter has finished, however, we would try to set a
// now-disposed Win32 event. Crash! To deal with this race condition, we use a lock to
// protect access to the event object when setting and disposing of it. We also
// double-check that the event has not become null in the meantime when in the lock.
lock (eventObj)
{
if (m_eventObj != null)
{
// If somebody is waiting, we must set the event.
m_eventObj.Set();
}
}
}
}
/// <summary>
/// Sets the state of the event to nonsignaled, which causes threads to block.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Reset()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Reset()
{
ThrowIfDisposed();
// If there's an event, reset it.
if (m_eventObj != null)
{
m_eventObj.Reset();
}
// There is a race condition here. If another thread Sets the event, we will get into a state
// where m_state will be unsignaled, yet the Win32 event object will have been signaled.
// This could cause waiting threads to wake up even though the event is in an
// unsignaled state. This is fine -- those that are calling Reset concurrently are
// responsible for doing "the right thing" -- e.g. rechecking the condition and
// resetting the event manually.
// And finally set our state back to unsignaled.
IsSet = false;
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set.
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
public void Wait()
{
Wait(Timeout.Infinite, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> receives a signal,
/// while observing a <see cref="System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> to
/// observe.</param>
/// <exception cref="System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <exception cref="System.OperationCanceledException"><paramref name="cancellationToken"/> was
/// canceled.</exception>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
public void Wait(CancellationToken cancellationToken)
{
Wait(Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// <see cref="System.TimeSpan"/> to measure the time interval.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="int.MaxValue"/>.</exception>
/// <exception cref="System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// <see cref="System.TimeSpan"/> to measure the time interval, while observing a <see
/// cref="System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="int.MaxValue"/>.</exception>
/// <exception cref="System.OperationCanceledException"><paramref
/// name="cancellationToken"/> was canceled.</exception>
/// <exception cref="System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(TimeSpan timeout, CancellationToken cancellationToken)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// 32-bit signed integer to measure the time interval.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(int millisecondsTimeout)
{
return Wait(millisecondsTimeout, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// 32-bit signed integer to measure the time interval, while observing a <see
/// cref="System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <exception cref="System.OperationCanceledException"><paramref
/// name="cancellationToken"/> was canceled.</exception>
public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
{
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested(); // an early convenience check
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
}
if (!IsSet)
{
if (millisecondsTimeout == 0)
{
// For 0-timeouts, we just return immediately.
return false;
}
// We spin briefly before falling back to allocating and/or waiting on a true event.
uint startTime = 0;
bool bNeedTimeoutAdjustment = false;
int realMillisecondsTimeout = millisecondsTimeout; // this will be adjusted if necessary.
if (millisecondsTimeout != Timeout.Infinite)
{
// We will account for time spent spinning, so that we can decrement it from our
// timeout. In most cases the time spent in this section will be negligible. But
// we can't discount the possibility of our thread being switched out for a lengthy
// period of time. The timeout adjustments only take effect when and if we actually
// decide to block in the kernel below.
startTime = TimeoutHelper.GetTime();
bNeedTimeoutAdjustment = true;
}
// Spin
int spinCount = SpinCount;
var spinner = new SpinWait();
while (spinner.Count < spinCount)
{
spinner.SpinOnce(sleep1Threshold: -1);
if (IsSet)
{
return true;
}
if (spinner.Count >= 100 && spinner.Count % 10 == 0) // check the cancellation token if the user passed a very large spin count
cancellationToken.ThrowIfCancellationRequested();
}
// Now enter the lock and wait. Must be created before registering the cancellation callback,
// which will try to take this lock.
EnsureLockObjectCreated();
// We must register and unregister the token outside of the lock, to avoid deadlocks.
using (cancellationToken.UnsafeRegister(s_cancellationTokenCallback, this))
{
lock (m_lock!)
{
// Loop to cope with spurious wakeups from other waits being canceled
while (!IsSet)
{
// If our token was canceled, we must throw and exit.
cancellationToken.ThrowIfCancellationRequested();
// update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled)
if (bNeedTimeoutAdjustment)
{
realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout);
if (realMillisecondsTimeout <= 0)
return false;
}
// There is a race condition that Set will fail to see that there are waiters as Set does not take the lock,
// so after updating waiters, we must check IsSet again.
// Also, we must ensure there cannot be any reordering of the assignment to Waiters and the
// read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange
// operation which provides a full memory barrier.
// If we see IsSet=false, then we are guaranteed that Set() will see that we are
// waiting and will pulse the monitor correctly.
Waiters++;
if (IsSet) // This check must occur after updating Waiters.
{
Waiters--; // revert the increment.
return true;
}
// Now finally perform the wait.
try
{
// ** the actual wait **
if (!Monitor.Wait(m_lock, realMillisecondsTimeout))
return false; // return immediately if the timeout has expired.
}
finally
{
// Clean up: we're done waiting.
Waiters--;
}
// Now just loop back around, and the right thing will happen. Either:
// 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait)
// or 2. the wait was successful. (the loop will break)
}
}
}
} // automatically disposes (and unregisters) the callback
return true; // done. The wait was satisfied.
}
/// <summary>
/// Releases all resources used by the current instance of <see cref="ManualResetEventSlim"/>.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// When overridden in a derived class, releases the unmanaged resources used by the
/// <see cref="ManualResetEventSlim"/>, and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources;
/// false to release only unmanaged resources.</param>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose(bool)"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
if ((m_combinedState & Dispose_BitMask) != 0)
return; // already disposed
m_combinedState |= Dispose_BitMask; // set the dispose bit
if (disposing)
{
// We will dispose of the event object. We do this under a lock to protect
// against the race condition outlined in the Set method above.
ManualResetEvent? eventObj = m_eventObj;
if (eventObj != null)
{
lock (eventObj)
{
eventObj.Dispose();
m_eventObj = null;
}
}
}
}
/// <summary>
/// Throw ObjectDisposedException if the MRES is disposed
/// </summary>
private void ThrowIfDisposed()
{
if ((m_combinedState & Dispose_BitMask) != 0)
throw new ObjectDisposedException(SR.ManualResetEventSlim_Disposed);
}
/// <summary>
/// Private helper method to wake up waiters when a cancellationToken gets canceled.
/// </summary>
private static readonly Action<object?> s_cancellationTokenCallback = new Action<object?>(CancellationTokenCallback);
private static void CancellationTokenCallback(object? obj)
{
Debug.Assert(obj is ManualResetEventSlim, "Expected a ManualResetEventSlim");
ManualResetEventSlim mre = (ManualResetEventSlim)obj;
Debug.Assert(mre.m_lock != null); // the lock should have been created before this callback is registered for use.
lock (mre.m_lock)
{
Monitor.PulseAll(mre.m_lock); // awaken all waiters
}
}
/// <summary>
/// Private helper method for updating parts of a bit-string state value.
/// Mainly called from the IsSet and Waiters properties setters
/// </summary>
/// <remarks>
/// Note: the parameter types must be int as CompareExchange cannot take a Uint
/// </remarks>
/// <param name="newBits">The new value</param>
/// <param name="updateBitsMask">The mask used to set the bits</param>
private void UpdateStateAtomically(int newBits, int updateBitsMask)
{
SpinWait sw = new SpinWait();
Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask.");
while (true)
{
int oldState = m_combinedState; // cache the old value for testing in CAS
// Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111]
// then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111]
int newState = (oldState & ~updateBitsMask) | newBits;
if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState)
{
return;
}
sw.SpinOnce(sleep1Threshold: -1);
}
}
/// <summary>
/// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word.
/// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer
///
/// ?? is there a common place to put this rather than being private to MRES?
/// </summary>
/// <param name="state"></param>
/// <param name="mask"></param>
/// <param name="rightBitShiftCount"></param>
/// <returns></returns>
private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount)
{
// convert to uint before shifting so that right-shift does not replicate the sign-bit,
// then convert back to int.
return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount));
}
/// <summary>
/// Performs a Mask operation, but does not perform the shift.
/// This is acceptable for boolean values for which the shift is unnecessary
/// eg (val & Mask) != 0 is an appropriate way to extract a boolean rather than using
/// ((val & Mask) >> shiftAmount) == 1
///
/// ?? is there a common place to put this rather than being private to MRES?
/// </summary>
/// <param name="state"></param>
/// <param name="mask"></param>
private static int ExtractStatePortion(int state, int mask)
{
return state & mask;
}
}
}
| |
using CK.AspNet.Tester;
using CK.Auth;
using FluentAssertions;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using CK.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;
namespace CK.AspNet.Auth.Tests
{
[TestFixture]
public class WebFrontHandlerTests
{
const string basicLoginUri = "/.webfront/c/basicLogin";
const string unsafeDirectLoginUri = "/.webfront/c/unsafeDirectLogin";
const string refreshUri = "/.webfront/c/refresh";
const string logoutUri = "/.webfront/c/logout";
const string tokenExplainUri = "/.webfront/token";
[Test]
public async Task a_successful_basic_login_returns_valid_info_and_token()
{
using( var s = new AuthServer() )
{
HttpResponseMessage response = await s.Client.PostJSON( basicLoginUri, "{\"userName\":\"Albert\",\"password\":\"success\"}" );
response.EnsureSuccessStatusCode();
var c = RefreshResponse.Parse( s.TypeSystem, response.Content.ReadAsStringAsync().Result );
Debug.Assert( c.Info != null );
c.Info.User.UserId.Should().Be( 2 );
c.Info.User.UserName.Should().Be( "Albert" );
c.Info.User.Schemes.Should().HaveCount( 1 );
c.Info.User.Schemes[0].Name.Should().Be( "Basic" );
c.Info.User.Schemes[0].LastUsed.Should().BeCloseTo( DateTime.UtcNow, 1500 );
c.Info.ActualUser.Should().BeSameAs( c.Info.User );
c.Info.Level.Should().Be( AuthLevel.Normal );
c.Info.IsImpersonated.Should().BeFalse();
c.Token.Should().NotBeNullOrWhiteSpace();
c.Refreshable.Should().BeFalse( "Since by default Options.SlidingExpirationTime is 0." );
}
}
[Test]
public async Task basic_login_is_404NotFound_when_no_BasicAuthenticationProvider_exists()
{
using( var s = new AuthServer(configureServices: services => services.Replace<IWebFrontAuthLoginService, NoAuthWebFrontLoginService>() ) )
{
HttpResponseMessage response = await s.Client.PostJSON( basicLoginUri, "{\"userName\":\"Albert\",\"password\":\"success\"}" );
response.StatusCode.Should().Be( HttpStatusCode.NotFound );
}
}
class BasicDirectLoginAllower : IWebFrontAuthUnsafeDirectLoginAllowService
{
public Task<bool> AllowAsync( HttpContext ctx, IActivityMonitor monitor, string scheme, object payload )
{
return Task.FromResult( scheme == "Basic" );
}
}
[TestCase( AuthenticationCookieMode.WebFrontPath, false )]
[TestCase( AuthenticationCookieMode.RootPath, false )]
[TestCase( AuthenticationCookieMode.WebFrontPath, true )]
[TestCase( AuthenticationCookieMode.RootPath, true )]
public async Task successful_login_set_the_cookies_on_the_webfront_c_path_and_these_cookies_can_be_used_to_restore_the_authentication( AuthenticationCookieMode mode, bool useGenericWrapper )
{
using( var s = new AuthServer( opt => opt.CookieMode = mode,
services =>
{
if( useGenericWrapper )
{
services.AddSingleton<IWebFrontAuthUnsafeDirectLoginAllowService,BasicDirectLoginAllower>();
}
} ) )
{
// Login: the 2 cookies are set on .webFront/c/ path.
var login = await s.LoginAlbertViaBasicProviderAsync( useGenericWrapper );
Debug.Assert( login.Info != null );
DateTime basicLoginTime = login.Info.User.Schemes.Single( p => p.Name == "Basic" ).LastUsed;
string? originalToken = login.Token;
// Request with token: the authentication is based on the token.
{
s.Client.Token = originalToken;
HttpResponseMessage tokenRefresh = await s.Client.Get( refreshUri );
tokenRefresh.EnsureSuccessStatusCode();
var c = RefreshResponse.Parse( s.TypeSystem, tokenRefresh.Content.ReadAsStringAsync().Result );
Debug.Assert( c.Info != null );
c.Info.Level.Should().Be( AuthLevel.Normal );
c.Info.User.UserName.Should().Be( "Albert" );
c.Info.User.Schemes.Single( p => p.Name == "Basic" ).LastUsed.Should().Be( basicLoginTime );
}
// Token less request: the authentication is restored from the cookie.
{
s.Client.Token = null;
HttpResponseMessage tokenLessRefresh = await s.Client.Get( refreshUri );
tokenLessRefresh.EnsureSuccessStatusCode();
var c = RefreshResponse.Parse( s.TypeSystem, tokenLessRefresh.Content.ReadAsStringAsync().Result );
Debug.Assert( c.Info != null );
c.Info.Level.Should().Be( AuthLevel.Normal );
c.Info.User.UserName.Should().Be( "Albert" );
c.Info.User.Schemes.Single( p => p.Name == "Basic" ).LastUsed.Should().Be( basicLoginTime );
}
// Request with token and ?schemes query parametrers: we receive the providers.
{
s.Client.Token = originalToken;
HttpResponseMessage tokenRefresh = await s.Client.Get( refreshUri + "?schemes" );
tokenRefresh.EnsureSuccessStatusCode();
var c = RefreshResponse.Parse( s.TypeSystem, tokenRefresh.Content.ReadAsStringAsync().Result );
Debug.Assert( c.Info != null );
c.Info.Level.Should().Be( AuthLevel.Normal );
c.Info.User.UserName.Should().Be( "Albert" );
c.Info.User.Schemes.Single( p => p.Name == "Basic" ).LastUsed.Should().Be( basicLoginTime );
c.Schemes.Should().ContainSingle( "Basic" );
}
}
}
[TestCase( AuthenticationCookieMode.WebFrontPath )]
[TestCase( AuthenticationCookieMode.RootPath )]
public async Task bad_tokens_are_ignored_as_long_as_cookies_can_be_used( AuthenticationCookieMode mode )
{
using( var s = new AuthServer( opt => opt.CookieMode = mode ) )
{
var firstLogin = await s.LoginAlbertViaBasicProviderAsync();
string badToken = firstLogin.Token + 'B';
s.Client.Token = badToken;
RefreshResponse c = await s.CallRefreshEndPointAsync();
c.Info.Should().BeEquivalentTo( firstLogin.Info, "Authentication has been restored from cookies." );
c.Token.Should().NotBeNullOrWhiteSpace( "Regenerated token differs." );
}
}
[TestCase( AuthenticationCookieMode.WebFrontPath, true )]
[TestCase( AuthenticationCookieMode.RootPath, true )]
[TestCase( AuthenticationCookieMode.WebFrontPath, false )]
[TestCase( AuthenticationCookieMode.RootPath, false )]
public async Task logout_removes_both_cookies( AuthenticationCookieMode mode, bool logoutWithToken )
{
using( var s = new AuthServer( opt => opt.CookieMode = mode ) )
{
// Login: the 2 cookies are set.
var firstLogin = await s.LoginAlbertViaBasicProviderAsync();
DateTime basicLoginTime = firstLogin.Info.User.Schemes.Single( p => p.Name == "Basic" ).LastUsed;
string originalToken = firstLogin.Token;
// Logout
if( logoutWithToken ) s.Client.Token = originalToken;
HttpResponseMessage logout = await s.Client.Get( logoutUri );
logout.EnsureSuccessStatusCode();
// Refresh: no authentication.
s.Client.Token = null;
HttpResponseMessage tokenRefresh = await s.Client.Get( refreshUri );
tokenRefresh.EnsureSuccessStatusCode();
var c = RefreshResponse.Parse( s.TypeSystem, await tokenRefresh.Content.ReadAsStringAsync() );
c.Info.Level.Should().Be( AuthLevel.None );
}
}
[Test]
public async Task invalid_payload_to_basic_login_returns_a_400_bad_request()
{
using( var s = new AuthServer() )
{
HttpResponseMessage response = await s.Client.PostJSON( basicLoginUri, "{\"userName\":\"\",\"password\":\"success\"}" );
response.StatusCode.Should().Be( HttpStatusCode.BadRequest );
s.Client.Cookies.GetCookies( new Uri( s.Server.BaseAddress, "/.webfront/c/" ) ).Should().HaveCount( 0 );
response = await s.Client.PostJSON( basicLoginUri, "{\"userName\":\"toto\",\"password\":\"\"}" );
response.StatusCode.Should().Be( HttpStatusCode.BadRequest );
response = await s.Client.PostJSON( basicLoginUri, "not a json" );
response.StatusCode.Should().Be( HttpStatusCode.BadRequest );
}
}
[TestCase( false, Description = "With cookies on the .webfront path." )]
[TestCase( true, Description = "With cookies on the root path." )]
public async Task webfront_token_endpoint_returns_the_current_authentication_indented_JSON_and_enables_to_test_actual_authentication( bool rootCookiePath )
{
using( var s = new AuthServer( opt => opt.CookieMode = rootCookiePath ? AuthenticationCookieMode.RootPath : AuthenticationCookieMode.WebFrontPath ) )
{
HttpResponseMessage auth = await s.Client.PostJSON( basicLoginUri, "{\"userName\":\"Albert\",\"password\":\"success\"}" );
var c = RefreshResponse.Parse( s.TypeSystem, auth.Content.ReadAsStringAsync().Result );
{
// With token: it always works.
s.Client.Token = c.Token;
HttpResponseMessage req = await s.Client.Get( tokenExplainUri );
var tokenClear = req.Content.ReadAsStringAsync().Result;
tokenClear.Should().Contain( "Albert" );
}
{
// Without token: it works only when CookieMode is AuthenticationCookieMode.RootPath.
s.Client.Token = null;
HttpResponseMessage req = await s.Client.Get( tokenExplainUri );
var tokenClear = await req.Content.ReadAsStringAsync();
if( rootCookiePath )
{
// Authentication Cookie has been used.
tokenClear.Should().Contain( "Albert" );
}
else
{
tokenClear.Should().NotContain( "Albert" );
}
}
}
}
[TestCase( true, false )]
[TestCase( true, true )]
[TestCase( false, true )]
[TestCase( false, false )]
public async Task SlidingExpiration_works_as_expected_in_bearer_only_mode_by_calling_refresh_endpoint( bool useGenericWrapper, bool rememberMe )
{
using( var s = new AuthServer( opt =>
{
opt.ExpireTimeSpan = TimeSpan.FromSeconds( 2.0 );
opt.SlidingExpirationTime = TimeSpan.FromSeconds( 10 );
opt.CookieMode = AuthenticationCookieMode.None;
}, services =>
{
if( useGenericWrapper )
{
services.AddSingleton<IWebFrontAuthUnsafeDirectLoginAllowService, BasicDirectLoginAllower>();
}
} ) )
{
// This test is far from perfect but does the job without clock injection.
RefreshResponse auth = await s.LoginAlbertViaBasicProviderAsync( useGenericWrapper, rememberMe );
DateTime next = auth.Info.Expires.Value - TimeSpan.FromSeconds( 1.7 );
while( next > DateTime.UtcNow ) ;
s.Client.Token = auth.Token;
RefreshResponse refresh = await s.CallRefreshEndPointAsync();
refresh.Info.Expires.Value.Should().BeAfter( auth.Info.Expires.Value, "Refresh increased the expiration time." );
refresh.RememberMe.Should().BeFalse( "In CookieMode None, RememberMe is always false, no matter what." );
}
}
[Test]
public async Task SlidingExpiration_works_as_expected_in_rooted_Cookie_mode_where_any_request_can_do_the_job()
{
using( var s = new AuthServer( opt =>
{
opt.CookieMode = AuthenticationCookieMode.RootPath;
opt.ExpireTimeSpan = TimeSpan.FromSeconds( 2.0 );
opt.SlidingExpirationTime = TimeSpan.FromSeconds( 10 );
} ) )
{
// This test is far from perfect but does the job without clock injection.
RefreshResponse auth = await s.LoginAlbertViaBasicProviderAsync();
DateTime expCookie1 = s.Client.Cookies.GetCookies( s.Server.BaseAddress )[".webFront"].Expires.ToUniversalTime();
expCookie1.Should().BeCloseTo( auth.Info.Expires.Value, precision: 1000 );
DateTime next = auth.Info.Expires.Value - TimeSpan.FromSeconds( 1.7 );
while( next > DateTime.UtcNow ) ;
// Calling token endpoint (like any other endpoint that sollicitates authentication) is enough.
HttpResponseMessage req = await s.Client.Get( tokenExplainUri );
var response = JObject.Parse( req.Content.ReadAsStringAsync().Result );
((bool)response["rememberMe"]).Should().BeTrue();
IAuthenticationInfo refresh = s.TypeSystem.AuthenticationInfo.FromJObject( (JObject)response["info"] );
refresh.Expires.Value.Should().BeAfter( auth.Info.Expires.Value, "Token life time has been increased." );
DateTime expCookie2 = s.Client.Cookies.GetCookies( s.Server.BaseAddress )[".webFront"].Expires.ToUniversalTime();
expCookie2.Should().BeCloseTo( refresh.Expires.Value, precision: 1000 );
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class EENamedTypeSymbol : NamedTypeSymbol
{
internal readonly NamedTypeSymbol SubstitutedSourceType;
internal readonly ImmutableArray<TypeParameterSymbol> SourceTypeParameters;
private readonly NamespaceSymbol _container;
private readonly NamedTypeSymbol _baseType;
private readonly string _name;
private readonly CSharpSyntaxNode _syntax;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly ImmutableArray<MethodSymbol> _methods;
internal EENamedTypeSymbol(
NamespaceSymbol container,
NamedTypeSymbol baseType,
CSharpSyntaxNode syntax,
MethodSymbol currentFrame,
string typeName,
string methodName,
CompilationContext context,
GenerateMethodBody generateMethodBody) :
this(container, baseType, syntax, currentFrame, typeName, (m, t) => ImmutableArray.Create<MethodSymbol>(context.CreateMethod(t, methodName, syntax, generateMethodBody)))
{
}
internal EENamedTypeSymbol(
NamespaceSymbol container,
NamedTypeSymbol baseType,
CSharpSyntaxNode syntax,
MethodSymbol currentFrame,
string typeName,
Func<MethodSymbol, EENamedTypeSymbol, ImmutableArray<MethodSymbol>> getMethods,
ImmutableArray<TypeParameterSymbol> sourceTypeParameters,
Func<NamedTypeSymbol, EENamedTypeSymbol, ImmutableArray<TypeParameterSymbol>> getTypeParameters)
{
_container = container;
_baseType = baseType;
_syntax = syntax;
_name = typeName;
this.SourceTypeParameters = sourceTypeParameters;
_typeParameters = getTypeParameters(currentFrame.ContainingType, this);
VerifyTypeParameters(this, _typeParameters);
_methods = getMethods(currentFrame, this);
}
internal EENamedTypeSymbol(
NamespaceSymbol container,
NamedTypeSymbol baseType,
CSharpSyntaxNode syntax,
MethodSymbol currentFrame,
string typeName,
Func<MethodSymbol, EENamedTypeSymbol, ImmutableArray<MethodSymbol>> getMethods)
{
_container = container;
_baseType = baseType;
_syntax = syntax;
_name = typeName;
// What we want is to map all original type parameters to the corresponding new type parameters
// (since the old ones have the wrong owners). Unfortunately, we have a circular dependency:
// 1) Each new type parameter requires the entire map in order to be able to construct its constraint list.
// 2) The map cannot be constructed until all new type parameters exist.
// Our solution is to pass each new type parameter a lazy reference to the type map. We then
// initialize the map as soon as the new type parameters are available - and before they are
// handed out - so that there is never a period where they can require the type map and find
// it uninitialized.
var sourceType = currentFrame.ContainingType;
this.SourceTypeParameters = sourceType.GetAllTypeParameters();
TypeMap typeMap = null;
var getTypeMap = new Func<TypeMap>(() => typeMap);
_typeParameters = this.SourceTypeParameters.SelectAsArray(
(tp, i, arg) => (TypeParameterSymbol)new EETypeParameterSymbol(this, tp, i, getTypeMap),
(object)null);
typeMap = new TypeMap(this.SourceTypeParameters, _typeParameters);
VerifyTypeParameters(this, _typeParameters);
this.SubstitutedSourceType = typeMap.SubstituteNamedType(sourceType);
TypeParameterChecker.Check(this.SubstitutedSourceType, _typeParameters);
_methods = getMethods(currentFrame, this);
}
internal ImmutableArray<MethodSymbol> Methods
{
get { return _methods; }
}
internal override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
return SpecializedCollections.EmptyEnumerable<FieldSymbol>();
}
internal override IEnumerable<MethodSymbol> GetMethodsToEmit()
{
return _methods;
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit()
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override int Arity
{
get { return _typeParameters.Length; }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
internal override ImmutableArray<TypeSymbol> TypeArgumentsNoUseSiteDiagnostics
{
get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); }
}
internal override bool HasTypeArgumentsCustomModifiers
{
get
{
return false;
}
}
internal override ImmutableArray<ImmutableArray<CustomModifier>> TypeArgumentsCustomModifiers
{
get
{
return CreateEmptyTypeArgumentsCustomModifiers();
}
}
public override NamedTypeSymbol ConstructedFrom
{
get { return this; }
}
public override bool MightContainExtensionMethods
{
get { return false; }
}
internal override AttributeUsageInfo GetAttributeUsageInfo()
{
throw ExceptionUtilities.Unreachable;
}
public override string Name
{
get { return _name; }
}
// No additional name mangling since CompileExpression
// is providing an explicit type name.
internal override bool MangleName
{
get { return false; }
}
public override IEnumerable<string> MemberNames
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<Symbol> GetMembers()
{
return _methods.Cast<MethodSymbol, Symbol>();
}
public override ImmutableArray<Symbol> GetMembers(string name)
{
// Should not be requesting generated members
// by name other than constructors.
Debug.Assert((name == WellKnownMemberNames.InstanceConstructorName) || (name == WellKnownMemberNames.StaticConstructorName));
return this.GetMembers().WhereAsArray(m => m.Name == name);
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
throw ExceptionUtilities.Unreachable;
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
throw ExceptionUtilities.Unreachable;
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Internal; }
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers()
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name)
{
throw ExceptionUtilities.Unreachable;
}
internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<Symbol> basesBeingResolved)
{
return _baseType;
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<Symbol> basesBeingResolved)
{
throw ExceptionUtilities.Unreachable;
}
internal override bool HasSpecialName
{
get { return true; }
}
internal override bool IsComImport
{
get { return false; }
}
internal override bool IsWindowsRuntimeImport
{
get { return false; }
}
internal override bool ShouldAddWinRTMembers
{
get { return false; }
}
internal override bool IsSerializable
{
get { return false; }
}
internal override TypeLayout Layout
{
get { return default(TypeLayout); }
}
internal override System.Runtime.InteropServices.CharSet MarshallingCharSet
{
get { return System.Runtime.InteropServices.CharSet.Ansi; }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics
{
get { return _baseType; }
}
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<Symbol> basesBeingResolved)
{
throw ExceptionUtilities.Unreachable;
}
public override TypeKind TypeKind
{
get { return TypeKind.Class; }
}
public override NamedTypeSymbol ContainingType
{
get { return null; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray<Location>.Empty; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { return ImmutableArray<SyntaxReference>.Empty; }
}
public override bool IsStatic
{
get { return true; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsSealed
{
get { return true; }
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { return null; }
}
internal override bool IsInterface
{
get { return false; }
}
[Conditional("DEBUG")]
internal static void VerifyTypeParameters(Symbol container, ImmutableArray<TypeParameterSymbol> typeParameters)
{
for (int i = 0; i < typeParameters.Length; i++)
{
var typeParameter = typeParameters[i];
Debug.Assert((object)typeParameter.ContainingSymbol == (object)container);
Debug.Assert(typeParameter.Ordinal == i);
}
}
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.Win32;
namespace UnrealBuildTool
{
public class AndroidToolChain : UEToolChain
{
// the number of the clang version being used to compile
static private float ClangVersionFloat = 0;
// the list of architectures we will compile for
static private List<string> Arches = null;
// the list of GPU architectures we will compile for
static private List<string> GPUArchitectures = null;
// a list of all architecture+GPUArchitecture names (-armv7-es2, etc)
static private List<string> AllComboNames = null;
static private Dictionary<string, string[]> AllArchNames = new Dictionary<string, string[]> {
{ "-armv7", new string[] { "armv7", "armeabi-v7a", } },
{ "-arm64", new string[] { "arm64", } },
{ "-x86", new string[] { "x86", } },
{ "-x64", new string[] { "x64", "x86_64", } },
};
static private Dictionary<string, string[]> LibrariesToSkip = new Dictionary<string, string[]> {
{ "-armv7", new string[] { } },
{ "-arm64", new string[] { "nvToolsExt", "oculus", "vrapi", "gpg", } },
{ "-x86", new string[] { "nvToolsExt", "oculus", "vrapi", } },
{ "-x64", new string[] { "nvToolsExt", "oculus", "vrapi", "gpg", } },
};
static private Dictionary<string, string[]> ModulesToSkip = new Dictionary<string, string[]> {
{ "-armv7", new string[] { } },
{ "-arm64", new string[] { "OnlineSubsystemGooglePlay", } },
{ "-x86", new string[] { } },
{ "-x64", new string[] { "OnlineSubsystemGooglePlay", } },
};
public static void ParseArchitectures()
{
// look in ini settings for what platforms to compile for
ConfigCacheIni Ini = new ConfigCacheIni(UnrealTargetPlatform.Android, "Engine", UnrealBuildTool.GetUProjectPath());
Arches = new List<string>();
bool bBuild = true;
if (Ini.GetBool("/Script/AndroidRuntimeSettings.AndroidRuntimeSettings", "bBuildForArmV7", out bBuild) && bBuild)
{
Arches.Add("-armv7");
}
if (Ini.GetBool("/Script/AndroidRuntimeSettings.AndroidRuntimeSettings", "bBuildForArm64", out bBuild) && bBuild)
{
Arches.Add("-arm64");
}
if (Ini.GetBool("/Script/AndroidRuntimeSettings.AndroidRuntimeSettings", "bBuildForx86", out bBuild) && bBuild)
{
Arches.Add("-x86");
}
if (Ini.GetBool("/Script/AndroidRuntimeSettings.AndroidRuntimeSettings", "bBuildForx8664", out bBuild) && bBuild)
{
Arches.Add("-x64");
}
// force armv7 if something went wrong
if (Arches.Count == 0)
{
Arches.Add("-armv7");
}
// Parse selected GPU architectures
GPUArchitectures = new List<string>();
if (Ini.GetBool("/Script/AndroidRuntimeSettings.AndroidRuntimeSettings", "bBuildForES2", out bBuild) && bBuild)
{
GPUArchitectures.Add("-es2");
}
if (Ini.GetBool("/Script/AndroidRuntimeSettings.AndroidRuntimeSettings", "bBuildForES31", out bBuild) && bBuild)
{
GPUArchitectures.Add("-es31");
}
if (Ini.GetBool("/Script/AndroidRuntimeSettings.AndroidRuntimeSettings", "bBuildForGL4", out bBuild) && bBuild)
{
GPUArchitectures.Add("-gl4");
}
if (GPUArchitectures.Count == 0)
{
GPUArchitectures.Add("-es2");
}
AllComboNames = (from Arch in Arches
from GPUArch in GPUArchitectures
select Arch + GPUArch).ToList();
}
static public string GetGLESVersionFromGPUArch(string GPUArch)
{
GPUArch = GPUArch.Substring(1); // drop the '-' from the start
string GLESversion = "";
switch (GPUArch)
{
case "es2":
GLESversion = "0x00020000";
break;
case "es31":
GLESversion = "0x00030001";
break;
default:
GLESversion = "0x00020000";
break;
}
return GLESversion;
}
public override void SetUpGlobalEnvironment()
{
base.SetUpGlobalEnvironment();
ParseArchitectures();
}
static public List<string> GetAllArchitectures()
{
if (Arches == null)
{
ParseArchitectures();
}
return Arches;
}
static public List<string> GetAllGPUArchitectures()
{
if (GPUArchitectures == null)
{
ParseArchitectures();
}
return GPUArchitectures;
}
static public int GetNdkApiLevelInt(int MinNdk = 19)
{
string NDKVersion = AndroidToolChain.GetNdkApiLevel();
int NDKVersionInt = MinNdk;
if (NDKVersion.Contains("-"))
{
int Version;
if (int.TryParse(NDKVersion.Substring(NDKVersion.LastIndexOf('-') + 1), out Version))
{
if (Version > NDKVersionInt)
NDKVersionInt = Version;
}
}
return NDKVersionInt;
}
static public string GetNdkApiLevel()
{
// ask the .ini system for what version to use
ConfigCacheIni Ini = new ConfigCacheIni(UnrealTargetPlatform.Android, "Engine", UnrealBuildTool.GetUProjectPath());
string NDKLevel;
Ini.GetString("/Script/AndroidPlatformEditor.AndroidSDKSettings", "NDKAPILevel", out NDKLevel);
if (NDKLevel == "latest")
{
// get a list of NDK platforms
string PlatformsDir = Environment.ExpandEnvironmentVariables("%NDKROOT%/platforms");
if (!Directory.Exists(PlatformsDir))
{
throw new BuildException("No platforms found in {0}", PlatformsDir);
}
// return the largest of them
NDKLevel = GetLargestApiLevel(Directory.GetDirectories(PlatformsDir));
}
return NDKLevel;
}
static public string GetLargestApiLevel(string[] ApiLevels)
{
int LargestLevel = 0;
string LargestString = null;
// look for largest integer
foreach (string Level in ApiLevels)
{
string LocalLevel = Path.GetFileName(Level);
string[] Tokens = LocalLevel.Split("-".ToCharArray());
if (Tokens.Length >= 2)
{
try
{
int ParsedLevel = int.Parse(Tokens[1]);
// bigger? remember it
if (ParsedLevel > LargestLevel)
{
LargestLevel = ParsedLevel;
LargestString = LocalLevel;
}
}
catch (Exception)
{
// ignore poorly formed string
}
}
}
return LargestString;
}
public override void RegisterToolChain()
{
string NDKPath = Environment.GetEnvironmentVariable("NDKROOT");
// don't register if we don't have an NDKROOT specified
if (String.IsNullOrEmpty(NDKPath))
{
return;
}
NDKPath = NDKPath.Replace("\"", "");
string ClangVersion = "";
string GccVersion = "";
// prefer clang 3.6, but fall back if needed for now
if (Directory.Exists(Path.Combine(NDKPath, @"toolchains/llvm-3.6")))
{
ClangVersion = "3.6";
GccVersion = "4.9";
}
else if (Directory.Exists(Path.Combine(NDKPath, @"toolchains/llvm-3.5")))
{
ClangVersion = "3.5";
GccVersion = "4.9";
}
else if (Directory.Exists(Path.Combine(NDKPath, @"toolchains/llvm-3.3")))
{
ClangVersion = "3.3";
GccVersion = "4.8";
}
else if (Directory.Exists(Path.Combine(NDKPath, @"toolchains/llvm-3.1")))
{
ClangVersion = "3.1";
GccVersion = "4.6";
}
else
{
return;
}
ClangVersionFloat = float.Parse(ClangVersion, System.Globalization.CultureInfo.InvariantCulture);
// Console.WriteLine("Compiling with clang {0}", ClangVersionFloat);
string ArchitecturePath = "";
string ArchitecturePathWindows32 = @"prebuilt/windows";
string ArchitecturePathWindows64 = @"prebuilt/windows-x86_64";
string ArchitecturePathMac = @"prebuilt/darwin-x86_64";
string ExeExtension = ".exe";
if (Directory.Exists(Path.Combine(NDKPath, ArchitecturePathWindows64)))
{
Log.TraceVerbose(" Found Windows 64 bit versions of toolchain");
ArchitecturePath = ArchitecturePathWindows64;
}
else if (Directory.Exists(Path.Combine(NDKPath, ArchitecturePathWindows32)))
{
Log.TraceVerbose(" Found Windows 32 bit versions of toolchain");
ArchitecturePath = ArchitecturePathWindows32;
}
else if (Directory.Exists(Path.Combine(NDKPath, ArchitecturePathMac)))
{
Log.TraceVerbose(" Found Mac versions of toolchain");
ArchitecturePath = ArchitecturePathMac;
ExeExtension = "";
}
else
{
Log.TraceVerbose(" Did not find 32 bit or 64 bit versions of toolchain");
return;
}
// set up the path to our toolchains
ClangPath = Path.Combine(NDKPath, @"toolchains/llvm-" + ClangVersion, ArchitecturePath, @"bin/clang++" + ExeExtension);
ArPathArm = Path.Combine(NDKPath, @"toolchains/arm-linux-androideabi-" + GccVersion, ArchitecturePath, @"bin/arm-linux-androideabi-ar" + ExeExtension); //@todo android: use llvm-ar.exe instead?
ArPathArm64 = Path.Combine(NDKPath, @"toolchains/aarch64-linux-android-" + GccVersion, ArchitecturePath, @"bin/aarch64-linux-android-ar" + ExeExtension); //@todo android: use llvm-ar.exe instead?
ArPathx86 = Path.Combine(NDKPath, @"toolchains/x86-" + GccVersion, ArchitecturePath, @"bin/i686-linux-android-ar" + ExeExtension); //@todo android: verify x86 toolchain
ArPathx64 = Path.Combine(NDKPath, @"toolchains/x86_64-" + GccVersion, ArchitecturePath, @"bin/x86_64-linux-android-ar" + ExeExtension); //@todo android: verify x64 toolchain
// toolchain params
ToolchainParamsArm = " -target armv7-none-linux-androideabi" +
" --sysroot=\"" + Path.Combine(NDKPath, "platforms", GetNdkApiLevel(), "arch-arm") + "\"" +
" -gcc-toolchain \"" + Path.Combine(NDKPath, @"toolchains/arm-linux-androideabi-" + GccVersion, ArchitecturePath) + "\"";
ToolchainParamsArm64 = " -target aarch64-none-linux-android" +
" --sysroot=\"" + Path.Combine(NDKPath, "platforms", GetNdkApiLevel(), "arch-arm64") + "\"" +
" -gcc-toolchain \"" + Path.Combine(NDKPath, @"toolchains/aarch64-linux-android-" + GccVersion, ArchitecturePath) + "\"";
ToolchainParamsx86 = " -target i686-none-linux-android" +
" --sysroot=\"" + Path.Combine(NDKPath, "platforms", GetNdkApiLevel(), "arch-x86") + "\"" +
" -gcc-toolchain \"" + Path.Combine(NDKPath, @"toolchains/x86-" + GccVersion, ArchitecturePath) + "\"";
ToolchainParamsx64 = " -target x86_64-none-linux-android" +
" --sysroot=\"" + Path.Combine(NDKPath, "platforms", GetNdkApiLevel(), "arch-x86_64") + "\"" +
" -gcc-toolchain \"" + Path.Combine(NDKPath, @"toolchains\x86_64-" + GccVersion, ArchitecturePath) + "\"";
// Register this tool chain
Log.TraceVerbose(" Registered for {0}", CPPTargetPlatform.Android.ToString());
UEToolChain.RegisterPlatformToolChain(CPPTargetPlatform.Android, this);
}
static string GetCLArguments_Global(CPPEnvironment CompileEnvironment, string Architecture)
{
string Result = "";
switch (Architecture)
{
case "-armv7": Result += ToolchainParamsArm; break;
case "-arm64": Result += ToolchainParamsArm64; break;
case "-x86": Result += ToolchainParamsx86; break;
case "-x64": Result += ToolchainParamsx64; break;
default: Result += ToolchainParamsArm; break;
}
// build up the commandline common to C and C++
Result += " -c";
Result += " -fdiagnostics-format=msvc";
Result += " -Wall";
Result += " -Wno-unused-variable";
// this will hide the warnings about static functions in headers that aren't used in every single .cpp file
Result += " -Wno-unused-function";
// this hides the "enumeration value 'XXXXX' not handled in switch [-Wswitch]" warnings - we should maybe remove this at some point and add UE_LOG(, Fatal, ) to default cases
Result += " -Wno-switch";
// this hides the "warning : comparison of unsigned expression < 0 is always false" type warnings due to constant comparisons, which are possible with template arguments
Result += " -Wno-tautological-compare";
//This will prevent the issue of warnings for unused private variables.
Result += " -Wno-unused-private-field";
Result += " -Wno-local-type-template-args"; // engine triggers this
Result += " -Wno-return-type-c-linkage"; // needed for PhysX
Result += " -Wno-reorder"; // member initialization order
Result += " -Wno-unknown-pragmas"; // probably should kill this one, sign of another issue in PhysX?
Result += " -Wno-invalid-offsetof"; // needed to suppress warnings about using offsetof on non-POD types.
Result += " -Wno-logical-op-parentheses"; // needed for external headers we can't change
if (CompileEnvironment.Config.bEnableShadowVariableWarning)
{
Result += " -Wshadow -Wno-error=shadow";
}
// new for clang4.5 warnings:
if (ClangVersionFloat >= 3.5f)
{
Result += " -Wno-undefined-bool-conversion"; // 'this' pointer cannot be null in well-defined C++ code; pointer may be assumed to always convert to true (if (this))
}
if (ClangVersionFloat >= 3.6f)
{
Result += " -Wno-unused-local-typedef"; // clang is being overly strict here? PhysX headers trigger this.
Result += " -Wno-inconsistent-missing-override"; // these have to be suppressed for UE 4.8, should be fixed later.
}
// shipping builds will cause this warning with "ensure", so disable only in those case
if (CompileEnvironment.Config.Target.Configuration == CPPTargetConfiguration.Shipping)
{
Result += " -Wno-unused-value";
}
// debug info
if (CompileEnvironment.Config.bCreateDebugInfo)
{
Result += " -g2 -gdwarf-2";
}
// optimization level
if (CompileEnvironment.Config.Target.Configuration == CPPTargetConfiguration.Debug)
{
Result += " -O0";
}
else
{
if (UEBuildConfiguration.bCompileForSize)
{
Result += " -Oz";
}
else
{
Result += " -O3";
}
}
//@todo android: these are copied verbatim from UE3 and probably need adjustment
if (Architecture == "-armv7")
{
// Result += " -mthumb-interwork"; // Generates code which supports calling between ARM and Thumb instructions, w/o it you can't reliability use both together
Result += " -funwind-tables"; // Just generates any needed static data, affects no code
Result += " -fstack-protector"; // Emits extra code to check for buffer overflows
// Result += " -mlong-calls"; // Perform function calls by first loading the address of the function into a reg and then performing the subroutine call
Result += " -fno-strict-aliasing"; // Prevents unwanted or invalid optimizations that could produce incorrect code
Result += " -fpic"; // Generates position-independent code (PIC) suitable for use in a shared library
Result += " -fno-exceptions"; // Do not enable exception handling, generates extra code needed to propagate exceptions
Result += " -fno-rtti"; //
Result += " -fno-short-enums"; // Do not allocate to an enum type only as many bytes as it needs for the declared range of possible values
// Result += " -finline-limit=64"; // GCC limits the size of functions that can be inlined, this flag allows coarse control of this limit
// Result += " -Wno-psabi"; // Warn when G++ generates code that is probably not compatible with the vendor-neutral C++ ABI
Result += " -march=armv7-a";
Result += " -mfloat-abi=softfp";
Result += " -mfpu=vfpv3-d16"; //@todo android: UE3 was just vfp. arm7a should all support v3 with 16 registers
// Add flags for on-device debugging
if (CompileEnvironment.Config.Target.Configuration == CPPTargetConfiguration.Debug)
{
Result += " -fno-omit-frame-pointer"; // Disable removing the save/restore frame pointer for better debugging
if (ClangVersionFloat >= 3.6f)
{
Result += " -fno-function-sections"; // Improve breakpoint location
}
}
// Some switches interfere with on-device debugging
if (CompileEnvironment.Config.Target.Configuration != CPPTargetConfiguration.Debug)
{
Result += " -ffunction-sections"; // Places each function in its own section of the output file, linker may be able to perform opts to improve locality of reference
}
Result += " -fsigned-char"; // Treat chars as signed //@todo android: any concerns about ABI compatibility with libs here?
}
else if (Architecture == "-arm64")
{
Result += " -funwind-tables"; // Just generates any needed static data, affects no code
Result += " -fstack-protector"; // Emits extra code to check for buffer overflows
Result += " -fno-strict-aliasing"; // Prevents unwanted or invalid optimizations that could produce incorrect code
Result += " -fpic"; // Generates position-independent code (PIC) suitable for use in a shared library
Result += " -fno-exceptions"; // Do not enable exception handling, generates extra code needed to propagate exceptions
Result += " -fno-rtti"; //
Result += " -fno-short-enums"; // Do not allocate to an enum type only as many bytes as it needs for the declared range of possible values
Result += " -march=armv8-a";
//Result += " -mfloat-abi=softfp";
//Result += " -mfpu=vfpv3-d16"; //@todo android: UE3 was just vfp. arm7a should all support v3 with 16 registers
// Some switches interfere with on-device debugging
if (CompileEnvironment.Config.Target.Configuration != CPPTargetConfiguration.Debug)
{
Result += " -ffunction-sections"; // Places each function in its own section of the output file, linker may be able to perform opts to improve locality of reference
}
Result += " -fsigned-char"; // Treat chars as signed //@todo android: any concerns about ABI compatibility with libs here?
}
else if (Architecture == "-x86")
{
Result += " -fstrict-aliasing";
Result += " -fno-omit-frame-pointer";
Result += " -fno-strict-aliasing";
Result += " -fno-short-enums";
Result += " -fno-exceptions";
Result += " -fno-rtti";
Result += " -march=atom";
}
else if (Architecture == "-x64")
{
Result += " -fstrict-aliasing";
Result += " -fno-omit-frame-pointer";
Result += " -fno-strict-aliasing";
Result += " -fno-short-enums";
Result += " -fno-exceptions";
Result += " -fno-rtti";
Result += " -march=atom";
}
return Result;
}
static string GetCompileArguments_CPP(bool bDisableOptimizations)
{
string Result = "";
Result += " -x c++";
Result += " -std=c++11";
// optimization level
if (bDisableOptimizations)
{
Result += " -O0";
}
else
{
Result += " -O3";
}
return Result;
}
static string GetCompileArguments_C(bool bDisableOptimizations)
{
string Result = "";
Result += " -x c";
// optimization level
if (bDisableOptimizations)
{
Result += " -O0";
}
else
{
Result += " -O3";
}
return Result;
}
static string GetCompileArguments_PCH(bool bDisableOptimizations)
{
string Result = "";
Result += " -x c++-header";
Result += " -std=c++11";
// optimization level
if (bDisableOptimizations)
{
Result += " -O0";
}
else
{
Result += " -O3";
}
return Result;
}
static string GetLinkArguments(LinkEnvironment LinkEnvironment, string Architecture)
{
string Result = "";
Result += " -nostdlib";
Result += " -Wl,-shared,-Bsymbolic";
Result += " -Wl,--no-undefined";
if (Architecture == "-arm64")
{
Result += ToolchainParamsArm64;
Result += " -march=armv8-a";
}
else if (Architecture == "-x86")
{
Result += ToolchainParamsx86;
Result += " -march=atom";
}
else if (Architecture == "-x64")
{
Result += ToolchainParamsx64;
Result += " -march=atom";
}
else // if (Architecture == "-armv7")
{
Result += ToolchainParamsArm;
Result += " -march=armv7-a";
Result += " -Wl,--fix-cortex-a8"; // required to route around a CPU bug in some Cortex-A8 implementations
}
if (BuildConfiguration.bUseUnityBuild && ClangVersionFloat >= 3.6f)
{
Result += " -fuse-ld=gold"; // ld.gold is available in r10e (clang 3.6)
}
// verbose output from the linker
// Result += " -v";
return Result;
}
static string GetArArguments(LinkEnvironment LinkEnvironment)
{
string Result = "";
Result += " -r";
return Result;
}
public static void CompileOutputReceivedDataEventHandler(Object Sender, DataReceivedEventArgs Line)
{
if ((Line != null) && (Line.Data != null) && (Line.Data != ""))
{
bool bWasHandled = false;
// does it look like an error? something like this:
// 2>Core/Inc/UnStats.h:478:3: error : no matching constructor for initialization of 'FStatCommonData'
try
{
if (!Line.Data.StartsWith(" ") && !Line.Data.StartsWith(","))
{
// if we split on colon, an error will have at least 4 tokens
string[] Tokens = Line.Data.Split("(".ToCharArray());
if (Tokens.Length > 1)
{
// make sure what follows the parens is what we expect
string Filename = Path.GetFullPath(Tokens[0]);
// build up the final string
string Output = string.Format("{0}({1}", Filename, Tokens[1], Line.Data[0]);
for (int T = 3; T < Tokens.Length; T++)
{
Output += Tokens[T];
if (T < Tokens.Length - 1)
{
Output += "(";
}
}
// output the result
Log.TraceInformation(Output);
bWasHandled = true;
}
}
}
catch (Exception)
{
bWasHandled = false;
}
// write if not properly handled
if (!bWasHandled)
{
Log.TraceWarning("{0}", Line.Data);
}
}
}
static bool IsDirectoryForArch(string Dir, string Arch)
{
// make sure paths use one particular slash
Dir = Dir.Replace("\\", "/").ToLowerInvariant();
// look for other architectures in the Dir path, and fail if it finds it
foreach (var Pair in AllArchNames)
{
if (Pair.Key != Arch)
{
foreach (var ArchName in Pair.Value)
{
// if there's a directory in the path with a bad architecture name, reject it
if (Regex.IsMatch(Dir, "/" + ArchName + "$") || Regex.IsMatch(Dir, "/" + ArchName + "/"))
{
return false;
}
}
}
}
// if nothing was found, we are okay
return true;
}
static bool ShouldSkipModule(string ModuleName, string Arch)
{
foreach (var ModName in ModulesToSkip[Arch])
{
if (ModName == ModuleName)
{
return true;
}
}
// if nothing was found, we are okay
return false;
}
static bool ShouldSkipLib(string Lib, string Arch, string GPUArchitecture)
{
// reject any libs we outright don't want to link with
foreach (var LibName in LibrariesToSkip[Arch])
{
if (LibName == Lib)
{
return true;
}
}
// if another architecture is in the filename, reject it
foreach (string ComboName in AllComboNames)
{
if (ComboName != Arch + GPUArchitecture)
{
if (Path.GetFileNameWithoutExtension(Lib).EndsWith(ComboName))
{
return true;
}
}
}
// if nothing was found, we are okay
return false;
}
static void ConditionallyAddNDKSourceFiles(List<FileItem> SourceFiles, string ModuleName)
{
// We need to add the extra glue and cpu code only to Launch module.
if (ModuleName.Equals("Launch"))
{
SourceFiles.Add(FileItem.GetItemByPath(Environment.GetEnvironmentVariable("NDKROOT") + "/sources/android/native_app_glue/android_native_app_glue.c"));
// Newer NDK cpu_features.c uses getauxval() which causes a SIGSEGV in libhoudini.so (ARM on Intel translator) in older versions of Houdini
// so we patch the file to use alternative methods of detecting CPU features if libhoudini.so is detected
// The basis for this patch is from here: https://android-review.googlesource.com/#/c/110650/
String CpuFeaturesPath = Environment.GetEnvironmentVariable("NDKROOT") + "/sources/android/cpufeatures/";
String CpuFeaturesPatchedFile = CpuFeaturesPath + "cpu-features-patched.c";
if (!File.Exists(CpuFeaturesPatchedFile))
{
// Either make a copy or patch it
String[] CpuFeaturesLines = File.ReadAllLines(CpuFeaturesPath + "cpu-features.c");
// Look for get_elf_hwcap_from_getauxval in the file
bool NeedsPatch = false;
int LineIndex;
for (LineIndex = 0; LineIndex < CpuFeaturesLines.Length; ++LineIndex)
{
if (CpuFeaturesLines[LineIndex].Contains("get_elf_hwcap_from_getauxval"))
{
NeedsPatch = true;
// Make sure it doesn't already have the patch (r10c and 10d have it already, but removed in 10e)
for (int LineIndex2 = LineIndex; LineIndex2 < CpuFeaturesLines.Length; ++LineIndex2)
{
if (CpuFeaturesLines[LineIndex2].Contains("has_houdini_binary_translator(void)"))
{
NeedsPatch = false;
break;
}
}
break;
}
}
// Apply patch or write unchanged
if (NeedsPatch)
{
List<string> CpuFeaturesList = new List<string>(CpuFeaturesLines);
// Skip down to section to add Houdini check function for arm
while (!CpuFeaturesList[++LineIndex].StartsWith("#if defined(__arm__)")) ;
CpuFeaturesList.Insert(++LineIndex, "/* Check Houdini Binary Translator is installed on the system.");
CpuFeaturesList.Insert(++LineIndex, " *");
CpuFeaturesList.Insert(++LineIndex, " * If this function returns 1, get_elf_hwcap_from_getauxval() function");
CpuFeaturesList.Insert(++LineIndex, " * will causes SIGSEGV while calling getauxval() function.");
CpuFeaturesList.Insert(++LineIndex, " */");
CpuFeaturesList.Insert(++LineIndex, "static int");
CpuFeaturesList.Insert(++LineIndex, "has_houdini_binary_translator(void) {");
CpuFeaturesList.Insert(++LineIndex, " int found = 0;");
CpuFeaturesList.Insert(++LineIndex, " if (access(\"/system/lib/libhoudini.so\", F_OK) != -1) {");
CpuFeaturesList.Insert(++LineIndex, " D(\"Found Houdini binary translator\\n\");");
CpuFeaturesList.Insert(++LineIndex, " found = 1;");
CpuFeaturesList.Insert(++LineIndex, " }");
CpuFeaturesList.Insert(++LineIndex, " return found;");
CpuFeaturesList.Insert(++LineIndex, "}");
CpuFeaturesList.Insert(++LineIndex, "");
// Add the Houdini check call
while (!CpuFeaturesList[++LineIndex].Contains("/* Extract the list of CPU features from ELF hwcaps */")) ;
CpuFeaturesList.Insert(LineIndex++, " /* Check Houdini binary translator is installed */");
CpuFeaturesList.Insert(LineIndex++, " int has_houdini = has_houdini_binary_translator();");
CpuFeaturesList.Insert(LineIndex++, "");
// Make the get_elf_hwcap_from_getauxval() calls conditional
while (!CpuFeaturesList[++LineIndex].Contains("hwcaps = get_elf_hwcap_from_getauxval(AT_HWCAP);")) ;
CpuFeaturesList.Insert(LineIndex++, " if (!has_houdini) {");
CpuFeaturesList.Insert(++LineIndex, " }");
while (!CpuFeaturesList[++LineIndex].Contains("hwcaps2 = get_elf_hwcap_from_getauxval(AT_HWCAP2);")) ;
CpuFeaturesList.Insert(LineIndex++, " if (!has_houdini) {");
CpuFeaturesList.Insert(++LineIndex, " }");
File.WriteAllLines(CpuFeaturesPatchedFile, CpuFeaturesList.ToArray());
}
else
{
File.WriteAllLines(CpuFeaturesPatchedFile, CpuFeaturesLines);
}
}
SourceFiles.Add(FileItem.GetItemByPath(CpuFeaturesPatchedFile));
}
}
static void GenerateEmptyLinkFunctionsForRemovedModules(List<FileItem> SourceFiles, string ModuleName, string OutputDirectory)
{
// Only add to UELinkerFixups module
if (!ModuleName.Equals("Launch"))
{
return;
}
string LinkerExceptionsName = "../UELinkerExceptions";
string LinkerExceptionsCPPFilename = Path.Combine(OutputDirectory, LinkerExceptionsName + ".cpp");
// Create the cpp filename
if (!File.Exists(LinkerExceptionsCPPFilename))
{
// Create a dummy file in case it doesn't exist yet so that the module does not complain it's not there
ResponseFile.Create(LinkerExceptionsCPPFilename, new List<string>());
}
var Result = new List<string>();
foreach (string Arch in Arches)
{
switch (Arch)
{
case "-armv7": Result.Add("#if PLATFORM_ANDROID_ARM"); break;
case "-arm64": Result.Add("#if PLATFORM_ANDROID_ARM64"); break;
case "-x86": Result.Add("#if PLATFORM_ANDROID_X86"); break;
case "-x64": Result.Add("#if PLATFORM_ANDROID_X64"); break;
default: Result.Add("#if PLATFORM_ANDROID_ARM"); break;
}
foreach (var ModName in ModulesToSkip[Arch])
{
Result.Add(" void EmptyLinkFunctionForStaticInitialization" + ModName + "(){}");
}
Result.Add("#endif");
}
// Determine if the file changed. Write it if it either doesn't exist or the contents are different.
bool bShouldWriteFile = true;
if (File.Exists(LinkerExceptionsCPPFilename))
{
string[] ExistingExceptionText = File.ReadAllLines(LinkerExceptionsCPPFilename);
string JoinedNewContents = string.Join("", Result.ToArray());
string JoinedOldContents = string.Join("", ExistingExceptionText);
bShouldWriteFile = (JoinedNewContents != JoinedOldContents);
}
// If we determined that we should write the file, write it now.
if (bShouldWriteFile)
{
ResponseFile.Create(LinkerExceptionsCPPFilename, Result);
}
SourceFiles.Add(FileItem.GetItemByPath(LinkerExceptionsCPPFilename));
}
// cache the location of NDK tools
static string ClangPath;
static string ToolchainParamsArm;
static string ToolchainParamsArm64;
static string ToolchainParamsx86;
static string ToolchainParamsx64;
static string ArPathArm;
static string ArPathArm64;
static string ArPathx86;
static string ArPathx64;
static public string GetStripExecutablePath(string UE4Arch)
{
string StripPath;
switch (UE4Arch)
{
case "-armv7": StripPath = ArPathArm; break;
case "-arm64": StripPath = ArPathArm64; break;
case "-x86": StripPath = ArPathx86; break;
case "-x64": StripPath = ArPathx64; break;
default: StripPath = ArPathArm; break;
}
return StripPath.Replace("-ar", "-strip");
}
static private bool bHasPrintedApiLevel = false;
public override CPPOutput CompileCPPFiles(UEBuildTarget Target, CPPEnvironment CompileEnvironment, List<FileItem> SourceFiles, string ModuleName)
{
if (Arches.Count == 0)
{
throw new BuildException("At least one architecture (armv7, x86, etc) needs to be selected in the project settings to build");
}
if (!bHasPrintedApiLevel)
{
Console.WriteLine("Compiling Native code with NDK API '{0}'", GetNdkApiLevel());
bHasPrintedApiLevel = true;
}
string BaseArguments = "";
if (CompileEnvironment.Config.PrecompiledHeaderAction != PrecompiledHeaderAction.Create)
{
BaseArguments += " -Werror";
}
// Directly added NDK files for NDK extensions
ConditionallyAddNDKSourceFiles(SourceFiles, ModuleName);
// Deal with dynamic modules removed by architecture
GenerateEmptyLinkFunctionsForRemovedModules(SourceFiles, ModuleName, CompileEnvironment.Config.OutputDirectory);
// Add preprocessor definitions to the argument list.
foreach (string Definition in CompileEnvironment.Config.Definitions)
{
BaseArguments += string.Format(" -D \"{0}\"", Definition);
}
var BuildPlatform = UEBuildPlatform.GetBuildPlatformForCPPTargetPlatform(CompileEnvironment.Config.Target.Platform);
var NDKRoot = Environment.GetEnvironmentVariable("NDKROOT").Replace("\\", "/");
string BasePCHName = "";
var PCHExtension = UEBuildPlatform.BuildPlatformDictionary[UnrealTargetPlatform.Android].GetBinaryExtension(UEBuildBinaryType.PrecompiledHeader);
if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Include)
{
BasePCHName = RemoveArchName(CompileEnvironment.PrecompiledHeaderFile.AbsolutePath).Replace(PCHExtension, "");
}
// Create a compile action for each source file.
CPPOutput Result = new CPPOutput();
foreach (string Arch in Arches)
{
if (ShouldSkipModule(ModuleName, Arch))
{
continue;
}
foreach (string GPUArchitecture in GPUArchitectures)
{
// which toolchain to use
string Arguments = GetCLArguments_Global(CompileEnvironment, Arch) + BaseArguments;
switch (Arch)
{
case "-armv7": Arguments += " -DPLATFORM_64BITS=0 -DPLATFORM_ANDROID_ARM=1"; break;
case "-arm64": Arguments += " -DPLATFORM_64BITS=1 -DPLATFORM_ANDROID_ARM64=1"; break;
case "-x86": Arguments += " -DPLATFORM_64BITS=0 -DPLATFORM_ANDROID_X86=1"; break;
case "-x64": Arguments += " -DPLATFORM_64BITS=1 -DPLATFORM_ANDROID_X64=1"; break;
default: Arguments += " -DPLATFORM_64BITS=0 -DPLATFORM_ANDROID_ARM=1"; break;
}
if (GPUArchitecture == "-gl4")
{
Arguments += " -DPLATFORM_ANDROIDGL4=1";
}
else if (GPUArchitecture == "-es31")
{
Arguments += " -DPLATFORM_ANDROIDES31=1";
}
// which PCH file to include
string PCHArguments = "";
if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Include)
{
// Add the precompiled header file's path to the include path so Clang can find it.
// This needs to be before the other include paths to ensure Clang uses it instead of the source header file.
PCHArguments += string.Format(" -include \"{0}\"", InlineArchName(BasePCHName, Arch, GPUArchitecture));
}
// Add include paths to the argument list (filtered by architecture)
foreach (string IncludePath in CompileEnvironment.Config.CPPIncludeInfo.SystemIncludePaths)
{
if (IsDirectoryForArch(IncludePath, Arch))
{
Arguments += string.Format(" -I\"{0}\"", IncludePath);
}
}
foreach (string IncludePath in CompileEnvironment.Config.CPPIncludeInfo.IncludePaths)
{
if (IsDirectoryForArch(IncludePath, Arch))
{
Arguments += string.Format(" -I\"{0}\"", IncludePath);
}
}
foreach (FileItem SourceFile in SourceFiles)
{
Action CompileAction = new Action(ActionType.Compile);
string FileArguments = "";
bool bIsPlainCFile = Path.GetExtension(SourceFile.AbsolutePath).ToUpperInvariant() == ".C";
bool bDisableShadowWarning = false;
// should we disable optimizations on this file?
// @todo android - We wouldn't need this if we could disable optimizations per function (via pragma)
bool bDisableOptimizations = false;// SourceFile.AbsolutePath.ToUpperInvariant().IndexOf("\\SLATE\\") != -1;
if (bDisableOptimizations && CompileEnvironment.Config.Target.Configuration != CPPTargetConfiguration.Debug)
{
Log.TraceWarning("Disabling optimizations on {0}", SourceFile.AbsolutePath);
}
bDisableOptimizations = bDisableOptimizations || CompileEnvironment.Config.Target.Configuration == CPPTargetConfiguration.Debug;
// Add C or C++ specific compiler arguments.
if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Create)
{
FileArguments += GetCompileArguments_PCH(bDisableOptimizations);
}
else if (bIsPlainCFile)
{
FileArguments += GetCompileArguments_C(bDisableOptimizations);
// remove shadow variable warnings for NDK files
if (SourceFile.AbsolutePath.Replace("\\", "/").StartsWith(NDKRoot))
{
bDisableShadowWarning = true;
}
}
else
{
FileArguments += GetCompileArguments_CPP(bDisableOptimizations);
// only use PCH for .cpp files
FileArguments += PCHArguments;
}
// Add the C++ source file and its included files to the prerequisite item list.
AddPrerequisiteSourceFile(Target, BuildPlatform, CompileEnvironment, SourceFile, CompileAction.PrerequisiteItems);
if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Create)
{
// Add the precompiled header file to the produced item list.
FileItem PrecompiledHeaderFile = FileItem.GetItemByPath(
Path.Combine(
CompileEnvironment.Config.OutputDirectory,
Path.GetFileName(InlineArchName(SourceFile.AbsolutePath, Arch, GPUArchitecture) + PCHExtension)
)
);
CompileAction.ProducedItems.Add(PrecompiledHeaderFile);
Result.PrecompiledHeaderFile = PrecompiledHeaderFile;
// Add the parameters needed to compile the precompiled header file to the command-line.
FileArguments += string.Format(" -o \"{0}\"", PrecompiledHeaderFile.AbsolutePath, false);
}
else
{
if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Include)
{
CompileAction.bIsUsingPCH = true;
FileItem ArchPrecompiledHeaderFile = FileItem.GetItemByPath(InlineArchName(BasePCHName, Arch, GPUArchitecture) + PCHExtension);
CompileAction.PrerequisiteItems.Add(ArchPrecompiledHeaderFile);
}
var ObjectFileExtension = UEBuildPlatform.BuildPlatformDictionary[UnrealTargetPlatform.Android].GetBinaryExtension(UEBuildBinaryType.Object);
// Add the object file to the produced item list.
FileItem ObjectFile = FileItem.GetItemByPath(
InlineArchName( Path.Combine(
CompileEnvironment.Config.OutputDirectory,
Path.GetFileName(SourceFile.AbsolutePath) + ObjectFileExtension), Arch, GPUArchitecture
)
);
CompileAction.ProducedItems.Add(ObjectFile);
Result.ObjectFiles.Add(ObjectFile);
FileArguments += string.Format(" -o \"{0}\"", ObjectFile.AbsolutePath, false);
}
// Add the source file path to the command-line.
FileArguments += string.Format(" \"{0}\"", SourceFile.AbsolutePath);
// Build a full argument list
string AllArguments = Arguments + FileArguments + CompileEnvironment.Config.AdditionalArguments;
AllArguments = ActionThread.ExpandEnvironmentVariables(AllArguments);
AllArguments = AllArguments.Replace("\\", "/");
// Remove shadow warning for this file if requested
if (bDisableShadowWarning)
{
int WarningIndex = AllArguments.IndexOf(" -Wshadow");
if (WarningIndex > 0)
{
AllArguments = AllArguments.Remove(WarningIndex, 9);
}
}
// Create the response file
string ResponseFileName = CompileAction.ProducedItems[0].AbsolutePath + ".response";
string ResponseArgument = string.Format("@\"{0}\"", ResponseFile.Create(ResponseFileName, new List<string> { AllArguments }));
CompileAction.WorkingDirectory = Path.GetFullPath(".");
CompileAction.CommandPath = ClangPath;
CompileAction.CommandArguments = ResponseArgument;
CompileAction.StatusDescription = string.Format("{0} [{1}-{2}]", Path.GetFileName(SourceFile.AbsolutePath), Arch.Replace("-", ""), GPUArchitecture.Replace("-", ""));
CompileAction.OutputEventHandler = new DataReceivedEventHandler(CompileOutputReceivedDataEventHandler);
// VC++ always outputs the source file name being compiled, so we don't need to emit this ourselves
CompileAction.bShouldOutputStatusDescription = true;
// Don't farm out creation of pre-compiled headers as it is the critical path task.
CompileAction.bCanExecuteRemotely =
CompileEnvironment.Config.PrecompiledHeaderAction != PrecompiledHeaderAction.Create ||
BuildConfiguration.bAllowRemotelyCompiledPCHs;
}
}
}
return Result;
}
public override FileItem LinkFiles(LinkEnvironment LinkEnvironment, bool bBuildImportLibraryOnly)
{
return null;
}
static public string InlineArchName(string Pathname, string Arch, string GPUArchitecture)
{
return Path.Combine(Path.GetDirectoryName(Pathname), Path.GetFileNameWithoutExtension(Pathname) + Arch + GPUArchitecture + Path.GetExtension(Pathname));
}
static public string RemoveArchName(string Pathname)
{
// remove all architecture names
foreach (string Arch in Arches)
{
foreach (string GPUArchitecture in GPUArchitectures)
{
Pathname = Path.Combine(Path.GetDirectoryName(Pathname), Path.GetFileName(Pathname).Replace(Arch+GPUArchitecture, ""));
}
}
return Pathname;
}
public override FileItem[] LinkAllFiles(LinkEnvironment LinkEnvironment, bool bBuildImportLibraryOnly)
{
List<FileItem> Outputs = new List<FileItem>();
for (int ArchIndex = 0; ArchIndex < Arches.Count; ArchIndex++)
{
string Arch = Arches[ArchIndex];
for (int GPUArchIndex = 0; GPUArchIndex < GPUArchitectures.Count; GPUArchIndex++)
{
string GPUArchitecture = GPUArchitectures[GPUArchIndex];
int OutputPathIndex = ArchIndex * GPUArchitectures.Count + GPUArchIndex;
// Android will have an array of outputs
if (LinkEnvironment.Config.OutputFilePaths.Count < OutputPathIndex ||
!Path.GetFileNameWithoutExtension(LinkEnvironment.Config.OutputFilePaths[OutputPathIndex]).EndsWith(Arch + GPUArchitecture))
{
throw new BuildException("The OutputFilePaths array didn't match the Arches array in AndroidToolChain.LinkAllFiles");
}
// Create an action that invokes the linker.
Action LinkAction = new Action(ActionType.Link);
LinkAction.WorkingDirectory = Path.GetFullPath(".");
if (LinkEnvironment.Config.bIsBuildingLibrary)
{
switch (Arch)
{
case "-armv7": LinkAction.CommandPath = ArPathArm; break;
case "-arm64": LinkAction.CommandPath = ArPathArm64; break;
case "-x86": LinkAction.CommandPath = ArPathx86; ; break;
case "-x64": LinkAction.CommandPath = ArPathx64; ; break;
default: LinkAction.CommandPath = ArPathArm; ; break;
}
}
else
{
LinkAction.CommandPath = ClangPath;
}
string LinkerPath = LinkAction.WorkingDirectory;
LinkAction.WorkingDirectory = LinkEnvironment.Config.IntermediateDirectory;
// Get link arguments.
LinkAction.CommandArguments = LinkEnvironment.Config.bIsBuildingLibrary ? GetArArguments(LinkEnvironment) : GetLinkArguments(LinkEnvironment, Arch);
// Add the output file as a production of the link action.
FileItem OutputFile;
OutputFile = FileItem.GetItemByPath(LinkEnvironment.Config.OutputFilePaths[OutputPathIndex]);
Outputs.Add(OutputFile);
LinkAction.ProducedItems.Add(OutputFile);
LinkAction.StatusDescription = string.Format("{0}", Path.GetFileName(OutputFile.AbsolutePath));
// LinkAction.bPrintDebugInfo = true;
// Add the output file to the command-line.
if (LinkEnvironment.Config.bIsBuildingLibrary)
{
LinkAction.CommandArguments += string.Format(" \"{0}\"", OutputFile.AbsolutePath);
}
else
{
LinkAction.CommandArguments += string.Format(" -o \"{0}\"", OutputFile.AbsolutePath);
}
// Add the input files to a response file, and pass the response file on the command-line.
List<string> InputFileNames = new List<string>();
foreach (FileItem InputFile in LinkEnvironment.InputFiles)
{
// make sure it's for current Arch
if (Path.GetFileNameWithoutExtension(InputFile.AbsolutePath).EndsWith(Arch + GPUArchitecture))
{
string AbsolutePath = InputFile.AbsolutePath.Replace("\\", "/");
AbsolutePath = AbsolutePath.Replace(LinkEnvironment.Config.IntermediateDirectory.Replace("\\", "/"), "");
AbsolutePath = AbsolutePath.TrimStart(new char[] { '/' });
InputFileNames.Add(string.Format("\"{0}\"", AbsolutePath));
LinkAction.PrerequisiteItems.Add(InputFile);
}
}
string ResponseFileName = GetResponseFileName(LinkEnvironment, OutputFile);
LinkAction.CommandArguments += string.Format(" @\"{0}\"", ResponseFile.Create(ResponseFileName, InputFileNames));
// libs don't link in other libs
if (!LinkEnvironment.Config.bIsBuildingLibrary)
{
// Add the library paths to the argument list.
foreach (string LibraryPath in LinkEnvironment.Config.LibraryPaths)
{
// LinkerPaths could be relative or absolute
string AbsoluteLibraryPath = ActionThread.ExpandEnvironmentVariables(LibraryPath);
if (IsDirectoryForArch(AbsoluteLibraryPath, Arch))
{
// environment variables aren't expanded when using the $( style
if (Path.IsPathRooted(AbsoluteLibraryPath) == false)
{
AbsoluteLibraryPath = Path.Combine(LinkerPath, AbsoluteLibraryPath);
}
LinkAction.CommandArguments += string.Format(" -L\"{0}\"", AbsoluteLibraryPath);
}
}
// add libraries in a library group
LinkAction.CommandArguments += string.Format(" -Wl,--start-group");
foreach (string AdditionalLibrary in LinkEnvironment.Config.AdditionalLibraries)
{
if (!ShouldSkipLib(AdditionalLibrary, Arch, GPUArchitecture))
{
if (String.IsNullOrEmpty(Path.GetDirectoryName(AdditionalLibrary)))
{
LinkAction.CommandArguments += string.Format(" \"-l{0}\"", AdditionalLibrary);
}
else
{
// full pathed libs are compiled by us, so we depend on linking them
LinkAction.CommandArguments += string.Format(" \"{0}\"", Path.GetFullPath(AdditionalLibrary));
LinkAction.PrerequisiteItems.Add(FileItem.GetItemByPath(AdditionalLibrary));
}
}
}
LinkAction.CommandArguments += string.Format(" -Wl,--end-group");
}
// Add the additional arguments specified by the environment.
LinkAction.CommandArguments += LinkEnvironment.Config.AdditionalArguments;
LinkAction.CommandArguments = LinkAction.CommandArguments.Replace("\\", "/");
// Only execute linking on the local PC.
LinkAction.bCanExecuteRemotely = false;
}
}
return Outputs.ToArray();
}
public override void AddFilesToReceipt(BuildReceipt Receipt, UEBuildBinary Binary)
{
// the binary will have all of the .so's in the output files, we need to trim down to the shared apk (which is what needs to go into the manifest)
if (Binary.Config.Type != UEBuildBinaryType.StaticLibrary)
{
foreach (string BinaryPath in Binary.Config.OutputFilePaths)
{
string ApkFile = Path.ChangeExtension(BinaryPath, ".apk");
Receipt.AddBuildProduct(ApkFile, BuildProductType.Executable);
}
}
}
public override void CompileCSharpProject(CSharpEnvironment CompileEnvironment, string ProjectFileName, string DestinationFile)
{
throw new BuildException("Android cannot compile C# files");
}
public static void OutputReceivedDataEventHandler(Object Sender, DataReceivedEventArgs Line)
{
if ((Line != null) && (Line.Data != null))
{
Log.TraceInformation(Line.Data);
}
}
public override UnrealTargetPlatform GetPlatform()
{
return UnrealTargetPlatform.Android;
}
public override void StripSymbols(string SourceFileName, string TargetFileName)
{
File.Copy(SourceFileName, TargetFileName, true);
ProcessStartInfo StartInfo = new ProcessStartInfo();
if(SourceFileName.Contains("-armv7"))
{
StartInfo.FileName = ArPathArm.Replace("-ar.exe", "-strip.exe");
}
else
{
throw new BuildException("Couldn't determine Android architecture to strip symbols from {0}", SourceFileName);
}
StartInfo.Arguments = "--strip-debug " + TargetFileName;
StartInfo.UseShellExecute = false;
StartInfo.CreateNoWindow = true;
Utils.RunLocalProcessAndLogOutput(StartInfo);
}
};
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ds-2015-04-16.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.DirectoryService.Model;
namespace Amazon.DirectoryService
{
/// <summary>
/// Interface for accessing DirectoryService
///
/// AWS Directory Service
/// <para>
/// This is the <i>AWS Directory Service API Reference</i>. This guide provides detailed
/// information about AWS Directory Service operations, data types, parameters, and errors.
/// </para>
/// </summary>
public partial interface IAmazonDirectoryService : IDisposable
{
#region ConnectDirectory
/// <summary>
/// Creates an AD Connector to connect an on-premises directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ConnectDirectory service method.</param>
///
/// <returns>The response from the ConnectDirectory service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.DirectoryLimitExceededException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
ConnectDirectoryResponse ConnectDirectory(ConnectDirectoryRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ConnectDirectory operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ConnectDirectory operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndConnectDirectory
/// operation.</returns>
IAsyncResult BeginConnectDirectory(ConnectDirectoryRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ConnectDirectory operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginConnectDirectory.</param>
///
/// <returns>Returns a ConnectDirectoryResult from DirectoryService.</returns>
ConnectDirectoryResponse EndConnectDirectory(IAsyncResult asyncResult);
#endregion
#region CreateAlias
/// <summary>
/// Creates an alias for a directory and assigns the alias to the directory. The alias
/// is used to construct the access URL for the directory, such as <code>http://<alias>.awsapps.com</code>.
///
/// <important>
/// <para>
/// After an alias has been created, it cannot be deleted or reused, so this operation
/// should only be used when absolutely necessary.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateAlias service method.</param>
///
/// <returns>The response from the CreateAlias service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityAlreadyExistsException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
CreateAliasResponse CreateAlias(CreateAliasRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateAlias operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateAlias operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateAlias
/// operation.</returns>
IAsyncResult BeginCreateAlias(CreateAliasRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateAlias operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateAlias.</param>
///
/// <returns>Returns a CreateAliasResult from DirectoryService.</returns>
CreateAliasResponse EndCreateAlias(IAsyncResult asyncResult);
#endregion
#region CreateComputer
/// <summary>
/// Creates a computer account in the specified directory, and joins the computer to the
/// directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateComputer service method.</param>
///
/// <returns>The response from the CreateComputer service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.AuthenticationFailedException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.DirectoryUnavailableException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityAlreadyExistsException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.UnsupportedOperationException">
///
/// </exception>
CreateComputerResponse CreateComputer(CreateComputerRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateComputer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateComputer operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateComputer
/// operation.</returns>
IAsyncResult BeginCreateComputer(CreateComputerRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateComputer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateComputer.</param>
///
/// <returns>Returns a CreateComputerResult from DirectoryService.</returns>
CreateComputerResponse EndCreateComputer(IAsyncResult asyncResult);
#endregion
#region CreateDirectory
/// <summary>
/// Creates a Simple AD directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateDirectory service method.</param>
///
/// <returns>The response from the CreateDirectory service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.DirectoryLimitExceededException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
CreateDirectoryResponse CreateDirectory(CreateDirectoryRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateDirectory operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateDirectory operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateDirectory
/// operation.</returns>
IAsyncResult BeginCreateDirectory(CreateDirectoryRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateDirectory operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateDirectory.</param>
///
/// <returns>Returns a CreateDirectoryResult from DirectoryService.</returns>
CreateDirectoryResponse EndCreateDirectory(IAsyncResult asyncResult);
#endregion
#region CreateSnapshot
/// <summary>
/// Creates a snapshot of an existing directory.
///
///
/// <para>
/// You cannot take snapshots of extended or connected directories.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateSnapshot service method.</param>
///
/// <returns>The response from the CreateSnapshot service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.SnapshotLimitExceededException">
///
/// </exception>
CreateSnapshotResponse CreateSnapshot(CreateSnapshotRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateSnapshot operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateSnapshot operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateSnapshot
/// operation.</returns>
IAsyncResult BeginCreateSnapshot(CreateSnapshotRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateSnapshot operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateSnapshot.</param>
///
/// <returns>Returns a CreateSnapshotResult from DirectoryService.</returns>
CreateSnapshotResponse EndCreateSnapshot(IAsyncResult asyncResult);
#endregion
#region DeleteDirectory
/// <summary>
/// Deletes an AWS Directory Service directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteDirectory service method.</param>
///
/// <returns>The response from the DeleteDirectory service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
DeleteDirectoryResponse DeleteDirectory(DeleteDirectoryRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteDirectory operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteDirectory operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteDirectory
/// operation.</returns>
IAsyncResult BeginDeleteDirectory(DeleteDirectoryRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteDirectory operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteDirectory.</param>
///
/// <returns>Returns a DeleteDirectoryResult from DirectoryService.</returns>
DeleteDirectoryResponse EndDeleteDirectory(IAsyncResult asyncResult);
#endregion
#region DeleteSnapshot
/// <summary>
/// Deletes a directory snapshot.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteSnapshot service method.</param>
///
/// <returns>The response from the DeleteSnapshot service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
DeleteSnapshotResponse DeleteSnapshot(DeleteSnapshotRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteSnapshot operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteSnapshot operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteSnapshot
/// operation.</returns>
IAsyncResult BeginDeleteSnapshot(DeleteSnapshotRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteSnapshot operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteSnapshot.</param>
///
/// <returns>Returns a DeleteSnapshotResult from DirectoryService.</returns>
DeleteSnapshotResponse EndDeleteSnapshot(IAsyncResult asyncResult);
#endregion
#region DescribeDirectories
/// <summary>
/// Obtains information about the directories that belong to this account.
///
///
/// <para>
/// You can retrieve information about specific directories by passing the directory identifiers
/// in the <i>DirectoryIds</i> parameter. Otherwise, all directories that belong to the
/// current account are returned.
/// </para>
///
/// <para>
/// This operation supports pagination with the use of the <i>NextToken</i> request and
/// response parameters. If more results are available, the <i>DescribeDirectoriesResult.NextToken</i>
/// member contains a token that you pass in the next call to <a>DescribeDirectories</a>
/// to retrieve the next set of items.
/// </para>
///
/// <para>
/// You can also specify a maximum number of return results with the <i>Limit</i> parameter.
/// </para>
/// </summary>
///
/// <returns>The response from the DescribeDirectories service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidNextTokenException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
DescribeDirectoriesResponse DescribeDirectories();
/// <summary>
/// Obtains information about the directories that belong to this account.
///
///
/// <para>
/// You can retrieve information about specific directories by passing the directory identifiers
/// in the <i>DirectoryIds</i> parameter. Otherwise, all directories that belong to the
/// current account are returned.
/// </para>
///
/// <para>
/// This operation supports pagination with the use of the <i>NextToken</i> request and
/// response parameters. If more results are available, the <i>DescribeDirectoriesResult.NextToken</i>
/// member contains a token that you pass in the next call to <a>DescribeDirectories</a>
/// to retrieve the next set of items.
/// </para>
///
/// <para>
/// You can also specify a maximum number of return results with the <i>Limit</i> parameter.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeDirectories service method.</param>
///
/// <returns>The response from the DescribeDirectories service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidNextTokenException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
DescribeDirectoriesResponse DescribeDirectories(DescribeDirectoriesRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeDirectories operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeDirectories operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeDirectories
/// operation.</returns>
IAsyncResult BeginDescribeDirectories(DescribeDirectoriesRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeDirectories operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeDirectories.</param>
///
/// <returns>Returns a DescribeDirectoriesResult from DirectoryService.</returns>
DescribeDirectoriesResponse EndDescribeDirectories(IAsyncResult asyncResult);
#endregion
#region DescribeSnapshots
/// <summary>
/// Obtains information about the directory snapshots that belong to this account.
///
///
/// <para>
/// This operation supports pagination with the use of the <i>NextToken</i> request and
/// response parameters. If more results are available, the <i>DescribeSnapshots.NextToken</i>
/// member contains a token that you pass in the next call to <a>DescribeSnapshots</a>
/// to retrieve the next set of items.
/// </para>
///
/// <para>
/// You can also specify a maximum number of return results with the <i>Limit</i> parameter.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots service method.</param>
///
/// <returns>The response from the DescribeSnapshots service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidNextTokenException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
DescribeSnapshotsResponse DescribeSnapshots(DescribeSnapshotsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeSnapshots operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeSnapshots
/// operation.</returns>
IAsyncResult BeginDescribeSnapshots(DescribeSnapshotsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeSnapshots operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeSnapshots.</param>
///
/// <returns>Returns a DescribeSnapshotsResult from DirectoryService.</returns>
DescribeSnapshotsResponse EndDescribeSnapshots(IAsyncResult asyncResult);
#endregion
#region DisableRadius
/// <summary>
/// Disables multi-factor authentication (MFA) with Remote Authentication Dial In User
/// Service (RADIUS) for an AD Connector directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DisableRadius service method.</param>
///
/// <returns>The response from the DisableRadius service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
DisableRadiusResponse DisableRadius(DisableRadiusRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DisableRadius operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DisableRadius operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDisableRadius
/// operation.</returns>
IAsyncResult BeginDisableRadius(DisableRadiusRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DisableRadius operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDisableRadius.</param>
///
/// <returns>Returns a DisableRadiusResult from DirectoryService.</returns>
DisableRadiusResponse EndDisableRadius(IAsyncResult asyncResult);
#endregion
#region DisableSso
/// <summary>
/// Disables single-sign on for a directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DisableSso service method.</param>
///
/// <returns>The response from the DisableSso service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.AuthenticationFailedException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InsufficientPermissionsException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
DisableSsoResponse DisableSso(DisableSsoRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DisableSso operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DisableSso operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDisableSso
/// operation.</returns>
IAsyncResult BeginDisableSso(DisableSsoRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DisableSso operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDisableSso.</param>
///
/// <returns>Returns a DisableSsoResult from DirectoryService.</returns>
DisableSsoResponse EndDisableSso(IAsyncResult asyncResult);
#endregion
#region EnableRadius
/// <summary>
/// Enables multi-factor authentication (MFA) with Remote Authentication Dial In User
/// Service (RADIUS) for an AD Connector directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the EnableRadius service method.</param>
///
/// <returns>The response from the EnableRadius service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityAlreadyExistsException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
EnableRadiusResponse EnableRadius(EnableRadiusRequest request);
/// <summary>
/// Initiates the asynchronous execution of the EnableRadius operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the EnableRadius operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndEnableRadius
/// operation.</returns>
IAsyncResult BeginEnableRadius(EnableRadiusRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the EnableRadius operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginEnableRadius.</param>
///
/// <returns>Returns a EnableRadiusResult from DirectoryService.</returns>
EnableRadiusResponse EndEnableRadius(IAsyncResult asyncResult);
#endregion
#region EnableSso
/// <summary>
/// Enables single-sign on for a directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the EnableSso service method.</param>
///
/// <returns>The response from the EnableSso service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.AuthenticationFailedException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InsufficientPermissionsException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
EnableSsoResponse EnableSso(EnableSsoRequest request);
/// <summary>
/// Initiates the asynchronous execution of the EnableSso operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the EnableSso operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndEnableSso
/// operation.</returns>
IAsyncResult BeginEnableSso(EnableSsoRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the EnableSso operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginEnableSso.</param>
///
/// <returns>Returns a EnableSsoResult from DirectoryService.</returns>
EnableSsoResponse EndEnableSso(IAsyncResult asyncResult);
#endregion
#region GetDirectoryLimits
/// <summary>
/// Obtains directory limit information for the current region.
/// </summary>
///
/// <returns>The response from the GetDirectoryLimits service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
GetDirectoryLimitsResponse GetDirectoryLimits();
/// <summary>
/// Obtains directory limit information for the current region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetDirectoryLimits service method.</param>
///
/// <returns>The response from the GetDirectoryLimits service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
GetDirectoryLimitsResponse GetDirectoryLimits(GetDirectoryLimitsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetDirectoryLimits operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetDirectoryLimits operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetDirectoryLimits
/// operation.</returns>
IAsyncResult BeginGetDirectoryLimits(GetDirectoryLimitsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetDirectoryLimits operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetDirectoryLimits.</param>
///
/// <returns>Returns a GetDirectoryLimitsResult from DirectoryService.</returns>
GetDirectoryLimitsResponse EndGetDirectoryLimits(IAsyncResult asyncResult);
#endregion
#region GetSnapshotLimits
/// <summary>
/// Obtains the manual snapshot limits for a directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetSnapshotLimits service method.</param>
///
/// <returns>The response from the GetSnapshotLimits service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
GetSnapshotLimitsResponse GetSnapshotLimits(GetSnapshotLimitsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetSnapshotLimits operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetSnapshotLimits operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetSnapshotLimits
/// operation.</returns>
IAsyncResult BeginGetSnapshotLimits(GetSnapshotLimitsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetSnapshotLimits operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetSnapshotLimits.</param>
///
/// <returns>Returns a GetSnapshotLimitsResult from DirectoryService.</returns>
GetSnapshotLimitsResponse EndGetSnapshotLimits(IAsyncResult asyncResult);
#endregion
#region RestoreFromSnapshot
/// <summary>
/// Restores a directory using an existing directory snapshot.
///
///
/// <para>
/// When you restore a directory from a snapshot, any changes made to the directory after
/// the snapshot date are overwritten.
/// </para>
///
/// <para>
/// This action returns as soon as the restore operation is initiated. You can monitor
/// the progress of the restore operation by calling the <a>DescribeDirectories</a> operation
/// with the directory identifier. When the <b>DirectoryDescription.Stage</b> value changes
/// to <code>Active</code>, the restore operation is complete.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RestoreFromSnapshot service method.</param>
///
/// <returns>The response from the RestoreFromSnapshot service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
RestoreFromSnapshotResponse RestoreFromSnapshot(RestoreFromSnapshotRequest request);
/// <summary>
/// Initiates the asynchronous execution of the RestoreFromSnapshot operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RestoreFromSnapshot operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRestoreFromSnapshot
/// operation.</returns>
IAsyncResult BeginRestoreFromSnapshot(RestoreFromSnapshotRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the RestoreFromSnapshot operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRestoreFromSnapshot.</param>
///
/// <returns>Returns a RestoreFromSnapshotResult from DirectoryService.</returns>
RestoreFromSnapshotResponse EndRestoreFromSnapshot(IAsyncResult asyncResult);
#endregion
#region UpdateRadius
/// <summary>
/// Updates the Remote Authentication Dial In User Service (RADIUS) server information
/// for an AD Connector directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateRadius service method.</param>
///
/// <returns>The response from the UpdateRadius service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
UpdateRadiusResponse UpdateRadius(UpdateRadiusRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateRadius operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateRadius operation on AmazonDirectoryServiceClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateRadius
/// operation.</returns>
IAsyncResult BeginUpdateRadius(UpdateRadiusRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateRadius operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateRadius.</param>
///
/// <returns>Returns a UpdateRadiusResult from DirectoryService.</returns>
UpdateRadiusResponse EndUpdateRadius(IAsyncResult asyncResult);
#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.IO.PortsTests;
using System.Text;
using System.Threading;
using Legacy.Support;
using Xunit;
using ThreadState = System.Threading.ThreadState;
namespace System.IO.Ports.Tests
{
public class Write_byte_int_int_generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low write will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the write method and the testcase fails.
private const double maxPercentageDifference = .15;
//The byte size used when veryifying exceptions that write will throw
private const int BYTE_SIZE_EXCEPTION = 4;
//The byte size used when veryifying timeout
private const int BYTE_SIZE_TIMEOUT = 4;
//The byte size used when veryifying BytesToWrite
private const int BYTE_SIZE_BYTES_TO_WRITE = 4;
//The bytes size used when veryifying Handshake
private const int BYTE_SIZE_HANDSHAKE = 8;
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void WriteWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying write method throws exception without a call to Open()");
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying write method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verfifying a write method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying write method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[OuterLoop("Slow test")]
[ConditionalFact(nameof(HasNullModem))]
public void Timeout()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] XOffBuffer = new byte[1];
XOffBuffer[0] = 19;
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.XOnXOff;
Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout);
com1.Open();
com2.Open();
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
com2.Close();
VerifyTimeout(com1);
}
}
[OuterLoop("Slow test")]
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com.Handshake = Handshake.RequestToSendXOnXOff;
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout);
com.Open();
try
{
com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeoutWithWriteSucceeding()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
AsyncEnableRts asyncEnableRts = new AsyncEnableRts();
Thread t = new Thread(asyncEnableRts.EnableRTS);
int waitTime;
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.RequestToSend;
com1.Encoding = new UTF8Encoding();
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout);
com1.Open();
//Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed
//before the timeout is reached
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
//Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
try
{
com1.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
asyncEnableRts.Stop();
while (t.IsAlive)
Thread.Sleep(100);
VerifyTimeout(com1);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void BytesToWrite()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_BYTES_TO_WRITE);
Thread t = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
int waitTime;
Debug.WriteLine("Verifying BytesToWrite with one call to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 500;
//Write a random byte[] asynchronously so we can verify some things while the write call is blocking
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{ //Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForExactWriteBufferLoad(com, BYTE_SIZE_BYTES_TO_WRITE);
//Wait for write method to timeout
while (t.IsAlive)
Thread.Sleep(100);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void BytesToWriteSuccessive()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_BYTES_TO_WRITE);
Thread t1 = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
Thread t2 = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
int waitTime;
Debug.WriteLine("Verifying BytesToWrite with successive calls to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 1000;
//Write a random byte[] asynchronously so we can verify some things while the write call is blocking
t1.Start();
waitTime = 0;
while (t1.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{ //Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForExactWriteBufferLoad(com, BYTE_SIZE_BYTES_TO_WRITE);
//Write a random byte[] asynchronously so we can verify some things while the write call is blocking
t2.Start();
waitTime = 0;
while (t2.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{ //Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForExactWriteBufferLoad(com, BYTE_SIZE_BYTES_TO_WRITE * 2);
//Wait for both write methods to timeout
while (t1.IsAlive || t2.IsAlive)
Thread.Sleep(100);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_None()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_HANDSHAKE);
Thread t = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
int waitTime;
//Write a random byte[] asynchronously so we can verify some things while the write call is blocking
Debug.WriteLine("Verifying Handshake=None");
com.Open();
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{ //Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
//Wait for write method to timeout
while (t.IsAlive)
Thread.Sleep(100);
if (0 != com.BytesToWrite)
{
Fail("ERROR!!! Expcted BytesToWrite=0 actual {0}", com.BytesToWrite);
}
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSend()
{
Verify_Handshake(Handshake.RequestToSend);
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_XOnXOff()
{
Verify_Handshake(Handshake.XOnXOff);
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSendXOnXOff()
{
Verify_Handshake(Handshake.RequestToSendXOnXOff);
}
private class AsyncEnableRts
{
private bool _stop;
public void EnableRTS()
{
lock (this)
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.RtsEnable = true;
while (!_stop)
Monitor.Wait(this);
com2.RtsEnable = false;
}
}
}
public void Stop()
{
lock (this)
{
_stop = true;
Monitor.Pulse(this);
}
}
}
private class AsyncWriteRndByteArray
{
private readonly SerialPort _com;
private readonly int _byteLength;
public AsyncWriteRndByteArray(SerialPort com, int byteLength)
{
_com = com;
_byteLength = byteLength;
}
public void WriteRndByteArray()
{
byte[] buffer = new byte[_byteLength];
Random rndGen = new Random(-55);
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)rndGen.Next(0, 256);
}
try
{
_com.Write(buffer, 0, buffer.Length);
}
catch (TimeoutException)
{
}
}
}
#endregion
#region Verification for Test Cases
private static void VerifyWriteException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.Write(new byte[BYTE_SIZE_EXCEPTION], 0, BYTE_SIZE_EXCEPTION));
}
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.WriteTimeout;
int actualTime = 0;
double percentageDifference;
try
{
com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT); //Warm up write method
}
catch (TimeoutException) { }
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
try
{
com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT);
}
catch (TimeoutException) { }
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void Verify_Handshake(Handshake handshake)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com1, BYTE_SIZE_HANDSHAKE);
Thread t = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
byte[] XOffBuffer = new byte[1];
byte[] XOnBuffer = new byte[1];
int waitTime;
XOffBuffer[0] = 19;
XOnBuffer[0] = 17;
Debug.WriteLine("Verifying Handshake={0}", handshake);
com1.Handshake = handshake;
com1.Open();
com2.Open();
//Setup to ensure write will bock with type of handshake method being used
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = false;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
}
//Write a random byte asynchronously so we can verify some things while the write call is blocking
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
//Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
waitTime = 0;
TCSupport.WaitForExactWriteBufferLoad(com1, BYTE_SIZE_HANDSHAKE);
//Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding)
{
Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding);
}
//Setup to ensure write will succeed
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = true;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.Write(XOnBuffer, 0, 1);
}
//Wait till write finishes
while (t.IsAlive)
Thread.Sleep(100);
Assert.Equal(0, com1.BytesToWrite);
//Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) &&
!com1.CtsHolding)
{
Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding);
}
}
}
#endregion
}
}
| |
#region License
//
// InputAttribute.cs July 2006
//
// Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net>
//
// 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
#region Using directives
using System;
#endregion
namespace SimpleFramework.Xml.Stream {
/// <summary>
/// The <c>InputAttribute</c> is used to represent an attribute
/// within an element. Rather than representing an attribute as a
/// name value pair of strings, an attribute is instead represented
/// as an input node, in the same manner as an element. The reason
/// for representing an attribute in this way is such that a uniform
/// means of extracting and parsing values can be used for inputs.
/// </summary>
class InputAttribute : InputNode {
/// <summary>
/// This is the parent node to this attribute instance.
/// </summary>
private InputNode parent;
/// <summary>
/// This is the reference associated with this attribute node.
/// </summary>
private String reference;
/// <summary>
/// This is the prefix associated with this attribute node.
/// </summary>
private String prefix;
/// <summary>
/// Represents the name of this input attribute instance.
/// </summary>
private String name;
/// <summary>
/// Represents the value for this input attribute instance.
/// </summary>
private String value;
/// <summary>
/// This is the source associated with this input attribute.
/// </summary>
private Object source;
/// <summary>
/// Constructor for the <c>InputAttribute</c> object. This
/// is used to create an input attribute using the provided name
/// and value, all other values for this input node will be null.
/// </summary>
/// <param name="parent">
/// this is the parent node to this attribute
/// </param>
/// <param name="name">
/// this is the name for this attribute object
/// </param>
/// <param name="value">
/// this is the value for this attribute object
/// </param>
public InputAttribute(InputNode parent, String name, String value) {
this.parent = parent;
this.value = value;
this.name = name;
}
/// <summary>
/// Constructor for the <c>InputAttribute</c> object. This
/// is used to create an input attribute using the provided name
/// and value, all other values for this input node will be null.
/// </summary>
/// <param name="parent">
/// this is the parent node to this attribute
/// </param>
/// <param name="attribute">
/// this is the attribute containing the details
/// </param>
public InputAttribute(InputNode parent, Attribute attribute) {
this.reference = attribute.Reference;
this.prefix = attribute.Prefix;
this.source = attribute.Source;
this.value = attribute.Value;
this.name = attribute.Name;
this.parent = parent;
}
/// <summary>
/// This is used to return the source object for this node. This
/// is used primarily as a means to determine which XML provider
/// is parsing the source document and producing the nodes. It
/// is useful to be able to determine the XML provider like this.
/// </summary>
/// <returns>
/// this returns the source of this input node
/// </returns>
public Object Source {
get {
return source;
}
}
//public Object GetSource() {
// return source;
//}
/// This is used to acquire the <c>Node</c> that is the
/// parent of this node. This will return the node that is
/// the direct parent of this node and allows for siblings to
/// make use of nodes with their parents if required.
/// </summary>
/// <returns>
/// this returns the parent node for this node
/// </returns>
public InputNode Parent {
get {
return parent;
}
}
//public InputNode GetParent() {
// return parent;
//}
/// This provides the position of this node within the document.
/// This allows the user of this node to report problems with
/// the location within the document, allowing the XML to be
/// debugged if it does not match the class schema.
/// </summary>
/// <returns>
/// this returns the position of the XML read cursor
/// </returns>
public Position Position {
get {
return parent.Position;
}
}
//public Position GetPosition() {
// return parent.Position;
//}
/// Returns the name of the node that this represents. This is
/// an immutable property and will not change for this node.
/// </summary>
/// <returns>
/// returns the name of the node that this represents
/// </returns>
public String Name {
get {
return name;
}
}
//public String GetName() {
// return name;
//}
/// This is used to acquire the namespace prefix for the node.
/// If there is no namespace prefix for the node then this will
/// return null. Acquiring the prefix enables the qualification
/// of the node to be determined. It also allows nodes to be
/// grouped by its prefix and allows group operations.
/// </summary>
/// <returns>
/// this returns the prefix associated with this node
/// </returns>
public String Prefix {
get {
return prefix;
}
}
//public String GetPrefix() {
// return prefix;
//}
/// This allows the namespace reference URI to be determined.
/// A reference is a globally unique string that allows the
/// node to be identified. Typically the reference will be a URI
/// but it can be any unique string used to identify the node.
/// This allows the node to be identified within the namespace.
/// </summary>
/// <returns>
/// this returns the associated namespace reference URI
/// </returns>
public String Reference {
get {
return reference;
}
}
//public String GetReference() {
// return reference;
//}
/// Returns the value for the node that this represents. This
/// is an immutable value for the node and cannot be changed.
/// </summary>
/// <returns>
/// the name of the value for this node instance
/// </returns>
public String Value {
get {
return value;
}
}
//public String GetValue() {
// return value;
//}
/// This method is used to determine if this node is the root
/// node for the XML document. This will return false as this
/// node can never be the root node because it is an attribute.
/// </summary>
/// <returns>
/// this will always return false for attribute nodes
/// </returns>
public bool IsRoot() {
return false;
}
/// <summary>
/// This is used to determine if this node is an element. This
/// node instance can not be an element so this method returns
/// false. Returning null tells the users of this node that any
/// attributes added to the node map will be permenantly lost.
/// </summary>
/// <returns>
/// this returns false as this is an attribute node
/// </returns>
public bool IsElement() {
return false;
}
/// <summary>
/// Because the <c>InputAttribute</c> object represents an
/// attribute this method will return null. If nodes are added
/// to the node map the values will not be available here.
/// </summary>
/// <returns>
/// this always returns null for a requested attribute
/// </returns>
public InputNode GetAttribute(String name) {
return null;
}
/// <summary>
/// Because the <c>InputAttribute</c> object represents an
/// attribute this method will return an empty map. If nodes are
/// added to the node map the values will not be maintained.
/// </summary>
/// <returns>
/// this always returns an empty node map of attributes
/// </returns>
public NodeMap<InputNode> Attributes {
get {
return new InputNodeMap(this);
}
}
//public NodeMap<InputNode> GetAttributes() {
// return new InputNodeMap(this);
//}
/// Because the <c>InputAttribute</c> object represents an
/// attribute this method will return null. An attribute is a
/// simple name value pair an so can not contain any child nodes.
/// </summary>
/// <returns>
/// this always returns null for a requested child node
/// </returns>
public InputNode Next {
get {
return null;
}
}
//public InputNode GetNext() {
// return null;
//}
/// Because the <c>InputAttribute</c> object represents an
/// attribute this method will return null. An attribute is a
/// simple name value pair an so can not contain any child nodes.
/// </summary>
/// <param name="name">
/// this is the name of the next expected element
/// </param>
/// <returns>
/// this always returns null for a requested child node
/// </returns>
public InputNode GetNext(String name) {
return null;
}
/// <summary>
/// This method is used to skip all child elements from this
/// element. This allows elements to be effectively skipped such
/// that when parsing a document if an element is not required
/// then that element can be completely removed from the XML.
/// </summary>
public void Skip() {
return;
}
/// <summary>
/// This is used to determine if this input node is empty. An
/// empty node is one with no attributes or children. This can
/// be used to determine if a given node represents an empty
/// entity, with which no extra data can be extracted.
/// </summary>
/// <returns>
/// this will always return false as it has a value
/// </returns>
public bool IsEmpty() {
return false;
}
/// <summary>
/// This is the string representation of the attribute. It is
/// used for debugging purposes. When evaluating the attribute
/// the to string can be used to print out the attribute name.
/// </summary>
/// <returns>
/// this returns a text description of the attribute
/// </returns>
public String ToString() {
return String.Format("attribute %s='%s'", name, value);
}
}
}
| |
//
// Reflect.cs: Creates Element classes from an instance
//
// Author:
// Miguel de Icaza (miguel@gnome.org)
//
// Copyright 2010, Novell, Inc.
//
// Code licensed under the MIT X11 license
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using UIKit;
using CoreGraphics;
using Foundation;
using MonoTouch.Dialog;
/*
Cloned from https://github.com/migueldeicaza/MonoTouch.Dialog/blob/master/MonoTouch.Dialog/Reflect.cs
to add localization ability. Unfortunately RootElement.group is marked 'internal' in MonoTouch.Dialog
so this implementation is missing RadioGroup functionality ~ scroll to the end of the file to see
the commented-out lines.
Patch to original file
https://github.com/conceptdev/MonoTouch.Dialog/commit/74a7898861d542b367af3b98b7d84079f08926f4
*/
namespace MonoTouch.Dialog
{
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class LocalizeAttribute : Attribute {}
public class LocalizableBindingContext : IDisposable {
public RootElement Root;
Dictionary<Element,MemberAndInstance> mappings;
class MemberAndInstance {
public MemberAndInstance (MemberInfo mi, object o)
{
Member = mi;
Obj = o;
}
public MemberInfo Member;
public object Obj;
}
static object GetValue (MemberInfo mi, object o)
{
var fi = mi as FieldInfo;
if (fi != null)
return fi.GetValue (o);
var pi = mi as PropertyInfo;
var getMethod = pi.GetGetMethod ();
return getMethod.Invoke (o, new object [0]);
}
static void SetValue (MemberInfo mi, object o, object val)
{
var fi = mi as FieldInfo;
if (fi != null){
fi.SetValue (o, val);
return;
}
var pi = mi as PropertyInfo;
var setMethod = pi.GetSetMethod ();
setMethod.Invoke (o, new object [] { val });
}
static string MakeCaption (string name)
{
var sb = new StringBuilder (name.Length);
bool nextUp = true;
foreach (char c in name){
if (nextUp){
sb.Append (Char.ToUpper (c));
nextUp = false;
} else {
if (c == '_'){
sb.Append (' ');
continue;
}
if (Char.IsUpper (c))
sb.Append (' ');
sb.Append (c);
}
}
return sb.ToString ();
}
// Returns the type for fields and properties and null for everything else
static Type GetTypeForMember (MemberInfo mi)
{
if (mi is FieldInfo)
return ((FieldInfo) mi).FieldType;
else if (mi is PropertyInfo)
return ((PropertyInfo) mi).PropertyType;
return null;
}
public LocalizableBindingContext (object callbacks, object o, string title)
{
if (o == null)
throw new ArgumentNullException ("o");
mappings = new Dictionary<Element,MemberAndInstance> ();
Root = new RootElement (title);
Populate (callbacks, o, Root);
}
void Populate (object callbacks, object o, RootElement root)
{
MemberInfo last_radio_index = null;
var members = o.GetType ().GetMembers (BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance
);
Section section = null;
foreach (var mi in members) {
Type mType = GetTypeForMember (mi);
if (mType == null)
continue;
string caption = null;
//string key = null; // l18n
object [] attrs = mi.GetCustomAttributes (false);
bool skip = false;
bool localize = false;
foreach (var attr in attrs) {
if (attr is LocalizeAttribute) {
localize = true;
break;
}
}
foreach (var attr in attrs) {
if (attr is SkipAttribute || attr is System.Runtime.CompilerServices.CompilerGeneratedAttribute)
skip = true;
else if (attr is CaptionAttribute) {
caption = ((CaptionAttribute)attr).Caption;
if (localize)
caption = NSBundle.MainBundle.GetLocalizedString (caption, caption);
} else if (attr is SectionAttribute) {
if (section != null)
root.Add (section);
var sa = attr as SectionAttribute;
var header = sa.Caption;
var footer = sa.Footer;
if (localize) {
header = NSBundle.MainBundle.GetLocalizedString (header, header);
footer = NSBundle.MainBundle.GetLocalizedString (footer, footer);
}
section = new Section (header, footer);
}
}
if (skip)
continue;
if (caption == null) {
caption = MakeCaption (mi.Name);
if (localize)
caption = NSBundle.MainBundle.GetLocalizedString (caption, caption);
}
if (section == null)
section = new Section ();
Element element = null;
if (mType == typeof(string)) {
PasswordAttribute pa = null;
AlignmentAttribute align = null;
EntryAttribute ea = null;
object html = null;
Action invoke = null;
bool multi = false;
foreach (object attr in attrs) {
if (attr is PasswordAttribute)
pa = attr as PasswordAttribute;
else if (attr is EntryAttribute)
ea = attr as EntryAttribute;
else if (attr is MultilineAttribute)
multi = true;
else if (attr is HtmlAttribute)
html = attr;
else if (attr is AlignmentAttribute)
align = attr as AlignmentAttribute;
if (attr is OnTapAttribute) {
string mname = ((OnTapAttribute)attr).Method;
if (callbacks == null) {
throw new Exception ("Your class contains [OnTap] attributes, but you passed a null object for `context' in the constructor");
}
var method = callbacks.GetType ().GetMethod (mname);
if (method == null)
throw new Exception ("Did not find method " + mname);
invoke = delegate {
method.Invoke (method.IsStatic ? null : callbacks, new object [0]);
};
}
}
string value = (string)GetValue (mi, o);
if (pa != null) {
var placeholder = pa.Placeholder;
if (localize)
placeholder = NSBundle.MainBundle.GetLocalizedString (placeholder, placeholder);
element = new EntryElement (caption, placeholder, value, true);
} else if (ea != null) {
var placeholder = ea.Placeholder;
if (localize)
placeholder = NSBundle.MainBundle.GetLocalizedString (placeholder, placeholder);
element = new EntryElement (caption, placeholder, value) { KeyboardType = ea.KeyboardType, AutocapitalizationType = ea.AutocapitalizationType, AutocorrectionType = ea.AutocorrectionType, ClearButtonMode = ea.ClearButtonMode };
} else if (multi)
element = new MultilineElement (caption, value);
else if (html != null)
element = new HtmlElement (caption, value);
else {
var selement = new StringElement (caption, value);
element = selement;
if (align != null)
selement.Alignment = align.Alignment;
}
if (invoke != null)
((StringElement)element).Tapped += invoke;
} else if (mType == typeof(float)) {
var floatElement = new FloatElement (null, null, (float)GetValue (mi, o));
floatElement.Caption = caption;
element = floatElement;
foreach (object attr in attrs) {
if (attr is RangeAttribute) {
var ra = attr as RangeAttribute;
floatElement.MinValue = ra.Low;
floatElement.MaxValue = ra.High;
floatElement.ShowCaption = ra.ShowCaption;
}
}
} else if (mType == typeof(bool)) {
bool checkbox = false;
foreach (object attr in attrs) {
if (attr is CheckboxAttribute)
checkbox = true;
}
if (checkbox)
element = new CheckboxElement (caption, (bool)GetValue (mi, o));
else
element = new BooleanElement (caption, (bool)GetValue (mi, o));
} else if (mType == typeof(DateTime)) {
var dateTime = (DateTime)GetValue (mi, o);
bool asDate = false, asTime = false;
foreach (object attr in attrs) {
if (attr is DateAttribute)
asDate = true;
else if (attr is TimeAttribute)
asTime = true;
}
if (asDate)
element = new DateElement (caption, dateTime);
else if (asTime)
element = new TimeElement (caption, dateTime);
else
element = new DateTimeElement (caption, dateTime);
} else if (mType.IsEnum) {
var csection = new Section ();
ulong evalue = Convert.ToUInt64 (GetValue (mi, o), null);
int idx = 0;
int selected = 0;
foreach (var fi in mType.GetFields (BindingFlags.Public | BindingFlags.Static)) {
ulong v = Convert.ToUInt64 (GetValue (fi, null));
if (v == evalue)
selected = idx;
CaptionAttribute ca = Attribute.GetCustomAttribute (fi, typeof(CaptionAttribute)) as CaptionAttribute;
var cap = ca != null ? ca.Caption : MakeCaption (fi.Name);
if (localize)
NSBundle.MainBundle.GetLocalizedString (cap, cap);
csection.Add (new RadioElement (cap));
idx++;
}
element = new RootElement (caption, new RadioGroup (null, selected)) { csection };
} else if (mType == typeof (UIImage)){
element = new ImageElement ((UIImage) GetValue (mi, o));
} else if (typeof (System.Collections.IEnumerable).IsAssignableFrom (mType)){
var csection = new Section ();
int count = 0;
if (last_radio_index == null)
throw new Exception ("IEnumerable found, but no previous int found");
foreach (var e in (IEnumerable) GetValue (mi, o)){
csection.Add (new RadioElement (e.ToString ()));
count++;
}
int selected = (int) GetValue (last_radio_index, o);
if (selected >= count || selected < 0)
selected = 0;
element = new RootElement (caption, new MemberRadioGroup (null, selected, last_radio_index)) { csection };
last_radio_index = null;
} else if (typeof (int) == mType){
foreach (object attr in attrs){
if (attr is RadioSelectionAttribute){
last_radio_index = mi;
break;
}
}
} else {
var nested = GetValue (mi, o);
if (nested != null){
var newRoot = new RootElement (caption);
Populate (callbacks, nested, newRoot);
element = newRoot;
}
}
if (element == null)
continue;
section.Add (element);
mappings [element] = new MemberAndInstance (mi, o);
}
root.Add (section);
}
class MemberRadioGroup : RadioGroup {
public MemberInfo mi;
public MemberRadioGroup (string key, int selected, MemberInfo mi) : base (key, selected)
{
this.mi = mi;
}
}
public void Dispose ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (disposing){
foreach (var element in mappings.Keys){
element.Dispose ();
}
mappings = null;
}
}
public void Fetch ()
{
foreach (var dk in mappings){
Element element = dk.Key;
MemberInfo mi = dk.Value.Member;
object obj = dk.Value.Obj;
if (element is DateTimeElement)
SetValue (mi, obj, ((DateTimeElement) element).DateValue);
else if (element is FloatElement)
SetValue (mi, obj, ((FloatElement) element).Value);
else if (element is BooleanElement)
SetValue (mi, obj, ((BooleanElement) element).Value);
else if (element is CheckboxElement)
SetValue (mi, obj, ((CheckboxElement) element).Value);
else if (element is EntryElement){
var entry = (EntryElement) element;
entry.FetchValue ();
SetValue (mi, obj, entry.Value);
} else if (element is ImageElement)
SetValue (mi, obj, ((ImageElement) element).Value);
else if (element is RootElement){
//HACK: RootElement.group is INTERNAL
// var re = element as RootElement;
// if (re.group as MemberRadioGroup != null){
// var group = re.group as MemberRadioGroup;
// SetValue (group.mi, obj, re.RadioSelected);
// } else if (re.group as RadioGroup != null){
// var mType = GetTypeForMember (mi);
// var fi = mType.GetFields (BindingFlags.Public | BindingFlags.Static) [re.RadioSelected];
//
// SetValue (mi, obj, fi.GetValue (null));
// }
}
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Microsoft.Win32;
using HtmlHelp;
using HtmlHelp.UIComponents;
using HtmlHelp.ChmDecoding;
using AxSHDocVw;
namespace HtmlHelpViewer
{
/// <summary>
/// This class implements the main form for the htmlhelp viewer
/// </summary>
public class Viewer : System.Windows.Forms.Form, IHelpViewer
{
private static Viewer _current = null;
private string LM_Key = @"Software\Klaus Weisser\HtmlHelpViewer\";
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.Panel panel3;
private AxSHDocVw.AxWebBrowser axWebBrowser1;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabContents;
private System.Windows.Forms.TabPage tabIndex;
private System.Windows.Forms.TabPage tabSearch;
private HtmlHelp.UIComponents.TocTree tocTree1;
private HtmlHelp.UIComponents.helpIndex helpIndex1;
private HtmlHelp.UIComponents.helpSearch helpSearch2;
private System.ComponentModel.IContainer components;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem miFile;
private System.Windows.Forms.MenuItem miOpen;
private System.Windows.Forms.MenuItem miMerge;
private System.Windows.Forms.MenuItem miSep1;
private System.Windows.Forms.MenuItem miPrint;
private System.Windows.Forms.MenuItem miSep2;
private System.Windows.Forms.MenuItem miExit;
private System.Windows.Forms.ToolBar toolBar1;
private System.Windows.Forms.ImageList imgToolBar;
private System.Windows.Forms.ToolBarButton btnBack;
private System.Windows.Forms.ToolBarButton btnNext;
private System.Windows.Forms.ToolBarButton btnStop;
private System.Windows.Forms.ToolBarButton btnRefresh;
private System.Windows.Forms.ToolBarButton btnHome;
private System.Windows.Forms.ToolBarButton btnSep1;
private System.Windows.Forms.ToolBarButton btnContents;
private System.Windows.Forms.ToolBarButton btnIndex;
private System.Windows.Forms.ToolBarButton btnSearch;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.MenuItem miPageSetup;
private System.Windows.Forms.MenuItem miPrintPreview;
private System.Windows.Forms.MenuItem miView;
private System.Windows.Forms.MenuItem miBrowser;
private System.Windows.Forms.MenuItem miBack;
private System.Windows.Forms.MenuItem miForward;
private System.Windows.Forms.MenuItem miSep4;
private System.Windows.Forms.MenuItem miHome;
private System.Windows.Forms.MenuItem miNav;
private System.Windows.Forms.MenuItem miContents;
private System.Windows.Forms.MenuItem miIndex;
private System.Windows.Forms.MenuItem miSearch;
private System.Windows.Forms.MenuItem miHelp;
private System.Windows.Forms.MenuItem miContents1;
private System.Windows.Forms.MenuItem miIndex1;
private System.Windows.Forms.MenuItem miSearch1;
private System.Windows.Forms.MenuItem miSep5;
private System.Windows.Forms.MenuItem miAbout;
private System.Windows.Forms.MenuItem miTools;
private System.Windows.Forms.MenuItem miDmpConfig;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem miPreferences;
private System.Windows.Forms.MenuItem miCloseFile;
private System.Windows.Forms.MenuItem miCustomize;
private System.Windows.Forms.ToolBarButton btnSynch;
HtmlHelpSystem _reader = null;
DumpingInfo _dmpInfo=null;
InfoTypeCategoryFilter _filter = new InfoTypeCategoryFilter();
string _prefDumpOutput="";
DumpCompression _prefDumpCompression = DumpCompression.Medium;
DumpingFlags _prefDumpFlags = DumpingFlags.DumpBinaryTOC | DumpingFlags.DumpTextTOC |
DumpingFlags.DumpTextIndex | DumpingFlags.DumpBinaryIndex |
DumpingFlags.DumpUrlStr | DumpingFlags.DumpStrings;
string _prefURLPrefix = "mk:@MSITStore:";
bool _prefUseHH2TreePics = false;
/// <summary>
/// Gets the current viewer window
/// </summary>
public static Viewer Current
{
get { return _current; }
}
/// <summary>
/// Constructor of the class
/// </summary>
public Viewer()
{
Viewer._current = this;
// create a new instance of the classlibrary's main class
_reader = new HtmlHelpSystem();
HtmlHelpSystem.UrlPrefix = "mk:@MSITStore:";
// use temporary folder for data dumping
string sTemp = System.Environment.GetEnvironmentVariable("TEMP");
if(sTemp.Length <= 0)
sTemp = System.Environment.GetEnvironmentVariable("TMP");
_prefDumpOutput = sTemp;
// create a dump info instance used for dumping data
_dmpInfo =
new DumpingInfo(DumpingFlags.DumpBinaryTOC | DumpingFlags.DumpTextTOC |
DumpingFlags.DumpTextIndex | DumpingFlags.DumpBinaryIndex |
DumpingFlags.DumpUrlStr | DumpingFlags.DumpStrings,
sTemp, DumpCompression.Medium);
LoadRegistryPreferences();
HtmlHelpSystem.UrlPrefix = _prefURLPrefix;
HtmlHelpSystem.UseHH2TreePics = _prefUseHH2TreePics;
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Viewer));
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.panel1 = new System.Windows.Forms.Panel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.panel2 = new System.Windows.Forms.Panel();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabContents = new System.Windows.Forms.TabPage();
this.tocTree1 = new HtmlHelp.UIComponents.TocTree();
this.tabIndex = new System.Windows.Forms.TabPage();
this.helpIndex1 = new HtmlHelp.UIComponents.helpIndex();
this.tabSearch = new System.Windows.Forms.TabPage();
this.helpSearch2 = new HtmlHelp.UIComponents.helpSearch();
this.splitter1 = new System.Windows.Forms.Splitter();
this.panel3 = new System.Windows.Forms.Panel();
this.axWebBrowser1 = new AxSHDocVw.AxWebBrowser();
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.miFile = new System.Windows.Forms.MenuItem();
this.miOpen = new System.Windows.Forms.MenuItem();
this.miMerge = new System.Windows.Forms.MenuItem();
this.miCloseFile = new System.Windows.Forms.MenuItem();
this.miSep1 = new System.Windows.Forms.MenuItem();
this.miPageSetup = new System.Windows.Forms.MenuItem();
this.miPrintPreview = new System.Windows.Forms.MenuItem();
this.miPrint = new System.Windows.Forms.MenuItem();
this.miSep2 = new System.Windows.Forms.MenuItem();
this.miExit = new System.Windows.Forms.MenuItem();
this.miView = new System.Windows.Forms.MenuItem();
this.miBrowser = new System.Windows.Forms.MenuItem();
this.miBack = new System.Windows.Forms.MenuItem();
this.miForward = new System.Windows.Forms.MenuItem();
this.miSep4 = new System.Windows.Forms.MenuItem();
this.miHome = new System.Windows.Forms.MenuItem();
this.miNav = new System.Windows.Forms.MenuItem();
this.miContents = new System.Windows.Forms.MenuItem();
this.miIndex = new System.Windows.Forms.MenuItem();
this.miSearch = new System.Windows.Forms.MenuItem();
this.miTools = new System.Windows.Forms.MenuItem();
this.miDmpConfig = new System.Windows.Forms.MenuItem();
this.miCustomize = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.miPreferences = new System.Windows.Forms.MenuItem();
this.miHelp = new System.Windows.Forms.MenuItem();
this.miContents1 = new System.Windows.Forms.MenuItem();
this.miIndex1 = new System.Windows.Forms.MenuItem();
this.miSearch1 = new System.Windows.Forms.MenuItem();
this.miSep5 = new System.Windows.Forms.MenuItem();
this.miAbout = new System.Windows.Forms.MenuItem();
this.toolBar1 = new System.Windows.Forms.ToolBar();
this.btnBack = new System.Windows.Forms.ToolBarButton();
this.btnNext = new System.Windows.Forms.ToolBarButton();
this.btnStop = new System.Windows.Forms.ToolBarButton();
this.btnRefresh = new System.Windows.Forms.ToolBarButton();
this.btnHome = new System.Windows.Forms.ToolBarButton();
this.btnSynch = new System.Windows.Forms.ToolBarButton();
this.btnSep1 = new System.Windows.Forms.ToolBarButton();
this.btnContents = new System.Windows.Forms.ToolBarButton();
this.btnIndex = new System.Windows.Forms.ToolBarButton();
this.btnSearch = new System.Windows.Forms.ToolBarButton();
this.imgToolBar = new System.Windows.Forms.ImageList(this.components);
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.tabControl1.SuspendLayout();
this.tabContents.SuspendLayout();
this.tabIndex.SuspendLayout();
this.tabSearch.SuspendLayout();
this.panel3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).BeginInit();
this.SuspendLayout();
//
// openFileDialog1
//
this.openFileDialog1.DefaultExt = "chm";
this.openFileDialog1.Filter = "Compiled HTML-Help files (*.chm)|*.chm|All files|*.*";
this.openFileDialog1.Title = "Open HTML-Help files";
//
// panel1
//
this.panel1.Controls.Add(this.pictureBox1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 28);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(754, 4);
this.panel1.TabIndex = 5;
//
// pictureBox1
//
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Top;
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(754, 2);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// panel2
//
this.panel2.Controls.Add(this.tabControl1);
this.panel2.Dock = System.Windows.Forms.DockStyle.Left;
this.panel2.Location = new System.Drawing.Point(0, 32);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(300, 510);
this.panel2.TabIndex = 7;
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabContents);
this.tabControl1.Controls.Add(this.tabIndex);
this.tabControl1.Controls.Add(this.tabSearch);
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl1.Location = new System.Drawing.Point(0, 0);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(300, 510);
this.tabControl1.TabIndex = 8;
//
// tabContents
//
this.tabContents.Controls.Add(this.tocTree1);
this.tabContents.Location = new System.Drawing.Point(4, 22);
this.tabContents.Name = "tabContents";
this.tabContents.Size = new System.Drawing.Size(292, 484);
this.tabContents.TabIndex = 0;
this.tabContents.Text = "Contents";
//
// tocTree1
//
this.tocTree1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tocTree1.DockPadding.All = 2;
this.tocTree1.Location = new System.Drawing.Point(0, 0);
this.tocTree1.Name = "tocTree1";
this.tocTree1.Size = new System.Drawing.Size(292, 484);
this.tocTree1.TabIndex = 0;
this.tocTree1.TocSelected += new HtmlHelp.UIComponents.TocSelectedEventHandler(this.tocTree1_TocSelected);
//
// tabIndex
//
this.tabIndex.Controls.Add(this.helpIndex1);
this.tabIndex.Location = new System.Drawing.Point(4, 22);
this.tabIndex.Name = "tabIndex";
this.tabIndex.Size = new System.Drawing.Size(292, 470);
this.tabIndex.TabIndex = 1;
this.tabIndex.Text = "Index";
//
// helpIndex1
//
this.helpIndex1.Dock = System.Windows.Forms.DockStyle.Fill;
this.helpIndex1.Location = new System.Drawing.Point(0, 0);
this.helpIndex1.Name = "helpIndex1";
this.helpIndex1.Size = new System.Drawing.Size(292, 470);
this.helpIndex1.TabIndex = 0;
this.helpIndex1.IndexSelected += new HtmlHelp.UIComponents.IndexSelectedEventHandler(this.helpIndex1_IndexSelected);
//
// tabSearch
//
this.tabSearch.Controls.Add(this.helpSearch2);
this.tabSearch.Location = new System.Drawing.Point(4, 22);
this.tabSearch.Name = "tabSearch";
this.tabSearch.Size = new System.Drawing.Size(292, 470);
this.tabSearch.TabIndex = 2;
this.tabSearch.Text = "Search";
//
// helpSearch2
//
this.helpSearch2.Dock = System.Windows.Forms.DockStyle.Fill;
this.helpSearch2.Location = new System.Drawing.Point(0, 0);
this.helpSearch2.Name = "helpSearch2";
this.helpSearch2.Size = new System.Drawing.Size(292, 470);
this.helpSearch2.TabIndex = 0;
this.helpSearch2.HitSelected += new HtmlHelp.UIComponents.HitSelectedEventHandler(this.helpSearch2_HitSelected);
this.helpSearch2.FTSearch += new HtmlHelp.UIComponents.FTSearchEventHandler(this.helpSearch2_FTSearch);
//
// splitter1
//
this.splitter1.Location = new System.Drawing.Point(300, 32);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(3, 510);
this.splitter1.TabIndex = 9;
this.splitter1.TabStop = false;
//
// panel3
//
this.panel3.BackColor = System.Drawing.SystemColors.Control;
this.panel3.Controls.Add(this.axWebBrowser1);
this.panel3.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel3.Location = new System.Drawing.Point(303, 32);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(451, 510);
this.panel3.TabIndex = 10;
//
// axWebBrowser1
//
this.axWebBrowser1.ContainingControl = this;
this.axWebBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
this.axWebBrowser1.Enabled = true;
this.axWebBrowser1.Location = new System.Drawing.Point(0, 0);
this.axWebBrowser1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axWebBrowser1.OcxState")));
this.axWebBrowser1.Size = new System.Drawing.Size(451, 510);
this.axWebBrowser1.TabIndex = 0;
this.axWebBrowser1.DownloadBegin += new System.EventHandler(this.axWebBrowser1_DownloadBegin);
this.axWebBrowser1.CommandStateChange += new AxSHDocVw.DWebBrowserEvents2_CommandStateChangeEventHandler(this.axWebBrowser1_CommandStateChanged);
this.axWebBrowser1.DownloadComplete += new System.EventHandler(this.axWebBrowser1_DownloadComplete);
this.axWebBrowser1.ProgressChange += new AxSHDocVw.DWebBrowserEvents2_ProgressChangeEventHandler(this.axWebBrowser1_ProgressChanged);
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miFile,
this.miView,
this.miTools,
this.miHelp});
//
// miFile
//
this.miFile.Index = 0;
this.miFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miOpen,
this.miMerge,
this.miCloseFile,
this.miSep1,
this.miPageSetup,
this.miPrintPreview,
this.miPrint,
this.miSep2,
this.miExit});
this.miFile.Text = "&File";
//
// miOpen
//
this.miOpen.Index = 0;
this.miOpen.Text = "&Open ...";
this.miOpen.Click += new System.EventHandler(this.miOpen_Click);
//
// miMerge
//
this.miMerge.Index = 1;
this.miMerge.Text = "&Merge ...";
this.miMerge.Click += new System.EventHandler(this.miMerge_Click);
//
// miCloseFile
//
this.miCloseFile.Index = 2;
this.miCloseFile.Text = "&Close file(s)";
this.miCloseFile.Click += new System.EventHandler(this.miCloseFile_Click);
//
// miSep1
//
this.miSep1.Index = 3;
this.miSep1.Text = "-";
//
// miPageSetup
//
this.miPageSetup.Index = 4;
this.miPageSetup.Text = "Page &setup ...";
this.miPageSetup.Click += new System.EventHandler(this.miPageSetup_Click);
//
// miPrintPreview
//
this.miPrintPreview.Index = 5;
this.miPrintPreview.Text = "Print p&review ...";
this.miPrintPreview.Click += new System.EventHandler(this.miPrintPreview_Click);
//
// miPrint
//
this.miPrint.Index = 6;
this.miPrint.Text = "&Print ...";
this.miPrint.Click += new System.EventHandler(this.miPrint_Click);
//
// miSep2
//
this.miSep2.Index = 7;
this.miSep2.Text = "-";
//
// miExit
//
this.miExit.Index = 8;
this.miExit.Text = "&Exit";
this.miExit.Click += new System.EventHandler(this.miExit_Click);
//
// miView
//
this.miView.Index = 1;
this.miView.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miBrowser,
this.miNav});
this.miView.Text = "&View";
//
// miBrowser
//
this.miBrowser.Index = 0;
this.miBrowser.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miBack,
this.miForward,
this.miSep4,
this.miHome});
this.miBrowser.Text = "Web brow&ser";
//
// miBack
//
this.miBack.Index = 0;
this.miBack.Text = "&Back";
this.miBack.Click += new System.EventHandler(this.miBack_Click);
//
// miForward
//
this.miForward.Index = 1;
this.miForward.Text = "&Forward";
this.miForward.Click += new System.EventHandler(this.miForward_Click);
//
// miSep4
//
this.miSep4.Index = 2;
this.miSep4.Text = "-";
//
// miHome
//
this.miHome.Index = 3;
this.miHome.Text = "&Home";
this.miHome.Click += new System.EventHandler(this.miHome_Click);
//
// miNav
//
this.miNav.Index = 1;
this.miNav.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miContents,
this.miIndex,
this.miSearch});
this.miNav.Text = "&Navigation";
//
// miContents
//
this.miContents.Index = 0;
this.miContents.Text = "&Contents";
this.miContents.Click += new System.EventHandler(this.miContents_Click);
//
// miIndex
//
this.miIndex.Index = 1;
this.miIndex.Text = "&Index";
this.miIndex.Click += new System.EventHandler(this.miIndex_Click);
//
// miSearch
//
this.miSearch.Index = 2;
this.miSearch.Text = "&Search";
this.miSearch.Click += new System.EventHandler(this.miSearch_Click);
//
// miTools
//
this.miTools.Index = 2;
this.miTools.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miDmpConfig,
this.miCustomize,
this.menuItem1,
this.miPreferences});
this.miTools.Text = "&Tools";
//
// miDmpConfig
//
this.miDmpConfig.Index = 0;
this.miDmpConfig.Text = "&Configure data dumping ...";
this.miDmpConfig.Click += new System.EventHandler(this.miDmpConfig_Click);
//
// miCustomize
//
this.miCustomize.Index = 1;
this.miCustomize.Text = "Customize &help contents ...";
this.miCustomize.Click += new System.EventHandler(this.miCustomize_Click);
//
// menuItem1
//
this.menuItem1.Index = 2;
this.menuItem1.Text = "-";
//
// miPreferences
//
this.miPreferences.Index = 3;
this.miPreferences.Text = "&Preferences ...";
this.miPreferences.Click += new System.EventHandler(this.miPreferences_Click);
//
// miHelp
//
this.miHelp.Index = 3;
this.miHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miContents1,
this.miIndex1,
this.miSearch1,
this.miSep5,
this.miAbout});
this.miHelp.Text = "&Help";
//
// miContents1
//
this.miContents1.Index = 0;
this.miContents1.Text = "&Contents";
this.miContents1.Click += new System.EventHandler(this.miContents1_Click);
//
// miIndex1
//
this.miIndex1.Index = 1;
this.miIndex1.Text = "&Index";
this.miIndex1.Click += new System.EventHandler(this.miIndex1_Click);
//
// miSearch1
//
this.miSearch1.Index = 2;
this.miSearch1.Text = "&Search";
this.miSearch1.Click += new System.EventHandler(this.miSearch1_Click);
//
// miSep5
//
this.miSep5.Index = 3;
this.miSep5.Text = "-";
//
// miAbout
//
this.miAbout.Index = 4;
this.miAbout.Text = "&About ...";
this.miAbout.Click += new System.EventHandler(this.miAbout_Click);
//
// toolBar1
//
this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.btnBack,
this.btnNext,
this.btnStop,
this.btnRefresh,
this.btnHome,
this.btnSynch,
this.btnSep1,
this.btnContents,
this.btnIndex,
this.btnSearch});
this.toolBar1.DropDownArrows = true;
this.toolBar1.ImageList = this.imgToolBar;
this.toolBar1.Location = new System.Drawing.Point(0, 0);
this.toolBar1.Name = "toolBar1";
this.toolBar1.ShowToolTips = true;
this.toolBar1.Size = new System.Drawing.Size(754, 28);
this.toolBar1.TabIndex = 0;
this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
//
// btnBack
//
this.btnBack.ImageIndex = 0;
this.btnBack.ToolTipText = "Back";
//
// btnNext
//
this.btnNext.ImageIndex = 1;
this.btnNext.ToolTipText = "Forward";
//
// btnStop
//
this.btnStop.ImageIndex = 2;
this.btnStop.ToolTipText = "Stop";
//
// btnRefresh
//
this.btnRefresh.ImageIndex = 3;
this.btnRefresh.ToolTipText = "Refresh";
//
// btnHome
//
this.btnHome.ImageIndex = 4;
this.btnHome.ToolTipText = "Default topic";
//
// btnSynch
//
this.btnSynch.ImageIndex = 8;
this.btnSynch.ToolTipText = "Snychronize contents";
//
// btnSep1
//
this.btnSep1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// btnContents
//
this.btnContents.ImageIndex = 5;
this.btnContents.ToolTipText = "Show help contents";
//
// btnIndex
//
this.btnIndex.ImageIndex = 6;
this.btnIndex.ToolTipText = "Show help index";
//
// btnSearch
//
this.btnSearch.ImageIndex = 7;
this.btnSearch.ToolTipText = "Fulltext search";
//
// imgToolBar
//
this.imgToolBar.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit;
this.imgToolBar.ImageSize = new System.Drawing.Size(16, 16);
this.imgToolBar.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgToolBar.ImageStream")));
this.imgToolBar.TransparentColor = System.Drawing.Color.FromArgb(((System.Byte)(214)), ((System.Byte)(211)), ((System.Byte)(206)));
//
// Viewer
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(754, 542);
this.Controls.Add(this.panel3);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Controls.Add(this.toolBar1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu1;
this.Name = "Viewer";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "HtmlHelp - Viewer";
this.Closing += new System.ComponentModel.CancelEventHandler(this.Viewer_Closing);
this.Load += new System.EventHandler(this.Form1_Load);
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.tabControl1.ResumeLayout(false);
this.tabContents.ResumeLayout(false);
this.tabIndex.ResumeLayout(false);
this.tabSearch.ResumeLayout(false);
this.panel3.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Viewer());
}
/// <summary>
/// Navigates the embedded browser to the specified url
/// </summary>
/// <param name="url">url to navigate</param>
private void NavigateBrowser(string url)
{
object flags = 0;
object targetFrame = String.Empty;
object postData = String.Empty;
object headers = String.Empty;
object oUrl = url;
//axWebBrowser1.Navigate(url, ref flags, ref targetFrame, ref postData, ref headers);
axWebBrowser1.Navigate2(ref oUrl, ref flags, ref targetFrame, ref postData, ref headers);
}
#region Registry preferences
/// <summary>
/// Loads viewer preferences from registry
/// </summary>
private void LoadRegistryPreferences()
{
RegistryKey regKey = Registry.LocalMachine.CreateSubKey(LM_Key);
bool bEnable = bool.Parse(regKey.GetValue("EnableDumping", true).ToString());
_prefDumpOutput = (string) regKey.GetValue("DumpOutputDir", _prefDumpOutput);
_prefDumpCompression = (DumpCompression) ((int)regKey.GetValue("CompressionLevel", _prefDumpCompression));
_prefDumpFlags = (DumpingFlags) ((int)regKey.GetValue("DumpingFlags", _prefDumpFlags));
if(bEnable)
_dmpInfo = new DumpingInfo(_prefDumpFlags, _prefDumpOutput, _prefDumpCompression);
else
_dmpInfo = null;
_prefURLPrefix = (string) regKey.GetValue("ITSUrlPrefix", _prefURLPrefix);
_prefUseHH2TreePics = bool.Parse(regKey.GetValue("UseHH2TreePics", _prefUseHH2TreePics).ToString());
}
/// <summary>
/// Saves viewer preferences to registry
/// </summary>
private void SaveRegistryPreferences()
{
RegistryKey regKey = Registry.LocalMachine.CreateSubKey(LM_Key);
regKey.SetValue("EnableDumping", (_dmpInfo!=null));
regKey.SetValue("DumpOutputDir", _prefDumpOutput);
regKey.SetValue("CompressionLevel", (int)_prefDumpCompression);
regKey.SetValue("DumpingFlags", (int)_prefDumpFlags);
regKey.SetValue("ITSUrlPrefix", _prefURLPrefix);
regKey.SetValue("UseHH2TreePics", _prefUseHH2TreePics);
}
#endregion
#region Eventhandlers for library usercontrols
/// <summary>
/// Called if the user hits the "Search" button on the full-text search pane
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameters</param>
private void helpSearch2_FTSearch(object sender, SearchEventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
DataTable dtResults = _reader.PerformSearch( e.Words, 500, e.PartialWords, e.TitlesOnly);
helpSearch2.SetResults(dtResults);
}
finally
{
this.Cursor = Cursors.Arrow;
}
}
/// <summary>
/// Called if the user selects an entry from the search results.
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameters</param>
private void helpSearch2_HitSelected(object sender, HitEventArgs e)
{
if( e.URL.Length > 0)
{
NavigateBrowser(e.URL);
}
}
/// <summary>
/// Called if the user selects a new table of contents item
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameters</param>
private void tocTree1_TocSelected(object sender, TocEventArgs e)
{
if( e.Item.Local.Length > 0)
{
NavigateBrowser(e.Item.Url);
}
}
/// <summary>
/// Called if the user selects an index topic
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameters</param>
private void helpIndex1_IndexSelected(object sender, IndexEventArgs e)
{
if(e.URL.Length > 0)
NavigateBrowser(e.URL);
}
#endregion
#region IHelpViewer interface implementation
/// <summary>
/// Navigates the helpviewer to a specific help url
/// </summary>
/// <param name="url">url</param>
void IHelpViewer.NavigateTo(string url)
{
NavigateBrowser(url);
}
/// <summary>
/// Shows help for a specific url
/// </summary>
/// <param name="namespaceFilter">namespace filter (used for merged files)</param>
/// <param name="hlpNavigator">navigator value</param>
/// <param name="keyword">keyword</param>
void IHelpViewer.ShowHelp(string namespaceFilter, HelpNavigator hlpNavigator, string keyword)
{
((IHelpViewer)this).ShowHelp(namespaceFilter, hlpNavigator, keyword, "");
}
/// <summary>
/// Shows help for a specific keyword
/// </summary>
/// <param name="namespaceFilter">namespace filter (used for merged files)</param>
/// <param name="hlpNavigator">navigator value</param>
/// <param name="keyword">keyword</param>
/// <param name="url">url</param>
void IHelpViewer.ShowHelp(string namespaceFilter, HelpNavigator hlpNavigator, string keyword, string url)
{
switch(hlpNavigator)
{
case HelpNavigator.AssociateIndex:
{
IndexItem foundIdx = _reader.Index.SearchIndex(keyword, IndexType.AssiciativeLinks);
if(foundIdx != null)
{
if(foundIdx.Topics.Count > 0)
{
IndexTopic topic = foundIdx.Topics[0] as IndexTopic;
if(topic.Local.Length>0)
NavigateBrowser(topic.URL);
}
}
};break;
case HelpNavigator.Find:
{
this.Cursor = Cursors.WaitCursor;
this.helpSearch2.SetSearchText(keyword);
DataTable dtResults = _reader.PerformSearch(keyword, 500, true, false);
this.helpSearch2.SetResults(dtResults);
this.Cursor = Cursors.Arrow;
this.helpSearch2.Focus();
};break;
case HelpNavigator.Index:
{
((IHelpViewer)this).ShowHelpIndex(url);
};break;
case HelpNavigator.KeywordIndex:
{
IndexItem foundIdx = _reader.Index.SearchIndex(keyword, IndexType.KeywordLinks);
if(foundIdx != null)
{
if(foundIdx.Topics.Count == 1)
{
IndexTopic topic = foundIdx.Topics[0] as IndexTopic;
if(topic.Local.Length>0)
NavigateBrowser(topic.URL);
}
else if(foundIdx.Topics.Count>1)
{
this.helpIndex1.SelectText(foundIdx.IndentKeyWord);
}
}
this.helpIndex1.Focus();
};break;
case HelpNavigator.TableOfContents:
{
TOCItem foundTOC = _reader.TableOfContents.SearchTopic(keyword);
if(foundTOC != null)
{
if(foundTOC.Local.Length>0)
NavigateBrowser(foundTOC.Url);
}
this.tocTree1.Focus();
};break;
case HelpNavigator.Topic:
{
TOCItem foundTOC = _reader.TableOfContents.SearchTopic(keyword);
if(foundTOC != null)
{
if(foundTOC.Local.Length>0)
NavigateBrowser(foundTOC.Url);
}
};break;
}
}
/// <summary>
/// Shows the help index
/// </summary>
/// <param name="url">url</param>
void IHelpViewer.ShowHelpIndex(string url)
{
if( url.Length == 0)
url = HtmlHelpSystem.Current.DefaultTopic;
NavigateBrowser(url);
}
/// <summary>
/// Shows a help popup window
/// </summary>
/// <param name="parent">the parent control for the popup window</param>
/// <param name="text">help text</param>
/// <param name="location">display location</param>
void IHelpViewer.ShowPopup(Control parent, string text, Point location)
{
// Display a native toolwindow and display the help string
HelpToolTipWindow hlpTTip = new HelpToolTipWindow();
hlpTTip.Location = location;
hlpTTip.Text = text;
hlpTTip.ShowShadow = true;
hlpTTip.MaximumDuration = 300; // duration before hiding (after focus lost)
hlpTTip.Show();
}
#endregion
/// <summary>
/// Called if the form loads
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void Form1_Load(object sender, System.EventArgs e)
{
tocTree1.Enabled = false;
helpIndex1.Enabled = false;
helpSearch2.Enabled = false;
btnContents.Enabled = false;
btnIndex.Enabled = false;
btnSearch.Enabled = false;
miContents.Enabled = false;
miContents1.Enabled = false;
miIndex.Enabled = false;
miIndex1.Enabled = false;
miSearch.Enabled = false;
miSearch1.Enabled = false;
btnBack.Enabled = false;
miBack.Enabled = false;
btnNext.Enabled = false;
miForward.Enabled = false;
btnStop.Enabled = false;
btnRefresh.Enabled = false;
btnHome.Enabled = false;
miHome.Enabled = false;
btnSynch.Enabled = false;
miMerge.Enabled = false;
miCloseFile.Enabled = false;
miCustomize.Enabled = false;
miPageSetup.Enabled = false;
miPrint.Enabled = false;
miPrintPreview.Enabled = false;
}
/// <summary>
/// Called if the viewer is closing
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void Viewer_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
SaveRegistryPreferences();
}
/// <summary>
/// Called if the browser changes its command state (forward/back button)
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void axWebBrowser1_CommandStateChanged(object sender, AxSHDocVw.DWebBrowserEvents2_CommandStateChangeEvent e)
{
switch(e.command)
{
case 1: // forward command update
{
btnNext.Enabled = e.enable;
miForward.Enabled = e.enable;
};break;
case 2:
case 3: // back command update
{
btnBack.Enabled = e.enable;
miBack.Enabled = e.enable;
};break;
}
}
/// <summary>
/// Called wenn the download progress of the browser changes
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void axWebBrowser1_ProgressChanged(object sender, AxSHDocVw.DWebBrowserEvents2_ProgressChangeEvent e)
{
double dPercent = ((double)e.progress * 100.0)/(double)e.progressMax;
dPercent = Math.Round(dPercent);
//((IStatusBar)base.ServiceProvider.GetService(typeof(IStatusBar))).SetProgress((int)dPercent);
}
/// <summary>
/// Called if the browser begins to download content
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void axWebBrowser1_DownloadBegin(object sender, System.EventArgs e)
{
btnStop.Enabled = true;
btnHome.Enabled = false;
miHome.Enabled = false;
btnBack.Enabled = false;
miBack.Enabled = false;
btnNext.Enabled = false;
miForward.Enabled = false;
}
/// <summary>
/// Called if the browser has finished downloading content
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void axWebBrowser1_DownloadComplete(object sender, System.EventArgs e)
{
btnStop.Enabled = false;
btnHome.Enabled = true;
miHome.Enabled = true;
miPageSetup.Enabled = true;
miPrint.Enabled = true;
miPrintPreview.Enabled = true;
}
/// <summary>
/// Called if the user clicks the File-Exit menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
/// <summary>
/// Called if the user clicks the File-Open menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miOpen_Click(object sender, System.EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK )
{
this.Cursor = Cursors.WaitCursor;
try
{
// clear current items
tocTree1.ClearContents();
helpIndex1.ClearContents();
helpSearch2.ClearContents();
// open the chm-file selected in the OpenFileDialog
_reader.OpenFile( openFileDialog1.FileName, _dmpInfo );
// Enable the toc-tree pane if the opened file has a table of contents
tocTree1.Enabled = _reader.HasTableOfContents;
// Enable the index pane if the opened file has an index
helpIndex1.Enabled = _reader.HasIndex;
// Enable the full-text search pane if the opened file supports full-text searching
helpSearch2.Enabled = _reader.FullTextSearch;
btnContents.Enabled = _reader.HasTableOfContents;
btnIndex.Enabled = _reader.HasIndex;
btnSearch.Enabled = _reader.FullTextSearch;
miContents.Enabled = _reader.HasTableOfContents;
miContents1.Enabled = _reader.HasTableOfContents;
miIndex.Enabled = _reader.HasIndex;
miIndex1.Enabled = _reader.HasIndex;
miSearch.Enabled = _reader.FullTextSearch;
miSearch1.Enabled = _reader.FullTextSearch;
btnSynch.Enabled = _reader.HasTableOfContents;
tabControl1.SelectedIndex = 0;
btnRefresh.Enabled = true;
if( _reader.DefaultTopic.Length > 0)
{
btnHome.Enabled = true;
miHome.Enabled = true;
}
// Build the table of contents tree view in the classlibrary control
tocTree1.BuildTOC( _reader.TableOfContents, _filter );
// Build the index entries in the classlibrary control
if( _reader.HasKLinks )
helpIndex1.BuildIndex( _reader.Index, IndexType.KeywordLinks, _filter );
else if( _reader.HasALinks )
helpIndex1.BuildIndex( _reader.Index, IndexType.AssiciativeLinks, _filter );
// Navigate the embedded browser to the default help topic
NavigateBrowser( _reader.DefaultTopic );
miMerge.Enabled = true;
miCloseFile.Enabled = true;
this.Text = _reader.FileList[0].FileInfo.HelpWindowTitle + " - HtmlHelp - Viewer";
miCustomize.Enabled = ( _reader.HasInformationTypes || _reader.HasCategories);
// Force garbage collection to free memory
GC.Collect();
}
finally
{
this.Cursor = Cursors.Arrow;
}
this.Cursor = Cursors.Arrow;
}
}
/// <summary>
/// Called if the user clicks the File-Merge menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miMerge_Click(object sender, System.EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK )
{
this.Cursor = Cursors.WaitCursor;
try
{
// clear current items
tocTree1.ClearContents();
helpIndex1.ClearContents();
helpSearch2.ClearContents();
// merge the chm file selected in the OpenFileDialog to the existing one
// in the HtmlHelpSystem class
_reader.MergeFile( openFileDialog1.FileName, _dmpInfo );
// Enable the toc-tree pane if the opened file has a table of contents
tocTree1.Enabled = _reader.HasTableOfContents;
// Enable the index pane if the opened file has an index
helpIndex1.Enabled = _reader.HasIndex;
// Enable the full-text search pane if the opened file supports full-text searching
helpSearch2.Enabled = _reader.FullTextSearch;
btnContents.Enabled = _reader.HasTableOfContents;
btnIndex.Enabled = _reader.HasIndex;
btnSearch.Enabled = _reader.FullTextSearch;
miContents.Enabled = _reader.HasTableOfContents;
miContents1.Enabled = _reader.HasTableOfContents;
miIndex.Enabled = _reader.HasIndex;
miIndex1.Enabled = _reader.HasIndex;
miSearch.Enabled = _reader.FullTextSearch;
miSearch1.Enabled = _reader.FullTextSearch;
btnSynch.Enabled = _reader.HasTableOfContents;
tabControl1.SelectedIndex = 0;
btnRefresh.Enabled = true;
if( _reader.DefaultTopic.Length > 0)
{
btnHome.Enabled = true;
miHome.Enabled = true;
}
// Rebuild the table of contents tree view in the classlibrary control
// using the new merged table of contents
tocTree1.BuildTOC( _reader.TableOfContents, _filter );
// Rebuild the index entries in the classlibrary control
// using the new merged index
if( _reader.HasKLinks )
helpIndex1.BuildIndex( _reader.Index, IndexType.KeywordLinks, _filter );
else if( _reader.HasALinks )
helpIndex1.BuildIndex( _reader.Index, IndexType.AssiciativeLinks, _filter );
// Navigate the embedded browser to the default help topic
NavigateBrowser( _reader.DefaultTopic );
miCustomize.Enabled = ( _reader.HasInformationTypes || _reader.HasCategories);
// Force garbage collection to free memory
GC.Collect();
}
catch(Exception ex)
{
this.Cursor = Cursors.Arrow;
throw ex;
}
this.Cursor = Cursors.Arrow;
}
}
/// <summary>
/// Called if the user clicks the File-close file(s) menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>>
private void miCloseFile_Click(object sender, System.EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
// clear current items
tocTree1.ClearContents();
helpIndex1.ClearContents();
helpSearch2.ClearContents();
_reader.CloseAllFiles();
// Navigate the embedded browser to the default help topic
NavigateBrowser( "about:blank" );
// Force garbage collection to free memory
GC.Collect();
this.Cursor = Cursors.Arrow;
}
/// <summary>
/// Called if the user clicks the File-Page setup menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miPageSetup_Click(object sender, System.EventArgs e)
{
object pvaIn = String.Empty;
object pvaOut = String.Empty;
axWebBrowser1.ExecWB(SHDocVw.OLECMDID.OLECMDID_PAGESETUP, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref pvaIn, ref pvaOut);
}
/// <summary>
/// Called if the user clicks the File-Print preview menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miPrintPreview_Click(object sender, System.EventArgs e)
{
object pvaIn = String.Empty;
object pvaOut = String.Empty;
axWebBrowser1.ExecWB(SHDocVw.OLECMDID.OLECMDID_PRINTPREVIEW, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref pvaIn, ref pvaOut);
}
/// <summary>
/// Called if the user clicks the File-Print menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miPrint_Click(object sender, System.EventArgs e)
{
object pvaIn = String.Empty;
object pvaOut = String.Empty;
axWebBrowser1.ExecWB(SHDocVw.OLECMDID.OLECMDID_PRINT, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref pvaIn, ref pvaOut);
}
/// <summary>
/// Called if the user clicks a toolbar button
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
if( e.Button == btnContents ) // show help contents clicked
{
tabControl1.SelectedIndex = 0;
tocTree1.Focus();
}
if( e.Button == btnIndex ) // show help index clicked
{
tabControl1.SelectedIndex = 1;
helpIndex1.Focus();
}
if( e.Button == btnSearch ) // show help search clicked
{
tabControl1.SelectedIndex = 2;
helpSearch2.Focus();
}
if( e.Button == btnRefresh ) // refresh clicked
{
try
{
axWebBrowser1.Refresh();
}
catch(Exception)
{
}
}
if( e.Button == btnNext ) // next/forward clicked
{
try
{
axWebBrowser1.GoForward();
}
catch(Exception)
{
}
}
if( e.Button == btnBack ) // back clicked
{
try
{
axWebBrowser1.GoBack();
}
catch(Exception)
{
}
}
if( e.Button == btnHome ) // home clicked
{
NavigateBrowser( _reader.DefaultTopic );
}
if( e.Button == btnStop ) // stop clicked
{
try
{
axWebBrowser1.Stop();
}
catch(Exception)
{
}
}
if( e.Button == btnSynch )
{
this.Cursor = Cursors.WaitCursor;
tocTree1.Synchronize(axWebBrowser1.LocationURL);
this.Cursor = Cursors.Arrow;
}
}
/// <summary>
/// Called if the user clicks the Web browser-Back menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miBack_Click(object sender, System.EventArgs e)
{
try
{
axWebBrowser1.GoBack();
}
catch(Exception)
{
}
}
/// <summary>
/// Called if the user clicks the Web browser-Forward menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miForward_Click(object sender, System.EventArgs e)
{
try
{
axWebBrowser1.GoForward();
}
catch(Exception)
{
}
}
/// <summary>
/// Called if the user clicks the Web browser - home menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miHome_Click(object sender, System.EventArgs e)
{
NavigateBrowser( _reader.DefaultTopic );
}
/// <summary>
/// Called if the user clicks the Navigation-contents menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miContents_Click(object sender, System.EventArgs e)
{
tabControl1.SelectedIndex = 0;
tocTree1.Focus();
}
/// <summary>
/// Called if the user clicks the Navigation-index menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miIndex_Click(object sender, System.EventArgs e)
{
tabControl1.SelectedIndex = 1;
helpIndex1.Focus();
}
/// <summary>
/// Called if the user clicks the Navigation-search
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miSearch_Click(object sender, System.EventArgs e)
{
tabControl1.SelectedIndex = 2;
helpSearch2.Focus();
}
/// <summary>
/// Called if the user clicks on the Help-Contents menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miContents1_Click(object sender, System.EventArgs e)
{
tabControl1.SelectedIndex = 0;
tocTree1.Focus();
}
/// <summary>
/// Called if the user clicks on the Help-Index menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miIndex1_Click(object sender, System.EventArgs e)
{
tabControl1.SelectedIndex = 1;
helpIndex1.Focus();
}
/// <summary>
/// Called if the user clicks on the Help-Search menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miSearch1_Click(object sender, System.EventArgs e)
{
tabControl1.SelectedIndex = 2;
helpSearch2.Focus();
}
/// <summary>
/// Called if the user clicks the Help-About menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miAbout_Click(object sender, System.EventArgs e)
{
AboutDlg dlgA = new AboutDlg(_reader);
dlgA.ShowDialog();
}
/// <summary>
/// Called if the user clicks the Tools-Configure data dumping menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miDmpConfig_Click(object sender, System.EventArgs e)
{
DumpCfg dmpCfg = new DumpCfg();
dmpCfg.DumpingInfo = _dmpInfo;
dmpCfg.PreferencesOutput = _prefDumpOutput;
dmpCfg.PrefencesCompression = _prefDumpCompression;
dmpCfg.PreferencesFlags = _prefDumpFlags;
if(dmpCfg.ShowDialog() == DialogResult.OK)
{
_dmpInfo = dmpCfg.DumpingInfo;
_prefDumpOutput = dmpCfg.PreferencesOutput;
_prefDumpCompression = dmpCfg.PrefencesCompression;
_prefDumpFlags = dmpCfg.PreferencesFlags;
}
}
/// <summary>
/// Called if the user clicks the Tools-Preferences menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miPreferences_Click(object sender, System.EventArgs e)
{
Preferences prefDlg = new Preferences();
prefDlg.UrlPrefixPreference = _prefURLPrefix;
prefDlg.UseHH2TreePicsPreference = _prefUseHH2TreePics;
if( prefDlg.ShowDialog() == DialogResult.OK)
{
_prefURLPrefix = prefDlg.UrlPrefixPreference;
HtmlHelpSystem.UrlPrefix = _prefURLPrefix;
if( _prefUseHH2TreePics != prefDlg.UseHH2TreePicsPreference)
{
bool bChangeSetting = false;
if(_reader.FileList.Length <= 0)
{
bChangeSetting = true;
}
else
{
if( MessageBox.Show("Changing the image list preference requires to close all documents !\n \nShould the new setting should be applied ?",
"Warning",MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
bChangeSetting = true;
}
}
if(bChangeSetting)
{
miCloseFile_Click(sender,e);
_prefUseHH2TreePics = prefDlg.UseHH2TreePicsPreference;
HtmlHelpSystem.UseHH2TreePics = _prefUseHH2TreePics;
tocTree1.ReloadImageList();
}
}
}
}
/// <summary>
/// Called if the user clicks the Tools-customize help contents menu
/// </summary>
/// <param name="sender">sender of the event</param>
/// <param name="e">event parameter</param>
private void miCustomize_Click(object sender, System.EventArgs e)
{
CustomizeContent custDlg = new CustomizeContent();
custDlg.Filter = _filter;
if( custDlg.ShowDialog() == DialogResult.OK)
{
this.Cursor = Cursors.WaitCursor;
_filter = custDlg.Filter;
// clear current items
tocTree1.ClearContents();
helpIndex1.ClearContents();
helpSearch2.ClearContents();
// Rebuild the table of contents tree view in the classlibrary control
// applying the new filter
tocTree1.BuildTOC( _reader.TableOfContents, _filter );
// Rebuild the index entries in the classlibrary control
// applying the new filter
if( _reader.HasKLinks )
helpIndex1.BuildIndex( _reader.Index, IndexType.KeywordLinks, _filter );
else if( _reader.HasALinks )
helpIndex1.BuildIndex( _reader.Index, IndexType.AssiciativeLinks, _filter );
// Navigate the embedded browser to the default help topic
NavigateBrowser( _reader.DefaultTopic );
GC.Collect();
this.Cursor = Cursors.Arrow;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Internal.Resources.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Internal.Resources
{
/// <summary>
/// Operations for managing deployment operations.
/// </summary>
internal partial class DeploymentOperationOperations : IServiceOperations<ResourceManagementClient>, IDeploymentOperationOperations
{
/// <summary>
/// Initializes a new instance of the DeploymentOperationOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DeploymentOperationOperations(ResourceManagementClient client)
{
this._client = client;
}
private ResourceManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient.
/// </summary>
public ResourceManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Get a list of deployments operations.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='operationId'>
/// Required. Operation Id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Deployment operation.
/// </returns>
public async Task<DeploymentOperationsGetResult> GetAsync(string resourceGroupName, string deploymentName, string operationId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (operationId == null)
{
throw new ArgumentNullException("operationId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("operationId", operationId);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/operations/";
url = url + Uri.EscapeDataString(operationId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DeploymentOperationsGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DeploymentOperationsGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DeploymentOperation operationInstance = new DeploymentOperation();
result.Operation = operationInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
operationInstance.Id = idInstance;
}
JToken operationIdValue = responseDoc["operationId"];
if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
{
string operationIdInstance = ((string)operationIdValue);
operationInstance.OperationId = operationIdInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DeploymentOperationProperties propertiesInstance = new DeploymentOperationProperties();
operationInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken timestampValue = propertiesValue["timestamp"];
if (timestampValue != null && timestampValue.Type != JTokenType.Null)
{
DateTime timestampInstance = ((DateTime)timestampValue);
propertiesInstance.Timestamp = timestampInstance;
}
JToken statusCodeValue = propertiesValue["statusCode"];
if (statusCodeValue != null && statusCodeValue.Type != JTokenType.Null)
{
string statusCodeInstance = ((string)statusCodeValue);
propertiesInstance.StatusCode = statusCodeInstance;
}
JToken statusMessageValue = propertiesValue["statusMessage"];
if (statusMessageValue != null && statusMessageValue.Type != JTokenType.Null)
{
string statusMessageInstance = statusMessageValue.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.StatusMessage = statusMessageInstance;
}
JToken targetResourceValue = propertiesValue["targetResource"];
if (targetResourceValue != null && targetResourceValue.Type != JTokenType.Null)
{
TargetResource targetResourceInstance = new TargetResource();
propertiesInstance.TargetResource = targetResourceInstance;
JToken idValue2 = targetResourceValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
targetResourceInstance.Id = idInstance2;
}
JToken resourceNameValue = targetResourceValue["resourceName"];
if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null)
{
string resourceNameInstance = ((string)resourceNameValue);
targetResourceInstance.ResourceName = resourceNameInstance;
}
JToken resourceTypeValue = targetResourceValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
targetResourceInstance.ResourceType = resourceTypeInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a list of deployments operations.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of deployment operations.
/// </returns>
public async Task<DeploymentOperationsListResult> ListAsync(string resourceGroupName, string deploymentName, DeploymentOperationsListParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/operations";
List<string> queryParameters = new List<string>();
if (parameters != null && parameters.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString()));
}
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DeploymentOperationsListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DeploymentOperationsListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DeploymentOperation deploymentOperationInstance = new DeploymentOperation();
result.Operations.Add(deploymentOperationInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
deploymentOperationInstance.Id = idInstance;
}
JToken operationIdValue = valueValue["operationId"];
if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
{
string operationIdInstance = ((string)operationIdValue);
deploymentOperationInstance.OperationId = operationIdInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DeploymentOperationProperties propertiesInstance = new DeploymentOperationProperties();
deploymentOperationInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken timestampValue = propertiesValue["timestamp"];
if (timestampValue != null && timestampValue.Type != JTokenType.Null)
{
DateTime timestampInstance = ((DateTime)timestampValue);
propertiesInstance.Timestamp = timestampInstance;
}
JToken statusCodeValue = propertiesValue["statusCode"];
if (statusCodeValue != null && statusCodeValue.Type != JTokenType.Null)
{
string statusCodeInstance = ((string)statusCodeValue);
propertiesInstance.StatusCode = statusCodeInstance;
}
JToken statusMessageValue = propertiesValue["statusMessage"];
if (statusMessageValue != null && statusMessageValue.Type != JTokenType.Null)
{
string statusMessageInstance = statusMessageValue.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.StatusMessage = statusMessageInstance;
}
JToken targetResourceValue = propertiesValue["targetResource"];
if (targetResourceValue != null && targetResourceValue.Type != JTokenType.Null)
{
TargetResource targetResourceInstance = new TargetResource();
propertiesInstance.TargetResource = targetResourceInstance;
JToken idValue2 = targetResourceValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
targetResourceInstance.Id = idInstance2;
}
JToken resourceNameValue = targetResourceValue["resourceName"];
if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null)
{
string resourceNameInstance = ((string)resourceNameValue);
targetResourceInstance.ResourceName = resourceNameInstance;
}
JToken resourceTypeValue = targetResourceValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
targetResourceInstance.ResourceType = resourceTypeInstance;
}
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a next list of deployments operations.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of deployment operations.
/// </returns>
public async Task<DeploymentOperationsListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DeploymentOperationsListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DeploymentOperationsListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DeploymentOperation deploymentOperationInstance = new DeploymentOperation();
result.Operations.Add(deploymentOperationInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
deploymentOperationInstance.Id = idInstance;
}
JToken operationIdValue = valueValue["operationId"];
if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
{
string operationIdInstance = ((string)operationIdValue);
deploymentOperationInstance.OperationId = operationIdInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DeploymentOperationProperties propertiesInstance = new DeploymentOperationProperties();
deploymentOperationInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken timestampValue = propertiesValue["timestamp"];
if (timestampValue != null && timestampValue.Type != JTokenType.Null)
{
DateTime timestampInstance = ((DateTime)timestampValue);
propertiesInstance.Timestamp = timestampInstance;
}
JToken statusCodeValue = propertiesValue["statusCode"];
if (statusCodeValue != null && statusCodeValue.Type != JTokenType.Null)
{
string statusCodeInstance = ((string)statusCodeValue);
propertiesInstance.StatusCode = statusCodeInstance;
}
JToken statusMessageValue = propertiesValue["statusMessage"];
if (statusMessageValue != null && statusMessageValue.Type != JTokenType.Null)
{
string statusMessageInstance = statusMessageValue.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.StatusMessage = statusMessageInstance;
}
JToken targetResourceValue = propertiesValue["targetResource"];
if (targetResourceValue != null && targetResourceValue.Type != JTokenType.Null)
{
TargetResource targetResourceInstance = new TargetResource();
propertiesInstance.TargetResource = targetResourceInstance;
JToken idValue2 = targetResourceValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
targetResourceInstance.Id = idInstance2;
}
JToken resourceNameValue = targetResourceValue["resourceName"];
if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null)
{
string resourceNameInstance = ((string)resourceNameValue);
targetResourceInstance.ResourceName = resourceNameInstance;
}
JToken resourceTypeValue = targetResourceValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
targetResourceInstance.ResourceType = resourceTypeInstance;
}
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudioTools.Project;
namespace Microsoft.VisualStudioTools.Navigation {
/// <summary>
/// Inplementation of the service that builds the information to expose to the symbols
/// navigation tools (class view or object browser) from the source files inside a
/// hierarchy.
/// </summary>
internal abstract partial class LibraryManager : IDisposable, IVsRunningDocTableEvents {
private readonly CommonPackage/*!*/ _package;
private readonly Dictionary<uint, TextLineEventListener> _documents;
private readonly Dictionary<IVsHierarchy, HierarchyInfo> _hierarchies = new Dictionary<IVsHierarchy, HierarchyInfo>();
private readonly Dictionary<ModuleId, LibraryNode> _files;
private readonly Library _library;
private readonly IVsEditorAdaptersFactoryService _adapterFactory;
private uint _objectManagerCookie;
private uint _runningDocTableCookie;
public LibraryManager(CommonPackage/*!*/ package) {
Contract.Assert(package != null);
_package = package;
_documents = new Dictionary<uint, TextLineEventListener>();
_library = new Library(new Guid(CommonConstants.LibraryGuid));
_library.LibraryCapabilities = (_LIB_FLAGS2)_LIB_FLAGS.LF_PROJECT;
_files = new Dictionary<ModuleId, LibraryNode>();
var model = ((IServiceContainer)package).GetService(typeof(SComponentModel)) as IComponentModel;
_adapterFactory = model.GetService<IVsEditorAdaptersFactoryService>();
// Register our library now so it'll be available for find all references
RegisterLibrary();
}
public Library Library {
get { return _library; }
}
protected abstract LibraryNode CreateLibraryNode(LibraryNode parent, IScopeNode subItem, string namePrefix, IVsHierarchy hierarchy, uint itemid);
public virtual LibraryNode CreateFileLibraryNode(LibraryNode parent, HierarchyNode hierarchy, string name, string filename, LibraryNodeType libraryNodeType) {
return new LibraryNode(null, name, filename, libraryNodeType);
}
private object GetPackageService(Type/*!*/ type) {
return ((System.IServiceProvider)_package).GetService(type);
}
private void RegisterForRDTEvents() {
if (0 != _runningDocTableCookie) {
return;
}
IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (null != rdt) {
// Do not throw here in case of error, simply skip the registration.
rdt.AdviseRunningDocTableEvents(this, out _runningDocTableCookie);
}
}
private void UnregisterRDTEvents() {
if (0 == _runningDocTableCookie) {
return;
}
IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (null != rdt) {
// Do not throw in case of error.
rdt.UnadviseRunningDocTableEvents(_runningDocTableCookie);
}
_runningDocTableCookie = 0;
}
#region ILibraryManager Members
public void RegisterHierarchy(IVsHierarchy hierarchy) {
if ((null == hierarchy) || _hierarchies.ContainsKey(hierarchy)) {
return;
}
RegisterLibrary();
var commonProject = hierarchy.GetProject().GetCommonProject();
HierarchyListener listener = new HierarchyListener(hierarchy, this);
var node = _hierarchies[hierarchy] = new HierarchyInfo(
listener,
new ProjectLibraryNode(commonProject)
);
_library.AddNode(node.ProjectLibraryNode);
listener.StartListening(true);
RegisterForRDTEvents();
}
private void RegisterLibrary() {
if (0 == _objectManagerCookie) {
IVsObjectManager2 objManager = GetPackageService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (null == objManager) {
return;
}
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
objManager.RegisterSimpleLibrary(_library, out _objectManagerCookie));
}
}
public void UnregisterHierarchy(IVsHierarchy hierarchy) {
if ((null == hierarchy) || !_hierarchies.ContainsKey(hierarchy)) {
return;
}
HierarchyInfo info = _hierarchies[hierarchy];
if (null != info) {
info.Listener.Dispose();
}
_hierarchies.Remove(hierarchy);
_library.RemoveNode(info.ProjectLibraryNode);
if (0 == _hierarchies.Count) {
UnregisterRDTEvents();
}
lock (_files) {
ModuleId[] keys = new ModuleId[_files.Keys.Count];
_files.Keys.CopyTo(keys, 0);
foreach (ModuleId id in keys) {
if (hierarchy.Equals(id.Hierarchy)) {
_library.RemoveNode(_files[id]);
_files.Remove(id);
}
}
}
// Remove the document listeners.
uint[] docKeys = new uint[_documents.Keys.Count];
_documents.Keys.CopyTo(docKeys, 0);
foreach (uint id in docKeys) {
TextLineEventListener docListener = _documents[id];
if (hierarchy.Equals(docListener.FileID.Hierarchy)) {
_documents.Remove(id);
docListener.Dispose();
}
}
}
public void RegisterLineChangeHandler(uint document,
TextLineChangeEvent lineChanged, Action<IVsTextLines> onIdle) {
_documents[document].OnFileChangedImmediate += delegate(object sender, TextLineChange[] changes, int fLast) {
lineChanged(sender, changes, fLast);
};
_documents[document].OnFileChanged += (sender, args) => onIdle(args.TextBuffer);
}
#endregion
#region Library Member Production
/// <summary>
/// Overridden in the base class to receive notifications of when a file should
/// be analyzed for inclusion in the library. The derived class should queue
/// the parsing of the file and when it's complete it should call FileParsed
/// with the provided LibraryTask and an IScopeNode which provides information
/// about the members of the file.
/// </summary>
protected virtual void OnNewFile(LibraryTask task) {
}
/// <summary>
/// Called by derived class when a file has been parsed. The caller should
/// provide the LibraryTask received from the OnNewFile call and an IScopeNode
/// which represents the contents of the library.
///
/// It is safe to call this method from any thread.
/// </summary>
protected void FileParsed(LibraryTask task, IScopeNode scope) {
try {
var project = task.ModuleID.Hierarchy.GetProject().GetCommonProject();
HierarchyNode fileNode = fileNode = project.NodeFromItemId(task.ModuleID.ItemID);
HierarchyInfo parent;
if (fileNode == null || !_hierarchies.TryGetValue(task.ModuleID.Hierarchy, out parent)) {
return;
}
LibraryNode module = CreateFileLibraryNode(
parent.ProjectLibraryNode,
fileNode,
System.IO.Path.GetFileName(task.FileName),
task.FileName,
LibraryNodeType.Package | LibraryNodeType.Classes
);
// TODO: Creating the module tree should be done lazily as needed
// Currently we replace the entire tree and rely upon the libraries
// update count to invalidate the whole thing. We could do this
// finer grained and only update the changed nodes. But then we
// need to make sure we're not mutating lists which are handed out.
CreateModuleTree(module, scope, task.FileName + ":", task.ModuleID);
if (null != task.ModuleID) {
LibraryNode previousItem = null;
lock (_files) {
if (_files.TryGetValue(task.ModuleID, out previousItem)) {
_files.Remove(task.ModuleID);
parent.ProjectLibraryNode.RemoveNode(previousItem);
}
}
}
parent.ProjectLibraryNode.AddNode(module);
_library.Update();
if (null != task.ModuleID) {
lock (_files) {
_files.Add(task.ModuleID, module);
}
}
} catch (COMException) {
// we're shutting down and can't get the project
}
}
private void CreateModuleTree(LibraryNode current, IScopeNode scope, string namePrefix, ModuleId moduleId) {
if ((null == scope) || (null == scope.NestedScopes)) {
return;
}
foreach (IScopeNode subItem in scope.NestedScopes) {
LibraryNode newNode = CreateLibraryNode(current, subItem, namePrefix, moduleId.Hierarchy, moduleId.ItemID);
string newNamePrefix = namePrefix;
current.AddNode(newNode);
if ((newNode.NodeType & LibraryNodeType.Classes) != LibraryNodeType.None) {
newNamePrefix = namePrefix + newNode.Name + ".";
}
// Now use recursion to get the other types.
CreateModuleTree(newNode, subItem, newNamePrefix, moduleId);
}
}
#endregion
#region Hierarchy Events
private void OnNewFile(object sender, HierarchyEventArgs args) {
IVsHierarchy hierarchy = sender as IVsHierarchy;
if (null == hierarchy || IsNonMemberItem(hierarchy, args.ItemID)) {
return;
}
ITextBuffer buffer = null;
if (null != args.TextBuffer) {
buffer = _adapterFactory.GetDocumentBuffer(args.TextBuffer);
}
var id = new ModuleId(hierarchy, args.ItemID);
OnNewFile(new LibraryTask(args.CanonicalName, buffer, new ModuleId(hierarchy, args.ItemID)));
}
/// <summary>
/// Handles the delete event, checking to see if this is a project item.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void OnDeleteFile(object sender, HierarchyEventArgs args) {
IVsHierarchy hierarchy = sender as IVsHierarchy;
if (null == hierarchy || IsNonMemberItem(hierarchy, args.ItemID)) {
return;
}
OnDeleteFile(hierarchy, args);
}
/// <summary>
/// Does a delete w/o checking if it's a non-meber item, for handling the
/// transition from member item to non-member item.
/// </summary>
private void OnDeleteFile(IVsHierarchy hierarchy, HierarchyEventArgs args) {
ModuleId id = new ModuleId(hierarchy, args.ItemID);
LibraryNode node = null;
lock (_files) {
if (_files.TryGetValue(id, out node)) {
_files.Remove(id);
HierarchyInfo parent;
if (_hierarchies.TryGetValue(hierarchy, out parent)) {
parent.ProjectLibraryNode.RemoveNode(node);
}
}
}
if (null != node) {
_library.RemoveNode(node);
}
}
private void IsNonMemberItemChanged(object sender, HierarchyEventArgs args) {
IVsHierarchy hierarchy = sender as IVsHierarchy;
if (null == hierarchy) {
return;
}
if (!IsNonMemberItem(hierarchy, args.ItemID)) {
OnNewFile(hierarchy, args);
} else {
OnDeleteFile(hierarchy, args);
}
}
/// <summary>
/// Checks whether this hierarchy item is a project member (on disk items from show all
/// files aren't considered project members).
/// </summary>
protected bool IsNonMemberItem(IVsHierarchy hierarchy, uint itemId) {
object val;
int hr = hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_IsNonMemberItem, out val);
return ErrorHandler.Succeeded(hr) && (bool)val;
}
#endregion
#region IVsRunningDocTableEvents Members
public int OnAfterAttributeChange(uint docCookie, uint grfAttribs) {
if ((grfAttribs & (uint)(__VSRDTATTRIB.RDTA_MkDocument)) == (uint)__VSRDTATTRIB.RDTA_MkDocument) {
IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (rdt != null) {
uint flags, readLocks, editLocks, itemid;
IVsHierarchy hier;
IntPtr docData = IntPtr.Zero;
string moniker;
int hr;
try {
hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out editLocks, out moniker, out hier, out itemid, out docData);
TextLineEventListener listner;
if (_documents.TryGetValue(docCookie, out listner)) {
listner.FileName = moniker;
}
} finally {
if (IntPtr.Zero != docData) {
Marshal.Release(docData);
}
}
}
}
return VSConstants.S_OK;
}
public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame) {
return VSConstants.S_OK;
}
public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) {
return VSConstants.S_OK;
}
public int OnAfterSave(uint docCookie) {
return VSConstants.S_OK;
}
public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame) {
// Check if this document is in the list of the documents.
if (_documents.ContainsKey(docCookie)) {
return VSConstants.S_OK;
}
// Get the information about this document from the RDT.
IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (null != rdt) {
// Note that here we don't want to throw in case of error.
uint flags;
uint readLocks;
uint writeLoks;
string documentMoniker;
IVsHierarchy hierarchy;
uint itemId;
IntPtr unkDocData;
int hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out writeLoks,
out documentMoniker, out hierarchy, out itemId, out unkDocData);
try {
if (Microsoft.VisualStudio.ErrorHandler.Failed(hr) || (IntPtr.Zero == unkDocData)) {
return VSConstants.S_OK;
}
// Check if the herarchy is one of the hierarchies this service is monitoring.
if (!_hierarchies.ContainsKey(hierarchy)) {
// This hierarchy is not monitored, we can exit now.
return VSConstants.S_OK;
}
// Check the file to see if a listener is required.
if (_package.IsRecognizedFile(documentMoniker)) {
return VSConstants.S_OK;
}
// Create the module id for this document.
ModuleId docId = new ModuleId(hierarchy, itemId);
// Try to get the text buffer.
IVsTextLines buffer = Marshal.GetObjectForIUnknown(unkDocData) as IVsTextLines;
// Create the listener.
TextLineEventListener listener = new TextLineEventListener(buffer, documentMoniker, docId);
// Set the event handler for the change event. Note that there is no difference
// between the AddFile and FileChanged operation, so we can use the same handler.
listener.OnFileChanged += new EventHandler<HierarchyEventArgs>(OnNewFile);
// Add the listener to the dictionary, so we will not create it anymore.
_documents.Add(docCookie, listener);
} finally {
if (IntPtr.Zero != unkDocData) {
Marshal.Release(unkDocData);
}
}
}
// Always return success.
return VSConstants.S_OK;
}
public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) {
if ((0 != dwEditLocksRemaining) || (0 != dwReadLocksRemaining)) {
return VSConstants.S_OK;
}
TextLineEventListener listener;
if (!_documents.TryGetValue(docCookie, out listener) || (null == listener)) {
return VSConstants.S_OK;
}
using (listener) {
_documents.Remove(docCookie);
// Now make sure that the information about this file are up to date (e.g. it is
// possible that Class View shows something strange if the file was closed without
// saving the changes).
HierarchyEventArgs args = new HierarchyEventArgs(listener.FileID.ItemID, listener.FileName);
OnNewFile(listener.FileID.Hierarchy, args);
}
return VSConstants.S_OK;
}
#endregion
public void OnIdle(IOleComponentManager compMgr) {
foreach (TextLineEventListener listener in _documents.Values) {
if (compMgr.FContinueIdle() == 0) {
break;
}
listener.OnIdle();
}
}
#region IDisposable Members
public void Dispose() {
// Dispose all the listeners.
foreach (var info in _hierarchies.Values) {
info.Listener.Dispose();
}
_hierarchies.Clear();
foreach (TextLineEventListener textListener in _documents.Values) {
textListener.Dispose();
}
_documents.Clear();
// Remove this library from the object manager.
if (0 != _objectManagerCookie) {
IVsObjectManager2 mgr = GetPackageService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (null != mgr) {
mgr.UnregisterLibrary(_objectManagerCookie);
}
_objectManagerCookie = 0;
}
// Unregister this object from the RDT events.
UnregisterRDTEvents();
}
#endregion
class HierarchyInfo {
public readonly HierarchyListener Listener;
public readonly ProjectLibraryNode ProjectLibraryNode;
public HierarchyInfo(HierarchyListener listener, ProjectLibraryNode projectLibNode) {
Listener = listener;
ProjectLibraryNode = projectLibNode;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Principal;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
namespace Orleans.Counter.Control
{
using System.Collections.Generic;
using Orleans.Serialization;
using OrleansTelemetryConsumers.Counters;
/// <summary>
/// Control Orleans Counters - Register or Unregister the Orleans counter set
/// </summary>
internal class CounterControl
{
public bool Unregister { get; private set; }
public bool BruteForce { get; private set; }
public bool NeedRunAsAdministrator { get; private set; }
public bool IsRunningAsAdministrator { get; private set; }
public bool PauseAtEnd { get; private set; }
private static OrleansPerfCounterTelemetryConsumer perfCounterConsumer;
public CounterControl()
{
// Check user is Administrator and has granted UAC elevation permission to run this app
var userIdent = WindowsIdentity.GetCurrent();
var userPrincipal = new WindowsPrincipal(userIdent);
IsRunningAsAdministrator = userPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
perfCounterConsumer = new OrleansPerfCounterTelemetryConsumer();
}
public void PrintUsage()
{
using (var usageStr = new StringWriter())
{
usageStr.WriteLine(typeof(CounterControl).GetTypeInfo().Assembly.GetName().Name + ".exe {command}");
usageStr.WriteLine("Where commands are:");
usageStr.WriteLine(" /? or /help = Display usage info");
usageStr.WriteLine(" /r or /register = Register Windows performance counters for Orleans [default]");
usageStr.WriteLine(" /u or /unregister = Unregister Windows performance counters for Orleans");
usageStr.WriteLine(" /f or /force = Use brute force, if necessary");
usageStr.WriteLine(" /pause = Pause for user key press after operation");
ConsoleText.WriteUsage(usageStr.ToString());
}
}
public bool ParseArguments(string[] args)
{
bool ok = true;
NeedRunAsAdministrator = true;
Unregister = false;
foreach (var arg in args)
{
if (arg.StartsWith("/") || arg.StartsWith("-"))
{
var a = arg.ToLowerInvariant().Substring(1);
switch (a)
{
case "r":
case "register":
Unregister = false;
break;
case "u":
case "unregister":
Unregister = true;
break;
case "f":
case "force":
BruteForce = true;
break;
case "pause":
PauseAtEnd = true;
break;
case "?":
case "help":
NeedRunAsAdministrator = false;
ok = false;
break;
default:
NeedRunAsAdministrator = false;
ok = false;
break;
}
}
else
{
ConsoleText.WriteError("Unrecognised command line option: " + arg);
ok = false;
}
}
return ok;
}
public int Run()
{
if (NeedRunAsAdministrator && !IsRunningAsAdministrator)
{
ConsoleText.WriteError("Need to be running in Administrator role to perform the requested operations.");
return 1;
}
SerializationTestEnvironment.Initialize();
InitConsoleLogging();
try
{
if (Unregister)
{
ConsoleText.WriteStatus("Unregistering Orleans performance counters with Windows");
UnregisterWindowsPerfCounters(this.BruteForce);
}
else
{
ConsoleText.WriteStatus("Registering Orleans performance counters with Windows");
RegisterWindowsPerfCounters(true); // Always reinitialize counter registrations, even if already existed
}
ConsoleText.WriteStatus("Operation completed successfully.");
return 0;
}
catch (Exception exc)
{
ConsoleText.WriteError("Error running " + typeof(CounterControl).GetTypeInfo().Assembly.GetName().Name + ".exe", exc);
if (!BruteForce) return 2;
ConsoleText.WriteStatus("Ignoring error due to brute-force mode");
return 0;
}
}
/// <summary>
/// Initialize log infrastrtucture for Orleans runtime sub-components
/// </summary>
private static void InitConsoleLogging()
{
Trace.Listeners.Clear();
var cfg = new NodeConfiguration { TraceFilePattern = null, TraceToConsole = false };
LogManager.Initialize(cfg);
//TODO: Move it to use the APM APIs
//var logWriter = new LogWriterToConsole(true, true); // Use compact console output & no timestamps / log message metadata
//LogManager.LogConsumers.Add(logWriter);
}
/// <summary>
/// Create the set of Orleans counters, if they do not already exist
/// </summary>
/// <param name="useBruteForce">Use brute force, if necessary</param>
/// <remarks>Note: Program needs to be running as Administrator to be able to register Windows perf counters.</remarks>
private static void RegisterWindowsPerfCounters(bool useBruteForce)
{
try
{
if (OrleansPerfCounterTelemetryConsumer.AreWindowsPerfCountersAvailable())
{
if (!useBruteForce)
{
ConsoleText.WriteStatus("Orleans counters are already registered -- Use brute-force mode to re-initialize");
return;
}
// Delete any old perf counters
UnregisterWindowsPerfCounters(true);
}
if (GrainTypeManager.Instance == null)
{
var loader = new SiloAssemblyLoader(new Dictionary<string, SearchOption>());
var typeManager = new GrainTypeManager(false, loader, new RandomPlacementDefaultStrategy());
GrainTypeManager.Instance.Start(false);
}
// Register perf counters
perfCounterConsumer.InstallCounters();
if (OrleansPerfCounterTelemetryConsumer.AreWindowsPerfCountersAvailable())
ConsoleText.WriteStatus("Orleans counters registered successfully");
else
ConsoleText.WriteError("Orleans counters are NOT registered");
}
catch (Exception exc)
{
ConsoleText.WriteError("Error registering Orleans counters - {0}" + exc);
throw;
}
}
/// <summary>
/// Remove the set of Orleans counters, if they already exist
/// </summary>
/// <param name="useBruteForce">Use brute force, if necessary</param>
/// <remarks>Note: Program needs to be running as Administrator to be able to unregister Windows perf counters.</remarks>
private static void UnregisterWindowsPerfCounters(bool useBruteForce)
{
if (!OrleansPerfCounterTelemetryConsumer.AreWindowsPerfCountersAvailable())
{
ConsoleText.WriteStatus("Orleans counters are already unregistered");
return;
}
// Delete any old perf counters
try
{
perfCounterConsumer.DeleteCounters();
}
catch (Exception exc)
{
ConsoleText.WriteError("Error deleting old Orleans counters - {0}" + exc);
if (useBruteForce)
ConsoleText.WriteStatus("Ignoring error deleting Orleans counters due to brute-force mode");
else
throw;
}
}
private class RandomPlacementDefaultStrategy : DefaultPlacementStrategy
{
public RandomPlacementDefaultStrategy()
: base(GlobalConfiguration.DEFAULT_PLACEMENT_STRATEGY)
{
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QuantConnect.Data;
namespace QuantConnect.Securities
{
/// <summary>
/// Provides a means of keeping track of the different cash holdings of an algorithm
/// </summary>
public class CashBook : IDictionary<string, Cash>
{
/// <summary>
/// Gets the base currency used
/// </summary>
public const string AccountCurrency = "USD";
private readonly Dictionary<string, Cash> _currencies;
/// <summary>
/// Gets the total value of the cash book in units of the base currency
/// </summary>
public decimal TotalValueInAccountCurrency
{
get { return _currencies.Values.Sum(x => x.ValueInAccountCurrency); }
}
/// <summary>
/// Initializes a new instance of the <see cref="CashBook"/> class.
/// </summary>
public CashBook()
{
_currencies = new Dictionary<string, Cash>();
_currencies.Add(AccountCurrency, new Cash(AccountCurrency, 0, 1.0m));
}
/// <summary>
/// Adds a new cash of the specified symbol and quantity
/// </summary>
/// <param name="symbol">The symbol used to reference the new cash</param>
/// <param name="quantity">The amount of new cash to start</param>
/// <param name="conversionRate">The conversion rate used to determine the initial
/// portfolio value/starting capital impact caused by this currency position.</param>
public void Add(string symbol, decimal quantity, decimal conversionRate)
{
var cash = new Cash(symbol, quantity, conversionRate);
_currencies.Add(symbol, cash);
}
/// <summary>
/// Checks the current subscriptions and adds necessary currency pair feeds to provide real time conversion data
/// </summary>
/// <param name="securities">The SecurityManager for the algorithm</param>
/// <param name="subscriptions">The SubscriptionManager for the algorithm</param>
/// <param name="marketHoursDatabase">A security exchange hours provider instance used to resolve exchange hours for new subscriptions</param>
public void EnsureCurrencyDataFeeds(SecurityManager securities, SubscriptionManager subscriptions, MarketHoursDatabase marketHoursDatabase)
{
foreach (var cash in _currencies.Values)
{
cash.EnsureCurrencyDataFeed(securities, subscriptions, marketHoursDatabase);
}
}
/// <summary>
/// Converts a quantity of source currency units into the specified destination currency
/// </summary>
/// <param name="sourceQuantity">The quantity of source currency to be converted</param>
/// <param name="sourceCurrency">The source currency symbol</param>
/// <param name="destinationCurrency">The destination currency symbol</param>
/// <returns>The converted value</returns>
public decimal Convert(decimal sourceQuantity, string sourceCurrency, string destinationCurrency)
{
var source = this[sourceCurrency];
var destination = this[destinationCurrency];
var conversionRate = source.ConversionRate*destination.ConversionRate;
return sourceQuantity*conversionRate;
}
/// <summary>
/// Converts a quantity of source currency units into the account currency
/// </summary>
/// <param name="sourceQuantity">The quantity of source currency to be converted</param>
/// <param name="sourceCurrency">The source currency symbol</param>
/// <returns>The converted value</returns>
public decimal ConvertToAccountCurrency(decimal sourceQuantity, string sourceCurrency)
{
return Convert(sourceQuantity, sourceCurrency, AccountCurrency);
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine(string.Format("{0} {1,7} {2,10} = {3}", "Symbol", "Quantity", "Conversion", "Value in " + AccountCurrency));
foreach (var value in Values)
{
sb.AppendLine(value.ToString());
}
sb.AppendLine("-----------------------------------------");
sb.AppendLine(string.Format("CashBook Total Value: {0}", TotalValueInAccountCurrency.ToString("C")));
return sb.ToString();
}
#region IDictionary Implementation
/// <summary>
/// Gets the count of Cash items in this CashBook.
/// </summary>
/// <value>The count.</value>
public int Count
{
get { return _currencies.Count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value>
public bool IsReadOnly
{
get { return ((IDictionary<string, Cash>) _currencies).IsReadOnly; }
}
/// <summary>
/// Add the specified item to this CashBook.
/// </summary>
/// <param name="item">KeyValuePair of symbol -> Cash item</param>
public void Add(KeyValuePair<string, Cash> item)
{
_currencies.Add(item.Key, item.Value);
}
/// <summary>
/// Add the specified key and value.
/// </summary>
/// <param name="symbol">The symbol of the Cash value.</param>
/// <param name="value">Value.</param>
public void Add(string symbol, Cash value)
{
_currencies.Add(symbol, value);
}
/// <summary>
/// Clear this instance of all Cash entries.
/// </summary>
public void Clear()
{
_currencies.Clear();
}
/// <summary>
/// Remove the Cash item corresponding to the specified symbol
/// </summary>
/// <param name="symbol">The symbolto be removed</param>
public bool Remove(string symbol)
{
return _currencies.Remove (symbol);
}
/// <summary>
/// Remove the specified item.
/// </summary>
/// <param name="item">Item.</param>
public bool Remove(KeyValuePair<string, Cash> item)
{
return _currencies.Remove(item.Key);
}
/// <summary>
/// Determines whether the current instance contains an entry with the specified symbol.
/// </summary>
/// <returns><c>true</c>, if key was contained, <c>false</c> otherwise.</returns>
/// <param name="symbol">Key.</param>
public bool ContainsKey(string symbol)
{
return _currencies.ContainsKey(symbol);
}
/// <summary>
/// Try to get the value.
/// </summary>
/// <remarks>To be added.</remarks>
/// <returns><c>true</c>, if get value was tryed, <c>false</c> otherwise.</returns>
/// <param name="symbol">The symbol.</param>
/// <param name="value">Value.</param>
public bool TryGetValue(string symbol, out Cash value)
{
return _currencies.TryGetValue(symbol, out value);
}
/// <summary>
/// Determines whether the current collection contains the specified value.
/// </summary>
/// <param name="item">Item.</param>
public bool Contains(KeyValuePair<string, Cash> item)
{
return _currencies.Contains(item);
}
/// <summary>
/// Copies to the specified array.
/// </summary>
/// <param name="array">Array.</param>
/// <param name="arrayIndex">Array index.</param>
public void CopyTo(KeyValuePair<string, Cash>[] array, int arrayIndex)
{
((IDictionary<string, Cash>) _currencies).CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets or sets the <see cref="QuantConnect.Securities.Cash"/> with the specified symbol.
/// </summary>
/// <param name="symbol">Symbol.</param>
public Cash this[string symbol]
{
get
{
Cash cash;
if (!_currencies.TryGetValue(symbol, out cash))
{
throw new Exception("This cash symbol (" + symbol + ") was not found in your cash book.");
}
return cash;
}
set { _currencies[symbol] = value; }
}
/// <summary>
/// Gets the keys.
/// </summary>
/// <value>The keys.</value>
public ICollection<string> Keys
{
get { return _currencies.Keys; }
}
/// <summary>
/// Gets the values.
/// </summary>
/// <value>The values.</value>
public ICollection<Cash> Values
{
get { return _currencies.Values; }
}
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<KeyValuePair<string, Cash>> GetEnumerator()
{
return _currencies.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) _currencies).GetEnumerator();
}
#endregion
}
}
| |
using System;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using NBitcoin;
using NBitcoin.DataEncoders;
using NBitcoin.RPC;
using NBXplorer.DerivationStrategy;
using NBXplorer.Models;
using NBXplorer.Logging;
using NBitcoin.Scripting;
namespace NBXplorer
{
/// <summary>
/// Hack, ASP.NET core DI does not support having one singleton for multiple interfaces
/// </summary>
public class ScanUTXOSetServiceAccessor
{
public ScanUTXOSetService Instance
{
get; set;
}
}
public class ScanUTXOSetOptions
{
public int GapLimit { get; set; } = 10_000;
public int BatchSize { get; set; } = 1000;
public int From { get; set; }
}
public class ScanUTXOSetService : IHostedService
{
class ScanUTXOWorkItem
{
public ScanUTXOWorkItem(NBXplorerNetwork network,
DerivationStrategyBase derivationStrategy)
{
Network = network;
DerivationStrategy = new DerivationSchemeTrackedSource(derivationStrategy);
Id = DerivationStrategy.ToString();
StartTime = DateTime.UtcNow;
}
public string Id { get; set; }
public DateTimeOffset StartTime { get; set; }
public ScanUTXOSetOptions Options { get; set; }
public NBXplorerNetwork Network { get; }
public DerivationSchemeTrackedSource DerivationStrategy { get; set; }
public ScanUTXOInformation State { get; set; }
public bool Finished { get; internal set; }
}
class ScannedItems
{
public Dictionary<Script, KeyPathInformation> KeyPathInformations = new Dictionary<Script, KeyPathInformation>();
public List<OutputDescriptor> Descriptors = new List<OutputDescriptor>();
}
public ScanUTXOSetService(ScanUTXOSetServiceAccessor accessor,
RPCClientProvider rpcClients,
KeyPathTemplates keyPathTemplates,
RepositoryProvider repositories)
{
accessor.Instance = this;
RpcClients = rpcClients;
this.keyPathTemplates = keyPathTemplates;
Repositories = repositories;
}
Channel<string> _Channel = Channel.CreateBounded<string>(500);
ConcurrentDictionary<string, ScanUTXOWorkItem> _Progress = new ConcurrentDictionary<string, ScanUTXOWorkItem>();
internal bool EnqueueScan(NBXplorerNetwork network, DerivationStrategyBase derivationScheme, ScanUTXOSetOptions options)
{
var workItem = new ScanUTXOWorkItem(network, derivationScheme)
{
State = new ScanUTXOInformation()
{
Status = ScanUTXOStatus.Queued,
QueuedAt = DateTimeOffset.UtcNow
},
Options = options
};
var value = _Progress.AddOrUpdate(workItem.Id, workItem, (k, existing) => existing.Finished ? workItem : existing);
if (value != workItem)
return false;
if (!_Channel.Writer.TryWrite(workItem.Id))
{
_Progress.TryRemove(workItem.Id, out var unused);
return false;
}
CleanProgressList();
return true;
}
private void CleanProgressList()
{
var now = DateTimeOffset.UtcNow;
List<string> toCleanup = new List<string>();
foreach (var item in _Progress.Values.Where(p => p.Finished))
{
if (now - item.StartTime > TimeSpan.FromHours(24))
toCleanup.Add(item.Id);
}
foreach (var i in toCleanup)
_Progress.TryRemove(i, out var unused);
}
internal Task _Task;
CancellationTokenSource _Cts = new CancellationTokenSource();
private readonly KeyPathTemplates keyPathTemplates;
public RPCClientProvider RpcClients { get; }
public RepositoryProvider Repositories { get; }
public Task StartAsync(CancellationToken cancellationToken)
{
_Task = Listen();
return Task.CompletedTask;
}
private async Task Listen()
{
try
{
while (await _Channel.Reader.WaitToReadAsync(_Cts.Token) && _Channel.Reader.TryRead(out var item))
{
if (!_Progress.TryGetValue(item, out var workItem))
{
Logs.Explorer.LogError($"{workItem.Network.CryptoCode}: Work has been scheduled for {item}, but the work has not been found in _Progress dictionary. This is likely a bug, contact NBXplorer developers.");
continue;
}
Logs.Explorer.LogInformation($"{workItem.Network.CryptoCode}: Start scanning {workItem.DerivationStrategy.ToPrettyString()} from index {workItem.Options.From} with gap limit {workItem.Options.GapLimit}, batch size {workItem.Options.BatchSize}");
var rpc = RpcClients.GetRPCClient(workItem.Network);
try
{
var repo = Repositories.GetRepository(workItem.Network);
workItem.State.Progress = new ScanUTXOProgress()
{
Count = Math.Max(1, Math.Min(workItem.Options.BatchSize, workItem.Options.GapLimit)),
From = workItem.Options.From,
StartedAt = DateTimeOffset.UtcNow
};
foreach (var feature in keyPathTemplates.GetSupportedDerivationFeatures())
{
workItem.State.Progress.HighestKeyIndexFound.Add(feature, null);
}
workItem.State.Progress.UpdateRemainingBatches(workItem.Options.GapLimit);
workItem.State.Status = ScanUTXOStatus.Pending;
var scannedItems = GetScannedItems(workItem, workItem.State.Progress, workItem.Network);
var scanning = rpc.StartScanTxoutSetAsync(new ScanTxoutSetParameters(scannedItems.Descriptors));
while (true)
{
var progress = await rpc.GetStatusScanTxoutSetAsync();
if (progress != null)
{
workItem.State.Progress.CurrentBatchProgress = (int)Math.Round(progress.Value);
workItem.State.Progress.UpdateOverallProgress();
}
using (var cts = CancellationTokenSource.CreateLinkedTokenSource(_Cts.Token))
{
cts.CancelAfter(TimeSpan.FromSeconds(5.0));
try
{
var result = await scanning.WithCancellation(cts.Token);
var outputs = result.Outputs;
if (repo.MinUtxoValue != null)
{
outputs = outputs
.Where(o => o.Coin.Amount >= repo.MinUtxoValue)
.ToArray();
}
var progressObj = workItem.State.Progress.Clone();
progressObj.BatchNumber++;
progressObj.From += progressObj.Count;
progressObj.Found += outputs.Length;
progressObj.TotalSearched += scannedItems.Descriptors.Count;
progressObj.UpdateRemainingBatches(workItem.Options.GapLimit);
progressObj.UpdateOverallProgress();
Logs.Explorer.LogInformation($"{workItem.Network.CryptoCode}: Scanning of batch {workItem.State.Progress.BatchNumber} for {workItem.DerivationStrategy.ToPrettyString()} complete with {outputs.Length} UTXOs fetched");
await UpdateRepository(rpc, workItem.DerivationStrategy, repo, outputs, scannedItems, progressObj);
if (progressObj.RemainingBatches <= -1)
{
progressObj.BatchNumber--;
progressObj.From -= progressObj.Count;
progressObj.TotalSizeOfUTXOSet = result.SearchedItems;
progressObj.CompletedAt = DateTimeOffset.UtcNow;
progressObj.RemainingBatches = 0;
progressObj.CurrentBatchProgress = 100;
progressObj.UpdateRemainingBatches(workItem.Options.GapLimit);
progressObj.UpdateOverallProgress();
workItem.State.Progress = progressObj;
workItem.State.Status = ScanUTXOStatus.Complete;
Logs.Explorer.LogInformation($"{workItem.Network.CryptoCode}: Scanning {workItem.DerivationStrategy.ToPrettyString()} complete {progressObj.Found} UTXOs found in total");
break;
}
else
{
scannedItems = GetScannedItems(workItem, progressObj, workItem.Network);
workItem.State.Progress = progressObj;
scanning = rpc.StartScanTxoutSetAsync(new ScanTxoutSetParameters(scannedItems.Descriptors));
}
}
catch (OperationCanceledException) when (cts.Token.IsCancellationRequested)
{
}
}
}
}
catch (Exception ex) when (!_Cts.IsCancellationRequested)
{
workItem.State.Status = ScanUTXOStatus.Error;
workItem.State.Error = ex.Message;
var progress = workItem.State.Progress.Clone();
progress.CompletedAt = DateTimeOffset.UtcNow;
workItem.State.Progress = progress;
Logs.Explorer.LogError(ex, $"{workItem.Network.CryptoCode}: Error while scanning {workItem.DerivationStrategy.ToPrettyString()}");
}
finally
{
try { await rpc.AbortScanTxoutSetAsync(); }
catch { }
}
workItem.Finished = true;
}
}
catch (OperationCanceledException) when (_Cts.IsCancellationRequested)
{
}
}
private async Task UpdateRepository(RPCClient client, DerivationSchemeTrackedSource trackedSource, Repository repo, ScanTxoutOutput[] outputs, ScannedItems scannedItems, ScanUTXOProgress progressObj)
{
var clientBatch = client.PrepareBatch();
var blockIdsByHeight = new ConcurrentDictionary<int, uint256>();
await Task.WhenAll(outputs.Select(async o =>
{
blockIdsByHeight.TryAdd(o.Height, await clientBatch.GetBlockHashAsync(o.Height));
}).Concat(new[] { clientBatch.SendBatchAsync() }).ToArray());
var data = outputs
.GroupBy(o => o.Coin.Outpoint.Hash)
.Select(o => (Coins: o.Select(c => c.Coin).ToList(),
BlockId: blockIdsByHeight.TryGet(o.First().Height),
TxId: o.Select(c => c.Coin.Outpoint.Hash).FirstOrDefault(),
KeyPathInformations: o.Select(c => scannedItems.KeyPathInformations[c.Coin.ScriptPubKey]).ToList()))
.Where(o => o.BlockId != null)
.Select(o =>
{
foreach (var keyInfo in o.KeyPathInformations)
{
var index = keyInfo.KeyPath.Indexes.Last();
var highest = progressObj.HighestKeyIndexFound[keyInfo.Feature];
if (highest == null || index > highest.Value)
{
progressObj.HighestKeyIndexFound[keyInfo.Feature] = (int)index;
}
}
return o;
}).ToList();
var blockHeadersByBlockId = new ConcurrentDictionary<uint256, BlockHeader>();
clientBatch = client.PrepareBatch();
var gettingBlockHeaders = Task.WhenAll(data.Select(async o =>
{
blockHeadersByBlockId.TryAdd(o.BlockId, await clientBatch.GetBlockHeaderAsync(o.BlockId));
}).Concat(new[] { clientBatch.SendBatchAsync() }).ToArray());
await repo.SaveKeyInformations(scannedItems.
KeyPathInformations.
Select(p => p.Value).
Where(p =>
{
var highest = progressObj.HighestKeyIndexFound[p.Feature];
if (highest == null)
return false;
return p.KeyPath.Indexes.Last() <= highest.Value;
}).ToArray());
await repo.UpdateAddressPool(trackedSource, progressObj.HighestKeyIndexFound);
await gettingBlockHeaders;
DateTimeOffset now = DateTimeOffset.UtcNow;
await repo.SaveMatches(data.Select(o =>
{
var trackedTransaction = repo.CreateTrackedTransaction(trackedSource, new TrackedTransactionKey(o.TxId, o.BlockId, true), o.Coins, ToDictionary(o.KeyPathInformations));
trackedTransaction.Inserted = now;
trackedTransaction.FirstSeen = blockHeadersByBlockId.TryGetValue(o.BlockId, out var header) && header != null ? header.BlockTime : NBitcoin.Utils.UnixTimeToDateTime(0);
return trackedTransaction;
}).ToArray());
}
private static Dictionary<Script, KeyPath> ToDictionary(IEnumerable<KeyPathInformation> knownScriptMapping)
{
if (knownScriptMapping == null)
return null;
var result = new Dictionary<Script, KeyPath>();
foreach (var keypathInfo in knownScriptMapping)
{
result.TryAdd(keypathInfo.ScriptPubKey, keypathInfo.KeyPath);
}
return result;
}
private ScannedItems GetScannedItems(ScanUTXOWorkItem workItem, ScanUTXOProgress progress, NBXplorerNetwork network)
{
var items = new ScannedItems();
var derivationStrategy = workItem.DerivationStrategy;
foreach (var feature in keyPathTemplates.GetSupportedDerivationFeatures())
{
var keyPathTemplate = keyPathTemplates.GetKeyPathTemplate(feature);
var lineDerivation = workItem.DerivationStrategy.DerivationStrategy.GetLineFor(keyPathTemplate);
Enumerable.Range(progress.From, progress.Count)
.Select(index =>
{
var derivation = lineDerivation.Derive((uint)index);
var info = new KeyPathInformation(derivation, derivationStrategy, feature,
keyPathTemplate.GetKeyPath(index, false), network);
items.Descriptors.Add(OutputDescriptor.NewRaw(info.ScriptPubKey, network.NBitcoinNetwork));
items.KeyPathInformations.TryAdd(info.ScriptPubKey, info);
return info;
}).All(_ => true);
}
Logs.Explorer.LogInformation($"{workItem.Network.CryptoCode}: Start scanning batch {progress.BatchNumber} of {workItem.DerivationStrategy.ToPrettyString()} from index {progress.From}");
return items;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_Cts.Cancel();
_Channel.Writer.Complete();
return _Task;
}
public ScanUTXOInformation GetInformation(NBXplorerNetwork network, DerivationStrategyBase derivationScheme)
{
_Progress.TryGetValue(new ScanUTXOWorkItem(network, derivationScheme).Id, out var workItem);
return workItem?.State;
}
}
}
| |
using CoreGraphics;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using UIKit;
using Xamarin.Forms.Internals;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;
using static Xamarin.Forms.PlatformConfiguration.iOSSpecific.Page;
using PageUIStatusBarAnimation = Xamarin.Forms.PlatformConfiguration.iOSSpecific.UIStatusBarAnimation;
using PointF = CoreGraphics.CGPoint;
using RectangleF = CoreGraphics.CGRect;
namespace Xamarin.Forms.Platform.iOS
{
public class NavigationRenderer : UINavigationController, IVisualElementRenderer, IEffectControlProvider
{
internal const string UpdateToolbarButtons = "Xamarin.UpdateToolbarButtons";
bool _appeared;
bool _ignorePopCall;
bool _loaded;
MasterDetailPage _parentMasterDetailPage;
Size _queuedSize;
UIViewController[] _removeControllers;
UIToolbar _secondaryToolbar;
VisualElementTracker _tracker;
public NavigationRenderer()
{
MessagingCenter.Subscribe<IVisualElementRenderer>(this, UpdateToolbarButtons, sender =>
{
if (!ViewControllers.Any())
return;
var parentingViewController = (ParentingViewController)ViewControllers.Last();
UpdateLeftBarButtonItem(parentingViewController);
});
}
Page Current { get; set; }
IPageController PageController => Element as IPageController;
public VisualElement Element { get; private set; }
public event EventHandler<VisualElementChangedEventArgs> ElementChanged;
public SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
{
return NativeView.GetSizeRequest(widthConstraint, heightConstraint);
}
public UIView NativeView
{
get { return View; }
}
public void SetElement(VisualElement element)
{
var oldElement = Element;
Element = (NavigationPage)element;
OnElementChanged(new VisualElementChangedEventArgs(oldElement, element));
if (element != null)
element.SendViewInitialized(NativeView);
EffectUtilities.RegisterEffectControlProvider(this, oldElement, element);
}
public void SetElementSize(Size size)
{
if (_loaded)
Element.Layout(new Rectangle(Element.X, Element.Y, size.Width, size.Height));
else
_queuedSize = size;
}
public UIViewController ViewController
{
get { return this; }
}
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate(fromInterfaceOrientation);
View.SetNeedsLayout();
var parentingViewController = (ParentingViewController)ViewControllers.Last();
UpdateLeftBarButtonItem(parentingViewController);
}
public Task<bool> PopToRootAsync(Page page, bool animated = true)
{
return OnPopToRoot(page, animated);
}
public override UIViewController[] PopToRootViewController(bool animated)
{
if (!_ignorePopCall && ViewControllers.Length > 1)
RemoveViewControllers(animated);
return base.PopToRootViewController(animated);
}
public Task<bool> PopViewAsync(Page page, bool animated = true)
{
return OnPopViewAsync(page, animated);
}
public override UIViewController PopViewController(bool animated)
{
RemoveViewControllers(animated);
return base.PopViewController(animated);
}
public Task<bool> PushPageAsync(Page page, bool animated = true)
{
return OnPushAsync(page, animated);
}
public override void ViewDidAppear(bool animated)
{
if (!_appeared)
{
_appeared = true;
PageController?.SendAppearing();
}
base.ViewDidAppear(animated);
View.SetNeedsLayout();
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
if (!_appeared || Element == null)
return;
_appeared = false;
PageController.SendDisappearing();
}
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
UpdateToolBarVisible();
var navBarFrame = NavigationBar.Frame;
var toolbar = _secondaryToolbar;
// Use 0 if the NavBar is hidden or will be hidden
var toolbarY = NavigationBarHidden || NavigationBar.Translucent || !NavigationPage.GetHasNavigationBar(Current) ? 0 : navBarFrame.Bottom;
toolbar.Frame = new RectangleF(0, toolbarY, View.Frame.Width, toolbar.Frame.Height);
double trueBottom = toolbar.Hidden ? toolbarY : toolbar.Frame.Bottom;
var modelSize = _queuedSize.IsZero ? Element.Bounds.Size : _queuedSize;
PageController.ContainerArea =
new Rectangle(0, toolbar.Hidden ? 0 : toolbar.Frame.Height, modelSize.Width, modelSize.Height - trueBottom);
if (!_queuedSize.IsZero)
{
Element.Layout(new Rectangle(Element.X, Element.Y, _queuedSize.Width, _queuedSize.Height));
_queuedSize = Size.Zero;
}
_loaded = true;
foreach (var view in View.Subviews)
{
if (view == NavigationBar || view == _secondaryToolbar)
continue;
view.Frame = View.Bounds;
}
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
UpdateTranslucent();
_secondaryToolbar = new SecondaryToolbar { Frame = new RectangleF(0, 0, 320, 44) };
View.Add(_secondaryToolbar);
_secondaryToolbar.Hidden = true;
FindParentMasterDetail();
var navPage = (NavigationPage)Element;
if (navPage.CurrentPage == null)
{
throw new InvalidOperationException(
"NavigationPage must have a root Page before being used. Either call PushAsync with a valid Page, or pass a Page to the constructor before usage.");
}
var navController = ((INavigationPageController)navPage);
navController.PushRequested += OnPushRequested;
navController.PopRequested += OnPopRequested;
navController.PopToRootRequested += OnPopToRootRequested;
navController.RemovePageRequested += OnRemovedPageRequested;
navController.InsertPageBeforeRequested += OnInsertPageBeforeRequested;
UpdateTint();
UpdateBarBackgroundColor();
UpdateBarTextColor();
// If there is already stuff on the stack we need to push it
((INavigationPageController)navPage).StackCopy.Reverse().ForEach(async p => await PushPageAsync(p, false));
_tracker = new VisualElementTracker(this);
Element.PropertyChanged += HandlePropertyChanged;
UpdateToolBarVisible();
UpdateBackgroundColor();
Current = navPage.CurrentPage;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
MessagingCenter.Unsubscribe<IVisualElementRenderer>(this, UpdateToolbarButtons);
foreach (var childViewController in ViewControllers)
childViewController.Dispose();
if (_tracker != null)
_tracker.Dispose();
_secondaryToolbar.RemoveFromSuperview();
_secondaryToolbar.Dispose();
_secondaryToolbar = null;
_parentMasterDetailPage = null;
Current = null; // unhooks events
var navPage = (NavigationPage)Element;
navPage.PropertyChanged -= HandlePropertyChanged;
var navController = ((INavigationPageController)navPage);
navController.PushRequested -= OnPushRequested;
navController.PopRequested -= OnPopRequested;
navController.PopToRootRequested -= OnPopToRootRequested;
navController.RemovePageRequested -= OnRemovedPageRequested;
navController.InsertPageBeforeRequested -= OnInsertPageBeforeRequested;
}
base.Dispose(disposing);
if (_appeared)
{
PageController.SendDisappearing();
_appeared = false;
}
}
protected virtual void OnElementChanged(VisualElementChangedEventArgs e)
{
var changed = ElementChanged;
if (changed != null)
changed(this, e);
}
protected virtual async Task<bool> OnPopToRoot(Page page, bool animated)
{
_ignorePopCall = true;
var renderer = Platform.GetRenderer(page);
if (renderer == null || renderer.ViewController == null)
return false;
var task = GetAppearedOrDisappearedTask(page);
PopToRootViewController(animated);
_ignorePopCall = false;
var success = !await task;
UpdateToolBarVisible();
return success;
}
protected virtual async Task<bool> OnPopViewAsync(Page page, bool animated)
{
if (_ignorePopCall)
return true;
var renderer = Platform.GetRenderer(page);
if (renderer == null || renderer.ViewController == null)
return false;
var actuallyRemoved = false;
if (page != ((ParentingViewController)TopViewController).Child)
throw new NotSupportedException("Popped page does not appear on top of current navigation stack, please file a bug.");
var task = GetAppearedOrDisappearedTask(page);
UIViewController poppedViewController;
poppedViewController = base.PopViewController(animated);
if (poppedViewController == null)
{
// this happens only when the user does something REALLY dumb like pop right after putting the page as visible.
poppedViewController = TopViewController;
var newControllers = ViewControllers.Remove(poppedViewController);
ViewControllers = newControllers;
actuallyRemoved = true;
}
else
actuallyRemoved = !await task;
poppedViewController.Dispose();
UpdateToolBarVisible();
return actuallyRemoved;
}
protected virtual async Task<bool> OnPushAsync(Page page, bool animated)
{
var pack = CreateViewControllerForPage(page);
var task = GetAppearedOrDisappearedTask(page);
PushViewController(pack, animated);
var shown = await task;
UpdateToolBarVisible();
return shown;
}
ParentingViewController CreateViewControllerForPage(Page page)
{
if (Platform.GetRenderer(page) == null)
Platform.SetRenderer(page, Platform.CreateRenderer(page));
// must pack into container so padding can work
// otherwise the view controller is forced to 0,0
var pack = new ParentingViewController(this) { Child = page };
if (!string.IsNullOrWhiteSpace(page.Title))
pack.NavigationItem.Title = page.Title;
// First page and we have a master detail to contend with
UpdateLeftBarButtonItem(pack);
//var pack = Platform.GetRenderer (view).ViewController;
var titleIcon = NavigationPage.GetTitleIcon(page);
if (!string.IsNullOrEmpty(titleIcon))
{
try
{
//UIImage ctor throws on file not found if MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure is true;
pack.NavigationItem.TitleView = new UIImageView(new UIImage(titleIcon));
}
catch
{
}
}
var titleText = NavigationPage.GetBackButtonTitle(page);
if (titleText != null)
{
pack.NavigationItem.BackBarButtonItem =
new UIBarButtonItem(titleText, UIBarButtonItemStyle.Plain, async (o, e) => await PopViewAsync(page));
}
var pageRenderer = Platform.GetRenderer(page);
pack.View.AddSubview(pageRenderer.ViewController.View);
pack.AddChildViewController(pageRenderer.ViewController);
pageRenderer.ViewController.DidMoveToParentViewController(pack);
return pack;
}
void FindParentMasterDetail()
{
var parentPages = ((Page)Element).GetParentPages();
var masterDetail = parentPages.OfType<MasterDetailPage>().FirstOrDefault();
if (masterDetail != null && parentPages.Append((Page)Element).Contains(masterDetail.Detail))
_parentMasterDetailPage = masterDetail;
}
Task<bool> GetAppearedOrDisappearedTask(Page page)
{
var tcs = new TaskCompletionSource<bool>();
var parentViewController = Platform.GetRenderer(page).ViewController.ParentViewController as ParentingViewController;
if (parentViewController == null)
throw new NotSupportedException("ParentingViewController parent could not be found. Please file a bug.");
EventHandler appearing = null, disappearing = null;
appearing = (s, e) =>
{
parentViewController.Appearing -= appearing;
parentViewController.Disappearing -= disappearing;
Device.BeginInvokeOnMainThread(() => { tcs.SetResult(true); });
};
disappearing = (s, e) =>
{
parentViewController.Appearing -= appearing;
parentViewController.Disappearing -= disappearing;
Device.BeginInvokeOnMainThread(() => { tcs.SetResult(false); });
};
parentViewController.Appearing += appearing;
parentViewController.Disappearing += disappearing;
return tcs.Task;
}
void HandlePropertyChanged(object sender, PropertyChangedEventArgs e)
{
#pragma warning disable 0618 //retaining legacy call to obsolete code
if (e.PropertyName == NavigationPage.TintProperty.PropertyName)
#pragma warning restore 0618
UpdateTint();
if (e.PropertyName == NavigationPage.BarBackgroundColorProperty.PropertyName)
UpdateBarBackgroundColor();
else if (e.PropertyName == NavigationPage.BarTextColorProperty.PropertyName || e.PropertyName == PlatformConfiguration.iOSSpecific.NavigationPage.StatusBarTextColorModeProperty.PropertyName)
UpdateBarTextColor();
else if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
UpdateBackgroundColor();
else if (e.PropertyName == NavigationPage.CurrentPageProperty.PropertyName)
Current = ((NavigationPage)Element).CurrentPage;
else if (e.PropertyName == PlatformConfiguration.iOSSpecific.NavigationPage.IsNavigationBarTranslucentProperty.PropertyName)
UpdateTranslucent();
else if (e.PropertyName == PreferredStatusBarUpdateAnimationProperty.PropertyName)
UpdateCurrentPagePreferredStatusBarUpdateAnimation();
}
void UpdateCurrentPagePreferredStatusBarUpdateAnimation()
{
// Not using the extension method syntax here because for some reason it confuses the mono compiler
// and throws a CS0121 error
PageUIStatusBarAnimation animation = PlatformConfiguration.iOSSpecific.Page.PreferredStatusBarUpdateAnimation(((Page)Element).OnThisPlatform());
PlatformConfiguration.iOSSpecific.Page.SetPreferredStatusBarUpdateAnimation(Current.OnThisPlatform(), animation);
}
void UpdateTranslucent()
{
NavigationBar.Translucent = ((NavigationPage)Element).OnThisPlatform().IsNavigationBarTranslucent();
}
void InsertPageBefore(Page page, Page before)
{
if (before == null)
throw new ArgumentNullException("before");
if (page == null)
throw new ArgumentNullException("page");
var pageContainer = CreateViewControllerForPage(page);
var target = Platform.GetRenderer(before).ViewController.ParentViewController;
ViewControllers = ViewControllers.Insert(ViewControllers.IndexOf(target), pageContainer);
}
void OnInsertPageBeforeRequested(object sender, NavigationRequestedEventArgs e)
{
InsertPageBefore(e.Page, e.BeforePage);
}
void OnPopRequested(object sender, NavigationRequestedEventArgs e)
{
e.Task = PopViewAsync(e.Page, e.Animated);
}
void OnPopToRootRequested(object sender, NavigationRequestedEventArgs e)
{
e.Task = PopToRootAsync(e.Page, e.Animated);
}
void OnPushRequested(object sender, NavigationRequestedEventArgs e)
{
e.Task = PushPageAsync(e.Page, e.Animated);
}
void OnRemovedPageRequested(object sender, NavigationRequestedEventArgs e)
{
RemovePage(e.Page);
}
void RemovePage(Page page)
{
if (page == null)
throw new ArgumentNullException("page");
if (page == Current)
throw new NotSupportedException(); // should never happen as NavPage protects against this
var target = Platform.GetRenderer(page).ViewController.ParentViewController;
// So the ViewControllers property is not very property like on iOS. Assigning to it doesn't cause it to be
// immediately reflected into the property. The change will not be reflected until there has been sufficient time
// to process it (it ends up on the event queue). So to resolve this issue we keep our own stack until we
// know iOS has processed it, and make sure any updates use that.
// In the future we may want to make RemovePageAsync and deprecate RemovePage to handle cases where Push/Pop is called
// during a remove cycle.
if (_removeControllers == null)
{
_removeControllers = ViewControllers.Remove(target);
ViewControllers = _removeControllers;
Device.BeginInvokeOnMainThread(() => { _removeControllers = null; });
}
else
{
_removeControllers = _removeControllers.Remove(target);
ViewControllers = _removeControllers;
}
var parentingViewController = ViewControllers.Last() as ParentingViewController;
UpdateLeftBarButtonItem(parentingViewController, page);
}
void RemoveViewControllers(bool animated)
{
var controller = TopViewController as ParentingViewController;
if (controller == null || controller.Child == null)
return;
// Gesture in progress, lets not be proactive and just wait for it to finish
var count = ViewControllers.Length;
var task = GetAppearedOrDisappearedTask(controller.Child);
task.ContinueWith(async t =>
{
// task returns true if the user lets go of the page and is not popped
// however at this point the renderer is already off the visual stack so we just need to update the NavigationPage
// Also worth noting this task returns on the main thread
if (t.Result)
return;
_ignorePopCall = true;
// because iOS will just chain multiple animations together...
var removed = count - ViewControllers.Length;
for (var i = 0; i < removed; i++)
{
// lets just pop these suckers off, do not await, the true is there to make this fast
await ((INavigationPageController)Element).PopAsyncInner(animated, true);
}
// because we skip the normal pop process we need to dispose ourselves
controller.Dispose();
_ignorePopCall = false;
}, TaskScheduler.FromCurrentSynchronizationContext());
}
void UpdateBackgroundColor()
{
var color = Element.BackgroundColor == Color.Default ? Color.White : Element.BackgroundColor;
View.BackgroundColor = color.ToUIColor();
}
void UpdateBarBackgroundColor()
{
var barBackgroundColor = ((NavigationPage)Element).BarBackgroundColor;
// Set navigation bar background color
NavigationBar.BarTintColor = barBackgroundColor == Color.Default
? UINavigationBar.Appearance.BarTintColor
: barBackgroundColor.ToUIColor();
}
void UpdateBarTextColor()
{
var barTextColor = ((NavigationPage)Element).BarTextColor;
var globalAttributes = UINavigationBar.Appearance.GetTitleTextAttributes();
if (barTextColor == Color.Default)
{
if (NavigationBar.TitleTextAttributes != null)
{
var attributes = new UIStringAttributes();
attributes.ForegroundColor = globalAttributes.TextColor;
attributes.Font = globalAttributes.Font;
NavigationBar.TitleTextAttributes = attributes;
}
}
else
{
var titleAttributes = new UIStringAttributes();
titleAttributes.Font = globalAttributes.Font;
// TODO: the ternary if statement here will always return false because of the encapsulating if statement.
// What was the intention?
titleAttributes.ForegroundColor = barTextColor == Color.Default
? titleAttributes.ForegroundColor ?? UINavigationBar.Appearance.TintColor
: barTextColor.ToUIColor();
NavigationBar.TitleTextAttributes = titleAttributes;
}
var statusBarColorMode = (Element as NavigationPage).OnThisPlatform().GetStatusBarTextColorMode();
// set Tint color (i. e. Back Button arrow and Text)
NavigationBar.TintColor = barTextColor == Color.Default || statusBarColorMode == StatusBarTextColorMode.DoNotAdjust
? UINavigationBar.Appearance.TintColor
: barTextColor.ToUIColor();
if (statusBarColorMode == StatusBarTextColorMode.DoNotAdjust || barTextColor.Luminosity <= 0.5)
{
// Use dark text color for status bar
UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.Default;
}
else
{
// Use light text color for status bar
UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent;
}
}
void UpdateLeftBarButtonItem(ParentingViewController containerController, Page pageBeingRemoved = null)
{
if (containerController == null)
return;
var currentChild = containerController.Child;
var firstPage = ((INavigationPageController)Element).StackCopy.LastOrDefault();
if ((firstPage != pageBeingRemoved && currentChild != firstPage && NavigationPage.GetHasBackButton(currentChild)) || _parentMasterDetailPage == null)
return;
if (!_parentMasterDetailPage.ShouldShowToolbarButton())
{
containerController.NavigationItem.LeftBarButtonItem = null;
return;
}
var shouldUseIcon = _parentMasterDetailPage.Master.Icon != null;
if (shouldUseIcon)
{
try
{
containerController.NavigationItem.LeftBarButtonItem =
new UIBarButtonItem(new UIImage(_parentMasterDetailPage.Master.Icon), UIBarButtonItemStyle.Plain,
(o, e) => _parentMasterDetailPage.IsPresented = !_parentMasterDetailPage.IsPresented);
}
catch (Exception)
{
// Throws Exception otherwise would catch more specific exception type
shouldUseIcon = false;
}
}
if (!shouldUseIcon)
{
containerController.NavigationItem.LeftBarButtonItem = new UIBarButtonItem(_parentMasterDetailPage.Master.Title,
UIBarButtonItemStyle.Plain,
(o, e) => _parentMasterDetailPage.IsPresented = !_parentMasterDetailPage.IsPresented);
}
}
void UpdateTint()
{
#pragma warning disable 0618 //retaining legacy call to obsolete code
var tintColor = ((NavigationPage)Element).Tint;
#pragma warning restore 0618
NavigationBar.BarTintColor = tintColor == Color.Default
? UINavigationBar.Appearance.BarTintColor
: tintColor.ToUIColor();
if (tintColor == Color.Default)
NavigationBar.TintColor = UINavigationBar.Appearance.TintColor;
else
NavigationBar.TintColor = tintColor.Luminosity > 0.5 ? UIColor.Black : UIColor.White;
}
void UpdateToolBarVisible()
{
if (_secondaryToolbar == null)
return;
if (TopViewController != null && TopViewController.ToolbarItems != null && TopViewController.ToolbarItems.Any())
{
_secondaryToolbar.Hidden = false;
_secondaryToolbar.Items = TopViewController.ToolbarItems;
}
else
{
_secondaryToolbar.Hidden = true;
//secondaryToolbar.Items = null;
}
}
class SecondaryToolbar : UIToolbar
{
readonly List<UIView> _lines = new List<UIView>();
public SecondaryToolbar()
{
TintColor = UIColor.White;
}
public override UIBarButtonItem[] Items
{
get { return base.Items; }
set
{
base.Items = value;
SetupLines();
}
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (Items == null || Items.Length == 0)
return;
nfloat padding = 11f;
var itemWidth = (Bounds.Width - padding) / Items.Length - padding;
var x = padding;
var itemH = Bounds.Height - 10;
foreach (var item in Items)
{
var frame = new RectangleF(x, 5, itemWidth, itemH);
item.CustomView.Frame = frame;
x += itemWidth + padding;
}
x = itemWidth + padding * 1.5f;
var y = Bounds.GetMidY();
foreach (var l in _lines)
{
l.Center = new PointF(x, y);
x += itemWidth + padding;
}
}
void SetupLines()
{
_lines.ForEach(l => l.RemoveFromSuperview());
_lines.Clear();
if (Items == null)
return;
for (var i = 1; i < Items.Length; i++)
{
var l = new UIView(new RectangleF(0, 0, 1, 24)) { BackgroundColor = new UIColor(0, 0, 0, 0.2f) };
AddSubview(l);
_lines.Add(l);
}
}
}
class ParentingViewController : UIViewController
{
readonly WeakReference<NavigationRenderer> _navigation;
Page _child;
ToolbarTracker _tracker = new ToolbarTracker();
public ParentingViewController(NavigationRenderer navigation)
{
AutomaticallyAdjustsScrollViewInsets = false;
_navigation = new WeakReference<NavigationRenderer>(navigation);
}
public Page Child
{
get { return _child; }
set
{
if (_child == value)
return;
if (_child != null)
_child.PropertyChanged -= HandleChildPropertyChanged;
_child = value;
if (_child != null)
_child.PropertyChanged += HandleChildPropertyChanged;
UpdateHasBackButton();
}
}
public event EventHandler Appearing;
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate(fromInterfaceOrientation);
View.SetNeedsLayout();
}
public event EventHandler Disappearing;
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
var handler = Appearing;
if (handler != null)
handler(this, EventArgs.Empty);
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
var handler = Disappearing;
if (handler != null)
handler(this, EventArgs.Empty);
}
public override void ViewDidLayoutSubviews()
{
IVisualElementRenderer childRenderer;
if (Child != null && (childRenderer = Platform.GetRenderer(Child)) != null)
childRenderer.NativeView.Frame = Child.Bounds.ToRectangleF();
base.ViewDidLayoutSubviews();
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
_tracker.Target = Child;
_tracker.AdditionalTargets = Child.GetParentPages();
_tracker.CollectionChanged += TrackerOnCollectionChanged;
UpdateToolbarItems();
}
public override void ViewWillAppear(bool animated)
{
UpdateNavigationBarVisibility(animated);
NavigationRenderer n;
var isTranslucent = false;
if (_navigation.TryGetTarget(out n))
isTranslucent = n.NavigationBar.Translucent;
EdgesForExtendedLayout = isTranslucent ? UIRectEdge.All : UIRectEdge.None;
base.ViewWillAppear(animated);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((IPageController)Child).SendDisappearing();
if (Child != null)
{
Child.PropertyChanged -= HandleChildPropertyChanged;
Child = null;
}
_tracker.Target = null;
_tracker.CollectionChanged -= TrackerOnCollectionChanged;
_tracker = null;
if (NavigationItem.RightBarButtonItems != null)
{
for (var i = 0; i < NavigationItem.RightBarButtonItems.Length; i++)
NavigationItem.RightBarButtonItems[i].Dispose();
}
if (ToolbarItems != null)
{
for (var i = 0; i < ToolbarItems.Length; i++)
ToolbarItems[i].Dispose();
}
}
base.Dispose(disposing);
}
void HandleChildPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == NavigationPage.HasNavigationBarProperty.PropertyName)
UpdateNavigationBarVisibility(true);
else if (e.PropertyName == Page.TitleProperty.PropertyName)
NavigationItem.Title = Child.Title;
else if (e.PropertyName == NavigationPage.HasBackButtonProperty.PropertyName)
UpdateHasBackButton();
else if (e.PropertyName == PrefersStatusBarHiddenProperty.PropertyName)
UpdatePrefersStatusBarHidden();
}
void UpdatePrefersStatusBarHidden()
{
View.SetNeedsLayout();
ParentViewController?.View.SetNeedsLayout();
}
void TrackerOnCollectionChanged(object sender, EventArgs eventArgs)
{
UpdateToolbarItems();
}
void UpdateHasBackButton()
{
if (Child == null)
return;
NavigationItem.HidesBackButton = !NavigationPage.GetHasBackButton(Child);
}
void UpdateNavigationBarVisibility(bool animated)
{
var current = Child;
if (current == null || NavigationController == null)
return;
var hasNavBar = NavigationPage.GetHasNavigationBar(current);
if (NavigationController.NavigationBarHidden == hasNavBar)
NavigationController.SetNavigationBarHidden(!hasNavBar, animated);
}
void UpdateToolbarItems()
{
if (NavigationItem.RightBarButtonItems != null)
{
for (var i = 0; i < NavigationItem.RightBarButtonItems.Length; i++)
NavigationItem.RightBarButtonItems[i].Dispose();
}
if (ToolbarItems != null)
{
for (var i = 0; i < ToolbarItems.Length; i++)
ToolbarItems[i].Dispose();
}
List<UIBarButtonItem> primaries = null;
List<UIBarButtonItem> secondaries = null;
foreach (var item in _tracker.ToolbarItems)
{
if (item.Order == ToolbarItemOrder.Secondary)
(secondaries = secondaries ?? new List<UIBarButtonItem>()).Add(item.ToUIBarButtonItem(true));
else
(primaries = primaries ?? new List<UIBarButtonItem>()).Add(item.ToUIBarButtonItem());
}
if (primaries != null)
primaries.Reverse();
NavigationItem.SetRightBarButtonItems(primaries == null ? new UIBarButtonItem[0] : primaries.ToArray(), false);
ToolbarItems = secondaries == null ? new UIBarButtonItem[0] : secondaries.ToArray();
NavigationRenderer n;
if (_navigation.TryGetTarget(out n))
n.UpdateToolBarVisible();
}
public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
{
IVisualElementRenderer childRenderer;
if (Child != null && (childRenderer = Platform.GetRenderer(Child)) != null)
return childRenderer.ViewController.GetSupportedInterfaceOrientations();
return base.GetSupportedInterfaceOrientations();
}
public override UIInterfaceOrientation PreferredInterfaceOrientationForPresentation()
{
IVisualElementRenderer childRenderer;
if (Child != null && (childRenderer = Platform.GetRenderer(Child)) != null)
return childRenderer.ViewController.PreferredInterfaceOrientationForPresentation();
return base.PreferredInterfaceOrientationForPresentation();
}
public override bool ShouldAutorotate()
{
IVisualElementRenderer childRenderer;
if (Child != null && (childRenderer = Platform.GetRenderer(Child)) != null)
return childRenderer.ViewController.ShouldAutorotate();
return base.ShouldAutorotate();
}
public override bool ShouldAutorotateToInterfaceOrientation(UIInterfaceOrientation toInterfaceOrientation)
{
IVisualElementRenderer childRenderer;
if (Child != null && (childRenderer = Platform.GetRenderer(Child)) != null)
return childRenderer.ViewController.ShouldAutorotateToInterfaceOrientation(toInterfaceOrientation);
return base.ShouldAutorotateToInterfaceOrientation(toInterfaceOrientation);
}
public override bool ShouldAutomaticallyForwardRotationMethods => true;
}
public override UIViewController ChildViewControllerForStatusBarHidden()
{
return (UIViewController)Platform.GetRenderer(Current);
}
void IEffectControlProvider.RegisterEffect(Effect effect)
{
VisualElementRenderer<VisualElement>.RegisterEffect(effect, View);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Microsoft.VisualStudio.Text.Differencing;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
public abstract class AbstractUserDiagnosticTest : AbstractCodeActionOrUserDiagnosticTest
{
internal abstract Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync(TestWorkspace workspace, string fixAllActionEquivalenceKey);
internal abstract Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(TestWorkspace workspace);
protected override async Task<IList<CodeAction>> GetCodeActionsWorkerAsync(TestWorkspace workspace, string fixAllActionEquivalenceKey)
{
var diagnostics = await GetDiagnosticAndFixAsync(workspace, fixAllActionEquivalenceKey);
return diagnostics?.Item2?.Fixes.Select(f => f.Action).ToList();
}
internal async Task<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixAsync(TestWorkspace workspace, string fixAllActionEquivalenceKey = null)
{
return (await GetDiagnosticAndFixesAsync(workspace, fixAllActionEquivalenceKey)).FirstOrDefault();
}
protected Document GetDocumentAndSelectSpan(TestWorkspace workspace, out TextSpan span)
{
var hostDocument = workspace.Documents.Single(d => d.SelectedSpans.Any());
span = hostDocument.SelectedSpans.Single();
return workspace.CurrentSolution.GetDocument(hostDocument.Id);
}
protected bool TryGetDocumentAndSelectSpan(TestWorkspace workspace, out Document document, out TextSpan span)
{
var hostDocument = workspace.Documents.FirstOrDefault(d => d.SelectedSpans.Any());
if (hostDocument == null)
{
document = null;
span = default(TextSpan);
return false;
}
span = hostDocument.SelectedSpans.Single();
document = workspace.CurrentSolution.GetDocument(hostDocument.Id);
return true;
}
protected Document GetDocumentAndAnnotatedSpan(TestWorkspace workspace, out string annotation, out TextSpan span)
{
var hostDocument = workspace.Documents.Single(d => d.AnnotatedSpans.Any());
var annotatedSpan = hostDocument.AnnotatedSpans.Single();
annotation = annotatedSpan.Key;
span = annotatedSpan.Value.Single();
return workspace.CurrentSolution.GetDocument(hostDocument.Id);
}
protected FixAllScope? GetFixAllScope(string annotation)
{
if (annotation == null)
{
return null;
}
switch (annotation)
{
case "FixAllInDocument":
return FixAllScope.Document;
case "FixAllInProject":
return FixAllScope.Project;
case "FixAllInSolution":
return FixAllScope.Solution;
case "FixAllInSelection":
return FixAllScope.Custom;
}
throw new InvalidProgramException("Incorrect FixAll annotation in test");
}
internal async Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync(
IEnumerable<Diagnostic> diagnostics,
DiagnosticAnalyzer provider,
CodeFixProvider fixer,
TestDiagnosticAnalyzerDriver testDriver,
Document document,
TextSpan span,
string annotation,
string fixAllActionId)
{
if (diagnostics.IsEmpty())
{
return SpecializedCollections.EmptyEnumerable<Tuple<Diagnostic, CodeFixCollection>>();
}
FixAllScope? scope = GetFixAllScope(annotation);
return await GetDiagnosticAndFixesAsync(diagnostics, provider, fixer, testDriver, document, span, scope, fixAllActionId);
}
private async Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync(
IEnumerable<Diagnostic> diagnostics,
DiagnosticAnalyzer provider,
CodeFixProvider fixer,
TestDiagnosticAnalyzerDriver testDriver,
Document document,
TextSpan span,
FixAllScope? scope,
string fixAllActionId)
{
Assert.NotEmpty(diagnostics);
var result = new List<Tuple<Diagnostic, CodeFixCollection>>();
if (scope == null)
{
// Simple code fix.
foreach (var diagnostic in diagnostics)
{
var fixes = new List<CodeFix>();
var context = new CodeFixContext(document, diagnostic, (a, d) => fixes.Add(new CodeFix(document.Project, a, d)), CancellationToken.None);
await fixer.RegisterCodeFixesAsync(context);
if (fixes.Any())
{
var codeFix = new CodeFixCollection(fixer, diagnostic.Location.SourceSpan, fixes);
result.Add(Tuple.Create(diagnostic, codeFix));
}
}
}
else
{
// Fix all fix.
var fixAllProvider = fixer.GetFixAllProvider();
Assert.NotNull(fixAllProvider);
var fixAllContext = GetFixAllContext(diagnostics, provider, fixer, testDriver, document, scope.Value, fixAllActionId);
var fixAllFix = await fixAllProvider.GetFixAsync(fixAllContext);
if (fixAllFix != null)
{
// Same fix applies to each diagnostic in scope.
foreach (var diagnostic in diagnostics)
{
var diagnosticSpan = diagnostic.Location.IsInSource ? diagnostic.Location.SourceSpan : default(TextSpan);
var codeFix = new CodeFixCollection(fixAllProvider, diagnosticSpan, ImmutableArray.Create(new CodeFix(document.Project, fixAllFix, diagnostic)));
result.Add(Tuple.Create(diagnostic, codeFix));
}
}
}
return result;
}
private static FixAllContext GetFixAllContext(
IEnumerable<Diagnostic> diagnostics,
DiagnosticAnalyzer provider,
CodeFixProvider fixer,
TestDiagnosticAnalyzerDriver testDriver,
Document document,
FixAllScope scope,
string fixAllActionId)
{
Assert.NotEmpty(diagnostics);
if (scope == FixAllScope.Custom)
{
// Bulk fixing diagnostics in selected scope.
var diagnosticsToFix = ImmutableDictionary.CreateRange(SpecializedCollections.SingletonEnumerable(KeyValuePair.Create(document, diagnostics.ToImmutableArray())));
return FixMultipleContext.Create(diagnosticsToFix, fixer, fixAllActionId, CancellationToken.None);
}
var diagnostic = diagnostics.First();
Func<Document, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getDocumentDiagnosticsAsync =
async (d, diagIds, c) =>
{
var root = await d.GetSyntaxRootAsync();
var diags = await testDriver.GetDocumentDiagnosticsAsync(provider, d, root.FullSpan);
diags = diags.Where(diag => diagIds.Contains(diag.Id));
return diags;
};
Func<Project, bool, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getProjectDiagnosticsAsync =
async (p, includeAllDocumentDiagnostics, diagIds, c) =>
{
var diags = includeAllDocumentDiagnostics
? await testDriver.GetAllDiagnosticsAsync(provider, p)
: await testDriver.GetProjectDiagnosticsAsync(provider, p);
diags = diags.Where(diag => diagIds.Contains(diag.Id));
return diags;
};
var diagnosticIds = ImmutableHashSet.Create(diagnostic.Id);
var fixAllDiagnosticProvider = new FixAllCodeActionContext.FixAllDiagnosticProvider(diagnosticIds, getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync);
return diagnostic.Location.IsInSource
? new FixAllContext(document, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider, CancellationToken.None)
: new FixAllContext(document.Project, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider, CancellationToken.None);
}
protected async Task TestEquivalenceKeyAsync(string initialMarkup, string equivalenceKey)
{
using (var workspace = await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions: null, compilationOptions: null))
{
var diagnosticAndFix = await GetDiagnosticAndFixAsync(workspace);
Assert.Equal(equivalenceKey, diagnosticAndFix.Item2.Fixes.ElementAt(index: 0).Action.EquivalenceKey);
}
}
protected async Task TestActionCountInAllFixesAsync(
string initialMarkup,
int count,
ParseOptions parseOptions = null, CompilationOptions compilationOptions = null)
{
using (var workspace = await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions))
{
var diagnosticAndFix = await GetDiagnosticAndFixesAsync(workspace, null);
var diagnosticCount = diagnosticAndFix.Select(x => x.Item2.Fixes.Count()).Sum();
Assert.Equal(count, diagnosticCount);
}
}
protected async Task TestSpansAsync(
string initialMarkup, string expectedMarkup,
int index = 0,
ParseOptions parseOptions = null, CompilationOptions compilationOptions = null,
string diagnosticId = null, string fixAllActionEquivalenceId = null)
{
IList<TextSpan> spansList;
string unused;
MarkupTestFile.GetSpans(expectedMarkup, out unused, out spansList);
var expectedTextSpans = spansList.ToSet();
using (var workspace = await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions))
{
ISet<TextSpan> actualTextSpans;
if (diagnosticId == null)
{
var diagnosticsAndFixes = await GetDiagnosticAndFixesAsync(workspace, fixAllActionEquivalenceId);
var diagnostics = diagnosticsAndFixes.Select(t => t.Item1);
actualTextSpans = diagnostics.Select(d => d.Location.SourceSpan).ToSet();
}
else
{
var diagnostics = await GetDiagnosticsAsync(workspace);
actualTextSpans = diagnostics.Where(d => d.Id == diagnosticId).Select(d => d.Location.SourceSpan).ToSet();
}
Assert.True(expectedTextSpans.SetEquals(actualTextSpans));
}
}
protected async Task TestAddDocument(
string initialMarkup, string expectedMarkup,
IList<string> expectedContainers,
string expectedDocumentName,
int index = 0,
bool compareTokens = true, bool isLine = true)
{
await TestAddDocument(initialMarkup, expectedMarkup, index, expectedContainers, expectedDocumentName, null, null, compareTokens, isLine);
await TestAddDocument(initialMarkup, expectedMarkup, index, expectedContainers, expectedDocumentName, GetScriptOptions(), null, compareTokens, isLine);
}
private async Task TestAddDocument(
string initialMarkup, string expectedMarkup,
int index,
IList<string> expectedContainers,
string expectedDocumentName,
ParseOptions parseOptions, CompilationOptions compilationOptions,
bool compareTokens, bool isLine)
{
using (var workspace = isLine
? await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions)
: await TestWorkspace.CreateAsync(initialMarkup))
{
var codeActions = await GetCodeActionsAsync(workspace, fixAllActionEquivalenceKey: null);
await TestAddDocument(workspace, expectedMarkup, index, expectedContainers, expectedDocumentName,
codeActions, compareTokens);
}
}
private async Task TestAddDocument(
TestWorkspace workspace,
string expectedMarkup,
int index,
IList<string> expectedFolders,
string expectedDocumentName,
IList<CodeAction> actions,
bool compareTokens)
{
var operations = await VerifyInputsAndGetOperationsAsync(index, actions);
await TestAddDocument(
workspace,
expectedMarkup,
operations,
hasProjectChange: false,
modifiedProjectId: null,
expectedFolders: expectedFolders,
expectedDocumentName: expectedDocumentName,
compareTokens: compareTokens);
}
private async Task<Tuple<Solution, Solution>> TestAddDocument(
TestWorkspace workspace,
string expected,
IEnumerable<CodeActionOperation> operations,
bool hasProjectChange,
ProjectId modifiedProjectId,
IList<string> expectedFolders,
string expectedDocumentName,
bool compareTokens)
{
var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
var oldSolution = appliedChanges.Item1;
var newSolution = appliedChanges.Item2;
Document addedDocument = null;
if (!hasProjectChange)
{
addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution);
}
else
{
Assert.NotNull(modifiedProjectId);
addedDocument = newSolution.GetProject(modifiedProjectId).Documents.SingleOrDefault(doc => doc.Name == expectedDocumentName);
}
Assert.NotNull(addedDocument);
AssertEx.Equal(expectedFolders, addedDocument.Folders);
Assert.Equal(expectedDocumentName, addedDocument.Name);
if (compareTokens)
{
TokenUtilities.AssertTokensEqual(
expected, (await addedDocument.GetTextAsync()).ToString(), GetLanguage());
}
else
{
Assert.Equal(expected, (await addedDocument.GetTextAsync()).ToString());
}
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
if (!hasProjectChange)
{
// If there is just one document change then we expect the preview to be a WpfTextView
var content = (await editHandler.GetPreviews(workspace, operations, CancellationToken.None).GetPreviewsAsync())[0];
var diffView = content as IWpfDifferenceViewer;
Assert.NotNull(diffView);
diffView.Close();
}
else
{
// If there are more changes than just the document we need to browse all the changes and get the document change
var contents = editHandler.GetPreviews(workspace, operations, CancellationToken.None);
bool hasPreview = false;
var previews = await contents.GetPreviewsAsync();
if (previews != null)
{
foreach (var preview in previews)
{
if (preview != null)
{
var diffView = preview as IWpfDifferenceViewer;
if (diffView != null)
{
hasPreview = true;
diffView.Close();
break;
}
}
}
}
Assert.True(hasPreview);
}
return Tuple.Create(oldSolution, newSolution);
}
internal async Task TestWithMockedGenerateTypeDialog(
string initial,
string languageName,
string typeName,
string expected = null,
bool isLine = true,
bool isMissing = false,
Accessibility accessibility = Accessibility.NotApplicable,
TypeKind typeKind = TypeKind.Class,
string projectName = null,
bool isNewFile = false,
string existingFilename = null,
IList<string> newFileFolderContainers = null,
string fullFilePath = null,
string newFileName = null,
string assertClassName = null,
bool checkIfUsingsIncluded = false,
bool checkIfUsingsNotIncluded = false,
string expectedTextWithUsings = null,
string defaultNamespace = "",
bool areFoldersValidIdentifiers = true,
GenerateTypeDialogOptions assertGenerateTypeDialogOptions = null,
IList<TypeKindOptions> assertTypeKindPresent = null,
IList<TypeKindOptions> assertTypeKindAbsent = null,
bool isCancelled = false)
{
using (var testState = await GenerateTypeTestState.CreateAsync(initial, isLine, projectName, typeName, existingFilename, languageName))
{
// Initialize the viewModel values
testState.TestGenerateTypeOptionsService.SetGenerateTypeOptions(
accessibility: accessibility,
typeKind: typeKind,
typeName: testState.TypeName,
project: testState.ProjectToBeModified,
isNewFile: isNewFile,
newFileName: newFileName,
folders: newFileFolderContainers,
fullFilePath: fullFilePath,
existingDocument: testState.ExistingDocument,
areFoldersValidIdentifiers: areFoldersValidIdentifiers,
isCancelled: isCancelled);
testState.TestProjectManagementService.SetDefaultNamespace(
defaultNamespace: defaultNamespace);
var diagnosticsAndFixes = await GetDiagnosticAndFixesAsync(testState.Workspace, null);
var generateTypeDiagFixes = diagnosticsAndFixes.SingleOrDefault(df => GenerateTypeTestState.FixIds.Contains(df.Item1.Id));
if (isMissing)
{
Assert.Null(generateTypeDiagFixes);
return;
}
var fixes = generateTypeDiagFixes.Item2.Fixes;
Assert.NotNull(fixes);
var fixActions = MassageActions(fixes.Select(f => f.Action).ToList());
Assert.NotNull(fixActions);
// Since the dialog option is always fed as the last CodeAction
var index = fixActions.Count() - 1;
var action = fixActions.ElementAt(index);
Assert.Equal(action.Title, FeaturesResources.GenerateNewType);
var operations = await action.GetOperationsAsync(CancellationToken.None);
Tuple<Solution, Solution> oldSolutionAndNewSolution = null;
if (!isNewFile)
{
oldSolutionAndNewSolution = await TestOperationsAsync(
testState.Workspace, expected, operations,
conflictSpans: null, renameSpans: null, warningSpans: null,
compareTokens: false, expectedChangedDocumentId: testState.ExistingDocument.Id);
}
else
{
oldSolutionAndNewSolution = await TestAddDocument(
testState.Workspace,
expected,
operations,
projectName != null,
testState.ProjectToBeModified.Id,
newFileFolderContainers,
newFileName,
compareTokens: false);
}
if (checkIfUsingsIncluded)
{
Assert.NotNull(expectedTextWithUsings);
await TestOperationsAsync(testState.Workspace, expectedTextWithUsings, operations,
conflictSpans: null, renameSpans: null, warningSpans: null, compareTokens: false,
expectedChangedDocumentId: testState.InvocationDocument.Id);
}
if (checkIfUsingsNotIncluded)
{
var oldSolution = oldSolutionAndNewSolution.Item1;
var newSolution = oldSolutionAndNewSolution.Item2;
var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution);
Assert.False(changedDocumentIds.Contains(testState.InvocationDocument.Id));
}
// Added into a different project than the triggering project
if (projectName != null)
{
var appliedChanges = ApplyOperationsAndGetSolution(testState.Workspace, operations);
var newSolution = appliedChanges.Item2;
var triggeredProject = newSolution.GetProject(testState.TriggeredProject.Id);
// Make sure the Project reference is present
Assert.True(triggeredProject.ProjectReferences.Any(pr => pr.ProjectId == testState.ProjectToBeModified.Id));
}
// Assert Option Calculation
if (assertClassName != null)
{
Assert.True(assertClassName == testState.TestGenerateTypeOptionsService.ClassName);
}
if (assertGenerateTypeDialogOptions != null || assertTypeKindPresent != null || assertTypeKindAbsent != null)
{
var generateTypeDialogOptions = testState.TestGenerateTypeOptionsService.GenerateTypeDialogOptions;
if (assertGenerateTypeDialogOptions != null)
{
Assert.True(assertGenerateTypeDialogOptions.IsPublicOnlyAccessibility == generateTypeDialogOptions.IsPublicOnlyAccessibility);
Assert.True(assertGenerateTypeDialogOptions.TypeKindOptions == generateTypeDialogOptions.TypeKindOptions);
Assert.True(assertGenerateTypeDialogOptions.IsAttribute == generateTypeDialogOptions.IsAttribute);
}
if (assertTypeKindPresent != null)
{
foreach (var typeKindPresentEach in assertTypeKindPresent)
{
Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) != 0);
}
}
if (assertTypeKindAbsent != null)
{
foreach (var typeKindPresentEach in assertTypeKindAbsent)
{
Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) == 0);
}
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using IxMilia.Dxf.Entities;
using IxMilia.Dxf.Sections;
using Xunit;
namespace IxMilia.Dxf.Test
{
public class HeaderTests : AbstractDxfTests
{
[Fact]
public void SpecificHeaderValuesTest()
{
var file = Section("HEADER",
(9, "$ACADMAINTVER"), (70, 16),
(9, "$ACADVER"), (1, "AC1012"),
(9, "$ANGBASE"), (50, 55.0),
(9, "$ANGDIR"), (70, 1),
(9, "$ATTMODE"), (70, 1),
(9, "$AUNITS"), (70, 3),
(9, "$AUPREC"), (70, 7),
(9, "$CLAYER"), (8, "<current layer>"),
(9, "$LUNITS"), (70, 6),
(9, "$LUPREC"), (70, 7)
);
Assert.Equal(16, file.Header.MaintenanceVersion);
Assert.Equal(DxfAcadVersion.R13, file.Header.Version);
Assert.Equal(55.0, file.Header.AngleZeroDirection);
Assert.Equal(DxfAngleDirection.Clockwise, file.Header.AngleDirection);
Assert.Equal(DxfAttributeVisibility.Normal, file.Header.AttributeVisibility);
Assert.Equal(DxfAngleFormat.Radians, file.Header.AngleUnitFormat);
Assert.Equal(7, file.Header.AngleUnitPrecision);
Assert.Equal("<current layer>", file.Header.CurrentLayer);
Assert.Equal(DxfUnitFormat.Architectural, file.Header.UnitFormat);
Assert.Equal(7, file.Header.UnitPrecision);
}
[Fact]
public void DateConversionTest()
{
// from Autodesk spec: 2451544.91568287 = December 31, 1999, 9:58:35 pm.
// verify reading
Assert.True(DxfTextReader.TryParseDoubleValue("2451544.91568287", out var dateAsDouble));
var date = DxfCommonConverters.DateDouble(dateAsDouble);
Assert.Equal(new DateTime(1999, 12, 31, 21, 58, 35), date);
// verify writing
dateAsDouble = DxfCommonConverters.DateDouble(date);
var dateAsString = DxfWriter.DoubleAsString(dateAsDouble);
Assert.Equal("2451544.91568287", dateAsString);
}
[Fact]
public void ReadLayerTableTest()
{
var file = Section("TABLES",
(0, "TABLE"),
(2, "LAYER"),
(0, "LAYER"),
(2, "a"),
(62, 12),
(0, "LAYER"),
(102, "{APP_NAME"),
(1, "foo"),
(2, "bar"),
(102, "}"),
(2, "b"),
(62, 13),
(0, "ENDTAB")
);
var layers = file.Layers;
Assert.Equal(2, layers.Count);
Assert.Equal("a", layers[0].Name);
Assert.Equal(12, layers[0].Color.RawValue);
Assert.Equal("b", layers[1].Name);
Assert.Equal(13, layers[1].Color.RawValue);
var group = layers[1].ExtensionDataGroups.Single();
Assert.Equal("APP_NAME", group.GroupName);
Assert.Equal(2, group.Items.Count);
Assert.Equal(new DxfCodePair(1, "foo"), group.Items[0]);
Assert.Equal(new DxfCodePair(2, "bar"), group.Items[1]);
}
[Fact]
public void WriteLayersTableTest()
{
var layer = new DxfLayer("layer-name");
layer.ExtensionDataGroups.Add(new DxfCodePairGroup("APP_NAME", new IDxfCodePairOrGroup[]
{
new DxfCodePair(1, "foo"),
new DxfCodePair(2, "bar"),
}));
var file = new DxfFile();
file.Layers.Add(layer);
VerifyFileContains(file,
(0, "LAYER"),
(5, "#"),
(102, "{APP_NAME"),
(1, "foo"),
(2, "bar"),
(102, "}")
);
}
[Fact]
public void ViewPortTableTest()
{
var file = Section("TABLES",
(0, "TABLE"),
(2, "VPORT"),
(0, "VPORT"), // empty vport
(0, "VPORT"), // vport with values
(2, "vport-2"), // name
(10, 11.0), // lower left
(20, 22.0),
(11, 33.0), // upper right
(21, 44.0),
(12, 55.0), // view center
(22, 66.0),
(13, 77.0), // snap base
(23, 88.0),
(14, 99.0), // snap spacing
(24, 12.0),
(15, 13.0), // grid spacing
(25, 14.0),
(16, 15.0), // view direction
(26, 16.0),
(36, 17.0),
(17, 18.0), // target view point
(27, 19.0),
(37, 20.0),
(40, 21.0), // view height
(41, 22.0), // view port aspect ratio
(42, 23.0), // lens length
(43, 24.0), // front clipping plane
(44, 25.0), // back clipping plane
(50, 26.0), // snap rotation angle
(51, 27.0), // view twist angle
(0, "ENDTAB")
);
var viewPorts = file.ViewPorts;
Assert.Equal(2, viewPorts.Count);
// defaults
Assert.Null(viewPorts[0].Name);
Assert.Equal(0.0, viewPorts[0].LowerLeft.X);
Assert.Equal(0.0, viewPorts[0].LowerLeft.Y);
Assert.Equal(1.0, viewPorts[0].UpperRight.X);
Assert.Equal(1.0, viewPorts[0].UpperRight.Y);
Assert.Equal(0.0, viewPorts[0].ViewCenter.X);
Assert.Equal(0.0, viewPorts[0].ViewCenter.Y);
Assert.Equal(0.0, viewPorts[0].SnapBasePoint.X);
Assert.Equal(0.0, viewPorts[0].SnapBasePoint.Y);
Assert.Equal(1.0, viewPorts[0].SnapSpacing.X);
Assert.Equal(1.0, viewPorts[0].SnapSpacing.Y);
Assert.Equal(1.0, viewPorts[0].GridSpacing.X);
Assert.Equal(1.0, viewPorts[0].GridSpacing.Y);
Assert.Equal(0.0, viewPorts[0].ViewDirection.X);
Assert.Equal(0.0, viewPorts[0].ViewDirection.Y);
Assert.Equal(1.0, viewPorts[0].ViewDirection.Z);
Assert.Equal(0.0, viewPorts[0].TargetViewPoint.X);
Assert.Equal(0.0, viewPorts[0].TargetViewPoint.Y);
Assert.Equal(0.0, viewPorts[0].TargetViewPoint.Z);
Assert.Equal(1.0, viewPorts[0].ViewHeight);
Assert.Equal(1.0, viewPorts[0].ViewPortAspectRatio);
Assert.Equal(50.0, viewPorts[0].LensLength);
Assert.Equal(0.0, viewPorts[0].FrontClippingPlane);
Assert.Equal(0.0, viewPorts[0].BackClippingPlane);
Assert.Equal(0.0, viewPorts[0].SnapRotationAngle);
Assert.Equal(0.0, viewPorts[0].ViewTwistAngle);
// specifics
Assert.Equal("vport-2", viewPorts[1].Name);
Assert.Equal(11.0, viewPorts[1].LowerLeft.X);
Assert.Equal(22.0, viewPorts[1].LowerLeft.Y);
Assert.Equal(33.0, viewPorts[1].UpperRight.X);
Assert.Equal(44.0, viewPorts[1].UpperRight.Y);
Assert.Equal(55.0, viewPorts[1].ViewCenter.X);
Assert.Equal(66.0, viewPorts[1].ViewCenter.Y);
Assert.Equal(77.0, viewPorts[1].SnapBasePoint.X);
Assert.Equal(88.0, viewPorts[1].SnapBasePoint.Y);
Assert.Equal(99.0, viewPorts[1].SnapSpacing.X);
Assert.Equal(12.0, viewPorts[1].SnapSpacing.Y);
Assert.Equal(13.0, viewPorts[1].GridSpacing.X);
Assert.Equal(14.0, viewPorts[1].GridSpacing.Y);
Assert.Equal(15.0, viewPorts[1].ViewDirection.X);
Assert.Equal(16.0, viewPorts[1].ViewDirection.Y);
Assert.Equal(17.0, viewPorts[1].ViewDirection.Z);
Assert.Equal(18.0, viewPorts[1].TargetViewPoint.X);
Assert.Equal(19.0, viewPorts[1].TargetViewPoint.Y);
Assert.Equal(20.0, viewPorts[1].TargetViewPoint.Z);
Assert.Equal(21.0, viewPorts[1].ViewHeight);
Assert.Equal(22.0, viewPorts[1].ViewPortAspectRatio);
Assert.Equal(23.0, viewPorts[1].LensLength);
Assert.Equal(24.0, viewPorts[1].FrontClippingPlane);
Assert.Equal(25.0, viewPorts[1].BackClippingPlane);
Assert.Equal(26.0, viewPorts[1].SnapRotationAngle);
Assert.Equal(27.0, viewPorts[1].ViewTwistAngle);
}
[Fact]
public void ReadAlternateVersionTest()
{
var file = Section("HEADER",
(9, "$ACADVER"), (1, "15.0S")
);
Assert.Equal(DxfAcadVersion.R2000, file.Header.Version);
Assert.True(file.Header.IsRestrictedVersion);
}
[Fact]
public void ReadEmptyFingerPrintGuidTest()
{
var file = Section("HEADER",
(9, "$FINGERPRINTGUID"), (2, ""),
(9, "$ACADVER"), (1, "AC1012")
);
Assert.Equal(Guid.Empty, file.Header.FingerprintGuid);
}
[Fact]
public void ReadAlternateMaintenenceVersionTest()
{
// traditional short value
var file = Section("HEADER",
(9, "$ACADMAINTVER"), (70, 42)
);
Assert.Equal(42, file.Header.MaintenanceVersion);
// alternate long value
file = Section("HEADER",
(9, "$ACADMAINTVER"), (90, 42)
);
Assert.Equal(42, file.Header.MaintenanceVersion);
}
[Fact]
public void WriteAppropriateMaintenenceVersionTest()
{
var file = new DxfFile();
file.Header.MaintenanceVersion = 42;
// < R2018 writes code 70
file.Header.Version = DxfAcadVersion.R2013;
VerifyFileContains(file,
DxfSectionType.Header,
(9, "$ACADMAINTVER"),
(70, 42)
);
// >= R2018 writes code 90
file.Header.Version = DxfAcadVersion.R2018;
VerifyFileContains(file,
DxfSectionType.Header,
(9, "$ACADMAINTVER"),
(90, 42)
);
}
[Fact]
public void WriteDefaultHeaderValuesTest()
{
VerifyFileContains(new DxfFile(),
DxfSectionType.Header,
(9, "$DIMGAP"), (40, 0.09)
);
}
[Fact]
public void WriteSpecificHeaderValuesTest()
{
var file = new DxfFile();
file.Header.DimensionLineGap = 11.0;
VerifyFileContains(file,
DxfSectionType.Header,
(9, "$DIMGAP"), (40, 11.0)
);
}
[Fact]
public void WriteLayersTest()
{
var file = new DxfFile();
file.Layers.Add(new DxfLayer("default"));
VerifyFileContains(file,
DxfSectionType.Tables,
(0, "LAYER"),
(5, "#"),
(100, "AcDbSymbolTableRecord"),
(2, "default"),
(70, 0),
(62, 7)
);
}
[Fact]
public void WriteViewportTest()
{
var file = new DxfFile();
file.ViewPorts.Add(new DxfViewPort());
VerifyFileContains(file,
DxfSectionType.Tables,
(0, "VPORT"),
(5, "#"),
(100, "AcDbSymbolTableRecord"),
(2, ""),
(70, 0),
(10, 0.0),
(20, 0.0),
(11, 1.0),
(21, 1.0),
(12, 0.0),
(22, 0.0),
(13, 0.0),
(23, 0.0),
(14, 1.0),
(24, 1.0),
(15, 1.0),
(25, 1.0),
(16, 0.0),
(26, 0.0),
(36, 1.0),
(17, 0.0),
(27, 0.0),
(37, 0.0),
(40, 1.0),
(41, 1.0),
(42, 50.0),
(43, 0.0),
(44, 0.0),
(50, 0.0),
(51, 0.0),
(71, 0),
(72, 1000),
(73, 1),
(74, 3),
(75, 0),
(76, 0),
(77, 0),
(78, 0)
);
}
[Fact]
public void WriteAndReadTypeDefaultsTest()
{
var file = new DxfFile();
SetAllPropertiesToDefault(file.Header);
// write each version of the header with default values
foreach (var version in new[] { DxfAcadVersion.R10, DxfAcadVersion.R11, DxfAcadVersion.R12, DxfAcadVersion.R13, DxfAcadVersion.R14, DxfAcadVersion.R2000, DxfAcadVersion.R2004, DxfAcadVersion.R2007, DxfAcadVersion.R2010, DxfAcadVersion.R2013 })
{
file.Header.Version = version;
using (var ms = new MemoryStream())
{
file.Save(ms);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
// ensure the header can be read back in, too
var file2 = DxfFile.Load(ms);
}
}
}
[Fact]
public void WriteAlternateVersionTest()
{
var file = new DxfFile();
file.Header.Version = DxfAcadVersion.R2000;
file.Header.IsRestrictedVersion = true;
VerifyFileContains(file,
(9, "$ACADVER"), (1, "AC1015S")
);
}
[Fact]
public void HeaderVariablesMatchOfficialR10Order()
{
var expectedOrderText = @"
$ACADVER
$INSBASE
$EXTMIN
$EXTMAX
$LIMMIN
$LIMMAX
$ORTHOMODE
$REGENMODE
$FILLMODE
$QTEXTMODE
$MIRRTEXT
$DRAGMODE
$LTSCALE
$OSMODE
$ATTMODE
$TEXTSIZE
$TRACEWID
$TEXTSTYLE
$CLAYER
$CELTYPE
$CECOLOR
$DIMSCALE
$DIMASZ
$DIMEXO
$DIMDLI
$DIMRND
$DIMDLE
$DIMEXE
$DIMTP
$DIMTM
$DIMTXT
$DIMCEN
$DIMTSZ
$DIMTOL
$DIMLIM
$DIMTIH
$DIMTOH
$DIMTAD
$DIMZIN
$DIMBLK
$DIMASO
$DIMSHO
$DIMPOST
$DIMAPOST
$DIMALT
$DIMALTD
$DIMALTF
$DIMLFAC
$DIMTOFL
$DIMTVP
$DIMTIX
$DIMSOXD
$DIMSAH
$DIMBLK1
$DIMBLK2
$DIMSTYLE
$LUNITS
$LUPREC
$SKETCHINC
$FILLETRAD
$AUNITS
$AUPREC
$MENU
$ELEVATION
$THICKNESS
$LIMCHECK
$BLIPMODE
$CHAMFERA
$CHAMFERB
$SKPOLY
$TDCREATE
$TDUPDATE
$TDINDWG
$TDUSRTIMER
$USRTIMER
$ANGBASE
$ANGDIR
$PDMODE
$PDSIZE
$PLINEWID
$COORDS
$SPLFRAME
$SPLINETYPE
$SPLINESEGS
$ATTDIA
$ATTREQ
$HANDLING
$HANDSEED
$SURFTAB1
$SURFTAB2
$SURFTYPE
$SURFU
$SURFV
$UCSNAME
$UCSORG
$UCSXDIR
$UCSYDIR
$USERI1
$USERI2
$USERI3
$USERI4
$USERI5
$USERR1
$USERR2
$USERR3
$USERR4
$USERR5
$WORLDVIEW
$AXISMODE
$AXISUNIT
$FASTZOOM
$GRIDMODE
$GRIDUNIT
$SNAPANG
$SNAPBASE
$SNAPISOPAIR
$SNAPMODE
$SNAPSTYLE
$SNAPUNIT
$VIEWCTR
$VIEWDIR
$VIEWSIZE";
TestHeaderOrder(expectedOrderText, DxfAcadVersion.R10);
}
[Fact]
public void HeaderVariablesMatchOfficialR12Order()
{
var expectedOrderText = @"
$ACADVER
$INSBASE
$EXTMIN
$EXTMAX
$LIMMIN
$LIMMAX
$ORTHOMODE
$REGENMODE
$FILLMODE
$QTEXTMODE
$MIRRTEXT
$DRAGMODE
$LTSCALE
$OSMODE
$ATTMODE
$TEXTSIZE
$TRACEWID
$TEXTSTYLE
$CLAYER
$CELTYPE
$CECOLOR
$DIMSCALE
$DIMASZ
$DIMEXO
$DIMDLI
$DIMRND
$DIMDLE
$DIMEXE
$DIMTP
$DIMTM
$DIMTXT
$DIMCEN
$DIMTSZ
$DIMTOL
$DIMLIM
$DIMTIH
$DIMTOH
$DIMSE1
$DIMSE2
$DIMTAD
$DIMZIN
$DIMBLK
$DIMASO
$DIMSHO
$DIMPOST
$DIMAPOST
$DIMALT
$DIMALTD
$DIMALTF
$DIMLFAC
$DIMTOFL
$DIMTVP
$DIMTIX
$DIMSOXD
$DIMSAH
$DIMBLK1
$DIMBLK2
$DIMSTYLE
$DIMCLRD
$DIMCLRE
$DIMCLRT
$DIMTFAC
$DIMGAP
$LUNITS
$LUPREC
$SKETCHINC
$FILLETRAD
$AUNITS
$AUPREC
$MENU
$ELEVATION
$PELEVATION
$THICKNESS
$LIMCHECK
$BLIPMODE
$CHAMFERA
$CHAMFERB
$SKPOLY
$TDCREATE
$TDUPDATE
$TDINDWG
$TDUSRTIMER
$USRTIMER
$ANGBASE
$ANGDIR
$PDMODE
$PDSIZE
$PLINEWID
$COORDS
$SPLFRAME
$SPLINETYPE
$SPLINESEGS
$ATTDIA
$ATTREQ
$HANDLING
$HANDSEED
$SURFTAB1
$SURFTAB2
$SURFTYPE
$SURFU
$SURFV
$UCSNAME
$UCSORG
$UCSXDIR
$UCSYDIR
$PUCSNAME
$PUCSORG
$PUCSXDIR
$PUCSYDIR
$USERI1
$USERI2
$USERI3
$USERI4
$USERI5
$USERR1
$USERR2
$USERR3
$USERR4
$USERR5
$WORLDVIEW
$SHADEDGE
$SHADEDIF
$TILEMODE
$MAXACTVP
$PLIMCHECK
$PEXTMIN
$PEXTMAX
$PLIMMIN
$PLIMMAX
$UNITMODE
$VISRETAIN
$PLINEGEN
$PSLTSCALE";
TestHeaderOrder(expectedOrderText, DxfAcadVersion.R12);
}
[Fact]
public void HeaderVariablesMatchOfficialR2000Order()
{
var expectedOrderText = @"
$ACADVER
$ACADMAINTVER
$DWGCODEPAGE
$INSBASE
$EXTMIN
$EXTMAX
$LIMMIN
$LIMMAX
$ORTHOMODE
$REGENMODE
$FILLMODE
$QTEXTMODE
$MIRRTEXT
$LTSCALE
$ATTMODE
$TEXTSIZE
$TRACEWID
$TEXTSTYLE
$CLAYER
$CELTYPE
$CECOLOR
$CELTSCALE
$DISPSILH
$DIMSCALE
$DIMASZ
$DIMEXO
$DIMDLI
$DIMRND
$DIMDLE
$DIMEXE
$DIMTP
$DIMTM
$DIMTXT
$DIMCEN
$DIMTSZ
$DIMTOL
$DIMLIM
$DIMTIH
$DIMTOH
$DIMSE1
$DIMSE2
$DIMTAD
$DIMZIN
$DIMBLK
$DIMASO
$DIMSHO
$DIMPOST
$DIMAPOST
$DIMALT
$DIMALTD
$DIMALTF
$DIMLFAC
$DIMTOFL
$DIMTVP
$DIMTIX
$DIMSOXD
$DIMSAH
$DIMBLK1
$DIMBLK2
$DIMSTYLE
$DIMCLRD
$DIMCLRE
$DIMCLRT
$DIMTFAC
$DIMGAP
$DIMJUST
$DIMSD1
$DIMSD2
$DIMTOLJ
$DIMTZIN
$DIMALTZ
$DIMALTTZ
$DIMUPT
$DIMDEC
$DIMTDEC
$DIMALTU
$DIMALTTD
$DIMTXSTY
$DIMAUNIT
$DIMADEC
$DIMALTRND
$DIMAZIN
$DIMDSEP
$DIMATFIT
$DIMFRAC
$DIMLDRBLK
$DIMLUNIT
$DIMLWD
$DIMLWE
$DIMTMOVE
$LUNITS
$LUPREC
$SKETCHINC
$FILLETRAD
$AUNITS
$AUPREC
$MENU
$ELEVATION
$PELEVATION
$THICKNESS
$LIMCHECK
$CHAMFERA
$CHAMFERB
$CHAMFERC
$CHAMFERD
$SKPOLY
$TDCREATE
$TDUCREATE
$TDUPDATE
$TDUUPDATE
$TDINDWG
$TDUSRTIMER
$USRTIMER
$ANGBASE
$ANGDIR
$PDMODE
$PDSIZE
$PLINEWID
$SPLFRAME
$SPLINETYPE
$SPLINESEGS
$HANDSEED
$SURFTAB1
$SURFTAB2
$SURFTYPE
$SURFU
$SURFV
$UCSBASE
$UCSNAME
$UCSORG
$UCSXDIR
$UCSYDIR
$UCSORTHOREF
$UCSORTHOVIEW
$UCSORGTOP
$UCSORGBOTTOM
$UCSORGLEFT
$UCSORGRIGHT
$UCSORGFRONT
$UCSORGBACK
$PUCSBASE
$PUCSNAME
$PUCSORG
$PUCSXDIR
$PUCSYDIR
$PUCSORTHOREF
$PUCSORTHOVIEW
$PUCSORGTOP
$PUCSORGBOTTOM
$PUCSORGLEFT
$PUCSORGRIGHT
$PUCSORGFRONT
$PUCSORGBACK
$USERI1
$USERI2
$USERI3
$USERI4
$USERI5
$USERR1
$USERR2
$USERR3
$USERR4
$USERR5
$WORLDVIEW
$SHADEDGE
$SHADEDIF
$TILEMODE
$MAXACTVP
$PINSBASE
$PLIMCHECK
$PEXTMIN
$PEXTMAX
$PLIMMIN
$PLIMMAX
$UNITMODE
$VISRETAIN
$PLINEGEN
$PSLTSCALE
$TREEDEPTH
$CMLSTYLE
$CMLJUST
$CMLSCALE
$PROXYGRAPHICS
$MEASUREMENT
$CELWEIGHT
$ENDCAPS
$JOINSTYLE
$LWDISPLAY
$INSUNITS
$HYPERLINKBASE
$STYLESHEET
$XEDIT
$CEPSNTYPE
$PSTYLEMODE
$FINGERPRINTGUID
$VERSIONGUID
$EXTNAMES
$PSVPSCALE
$OLESTARTUP";
TestHeaderOrder(expectedOrderText, DxfAcadVersion.R2000);
}
[Fact]
public void HeaderVariablesMatchOfficialR2004Order()
{
var expectedOrderText = @"
$ACADVER
$ACADMAINTVER
$DWGCODEPAGE
$LASTSAVEDBY
$INSBASE
$EXTMIN
$EXTMAX
$LIMMIN
$LIMMAX
$ORTHOMODE
$REGENMODE
$FILLMODE
$QTEXTMODE
$MIRRTEXT
$LTSCALE
$ATTMODE
$TEXTSIZE
$TRACEWID
$TEXTSTYLE
$CLAYER
$CELTYPE
$CECOLOR
$CELTSCALE
$DISPSILH
$DIMSCALE
$DIMASZ
$DIMEXO
$DIMDLI
$DIMRND
$DIMDLE
$DIMEXE
$DIMTP
$DIMTM
$DIMTXT
$DIMCEN
$DIMTSZ
$DIMTOL
$DIMLIM
$DIMTIH
$DIMTOH
$DIMSE1
$DIMSE2
$DIMTAD
$DIMZIN
$DIMBLK
$DIMASO
$DIMSHO
$DIMPOST
$DIMAPOST
$DIMALT
$DIMALTD
$DIMALTF
$DIMLFAC
$DIMTOFL
$DIMTVP
$DIMTIX
$DIMSOXD
$DIMSAH
$DIMBLK1
$DIMBLK2
$DIMSTYLE
$DIMCLRD
$DIMCLRE
$DIMCLRT
$DIMTFAC
$DIMGAP
$DIMJUST
$DIMSD1
$DIMSD2
$DIMTOLJ
$DIMTZIN
$DIMALTZ
$DIMALTTZ
$DIMUPT
$DIMDEC
$DIMTDEC
$DIMALTU
$DIMALTTD
$DIMTXSTY
$DIMAUNIT
$DIMADEC
$DIMALTRND
$DIMAZIN
$DIMDSEP
$DIMATFIT
$DIMFRAC
$DIMLDRBLK
$DIMLUNIT
$DIMLWD
$DIMLWE
$DIMTMOVE
$LUNITS
$LUPREC
$SKETCHINC
$FILLETRAD
$AUNITS
$AUPREC
$MENU
$ELEVATION
$PELEVATION
$THICKNESS
$LIMCHECK
$CHAMFERA
$CHAMFERB
$CHAMFERC
$CHAMFERD
$SKPOLY
$TDCREATE
$TDUCREATE
$TDUPDATE
$TDUUPDATE
$TDINDWG
$TDUSRTIMER
$USRTIMER
$ANGBASE
$ANGDIR
$PDMODE
$PDSIZE
$PLINEWID
$SPLFRAME
$SPLINETYPE
$SPLINESEGS
$HANDSEED
$SURFTAB1
$SURFTAB2
$SURFTYPE
$SURFU
$SURFV
$UCSBASE
$UCSNAME
$UCSORG
$UCSXDIR
$UCSYDIR
$UCSORTHOREF
$UCSORTHOVIEW
$UCSORGTOP
$UCSORGBOTTOM
$UCSORGLEFT
$UCSORGRIGHT
$UCSORGFRONT
$UCSORGBACK
$PUCSBASE
$PUCSNAME
$PUCSORG
$PUCSXDIR
$PUCSYDIR
$PUCSORTHOREF
$PUCSORTHOVIEW
$PUCSORGTOP
$PUCSORGBOTTOM
$PUCSORGLEFT
$PUCSORGRIGHT
$PUCSORGFRONT
$PUCSORGBACK
$USERI1
$USERI2
$USERI3
$USERI4
$USERI5
$USERR1
$USERR2
$USERR3
$USERR4
$USERR5
$WORLDVIEW
$SHADEDGE
$SHADEDIF
$TILEMODE
$MAXACTVP
$PINSBASE
$PLIMCHECK
$PEXTMIN
$PEXTMAX
$PLIMMIN
$PLIMMAX
$UNITMODE
$VISRETAIN
$PLINEGEN
$PSLTSCALE
$TREEDEPTH
$CMLSTYLE
$CMLJUST
$CMLSCALE
$PROXYGRAPHICS
$MEASUREMENT
$CELWEIGHT
$ENDCAPS
$JOINSTYLE
$LWDISPLAY
$INSUNITS
$HYPERLINKBASE
$STYLESHEET
$XEDIT
$CEPSNTYPE
$PSTYLEMODE
$FINGERPRINTGUID
$VERSIONGUID
$EXTNAMES
$PSVPSCALE
$OLESTARTUP
$SORTENTS
$INDEXCTL
$HIDETEXT
$XCLIPFRAME
$HALOGAP
$OBSCOLOR
$OBSLTYPE
$INTERSECTIONDISPLAY
$INTERSECTIONCOLOR
$DIMASSOC
$PROJECTNAME";
TestHeaderOrder(expectedOrderText, DxfAcadVersion.R2004);
}
[Fact]
public void HeaderVariablesMatchOfficialR2007Order()
{
var expectedOrderText = @"
$ACADVER
$ACADMAINTVER
$DWGCODEPAGE
$LASTSAVEDBY
$INSBASE
$EXTMIN
$EXTMAX
$LIMMIN
$LIMMAX
$ORTHOMODE
$REGENMODE
$FILLMODE
$QTEXTMODE
$MIRRTEXT
$LTSCALE
$ATTMODE
$TEXTSIZE
$TRACEWID
$TEXTSTYLE
$CLAYER
$CELTYPE
$CECOLOR
$CELTSCALE
$DISPSILH
$DIMSCALE
$DIMASZ
$DIMEXO
$DIMDLI
$DIMRND
$DIMDLE
$DIMEXE
$DIMTP
$DIMTM
$DIMTXT
$DIMCEN
$DIMTSZ
$DIMTOL
$DIMLIM
$DIMTIH
$DIMTOH
$DIMSE1
$DIMSE2
$DIMTAD
$DIMZIN
$DIMBLK
$DIMASO
$DIMSHO
$DIMPOST
$DIMAPOST
$DIMALT
$DIMALTD
$DIMALTF
$DIMLFAC
$DIMTOFL
$DIMTVP
$DIMTIX
$DIMSOXD
$DIMSAH
$DIMBLK1
$DIMBLK2
$DIMSTYLE
$DIMCLRD
$DIMCLRE
$DIMCLRT
$DIMTFAC
$DIMGAP
$DIMJUST
$DIMSD1
$DIMSD2
$DIMTOLJ
$DIMTZIN
$DIMALTZ
$DIMALTTZ
$DIMUPT
$DIMDEC
$DIMTDEC
$DIMALTU
$DIMALTTD
$DIMTXSTY
$DIMAUNIT
$DIMADEC
$DIMALTRND
$DIMAZIN
$DIMDSEP
$DIMATFIT
$DIMFRAC
$DIMLDRBLK
$DIMLUNIT
$DIMLWD
$DIMLWE
$DIMTMOVE
$DIMFXL
$DIMFXLON
$DIMJOGANG
$DIMTFILL
$DIMTFILLCLR
$DIMARCSYM
$DIMLTYPE
$DIMLTEX1
$DIMLTEX2
$LUNITS
$LUPREC
$SKETCHINC
$FILLETRAD
$AUNITS
$AUPREC
$MENU
$ELEVATION
$PELEVATION
$THICKNESS
$LIMCHECK
$CHAMFERA
$CHAMFERB
$CHAMFERC
$CHAMFERD
$SKPOLY
$TDCREATE
$TDUCREATE
$TDUPDATE
$TDUUPDATE
$TDINDWG
$TDUSRTIMER
$USRTIMER
$ANGBASE
$ANGDIR
$PDMODE
$PDSIZE
$PLINEWID
$SPLFRAME
$SPLINETYPE
$SPLINESEGS
$HANDSEED
$SURFTAB1
$SURFTAB2
$SURFTYPE
$SURFU
$SURFV
$UCSBASE
$UCSNAME
$UCSORG
$UCSXDIR
$UCSYDIR
$UCSORTHOREF
$UCSORTHOVIEW
$UCSORGTOP
$UCSORGBOTTOM
$UCSORGLEFT
$UCSORGRIGHT
$UCSORGFRONT
$UCSORGBACK
$PUCSBASE
$PUCSNAME
$PUCSORG
$PUCSXDIR
$PUCSYDIR
$PUCSORTHOREF
$PUCSORTHOVIEW
$PUCSORGTOP
$PUCSORGBOTTOM
$PUCSORGLEFT
$PUCSORGRIGHT
$PUCSORGFRONT
$PUCSORGBACK
$USERI1
$USERI2
$USERI3
$USERI4
$USERI5
$USERR1
$USERR2
$USERR3
$USERR4
$USERR5
$WORLDVIEW
$SHADEDGE
$SHADEDIF
$TILEMODE
$MAXACTVP
$PINSBASE
$PLIMCHECK
$PEXTMIN
$PEXTMAX
$PLIMMIN
$PLIMMAX
$UNITMODE
$VISRETAIN
$PLINEGEN
$PSLTSCALE
$TREEDEPTH
$CMLSTYLE
$CMLJUST
$CMLSCALE
$PROXYGRAPHICS
$MEASUREMENT
$CELWEIGHT
$ENDCAPS
$JOINSTYLE
$LWDISPLAY
$INSUNITS
$HYPERLINKBASE
$STYLESHEET
$XEDIT
$CEPSNTYPE
$PSTYLEMODE
$FINGERPRINTGUID
$VERSIONGUID
$EXTNAMES
$PSVPSCALE
$OLESTARTUP
$SORTENTS
$INDEXCTL
$HIDETEXT
$XCLIPFRAME
$HALOGAP
$OBSCOLOR
$OBSLTYPE
$INTERSECTIONDISPLAY
$INTERSECTIONCOLOR
$DIMASSOC
$PROJECTNAME
$CAMERADISPLAY
$LENSLENGTH
$CAMERAHEIGHT
$STEPSPERSEC
$STEPSIZE
$3DDWFPREC
$PSOLWIDTH
$PSOLHEIGHT
$LOFTANG1
$LOFTANG2
$LOFTMAG1
$LOFTMAG2
$LOFTPARAM
$LOFTNORMALS
$LATITUDE
$LONGITUDE
$NORTHDIRECTION
$TIMEZONE
$LIGHTGLYPHDISPLAY
$TILEMODELIGHTSYNCH
$CMATERIAL
$SOLIDHIST
$SHOWHIST
$DWFFRAME
$DGNFRAME
$REALWORLDSCALE
$INTERFERECOLOR
$INTERFEREOBJVS
$INTERFEREVPVS
$CSHADOW
$SHADOWPLANELOCATION";
TestHeaderOrder(expectedOrderText, DxfAcadVersion.R2007);
}
[Fact]
public void HeaderVariablesMatchOfficialR2010Order()
{
var expectedOrderText = @"
$ACADVER
$ACADMAINTVER
$DWGCODEPAGE
$LASTSAVEDBY
$INSBASE
$EXTMIN
$EXTMAX
$LIMMIN
$LIMMAX
$ORTHOMODE
$REGENMODE
$FILLMODE
$QTEXTMODE
$MIRRTEXT
$LTSCALE
$ATTMODE
$TEXTSIZE
$TRACEWID
$TEXTSTYLE
$CLAYER
$CELTYPE
$CECOLOR
$CELTSCALE
$DISPSILH
$DIMSCALE
$DIMASZ
$DIMEXO
$DIMDLI
$DIMRND
$DIMDLE
$DIMEXE
$DIMTP
$DIMTM
$DIMTXT
$DIMCEN
$DIMTSZ
$DIMTOL
$DIMLIM
$DIMTIH
$DIMTOH
$DIMSE1
$DIMSE2
$DIMTAD
$DIMZIN
$DIMBLK
$DIMASO
$DIMSHO
$DIMPOST
$DIMAPOST
$DIMALT
$DIMALTD
$DIMALTF
$DIMLFAC
$DIMTOFL
$DIMTVP
$DIMTIX
$DIMSOXD
$DIMSAH
$DIMBLK1
$DIMBLK2
$DIMSTYLE
$DIMCLRD
$DIMCLRE
$DIMCLRT
$DIMTFAC
$DIMGAP
$DIMJUST
$DIMSD1
$DIMSD2
$DIMTOLJ
$DIMTZIN
$DIMALTZ
$DIMALTTZ
$DIMUPT
$DIMDEC
$DIMTDEC
$DIMALTU
$DIMALTTD
$DIMTXSTY
$DIMAUNIT
$DIMADEC
$DIMALTRND
$DIMAZIN
$DIMDSEP
$DIMATFIT
$DIMFRAC
$DIMLDRBLK
$DIMLUNIT
$DIMLWD
$DIMLWE
$DIMTMOVE
$DIMFXL
$DIMFXLON
$DIMJOGANG
$DIMTFILL
$DIMTFILLCLR
$DIMARCSYM
$DIMLTYPE
$DIMLTEX1
$DIMLTEX2
$DIMTXTDIRECTION
$LUNITS
$LUPREC
$SKETCHINC
$FILLETRAD
$AUNITS
$AUPREC
$MENU
$ELEVATION
$PELEVATION
$THICKNESS
$LIMCHECK
$CHAMFERA
$CHAMFERB
$CHAMFERC
$CHAMFERD
$SKPOLY
$TDCREATE
$TDUCREATE
$TDUPDATE
$TDUUPDATE
$TDINDWG
$TDUSRTIMER
$USRTIMER
$ANGBASE
$ANGDIR
$PDMODE
$PDSIZE
$PLINEWID
$SPLFRAME
$SPLINETYPE
$SPLINESEGS
$HANDSEED
$SURFTAB1
$SURFTAB2
$SURFTYPE
$SURFU
$SURFV
$UCSBASE
$UCSNAME
$UCSORG
$UCSXDIR
$UCSYDIR
$UCSORTHOREF
$UCSORTHOVIEW
$UCSORGTOP
$UCSORGBOTTOM
$UCSORGLEFT
$UCSORGRIGHT
$UCSORGFRONT
$UCSORGBACK
$PUCSBASE
$PUCSNAME
$PUCSORG
$PUCSXDIR
$PUCSYDIR
$PUCSORTHOREF
$PUCSORTHOVIEW
$PUCSORGTOP
$PUCSORGBOTTOM
$PUCSORGLEFT
$PUCSORGRIGHT
$PUCSORGFRONT
$PUCSORGBACK
$USERI1
$USERI2
$USERI3
$USERI4
$USERI5
$USERR1
$USERR2
$USERR3
$USERR4
$USERR5
$WORLDVIEW
$SHADEDGE
$SHADEDIF
$TILEMODE
$MAXACTVP
$PINSBASE
$PLIMCHECK
$PEXTMIN
$PEXTMAX
$PLIMMIN
$PLIMMAX
$UNITMODE
$VISRETAIN
$PLINEGEN
$PSLTSCALE
$TREEDEPTH
$CMLSTYLE
$CMLJUST
$CMLSCALE
$PROXYGRAPHICS
$MEASUREMENT
$CELWEIGHT
$ENDCAPS
$JOINSTYLE
$LWDISPLAY
$INSUNITS
$HYPERLINKBASE
$STYLESHEET
$XEDIT
$CEPSNTYPE
$PSTYLEMODE
$FINGERPRINTGUID
$VERSIONGUID
$EXTNAMES
$PSVPSCALE
$OLESTARTUP
$SORTENTS
$INDEXCTL
$HIDETEXT
$XCLIPFRAME
$HALOGAP
$OBSCOLOR
$OBSLTYPE
$INTERSECTIONDISPLAY
$INTERSECTIONCOLOR
$DIMASSOC
$PROJECTNAME
$CAMERADISPLAY
$LENSLENGTH
$CAMERAHEIGHT
$STEPSPERSEC
$STEPSIZE
$3DDWFPREC
$PSOLWIDTH
$PSOLHEIGHT
$LOFTANG1
$LOFTANG2
$LOFTMAG1
$LOFTMAG2
$LOFTPARAM
$LOFTNORMALS
$LATITUDE
$LONGITUDE
$NORTHDIRECTION
$TIMEZONE
$LIGHTGLYPHDISPLAY
$TILEMODELIGHTSYNCH
$CMATERIAL
$SOLIDHIST
$SHOWHIST
$DWFFRAME
$DGNFRAME
$REALWORLDSCALE
$INTERFERECOLOR
$INTERFEREOBJVS
$INTERFEREVPVS
$CSHADOW
$SHADOWPLANELOCATION";
TestHeaderOrder(expectedOrderText, DxfAcadVersion.R2010);
}
[Fact]
public void HeaderVariablesMatchOfficialR2013Order()
{
var expectedOrderText = @"
$ACADVER
$ACADMAINTVER
$DWGCODEPAGE
$LASTSAVEDBY
$REQUIREDVERSIONS
$INSBASE
$EXTMIN
$EXTMAX
$LIMMIN
$LIMMAX
$ORTHOMODE
$REGENMODE
$FILLMODE
$QTEXTMODE
$MIRRTEXT
$LTSCALE
$ATTMODE
$TEXTSIZE
$TRACEWID
$TEXTSTYLE
$CLAYER
$CELTYPE
$CECOLOR
$CELTSCALE
$DISPSILH
$DIMSCALE
$DIMASZ
$DIMEXO
$DIMDLI
$DIMRND
$DIMDLE
$DIMEXE
$DIMTP
$DIMTM
$DIMTXT
$DIMCEN
$DIMTSZ
$DIMTOL
$DIMLIM
$DIMTIH
$DIMTOH
$DIMSE1
$DIMSE2
$DIMTAD
$DIMZIN
$DIMBLK
$DIMASO
$DIMSHO
$DIMPOST
$DIMAPOST
$DIMALT
$DIMALTD
$DIMALTF
$DIMLFAC
$DIMTOFL
$DIMTVP
$DIMTIX
$DIMSOXD
$DIMSAH
$DIMBLK1
$DIMBLK2
$DIMSTYLE
$DIMCLRD
$DIMCLRE
$DIMCLRT
$DIMTFAC
$DIMGAP
$DIMJUST
$DIMSD1
$DIMSD2
$DIMTOLJ
$DIMTZIN
$DIMALTZ
$DIMALTTZ
$DIMUPT
$DIMDEC
$DIMTDEC
$DIMALTU
$DIMALTTD
$DIMTXSTY
$DIMAUNIT
$DIMADEC
$DIMALTRND
$DIMAZIN
$DIMDSEP
$DIMATFIT
$DIMFRAC
$DIMLDRBLK
$DIMLUNIT
$DIMLWD
$DIMLWE
$DIMTMOVE
$DIMFXL
$DIMFXLON
$DIMJOGANG
$DIMTFILL
$DIMTFILLCLR
$DIMARCSYM
$DIMLTYPE
$DIMLTEX1
$DIMLTEX2
$DIMTXTDIRECTION
$LUNITS
$LUPREC
$SKETCHINC
$FILLETRAD
$AUNITS
$AUPREC
$MENU
$ELEVATION
$PELEVATION
$THICKNESS
$LIMCHECK
$CHAMFERA
$CHAMFERB
$CHAMFERC
$CHAMFERD
$SKPOLY
$TDCREATE
$TDUCREATE
$TDUPDATE
$TDUUPDATE
$TDINDWG
$TDUSRTIMER
$USRTIMER
$ANGBASE
$ANGDIR
$PDMODE
$PDSIZE
$PLINEWID
$SPLFRAME
$SPLINETYPE
$SPLINESEGS
$HANDSEED
$SURFTAB1
$SURFTAB2
$SURFTYPE
$SURFU
$SURFV
$UCSBASE
$UCSNAME
$UCSORG
$UCSXDIR
$UCSYDIR
$UCSORTHOREF
$UCSORTHOVIEW
$UCSORGTOP
$UCSORGBOTTOM
$UCSORGLEFT
$UCSORGRIGHT
$UCSORGFRONT
$UCSORGBACK
$PUCSBASE
$PUCSNAME
$PUCSORG
$PUCSXDIR
$PUCSYDIR
$PUCSORTHOREF
$PUCSORTHOVIEW
$PUCSORGTOP
$PUCSORGBOTTOM
$PUCSORGLEFT
$PUCSORGRIGHT
$PUCSORGFRONT
$PUCSORGBACK
$USERI1
$USERI2
$USERI3
$USERI4
$USERI5
$USERR1
$USERR2
$USERR3
$USERR4
$USERR5
$WORLDVIEW
$SHADEDGE
$SHADEDIF
$TILEMODE
$MAXACTVP
$PINSBASE
$PLIMCHECK
$PEXTMIN
$PEXTMAX
$PLIMMIN
$PLIMMAX
$UNITMODE
$VISRETAIN
$PLINEGEN
$PSLTSCALE
$TREEDEPTH
$CMLSTYLE
$CMLJUST
$CMLSCALE
$PROXYGRAPHICS
$MEASUREMENT
$CELWEIGHT
$ENDCAPS
$JOINSTYLE
$LWDISPLAY
$INSUNITS
$HYPERLINKBASE
$STYLESHEET
$XEDIT
$CEPSNTYPE
$PSTYLEMODE
$FINGERPRINTGUID
$VERSIONGUID
$EXTNAMES
$PSVPSCALE
$OLESTARTUP
$SORTENTS
$INDEXCTL
$HIDETEXT
$XCLIPFRAME
$HALOGAP
$OBSCOLOR
$OBSLTYPE
$INTERSECTIONDISPLAY
$INTERSECTIONCOLOR
$DIMASSOC
$PROJECTNAME
$CAMERADISPLAY
$LENSLENGTH
$CAMERAHEIGHT
$STEPSPERSEC
$STEPSIZE
$3DDWFPREC
$PSOLWIDTH
$PSOLHEIGHT
$LOFTANG1
$LOFTANG2
$LOFTMAG1
$LOFTMAG2
$LOFTPARAM
$LOFTNORMALS
$LATITUDE
$LONGITUDE
$NORTHDIRECTION
$TIMEZONE
$LIGHTGLYPHDISPLAY
$TILEMODELIGHTSYNCH
$CMATERIAL
$SOLIDHIST
$SHOWHIST
$DWFFRAME
$DGNFRAME
$REALWORLDSCALE
$INTERFERECOLOR
$INTERFEREOBJVS
$INTERFEREVPVS
$CSHADOW
$SHADOWPLANELOCATION";
TestHeaderOrder(expectedOrderText, DxfAcadVersion.R2013);
}
[Fact]
public void DontWriteNullPointersTest()
{
var header = new DxfHeader();
// ensure they default to 0
Assert.Equal(default(DxfHandle), header.CurrentMaterialHandle);
Assert.Equal(default(DxfHandle), header.InterferenceObjectVisualStylePointer);
Assert.Equal(default(DxfHandle), header.InterferenceViewPortVisualStylePointer);
var pairs = new List<DxfCodePair>();
header.AddValueToList(pairs);
Assert.DoesNotContain(pairs, p => p.Code == 9 && p.StringValue == "$CMATERIAL");
Assert.DoesNotContain(pairs, p => p.Code == 9 && p.StringValue == "$INTERFEREOBJVS");
Assert.DoesNotContain(pairs, p => p.Code == 9 && p.StringValue == "$INTERFEREVPVS");
}
private static void TestHeaderOrder(string expectedOrderText, DxfAcadVersion version)
{
var header = new DxfHeader();
header.Version = version;
header.CurrentMaterialHandle = new DxfHandle(100);
header.InterferenceObjectVisualStylePointer = new DxfHandle(101);
header.InterferenceViewPortVisualStylePointer = new DxfHandle(102);
var expectedOrder = expectedOrderText
.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Where(s => s.StartsWith("$"))
.Select(s => s.Trim())
.ToArray();
var pairs = new List<DxfCodePair>();
header.AddValueToList(pairs);
var actualOrder = pairs.Where(p => p.Code == 9).Select(p => p.StringValue).ToArray();
AssertArrayEqual(expectedOrder, actualOrder);
}
[Fact]
public void TimersTest()
{
var file = new DxfFile();
Thread.Sleep(TimeSpan.FromMilliseconds(20));
using (var ms = new MemoryStream())
{
// we don't really care what's written but this will force the timers to be updated
file.Save(ms);
}
Assert.True(file.Header.TimeInDrawing >= TimeSpan.FromMilliseconds(20));
}
[Fact]
public void DefaultValuesTest()
{
var header = new DxfHeader();
Assert.True(header.AlignDirection);
Assert.Equal(2, header.AlternateDimensioningDecimalPlaces);
Assert.Equal(25.4, header.AlternateDimensioningScaleFactor);
Assert.Null(header.AlternateDimensioningSuffix);
Assert.Equal(2, header.AlternateDimensioningToleranceDecimalPlaces);
Assert.Equal(DxfAlternateToleranceZeroSuppression.SuppressZeroFeetAndZeroInches, header.AlternateDimensioningToleranceZeroSupression);
Assert.Equal(0, header.AlternateDimensioningUnitRounding);
Assert.Equal(DxfUnitFormat.Decimal, header.AlternateDimensioningUnits);
Assert.Equal(DxfAlternateUnitZeroSuppression.SuppressZeroFeetAndZeroInches, header.AlternateDimensioningZeroSupression);
Assert.Equal(0, header.AngleBetweenYAxisAndNorth);
Assert.Equal(DxfAngleDirection.CounterClockwise, header.AngleDirection);
Assert.Equal(DxfAngleFormat.DecimalDegrees, header.AngleUnitFormat);
Assert.Equal(0, header.AngleUnitPrecision);
Assert.Equal(0, header.AngleZeroDirection);
Assert.Equal(0, header.AngularDimensionPrecision);
Assert.False(header.ApparentIntersectionSnap);
Assert.Null(header.ArrowBlockName);
Assert.Equal(DxfAttributeVisibility.Normal, header.AttributeVisibility);
Assert.False(header.AxisOn);
Assert.Equal(new DxfVector(0, 0, 0), header.AxisTickSpacing);
Assert.False(header.BlipMode);
Assert.Equal(0, header.CameraHeight);
Assert.True(header.CanUseInPlaceReferenceEditing);
Assert.Equal(0.09, header.CenterMarkSize);
Assert.True(header.CenterSnap);
Assert.Equal(0, header.ChamferAngle);
Assert.Equal(0, header.ChamferLength);
Assert.False(header.Close);
Assert.Equal(DxfCoordinateDisplay.ContinuousUpdate, header.CoordinateDisplay);
Assert.True(header.CreateAssociativeDimensioning);
Assert.Equal(DxfColor.ByLayer, header.CurrentEntityColor);
Assert.Equal("BYLAYER", header.CurrentEntityLineType);
Assert.Equal(1, header.CurrentEntityLineTypeScale);
Assert.Equal("0", header.CurrentLayer);
Assert.Equal(default(DxfHandle), header.CurrentMaterialHandle);
Assert.Equal(DxfJustification.Top, header.CurrentMultilineJustification);
Assert.Equal(1, header.CurrentMultilineScale);
Assert.Equal("STANDARD", header.CurrentMultilineStyle);
Assert.Equal(DxfUnits.Unitless, header.DefaultDrawingUnits);
Assert.Equal(0, header.DefaultPolylineWidth);
Assert.Equal(0.2, header.DefaultTextHeight);
Assert.Equal(DxfUnderlayFrameMode.None, header.DgnUnderlayFrameMode);
Assert.Equal(DxfAngularZeroSuppression.DisplayAllLeadingAndTrailingZeros, header.DimensionAngleZeroSuppression);
Assert.Equal(DxfDimensionArcSymbolDisplayMode.SymbolBeforeText, header.DimensionArcSymbolDisplayMode);
Assert.False(header.DimensionCursorControlsTextPosition);
Assert.Equal('.', header.DimensionDecimalSeparatorChar);
Assert.Equal(0, header.DimensionDistanceRoundingValue);
Assert.Equal(DxfColor.ByBlock, header.DimensionExtensionLineColor);
Assert.Equal(0.18, header.DimensionExtensionLineExtension);
Assert.Equal(0.0625, header.DimensionExtensionLineOffset);
Assert.Equal(DxfLineWeight.ByLayer, header.DimensionExtensionLineWeight);
Assert.Null(header.DimensionFirstExtensionLineType);
Assert.Equal(DxfAngleFormat.DecimalDegrees, header.DimensioningAngleFormat);
Assert.Equal(0.18, header.DimensioningArrowSize);
Assert.Equal(1, header.DimensioningScaleFactor);
Assert.Null(header.DimensioningSuffix);
Assert.Equal(0.18, header.DimensioningTextHeight);
Assert.Equal(0, header.DimensioningTickSize);
Assert.Null(header.DimensionLeaderBlockName);
Assert.Equal(1, header.DimensionLinearMeasurementsScaleFactor);
Assert.Equal(DxfColor.ByBlock, header.DimensionLineColor);
Assert.Equal(0, header.DimensionLineExtension);
Assert.Equal(1, header.DimensionLineFixedLength);
Assert.False(header.DimensionLineFixedLengthOn);
Assert.Equal(0.09, header.DimensionLineGap);
Assert.Equal(0.38, header.DimensionLineIncrement);
Assert.Null(header.DimensionLineType);
Assert.Equal(DxfLineWeight.ByLayer, header.DimensionLineWeight);
Assert.Equal(0, header.DimensionMinusTolerance);
Assert.Equal(DxfNonAngularUnits.Decimal, header.DimensionNonAngularUnits);
Assert.Equal(DxfDimensionAssociativity.NonAssociativeObjects, header.DimensionObjectAssociativity);
Assert.Equal(0, header.DimensionPlusTolerance);
Assert.Null(header.DimensionSecondExtensionLineType);
Assert.Equal("STANDARD", header.DimensionStyleName);
Assert.Equal(DxfDimensionFit.TextAndArrowsOutsideLines, header.DimensionTextAndArrowPlacement);
Assert.Equal(DxfDimensionTextBackgroundColorMode.None, header.DimensionTextBackgroundColorMode);
Assert.Equal(DxfColor.ByBlock, header.DimensionTextColor);
Assert.Equal(DxfTextDirection.LeftToRight, header.DimensionTextDirection);
Assert.Equal(DxfDimensionFractionFormat.HorizontalStacking, header.DimensionTextHeightScaleFactor);
Assert.True(header.DimensionTextInsideHorizontal);
Assert.Equal(DxfDimensionTextJustification.AboveLineCenter, header.DimensionTextJustification);
Assert.Equal(DxfDimensionTextMovementRule.MoveLineWithText, header.DimensionTextMovementRule);
Assert.True(header.DimensionTextOutsideHorizontal);
Assert.Equal("STANDARD", header.DimensionTextStyle);
Assert.Equal(4, header.DimensionToleranceDecimalPlaces);
Assert.Equal(1, header.DimensionToleranceDisplayScaleFactor);
Assert.Equal(DxfJustification.Middle, header.DimensionToleranceVerticalJustification);
Assert.Equal(DxfToleranceZeroSuppression.SuppressZeroFeetAndZeroInches, header.DimensionToleranceZeroSuppression);
Assert.Equal(Math.PI / 4.0, header.DimensionTransverseSegmentAngleInJoggedRadius);
Assert.Equal(DxfUnitFormat.Decimal, header.DimensionUnitFormat);
Assert.Equal(4, header.DimensionUnitToleranceDecimalPlaces);
Assert.Equal(DxfUnitZeroSuppression.SuppressZeroFeetAndZeroInches, header.DimensionUnitZeroSuppression);
Assert.Equal(0, header.DimensionVerticalTextPosition);
Assert.False(header.DisplayFractionsInInput);
Assert.False(header.DisplayIntersectionPolylines);
Assert.False(header.DisplayLineweightInModelAndLayoutTab);
Assert.False(header.DisplaySilhouetteCurvesInWireframeMode);
Assert.False(header.DisplaySplinePolygonControl);
Assert.Equal(DxfDragMode.Auto, header.DragMode);
Assert.Equal("ANSI_1252", header.DrawingCodePage);
Assert.Equal(DxfDrawingUnits.English, header.DrawingUnits);
Assert.False(header.DrawOrthoganalLines);
Assert.Equal(Dxf3DDwfPrecision.Deviation_0_5, header.Dwf3DPrecision);
Assert.Equal(DxfUnderlayFrameMode.DisplayNoPlot, header.DwfUnderlayFrameMode);
Assert.Equal(DxfColor.ByBlock, header.DxfDimensionTextBackgroundCustomColor);
Assert.Equal(DxfShadeEdgeMode.FacesInEntityColorEdgesInBlack, header.EdgeShading);
Assert.Equal(0, header.Elevation);
Assert.Equal(DxfEndCapSetting.None, header.EndCapSetting);
Assert.True(header.EndPointSnap);
Assert.False(header.ExtensionSnap);
Assert.True(header.FastZoom);
Assert.Equal(".", header.FileName);
Assert.Equal(0, header.FilletRadius);
Assert.True(header.FillModeOn);
Assert.Null(header.FirstArrowBlockName);
Assert.Equal(0, header.FirstChamferDistance);
Assert.False(header.ForceDimensionLineExtensionsOutsideIfTextIs);
Assert.False(header.ForceDimensionTextInsideExtensions);
Assert.False(header.GenerateDimensionLimits);
Assert.False(header.GenerateDimensionTolerances);
Assert.False(header.GridOn);
Assert.Equal(new DxfVector(1, 1, 0), header.GridSpacing);
Assert.Equal(0, header.HaloGapPercent);
Assert.True(header.HandlesEnabled);
Assert.False(header.HideTextObjectsWhenProducingHiddenView);
Assert.Null(header.HyperlinkBase);
Assert.Equal(new DxfPoint(0, 0, 0), header.InsertionBase);
Assert.False(header.InsertionSnap);
Assert.Equal(1, header.InterferenceObjectColor.Index);
Assert.Equal(default(DxfHandle), header.InterferenceObjectVisualStylePointer);
Assert.Equal(default(DxfHandle), header.InterferenceViewPortVisualStylePointer);
Assert.Equal(DxfColor.ByEntity, header.IntersectionPolylineColor);
Assert.True(header.IntersectionSnap);
Assert.False(header.IsPolylineContinuousAroundVertices);
Assert.False(header.IsRestrictedVersion);
Assert.True(header.IsViewportScaledToFit);
Assert.Equal(DxfXrefClippingBoundaryVisibility.DisplayedNotPlotted, header.IsXRefClippingBoundaryVisible);
Assert.Equal(4, header.LastPolySolidHeight);
Assert.Equal(0.25, header.LastPolySolidWidth);
Assert.Null(header.LastSavedBy);
Assert.Equal(37.795, header.Latitude);
Assert.Equal(DxfLayerAndSpatialIndexSaveMode.None, header.LayerAndSpatialIndexSaveMode);
Assert.Equal(50, header.LensLength);
Assert.False(header.LimitCheckingInPaperspace);
Assert.Equal(8, header.LineSegmentsPerSplinePatch);
Assert.Equal(1, header.LineTypeScale);
Assert.Equal(DxfJoinStyle.None, header.LineweightJointSetting);
Assert.Equal(DxfLoftedObjectNormalMode.SmoothFit, header.LoftedObjectNormalMode);
Assert.Equal(7, header.LoftFlags);
Assert.Equal(Math.PI / 2.0, header.LoftOperationFirstDraftAngle);
Assert.Equal(0, header.LoftOperationFirstMagnitude);
Assert.Equal(Math.PI / 2.0, header.LoftOperationSecondDraftAngle);
Assert.Equal(0, header.LoftOperationSecondMagnitude);
Assert.Equal(-122.394, header.Longitude);
Assert.Equal(0, header.MaintenanceVersion);
Assert.Equal(64, header.MaximumActiveViewports);
Assert.Equal(new DxfPoint(0, 0, 0), header.MaximumDrawingExtents);
Assert.Equal(new DxfPoint(12, 9, 0), header.MaximumDrawingLimits);
Assert.Equal(6, header.MeshTabulationsInFirstDirection);
Assert.Equal(6, header.MeshTabulationsInSecondDirection);
Assert.False(header.MidPointSnap);
Assert.Equal(new DxfPoint(0, 0, 0), header.MinimumDrawingExtents);
Assert.Equal(new DxfPoint(0, 0, 0), header.MinimumDrawingLimits);
Assert.False(header.MirrorText);
Assert.False(header.NearestSnap);
Assert.Equal(DxfLineWeight.ByBlock, header.NewObjectLineWeight);
Assert.Equal(DxfPlotStyle.ByLayer, header.NewObjectPlotStyle);
Assert.False(header.NewSolidsContainHistory);
Assert.Equal(default(DxfHandle), header.NextAvailableHandle);
Assert.False(header.NodeSnap);
Assert.True(header.NoTwist);
Assert.Equal(37, header.ObjectSnapFlags);
Assert.Equal(127, header.ObjectSortingMethodsFlags);
Assert.Equal(DxfColor.ByEntity, header.ObscuredLineColor);
Assert.Equal(DxfLineTypeStyle.Off, header.ObscuredLineTypeStyle);
Assert.False(header.OleStartup);
Assert.Equal(DxfOrthographicViewType.None, header.OrthographicViewType);
Assert.Null(header.OrthoUCSReference);
Assert.Equal(0, header.PaperspaceElevation);
Assert.Equal(new DxfPoint(0, 0, 0), header.PaperspaceInsertionBase);
Assert.Equal(new DxfPoint(-1E+20, -1E+20, -1E+20), header.PaperspaceMaximumDrawingExtents);
Assert.Equal(new DxfPoint(12, 9, 0), header.PaperspaceMaximumDrawingLimits);
Assert.Equal(new DxfPoint(1E+20, 1E+20, 1E+20), header.PaperspaceMinimumDrawingExtents);
Assert.Equal(new DxfPoint(0, 0, 0), header.PaperspaceMinimumDrawingLimits);
Assert.Equal(DxfOrthographicViewType.None, header.PaperspaceOrthographicViewType);
Assert.Null(header.PaperspaceOrthoUCSReference);
Assert.Null(header.PaperspaceUCSDefinitionName);
Assert.Null(header.PaperspaceUCSName);
Assert.Equal(new DxfPoint(0, 0, 0), header.PaperspaceUCSOrigin);
Assert.Equal(new DxfPoint(0, 0, 0), header.PaperspaceUCSOriginBack);
Assert.Equal(new DxfPoint(0, 0, 0), header.PaperspaceUCSOriginBottom);
Assert.Equal(new DxfPoint(0, 0, 0), header.PaperspaceUCSOriginFront);
Assert.Equal(new DxfPoint(0, 0, 0), header.PaperspaceUCSOriginLeft);
Assert.Equal(new DxfPoint(0, 0, 0), header.PaperspaceUCSOriginRight);
Assert.Equal(new DxfPoint(0, 0, 0), header.PaperspaceUCSOriginTop);
Assert.Equal(new DxfVector(1, 0, 0), header.PaperspaceXAxis);
Assert.Equal(new DxfVector(0, 1, 0), header.PaperspaceYAxis);
Assert.False(header.ParallelSnap);
Assert.Equal(6, header.PEditSmoothMDensity);
Assert.Equal(6, header.PEditSmoothNDensity);
Assert.Equal(DxfPolylineCurvedAndSmoothSurfaceType.CubicBSpline, header.PEditSmoothSurfaceType);
Assert.Equal(DxfPolylineCurvedAndSmoothSurfaceType.CubicBSpline, header.PEditSplineCurveType);
Assert.Equal(70, header.PercentAmbientToDiffuse);
Assert.False(header.PerpendicularSnap);
Assert.Equal(DxfPickStyle.Group, header.PickStyle);
Assert.Equal(0, header.PointDisplayMode);
Assert.Equal(0, header.PointDisplaySize);
Assert.Equal(DxfPolySketchMode.SketchLines, header.PolylineSketchMode);
Assert.True(header.PreviousReleaseTileCompatibility);
Assert.Null(header.ProjectName);
Assert.True(header.PromptForAttributeOnInsert);
Assert.False(header.QuadrantSnap);
Assert.True(header.RecomputeDimensionsWhileDragging);
Assert.Equal(0, header.RequiredVersions);
Assert.True(header.RetainDeletedObjects);
Assert.True(header.RetainXRefDependentVisibilitySettings);
Assert.True(header.SaveProxyGraphics);
Assert.True(header.ScaleLineTypesInPaperspace);
Assert.Null(header.SecondArrowBlockName);
Assert.Equal(0, header.SecondChamferDistance);
Assert.True(header.SetUCSToWCSInDViewOrVPoint);
Assert.Equal(DxfShadowMode.CastsAndReceivesShadows, header.ShadowMode);
Assert.Equal(0, header.ShadowPlaneZOffset);
Assert.True(header.ShowAttributeEntryDialogs);
Assert.True(header.Simplify);
Assert.Equal(0.1, header.SketchRecordIncrement);
Assert.Equal(new DxfPoint(0, 0, 0), header.SnapBasePoint);
Assert.Equal(DxfSnapIsometricPlane.Left, header.SnapIsometricPlane);
Assert.False(header.SnapOn);
Assert.Equal(0, header.SnapRotationAngle);
Assert.Equal(new DxfVector(1, 1, 0), header.SnapSpacing);
Assert.Equal(DxfSnapStyle.Standard, header.SnapStyle);
Assert.Equal(DxfSolidHistoryMode.DoesNotOverride, header.SolidHistoryMode);
Assert.True(header.SortObjectsForMSlide);
Assert.True(header.SortObjectsForObjectSelection);
Assert.True(header.SortObjectsForObjectSnap);
Assert.True(header.SortObjectsForPlotting);
Assert.True(header.SortObjectsForPostScriptOutput);
Assert.True(header.SortObjectsForRedraw);
Assert.True(header.SortObjectsForRegen);
Assert.Equal(3020, header.SpacialIndexMaxDepth);
Assert.Equal(6, header.StepSizeInWalkOrFlyMode);
Assert.Equal(2, header.StepsPerSecondInWalkOrFlyMode);
Assert.Null(header.Stylesheet);
Assert.False(header.SuppressFirstDimensionExtensionLine);
Assert.False(header.SuppressOutsideExtensionDimensionLines);
Assert.False(header.SuppressSecondDimensionExtensionLine);
Assert.False(header.TangentSnap);
Assert.False(header.TextAboveDimensionLine);
Assert.Equal("STANDARD", header.TextStyle);
Assert.Equal(0, header.Thickness);
Assert.Equal(DxfTimeZone.PacificTime_US_Canada_SanFrancisco_Vancouver, header.TimeZone);
Assert.Equal(0.05, header.TraceWidth);
Assert.Null(header.UCSDefinitionName);
Assert.Null(header.UCSName);
Assert.Equal(new DxfPoint(0, 0, 0), header.UCSOrigin);
Assert.Equal(new DxfPoint(0, 0, 0), header.UCSOriginBack);
Assert.Equal(new DxfPoint(0, 0, 0), header.UCSOriginBottom);
Assert.Equal(new DxfPoint(0, 0, 0), header.UCSOriginFront);
Assert.Equal(new DxfPoint(0, 0, 0), header.UCSOriginLeft);
Assert.Equal(new DxfPoint(0, 0, 0), header.UCSOriginRight);
Assert.Equal(new DxfPoint(0, 0, 0), header.UCSOriginTop);
Assert.Equal(new DxfVector(1, 0, 0), header.UCSXAxis);
Assert.Equal(new DxfVector(0, 1, 0), header.UCSYAxis);
Assert.Equal(DxfUnitFormat.Decimal, header.UnitFormat);
Assert.Equal(4, header.UnitPrecision);
Assert.True(header.UseACad2000SymbolTableNaming);
Assert.False(header.UseAlternateDimensioning);
Assert.False(header.UseCameraDisplay);
Assert.True(header.UseLightGlyphDisplay);
Assert.False(header.UseLimitsChecking);
Assert.False(header.UseQuickTextMode);
Assert.True(header.UseRealWorldScale);
Assert.True(header.UseRegenMode);
Assert.Equal(0, header.UserInt1);
Assert.Equal(0, header.UserInt2);
Assert.Equal(0, header.UserInt3);
Assert.Equal(0, header.UserInt4);
Assert.Equal(0, header.UserInt5);
Assert.Equal(0, header.UserReal1);
Assert.Equal(0, header.UserReal2);
Assert.Equal(0, header.UserReal3);
Assert.Equal(0, header.UserReal4);
Assert.Equal(0, header.UserReal5);
Assert.True(header.UserTimerOn);
Assert.True(header.UsesColorDependentPlotStyleTables);
Assert.False(header.UseSeparateArrowBlocksForDimensions);
Assert.True(header.UseTileModeLightSync);
Assert.Equal(DxfAcadVersion.R12, header.Version);
Assert.Equal(new DxfPoint(0, 0, 0), header.ViewCenter);
Assert.Equal(new DxfVector(0, 0, 1), header.ViewDirection);
Assert.Equal(1, header.ViewHeight);
Assert.Equal(0, header.ViewportViewScaleFactor);
}
[Fact]
public void WriteHeaderWithInvalidValuesTest()
{
var header = new DxfHeader();
header.DefaultTextHeight = -1.0; // $TEXTSIZE, normalized to 0.2
header.TraceWidth = 0.0; // $TRACEWID, normalized to 0.05
header.TextStyle = string.Empty; // $TEXTSTYLE, normalized to STANDARD
header.CurrentLayer = null; // $CLAYER, normalized to 0
header.CurrentEntityLineType = null; // $CELTYPE, normalized to BYLAYER
header.DimensionStyleName = null; // $DIMSTYLE, normalized to STANDARD
header.FileName = null; // $MENU, normalized to .
var pairs = new List<DxfCodePair>();
header.AddValueToList(pairs);
AssertContains(pairs,
(9, "$TEXTSIZE"), (40, 0.2)
);
AssertContains(pairs,
(9, "$TRACEWID"), (40, 0.05)
);
AssertContains(pairs,
(9, "$TEXTSTYLE"), (7, "STANDARD")
);
AssertContains(pairs,
(9, "$CLAYER"), (8, "0")
);
AssertContains(pairs,
(9, "$CELTYPE"), (6, "BYLAYER")
);
AssertContains(pairs,
(9, "$DIMSTYLE"), (2, "STANDARD")
);
AssertContains(pairs,
(9, "$MENU"), (1, ".")
);
}
}
}
| |
/*
* CP20277.cs - IBM EBCDIC (Denmark/Norway) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ibm-277.ucm".
namespace I18N.Rare
{
using System;
using I18N.Common;
public class CP20277 : ByteEncoding
{
public CP20277()
: base(20277, ToChars, "IBM EBCDIC (Denmark/Norway)",
"IBM277", "IBM277", "IBM277",
false, false, false, false, 1252)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009',
'\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087',
'\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083',
'\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089',
'\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007',
'\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095',
'\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B',
'\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0',
'\u00E2', '\u00E4', '\u00E0', '\u00E1', '\u00E3', '\u007D',
'\u00E7', '\u00F1', '\u0023', '\u002E', '\u003C', '\u0028',
'\u002B', '\u0021', '\u0026', '\u00E9', '\u00EA', '\u00EB',
'\u00E8', '\u00ED', '\u00EE', '\u00EF', '\u00EC', '\u00DF',
'\u00A4', '\u00C5', '\u002A', '\u0029', '\u003B', '\u005E',
'\u002D', '\u002F', '\u00C2', '\u00C4', '\u00C0', '\u00C1',
'\u00C3', '\u0024', '\u00C7', '\u00D1', '\u00F8', '\u002C',
'\u0025', '\u005F', '\u003E', '\u003F', '\u00A6', '\u00C9',
'\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF',
'\u00CC', '\u0060', '\u003A', '\u00C6', '\u00D8', '\u0027',
'\u003D', '\u0022', '\u0040', '\u0061', '\u0062', '\u0063',
'\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069',
'\u00AB', '\u00BB', '\u00F0', '\u00FD', '\u00FE', '\u00B1',
'\u00B0', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E',
'\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA',
'\u007B', '\u00B8', '\u005B', '\u005D', '\u00B5', '\u00FC',
'\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078',
'\u0079', '\u007A', '\u00A1', '\u00BF', '\u00D0', '\u00DD',
'\u00DE', '\u00AE', '\u00A2', '\u00A3', '\u00A5', '\u00B7',
'\u00A9', '\u00A7', '\u00B6', '\u00BC', '\u00BD', '\u00BE',
'\u00AC', '\u007C', '\u00AF', '\u00A8', '\u00B4', '\u00D7',
'\u00E6', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045',
'\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4',
'\u00F6', '\u00F2', '\u00F3', '\u00F5', '\u00E5', '\u004A',
'\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050',
'\u0051', '\u0052', '\u00B9', '\u00FB', '\u007E', '\u00F9',
'\u00FA', '\u00FF', '\u005C', '\u00F7', '\u0053', '\u0054',
'\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A',
'\u00B2', '\u00D4', '\u00D6', '\u00D2', '\u00D3', '\u00D5',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB',
'\u00DC', '\u00D9', '\u00DA', '\u009F',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0x4F; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x4A; break;
case 0x0024: ch = 0x67; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0x80; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0x9E; break;
case 0x005C: ch = 0xE0; break;
case 0x005D: ch = 0x9F; break;
case 0x005E: ch = 0x5F; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x79; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0x9C; break;
case 0x007C: ch = 0xBB; break;
case 0x007D: ch = 0x47; break;
case 0x007E: ch = 0xDC; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0xB1; break;
case 0x00A4: ch = 0x5A; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0x70; break;
case 0x00A7: ch = 0xB5; break;
case 0x00A8: ch = 0xBD; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0xBA; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xBC; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x63; break;
case 0x00C5: ch = 0x5B; break;
case 0x00C6: ch = 0x7B; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0x71; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x69; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0xEC; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x7C; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0x43; break;
case 0x00E5: ch = 0xD0; break;
case 0x00E6: ch = 0xC0; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x51; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x49; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0xCC; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x6A; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xA1; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x0110: ch = 0xAC; break;
case 0x203E: ch = 0xBC; break;
case 0xFF01: ch = 0x4F; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x4A; break;
case 0xFF04: ch = 0x67; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0x80; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0x9E; break;
case 0xFF3C: ch = 0xE0; break;
case 0xFF3D: ch = 0x9F; break;
case 0xFF3E: ch = 0x5F; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x79; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0x9C; break;
case 0xFF5C: ch = 0xBB; break;
case 0xFF5D: ch = 0x47; break;
case 0xFF5E: ch = 0xDC; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0x4F; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x4A; break;
case 0x0024: ch = 0x67; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0x80; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0x9E; break;
case 0x005C: ch = 0xE0; break;
case 0x005D: ch = 0x9F; break;
case 0x005E: ch = 0x5F; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x79; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0x9C; break;
case 0x007C: ch = 0xBB; break;
case 0x007D: ch = 0x47; break;
case 0x007E: ch = 0xDC; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0xB1; break;
case 0x00A4: ch = 0x5A; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0x70; break;
case 0x00A7: ch = 0xB5; break;
case 0x00A8: ch = 0xBD; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0xBA; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xBC; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x63; break;
case 0x00C5: ch = 0x5B; break;
case 0x00C6: ch = 0x7B; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0x71; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x69; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0xEC; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x7C; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0x43; break;
case 0x00E5: ch = 0xD0; break;
case 0x00E6: ch = 0xC0; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x51; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x49; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0xCC; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x6A; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xA1; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x0110: ch = 0xAC; break;
case 0x203E: ch = 0xBC; break;
case 0xFF01: ch = 0x4F; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x4A; break;
case 0xFF04: ch = 0x67; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0x80; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0x9E; break;
case 0xFF3C: ch = 0xE0; break;
case 0xFF3D: ch = 0x9F; break;
case 0xFF3E: ch = 0x5F; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x79; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0x9C; break;
case 0xFF5C: ch = 0xBB; break;
case 0xFF5D: ch = 0x47; break;
case 0xFF5E: ch = 0xDC; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP20277
public class ENCibm277 : CP20277
{
public ENCibm277() : base() {}
}; // class ENCibm277
}; // namespace I18N.Rare
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Xunit;
namespace System.Tests
{
public static class StringComparerTests
{
[Fact]
public static void TestCurrent()
{
VerifyComparer(StringComparer.CurrentCulture, false);
VerifyComparer(StringComparer.CurrentCultureIgnoreCase, true);
}
[Fact]
public static void TestOrdinal()
{
VerifyComparer(StringComparer.Ordinal, false);
VerifyComparer(StringComparer.OrdinalIgnoreCase, true);
}
[Fact]
public static void TestOrdinal_EmbeddedNull_ReturnsDifferentHashCodes()
{
StringComparer sc = StringComparer.Ordinal;
Assert.NotEqual(sc.GetHashCode("\0AAAAAAAAA"), sc.GetHashCode("\0BBBBBBBBBBBB"));
sc = StringComparer.OrdinalIgnoreCase;
Assert.NotEqual(sc.GetHashCode("\0AAAAAAAAA"), sc.GetHashCode("\0BBBBBBBBBBBB"));
}
private static void VerifyComparer(StringComparer sc, bool ignoreCase)
{
string s1 = "Hello";
string s1a = "Hello";
string s1b = "HELLO";
string s2 = "There";
string aa = "\0AAAAAAAAA";
string bb = "\0BBBBBBBBBBBB";
Assert.True(sc.Equals(s1, s1a));
Assert.True(sc.Equals(s1, s1a));
Assert.Equal(0, sc.Compare(s1, s1a));
Assert.Equal(0, ((IComparer)sc).Compare(s1, s1a));
Assert.True(sc.Equals(s1, s1));
Assert.True(((IEqualityComparer)sc).Equals(s1, s1));
Assert.Equal(0, sc.Compare(s1, s1));
Assert.Equal(0, ((IComparer)sc).Compare(s1, s1));
Assert.False(sc.Equals(s1, s2));
Assert.False(((IEqualityComparer)sc).Equals(s1, s2));
Assert.True(sc.Compare(s1, s2) < 0);
Assert.True(((IComparer)sc).Compare(s1, s2) < 0);
Assert.Equal(ignoreCase, sc.Equals(s1, s1b));
Assert.Equal(ignoreCase, ((IEqualityComparer)sc).Equals(s1, s1b));
Assert.NotEqual(0, ((IComparer)sc).Compare(aa, bb));
Assert.False(sc.Equals(aa, bb));
Assert.False(((IEqualityComparer)sc).Equals(aa, bb));
Assert.True(sc.Compare(aa, bb) < 0);
Assert.True(((IComparer)sc).Compare(aa, bb) < 0);
int result = sc.Compare(s1, s1b);
if (ignoreCase)
Assert.Equal(0, result);
else
Assert.NotEqual(0, result);
result = ((IComparer)sc).Compare(s1, s1b);
if (ignoreCase)
Assert.Equal(0, result);
else
Assert.NotEqual(0, result);
}
public static IEnumerable<object[]> UpperLowerCasing_TestData()
{
// lower upper Culture
yield return new object[] { "abcd", "ABCD", "en-US" };
yield return new object[] { "latin i", "LATIN I", "en-US" };
yield return new object[] { "turky \u0131", "TURKY I", "tr-TR" };
yield return new object[] { "turky i", "TURKY \u0130", "tr-TR" };
}
[Theory]
[MemberData(nameof(UpperLowerCasing_TestData))]
public static void CreateWithCulturesTest(string lowerForm, string upperForm, string cultureName)
{
CultureInfo ci = CultureInfo.GetCultureInfo(cultureName);
StringComparer sc = StringComparer.Create(ci, false);
Assert.False(sc.Equals(lowerForm, upperForm), "Not expected to have the lowercase equals the uppercase with ignore case is false");
Assert.False(sc.Equals((object) lowerForm, (object) upperForm), "Not expected to have the lowercase object equals the uppercase with ignore case is false");
Assert.NotEqual(sc.GetHashCode(lowerForm), sc.GetHashCode(upperForm));
Assert.NotEqual(sc.GetHashCode((object) lowerForm), sc.GetHashCode((object) upperForm));
sc = StringComparer.Create(ci, true);
Assert.True(sc.Equals(lowerForm, upperForm), "It is expected to have the lowercase equals the uppercase with ignore case is true");
Assert.True(sc.Equals((object) lowerForm, (object) upperForm), "It is expected to have the lowercase object equals the uppercase with ignore case is true");
Assert.Equal(sc.GetHashCode(lowerForm), sc.GetHashCode(upperForm));
Assert.Equal(sc.GetHashCode((object) lowerForm), sc.GetHashCode((object) upperForm));
}
[Fact]
public static void InvariantTest()
{
Assert.True(StringComparer.InvariantCulture.Equals("test", "test"), "Same casing strings with StringComparer.InvariantCulture should be equal");
Assert.True(StringComparer.InvariantCulture.Equals((object) "test", (object) "test"), "Same casing objects with StringComparer.InvariantCulture should be equal");
Assert.Equal(StringComparer.InvariantCulture.GetHashCode("test"), StringComparer.InvariantCulture.GetHashCode("test"));
Assert.Equal(0, StringComparer.InvariantCulture.Compare("test", "test"));
Assert.False(StringComparer.InvariantCulture.Equals("test", "TEST"), "different casing strings with StringComparer.InvariantCulture should not be equal");
Assert.False(StringComparer.InvariantCulture.Equals((object) "test", (object) "TEST"), "different casing objects with StringComparer.InvariantCulture should not be equal");
Assert.NotEqual(StringComparer.InvariantCulture.GetHashCode("test"), StringComparer.InvariantCulture.GetHashCode("TEST"));
Assert.NotEqual(0, StringComparer.InvariantCulture.Compare("test", "TEST"));
Assert.True(StringComparer.InvariantCultureIgnoreCase.Equals("test", "test"), "Same casing strings with StringComparer.InvariantCultureIgnoreCase should be equal");
Assert.True(StringComparer.InvariantCultureIgnoreCase.Equals((object) "test", (object) "test"), "Same casing objects with StringComparer.InvariantCultureIgnoreCase should be equal");
Assert.Equal(0, StringComparer.InvariantCultureIgnoreCase.Compare("test", "test"));
Assert.True(StringComparer.InvariantCultureIgnoreCase.Equals("test", "TEST"), "same strings with different casing with StringComparer.InvariantCultureIgnoreCase should be equal");
Assert.True(StringComparer.InvariantCultureIgnoreCase.Equals((object) "test", (object) "TEST"), "same objects with different casing with StringComparer.InvariantCultureIgnoreCase should be equal");
Assert.Equal(StringComparer.InvariantCultureIgnoreCase.GetHashCode("test"), StringComparer.InvariantCultureIgnoreCase.GetHashCode("TEST"));
Assert.Equal(0, StringComparer.InvariantCultureIgnoreCase.Compare("test", "TEST"));
}
public static readonly object[][] FromComparison_TestData =
{
// StringComparison StringComparer
new object[] { StringComparison.CurrentCulture, StringComparer.CurrentCulture },
new object[] { StringComparison.CurrentCultureIgnoreCase, StringComparer.CurrentCultureIgnoreCase },
new object[] { StringComparison.InvariantCulture, StringComparer.InvariantCulture },
new object[] { StringComparison.InvariantCultureIgnoreCase, StringComparer.InvariantCultureIgnoreCase },
new object[] { StringComparison.Ordinal, StringComparer.Ordinal },
new object[] { StringComparison.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase },
};
[Theory]
[MemberData(nameof(FromComparison_TestData))]
public static void FromComparisonTest(StringComparison comparison, StringComparer comparer)
{
Assert.Equal(comparer, StringComparer.FromComparison(comparison));
}
[Fact]
public static void FromComparisonInvalidTest()
{
StringComparison minInvalid = Enum.GetValues(typeof(StringComparison)).Cast<StringComparison>().Min() - 1;
StringComparison maxInvalid = Enum.GetValues(typeof(StringComparison)).Cast<StringComparison>().Max() + 1;
AssertExtensions.Throws<ArgumentException>("comparisonType", () => StringComparer.FromComparison(minInvalid));
AssertExtensions.Throws<ArgumentException>("comparisonType", () => StringComparer.FromComparison(maxInvalid));
}
public static TheoryData<string, string, string, CompareOptions, bool> CreateFromCultureAndOptionsData => new TheoryData<string, string, string, CompareOptions, bool>
{
{ "abcd", "ABCD", "en-US", CompareOptions.None, false},
{ "latin i", "LATIN I", "en-US", CompareOptions.None, false},
{ "turky \u0131", "TURKY I", "tr-TR", CompareOptions.None, false},
{ "turky i", "TURKY \u0130", "tr-TR", CompareOptions.None, false},
{ "abcd", "ABCD", "en-US", CompareOptions.IgnoreCase, true},
{ "latin i", "LATIN I", "en-US", CompareOptions.IgnoreCase, true},
{ "turky \u0131", "TURKY I", "tr-TR", CompareOptions.IgnoreCase, true},
{ "turky i", "TURKY \u0130", "tr-TR", CompareOptions.IgnoreCase, true},
{ "abcd", "ab cd", "en-US", CompareOptions.IgnoreSymbols, true },
{ "abcd", "ab+cd", "en-US", CompareOptions.IgnoreSymbols, true },
{ "abcd", "ab%cd", "en-US", CompareOptions.IgnoreSymbols, true },
{ "abcd", "ab&cd", "en-US", CompareOptions.IgnoreSymbols, true },
{ "abcd", "ab$cd", "en-US", CompareOptions.IgnoreSymbols, true },
{ "abcd", "ab$cd", "en-US", CompareOptions.IgnoreSymbols, true },
{ "a-bcd", "ab$cd", "en-US", CompareOptions.IgnoreSymbols, true },
{ "abcd*", "ab$cd", "en-US", CompareOptions.IgnoreSymbols, true },
{ "ab$dd", "ab$cd", "en-US", CompareOptions.IgnoreSymbols, false },
{ "abcd", "ab$cd", "en-US", CompareOptions.IgnoreSymbols, true },
};
public static TheoryData<string, string, string, CompareOptions, bool> CreateFromCultureAndOptionsStringSortData => new TheoryData<string, string, string, CompareOptions, bool>
{
{ "abcd", "abcd", "en-US", CompareOptions.StringSort, true },
{ "abcd", "ABcd", "en-US", CompareOptions.StringSort, false },
};
[Theory]
[MemberData(nameof(CreateFromCultureAndOptionsData))]
[MemberData(nameof(CreateFromCultureAndOptionsStringSortData))]
public static void CreateFromCultureAndOptions(string actualString, string expectedString, string cultureName, CompareOptions options, bool result)
{
CultureInfo ci = CultureInfo.GetCultureInfo(cultureName);
StringComparer sc = StringComparer.Create(ci, options);
Assert.Equal(result, sc.Equals(actualString, expectedString));
Assert.Equal(result, sc.Equals((object)actualString, (object)expectedString));
}
[Theory]
[MemberData(nameof(CreateFromCultureAndOptionsData))]
public static void CreateFromCultureAndOptionsStringSort(string actualString, string expectedString, string cultureName, CompareOptions options, bool result)
{
CultureInfo ci = CultureInfo.GetCultureInfo(cultureName);
StringComparer sc = StringComparer.Create(ci, options);
if (result)
{
Assert.Equal(sc.GetHashCode(actualString), sc.GetHashCode(expectedString));
Assert.Equal(sc.GetHashCode((object)actualString), sc.GetHashCode((object)actualString));
}
else
{
Assert.NotEqual(sc.GetHashCode(actualString), sc.GetHashCode(expectedString));
Assert.NotEqual(sc.GetHashCode((object)actualString), sc.GetHashCode((object)expectedString));
}
}
[Fact]
public static void CreateFromCultureAndOptionsOrdinal()
{
CultureInfo ci = CultureInfo.GetCultureInfo("en-US");
Assert.Throws<ArgumentException>(() => StringComparer.Create(ci, CompareOptions.Ordinal));
Assert.Throws<ArgumentException>(() => StringComparer.Create(ci, CompareOptions.OrdinalIgnoreCase));
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for RouteFiltersOperations.
/// </summary>
public static partial class RouteFiltersOperationsExtensions
{
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
public static void Delete(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName)
{
operations.DeleteAsync(resourceGroupName, routeFilterName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='expand'>
/// Expands referenced express route bgp peering resources.
/// </param>
public static RouteFilter Get(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, routeFilterName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='expand'>
/// Expands referenced express route bgp peering resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilter> GetAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeFilterName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
public static RouteFilter CreateOrUpdate(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilter> CreateOrUpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
public static RouteFilter Update(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters)
{
return operations.UpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilter> UpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<RouteFilter> ListByResourceGroup(this IRouteFiltersOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteFilter>> ListByResourceGroupAsync(this IRouteFiltersOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<RouteFilter> List(this IRouteFiltersOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteFilter>> ListAsync(this IRouteFiltersOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
public static void BeginDelete(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName)
{
operations.BeginDeleteAsync(resourceGroupName, routeFilterName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
public static RouteFilter BeginCreateOrUpdate(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilter> BeginCreateOrUpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
public static RouteFilter BeginUpdate(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters)
{
return operations.BeginUpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilter> BeginUpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteFilter> ListByResourceGroupNext(this IRouteFiltersOperations operations, string nextPageLink)
{
return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteFilter>> ListByResourceGroupNextAsync(this IRouteFiltersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteFilter> ListNext(this IRouteFiltersOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteFilter>> ListNextAsync(this IRouteFiltersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//
// GradientTool.cs
//
// Author:
// Olivier Dufour <olivier.duff@gmail.com>
//
// Copyright (c) 2010 Olivier Dufour
//
// 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 Cairo;
using Pinta.Core;
using Mono.Unix;
namespace Pinta.Tools
{
public class GradientTool : BaseTool
{
Cairo.PointD startpoint;
bool tracking;
protected ImageSurface undo_surface;
uint button;
static GradientTool ()
{
Gtk.IconFactory fact = new Gtk.IconFactory ();
fact.Add ("Toolbar.LinearGradient.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Toolbar.LinearGradient.png")));
fact.Add ("Toolbar.LinearReflectedGradient.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Toolbar.LinearReflectedGradient.png")));
fact.Add ("Toolbar.DiamondGradient.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Toolbar.DiamondGradient.png")));
fact.Add ("Toolbar.RadialGradient.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Toolbar.RadialGradient.png")));
fact.Add ("Toolbar.ConicalGradient.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Toolbar.ConicalGradient.png")));
fact.Add ("Toolbar.ColorMode.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Toolbar.ColorMode.png")));
fact.Add ("Toolbar.TransparentMode.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Toolbar.TransparentMode.png")));
fact.AddDefault ();
}
public override string Name {
get { return Catalog.GetString ("Gradient"); }
}
public override string Icon {
get { return "Tools.Gradient.png"; }
}
public override string StatusBarText {
get { return Catalog.GetString ("Click and drag to draw gradient from primary to secondary color. Right click to reverse."); }
}
public override Gdk.Key ShortcutKey { get { return Gdk.Key.G; } }
public override Gdk.Cursor DefaultCursor { get { return new Gdk.Cursor (PintaCore.Chrome.Canvas.Display, PintaCore.Resources.GetIcon ("Cursor.Gradient.png"), 9, 18); } }
public override int Priority { get { return 23; } }
#region Mouse Handlers
protected override void OnMouseDown (Gtk.DrawingArea canvas, Gtk.ButtonPressEventArgs args, Cairo.PointD point)
{
Document doc = PintaCore.Workspace.ActiveDocument;
// Protect against history corruption
if (tracking)
return;
startpoint = point;
if (!doc.Workspace.PointInCanvas(point))
return;
tracking = true;
button = args.Event.Button;
undo_surface = doc.CurrentUserLayer.Surface.Clone ();
}
protected override void OnMouseUp (Gtk.DrawingArea canvas, Gtk.ButtonReleaseEventArgs args, Cairo.PointD point)
{
Document doc = PintaCore.Workspace.ActiveDocument;
if (!tracking || args.Event.Button != button)
return;
tracking = false;
doc.History.PushNewItem (new SimpleHistoryItem (Icon, Name, undo_surface, doc.CurrentUserLayerIndex));
}
protected override void OnMouseMove (object o, Gtk.MotionNotifyEventArgs args, Cairo.PointD point)
{
Document doc = PintaCore.Workspace.ActiveDocument;
if (tracking) {
GradientRenderer gr = CreateGradientRenderer ();
if (button == 3) { // Right-click
gr.StartColor = PintaCore.Palette.SecondaryColor.ToColorBgra ();
gr.EndColor = PintaCore.Palette.PrimaryColor.ToColorBgra ();
} else { //1 Left-click
gr.StartColor = PintaCore.Palette.PrimaryColor.ToColorBgra ();
gr.EndColor = PintaCore.Palette.SecondaryColor.ToColorBgra ();
}
gr.StartPoint = startpoint;
gr.EndPoint = point;
gr.AlphaBlending = UseAlphaBlending;
gr.BeforeRender ();
Gdk.Rectangle selection_bounds = doc.GetSelectedBounds (true);
ImageSurface scratch_layer = doc.ToolLayer.Surface;
gr.Render (scratch_layer, new Gdk.Rectangle[] { selection_bounds });
using (var g = doc.CreateClippedContext ()) {
g.SetSource (scratch_layer);
g.Paint ();
}
doc.ToolLayer.Clear ();
selection_bounds.Inflate (5, 5);
doc.Workspace.Invalidate (selection_bounds);
}
}
private GradientRenderer CreateGradientRenderer ()
{
var normalBlendOp = new UserBlendOps.NormalBlendOp ();
bool alpha_only = SelectedGradientColorMode == GradientColorMode.Transparency;
switch (SelectedGradientType) {
case GradientType.Linear:
return new GradientRenderers.LinearClamped (alpha_only, normalBlendOp);
case GradientType.LinearReflected:
return new GradientRenderers.LinearReflected (alpha_only, normalBlendOp);
case GradientType.Radial:
return new GradientRenderers.Radial (alpha_only, normalBlendOp);
case GradientType.Diamond:
return new GradientRenderers.LinearDiamond (alpha_only, normalBlendOp);
case GradientType.Conical:
return new GradientRenderers.Conical (alpha_only, normalBlendOp);
}
throw new ArgumentOutOfRangeException ("Unknown gradient type.");
}
#endregion
#region ToolBar
private ToolBarLabel gradient_label;
private ToolBarDropDownButton gradient_button;
//private ToolBarLabel mode_label;
//private ToolBarDropDownButton mode_button;
protected override void OnBuildToolBar (Gtk.Toolbar tb)
{
base.OnBuildToolBar (tb);
if (gradient_label == null)
gradient_label = new ToolBarLabel (string.Format (" {0}: ", Catalog.GetString ("Gradient")));
tb.AppendItem (gradient_label);
if (gradient_button == null) {
gradient_button = new ToolBarDropDownButton ();
gradient_button.AddItem (Catalog.GetString ("Linear Gradient"), "Toolbar.LinearGradient.png", GradientType.Linear);
gradient_button.AddItem (Catalog.GetString ("Linear Reflected Gradient"), "Toolbar.LinearReflectedGradient.png", GradientType.LinearReflected);
gradient_button.AddItem (Catalog.GetString ("Linear Diamond Gradient"), "Toolbar.DiamondGradient.png", GradientType.Diamond);
gradient_button.AddItem (Catalog.GetString ("Radial Gradient"), "Toolbar.RadialGradient.png", GradientType.Radial);
gradient_button.AddItem (Catalog.GetString ("Conical Gradient"), "Toolbar.ConicalGradient.png", GradientType.Conical);
}
tb.AppendItem (gradient_button);
// Hide TransparentMode. The core issue is we can't just paint it on top of the
// current layer because it's transparent. Will require significant effort to support.
//tb.AppendItem (new Gtk.SeparatorToolItem ());
//if (mode_label == null)
// mode_label = new ToolBarLabel (string.Format (" {0}: ", Catalog.GetString ("Mode")));
//tb.AppendItem (mode_label);
//if (mode_button == null) {
// mode_button = new ToolBarDropDownButton ();
// mode_button.AddItem (Catalog.GetString ("Color Mode"), "Toolbar.ColorMode.png", GradientColorMode.Color);
// mode_button.AddItem (Catalog.GetString ("Transparency Mode"), "Toolbar.TransparentMode.png", GradientColorMode.Transparency);
//}
//tb.AppendItem (mode_button);
}
private GradientType SelectedGradientType {
get { return (GradientType)gradient_button.SelectedItem.Tag; }
}
private GradientColorMode SelectedGradientColorMode {
// get { return (GradientColorMode)mode_button.SelectedItem.Tag; }
get { return GradientColorMode.Color; }
}
#endregion
enum GradientType
{
Linear,
LinearReflected,
Diamond,
Radial,
Conical
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using System;
using Stratus.Interfaces;
namespace Stratus
{
public class ValidatorWindow : EditorWindow
{
public class ValidatorTreeView : TreeView
{
public ValidatorTreeView(TreeViewState treeViewState)
: base(treeViewState)
{
Reload();
}
protected override TreeViewItem BuildRoot()
{
// BuildRoot is called every time Reload is called to ensure that TreeViewItems
// are created from data. Here we create a fixed set of items. In a real world example,
// a data model should be passed into the TreeView and the items created from the model.
// This section illustrates that IDs should be unique. The root item is required to
// have a depth of -1, and the rest of the items increment from that.
var root = new TreeViewItem { id = 0, depth = -1, displayName = "Root" };
var allItems = new List<TreeViewItem>
{
new TreeViewItem {id = 1, depth = 0, displayName = "Animals"},
new TreeViewItem {id = 2, depth = 1, displayName = "Mammals"},
new TreeViewItem {id = 3, depth = 2, displayName = "Tiger"},
new TreeViewItem {id = 4, depth = 2, displayName = "Elephant"},
new TreeViewItem {id = 5, depth = 2, displayName = "Okapi"},
new TreeViewItem {id = 6, depth = 2, displayName = "Armadillo"},
new TreeViewItem {id = 7, depth = 1, displayName = "Reptiles"},
new TreeViewItem {id = 8, depth = 2, displayName = "Crocodile"},
new TreeViewItem {id = 9, depth = 2, displayName = "Lizard"},
};
// Utility method that initializes the TreeViewItem.children and .parent for all items.
SetupParentsAndChildrenFromDepths(root, allItems);
// Return root of the tree
return root;
}
}
//------------------------------------------------------------------------/
// Declarations
//------------------------------------------------------------------------/
//------------------------------------------------------------------------/
// Fields
//------------------------------------------------------------------------/
private string header;
private StratusObjectValidation[] messages;
public static ValidatorWindow window;
private Vector2 scrollPos, sidebarScrollPos;
[SerializeField]
private TreeViewState treeViewState;
private TreeView treeView;
//private TypeSelector validatorTypes;
//private TypeSelector validatorAggregatorTypes;
//private GUISplitter sidebar;
//private GUISplitter splitter;
//private Type[] validatorTypes = new Type[] { };
//private DropdownList<Type> validatorTypes;
private bool onFirstTime;
//------------------------------------------------------------------------/
// Methods: Static
//------------------------------------------------------------------------/
public static void Open(string header, StratusObjectValidation[] messages)
{
window = (ValidatorWindow)EditorWindow.GetWindow(typeof(ValidatorWindow), true, "Stratus Validator");
window.ShowValidation(header, messages);
}
[MenuItem("Stratus/Core/Validator")]
public static void Open()
{
window = (ValidatorWindow)EditorWindow.GetWindow(typeof(ValidatorWindow), true, "Stratus Validator");
}
//------------------------------------------------------------------------/
// Messages
//------------------------------------------------------------------------/
private void OnEnable()
{
if (treeViewState == null)
treeViewState = new TreeViewState();
treeView = new ValidatorTreeView(treeViewState);
//validatorTypes = new DropdownList<Type>(new Type[]
//{
// typeof(Validator),
// typeof(ValidatorAggregator)
//}, (Type type) => type.Name, 0);
//Trace.Script($"ValidatorTypes = {validatorTypes.subTypes.Length}");
//validatorTypes = new TypeSelector(typeof(MonoBehaviour), typeof(Interfaces.Validator), true);
//validatorAggregatorTypes = new TypeSelector(typeof(MonoBehaviour), typeof(Interfaces.ValidatorAggregator), true);
}
//protected override void OnMultiColumnEditorEnable(MenuBar menu, GUISplitter columns)
//{
// //sidebar = new GUISplitter(this, GUISplitter.OrientationType.Vertical);
// columns.Add(0.25f, DrawSidebar);
// columns.Add(0.75f, DrawMessages);
//}
private void OnGUI()
{
if (!onFirstTime)
{
EditorStyles.helpBox.richText = true;
onFirstTime = true;
}
//DrawTree();
//EditorGUILayout.BeginVertical(EditorStyles.toolbar);
//
//StratusGUIStyles.DrawBackgroundColor(position, StratusGUIStyles.Colors.cinnabar);
//GUI.backgroundColor = StratusGUIStyles.Colors.aquaIsland;
//GUI.DrawTexture(position, StratusGUIStyles.GetColorTexture(StratusGUIStyles.Colors.aquaIsland), ScaleMode.StretchToFill);
EditorGUILayout.BeginHorizontal();
{
DrawControls(position);
GUILayout.FlexibleSpace();
//EditorGUILayout.Separator();
DrawMessages(position);
GUILayout.FlexibleSpace();
}
EditorGUILayout.EndHorizontal();
}
//------------------------------------------------------------------------/
// Methods
//------------------------------------------------------------------------/
private void DrawControls(Rect rect)
{
EditorGUILayout.BeginVertical(StratusGUIStyles.box, GUILayout.ExpandHeight(true));
{
// Validation
if (GUILayout.Button(StratusGUIStyles.validateIcon, StratusGUIStyles.smallLayout))
{
var menu = new GenericMenu();
menu.AddItem(new GUIContent("Validator"), false, () => ShowValidation("Validator", Interfaces.Global.Validate()));
menu.AddItem(new GUIContent("Validator Aggregator"), false, () => ShowValidation("Validator", Interfaces.Global.ValidateAggregate()));
menu.ShowAsContext();
}
// Clear
if (GUILayout.Button(StratusGUIStyles.trashIcon, StratusGUIStyles.smallLayout))
{
messages = null;
}
}
EditorGUILayout.EndVertical();
}
private void DrawMessages(Rect rect)
{
//EditorGUILayout.LabelField("Messages", EditorStyles.toolbarButton, GUILayout.ExpandWidth(true));
//EditorGUILayout.Separator();
EditorGUILayout.BeginVertical(StratusGUIStyles.box, GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true));
EditorGUILayout.Separator();
EditorGUILayout.LabelField($"{header} Messages", StratusGUIStyles.header);
if (messages != null)
{
scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
foreach (var message in messages)
{
EditorGUILayout.HelpBox(message.message, message.type.Convert());
if (message.hasContext)
{
StratusEditorUtility.OnMouseClick(GUILayoutUtility.GetLastRect(), null, () =>
{
var menu = new GenericMenu();
if (message.target)
menu.AddItem(new GUIContent("Select"), false, () => { Selection.activeObject = message.target; });
if (message.onSelect != null)
menu.AddItem(new GUIContent("Select"), false, () => { message.onSelect(); });
menu.ShowAsContext();
});
}
}
EditorGUILayout.EndScrollView();
}
EditorGUILayout.EndVertical();
}
private void DrawTree()
{
treeView.OnGUI(new Rect(0, 0, position.width, position.height));
}
private void ShowValidation(string header, StratusObjectValidation[] messages)
{
this.header = header;
this.messages = messages;
}
private void Validate(Type validationType)
{
if (validationType == typeof(IStratusValidator))
{
ShowValidation("Validator", Interfaces.Global.Validate());
}
else if (validationType == typeof(IStratusValidator))
{
ShowValidation("Validator Aggregator", Interfaces.Global.ValidateAggregate());
}
}
}
}
| |
#region Using directives
#define USE_TRACING
using System;
using System.Collections;
using System.Collections.Generic;
using Google.GData.Client;
#endregion
//////////////////////////////////////////////////////////////////////
// contains typed collections based on the 1.1 .NET framework
// using typed collections has the benefit of additional code reliability
// and using them in the collection editor
//
//////////////////////////////////////////////////////////////////////
namespace Google.GData.Extensions
{
/// <summary>
/// base class to take an object pointer with extension information
/// and expose a localname/namespace subset as a collection
/// that still works on the original
/// </summary>
public class ExtensionCollection<T> : IList<T> where T : class, IExtensionElementFactory, new()
{
private static readonly Dictionary<Type, IExtensionElementFactory> _cache =
new Dictionary<Type, IExtensionElementFactory>();
private readonly List<T> _items = new List<T>();
/// <summary>holds the owning feed</summary>
private readonly IExtensionContainer container;
/// <summary>
/// protected default constructor, not usable by outside
/// </summary>
public ExtensionCollection()
{
}
/// <summary>
/// takes the base object, and the localname/ns combo to look for
/// will copy objects to an internal array for caching. Note that when the external
/// ExtensionList is modified, this will have no effect on this copy
/// </summary>
/// <param name="containerElement">the base element holding the extension list</param>
public ExtensionCollection(IExtensionContainer containerElement)
: this(containerElement, CtorXmlName(), CtorXmlNS())
{
}
/// <summary>
/// takes the base object, and the localname/ns combo to look for
/// will copy objects to an internal array for caching. Note that when the external
/// ExtensionList is modified, this will have no effect on this copy
/// </summary>
/// <param name="containerElement">the base element holding the extension list</param>
/// <param name="localName">the local name of the extension</param>
/// <param name="ns">the namespace</param>
public ExtensionCollection(IExtensionContainer containerElement, string localName, string ns)
{
container = containerElement;
if (container != null)
{
ExtensionList arr = container.FindExtensions(localName, ns);
foreach (T o in arr)
{
_items.Add(o);
}
}
}
/// <summary>standard typed accessor method </summary>
public T this[int index]
{
get { return _items[index]; }
set { setItem(index, value); }
}
/// <summary>
/// inserts an element into the collection by index
/// </summary>
/// <param name="index"></param>
/// <param name="value"></param>
public void Insert(int index, T value)
{
if (container != null && container.ExtensionElements.Contains(value))
{
container.ExtensionElements.Remove(value);
}
container.ExtensionElements.Add(value);
_items.Insert(index, value);
}
/// <summary>standard typed indexOf method </summary>
public int IndexOf(T value)
{
return (_items.IndexOf(value));
}
/// <summary>standard typed Contains method </summary>
public bool Contains(T value)
{
// If value is not of type AtomEntry, this will return false.
return (_items.Contains(value));
}
#region IList<T> Members
public void RemoveAt(int index)
{
T item = _items[index];
//_items.RemoveAt(index);
Remove(item);
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return _items.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return _items.GetEnumerator();
}
#endregion
/// <summary>
/// Get the XmlName for the Type
/// </summary>
/// <returns></returns>
private static string CtorXmlName()
{
IExtensionElementFactory val;
Type t = typeof (T);
lock (_cache)
{
if (!_cache.TryGetValue(t, out val))
{
val = new T();
_cache[t] = val;
}
}
return val.XmlName;
}
/// <summary>
/// Get the Xml Namespace for the Type
/// </summary>
/// <returns></returns>
private static string CtorXmlNS()
{
IExtensionElementFactory val;
Type t = typeof (T);
lock (_cache)
{
if (!_cache.TryGetValue(t, out val))
{
val = new T();
_cache[t] = val;
}
}
return val.XmlNameSpace;
}
/// <summary>
/// useful for subclasses that want to overload the set method
/// </summary>
/// <param name="index">the index in the array</param>
/// <param name="item">the item to set </param>
protected void setItem(int index, T item)
{
if (_items[index] != null)
{
if (container != null)
{
container.ExtensionElements.Remove(_items[index]);
}
}
_items[index] = item;
if (item != null && container != null)
{
container.ExtensionElements.Add(item);
}
}
/// <summary>
/// default untyped add implementation. Adds the object as well to the parent
/// object ExtensionList
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public int Add(T value)
{
if (container != null)
{
container.ExtensionElements.Add(value);
}
_items.Add(value);
return _items.Count - 1;
}
/// <summary>
/// removes an element from the collection
/// </summary>
/// <param name="value"></param>
public bool Remove(T value)
{
bool success = _items.Remove(value);
if (success && container != null)
{
success &= container.ExtensionElements.Remove(value);
}
return success;
}
/// <summary>standard override OnClear, to remove the objects from the extension list</summary>
protected void OnClear()
{
if (container != null)
{
for (int i = 0; i < Count; i++)
{
container.ExtensionElements.Remove(_items[i]);
}
}
}
#region ICollection<T> Members
void ICollection<T>.Add(T item)
{
Add(item);
}
public void Clear()
{
OnClear();
_items.Clear();
}
public void CopyTo(T[] array, int arrayIndex)
{
_items.ToArray().CopyTo(array, arrayIndex);
}
public int Count
{
get { return _items.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
bool ICollection<T>.Remove(T item)
{
return Remove(item);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class InKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterFrom()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var q = from $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFromIdentifier()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFromAndTypeAndIdentifier()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from int x $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterJoin()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var q = from x in y
join $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterJoinIdentifier()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
join z $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterJoinAndTypeAndIdentifier()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
join int z $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterJoinNotAfterIn()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var q = from x in y
join z in $$"));
}
[WorkItem(544158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544158")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterJoinPredefinedType()
{
await VerifyAbsenceAsync(
@"using System;
using System.Linq;
class C {
void M()
{
var q = from x in y
join int $$");
}
[WorkItem(544158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544158")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterJoinType()
{
await VerifyAbsenceAsync(
@"using System;
using System.Linq;
class C {
void M()
{
var q = from x in y
join Int32 $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForEach()
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach (var v $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForEach1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach (var v $$ c"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForEach2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach (var v $$ c"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInForEach()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"foreach ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInForEach1()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"foreach (var $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInForEach2()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"foreach (var v in $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInForEach3()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"foreach (var v in c $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInterfaceTypeVarianceAfterAngle()
{
await VerifyKeywordAsync(
@"interface IFoo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInterfaceTypeVarianceNotAfterIn()
{
await VerifyAbsenceAsync(
@"interface IFoo<in $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInterfaceTypeVarianceAfterComma()
{
await VerifyKeywordAsync(
@"interface IFoo<Foo, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInterfaceTypeVarianceAfterAttribute()
{
await VerifyKeywordAsync(
@"interface IFoo<[Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestDelegateTypeVarianceAfterAngle()
{
await VerifyKeywordAsync(
@"delegate void D<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestDelegateTypeVarianceAfterComma()
{
await VerifyKeywordAsync(
@"delegate void D<Foo, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestDelegateTypeVarianceAfterAttribute()
{
await VerifyKeywordAsync(
@"delegate void D<[Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInClassTypeVarianceAfterAngle()
{
await VerifyAbsenceAsync(
@"class IFoo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInStructTypeVarianceAfterAngle()
{
await VerifyAbsenceAsync(
@"struct IFoo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseListAfterAngle()
{
await VerifyAbsenceAsync(
@"interface IFoo : Bar<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGenericMethod()
{
await VerifyAbsenceAsync(
@"interface IFoo {
void Foo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestFrom2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q2 = from int x $$ ((IEnumerable)src))"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestFrom3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q2 = from x $$ ((IEnumerable)src))"));
}
[WorkItem(544158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544158")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterFromPredefinedType()
{
await VerifyAbsenceAsync(
@"using System;
using System.Linq;
class C {
void M()
{
var q = from int $$");
}
[WorkItem(544158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544158")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterFromType()
{
await VerifyAbsenceAsync(
@"using System;
using System.Linq;
class C {
void M()
{
var q = from Int32 $$");
}
}
}
| |
// Amplify Motion - Full-scene Motion Blur for Unity Pro
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9
#define UNITY_4
#endif
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5 || UNITY_5_6 || UNITY_5_7 || UNITY_5_8 || UNITY_5_9
#define UNITY_5
#endif
using System;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
#if !UNITY_4
using UnityEngine.Rendering;
#endif
namespace AmplifyMotion
{
internal class ClothState : AmplifyMotion.MotionState
{
#if UNITY_4
private InteractiveCloth m_cloth;
#else
private Cloth m_cloth;
#endif
private Renderer m_renderer;
private Matrix3x4 m_prevLocalToWorld;
private Matrix3x4 m_currLocalToWorld;
private int m_targetVertexCount;
private int[] m_targetRemap;
private Vector3[] m_prevVertices;
private Vector3[] m_currVertices;
private Mesh m_clonedMesh;
private MaterialDesc[] m_sharedMaterials;
private bool m_starting;
private bool m_wasVisible;
private static HashSet<AmplifyMotionObjectBase> m_uniqueWarnings = new HashSet<AmplifyMotionObjectBase>();
public ClothState( AmplifyMotionCamera owner, AmplifyMotionObjectBase obj )
: base( owner, obj )
{
#if UNITY_4
m_cloth = m_obj.GetComponent<InteractiveCloth>();
#else
m_cloth = m_obj.GetComponent<Cloth>();
#endif
}
void IssueError( string message )
{
if ( !m_uniqueWarnings.Contains( m_obj ) )
{
Debug.LogWarning( message );
m_uniqueWarnings.Add( m_obj );
}
m_error = true;
}
internal override void Initialize()
{
if ( m_cloth.vertices == null )
{
IssueError( "[AmplifyMotion] Invalid " + m_cloth.GetType().Name + " vertices in object " + m_obj.name + ". Skipping." );
return;
}
#if UNITY_4
Mesh clothMesh = m_cloth.mesh;
#else
SkinnedMeshRenderer skinnedRenderer = m_cloth.gameObject.GetComponent<SkinnedMeshRenderer>();
Mesh clothMesh = skinnedRenderer.sharedMesh;
#endif
if ( clothMesh == null || clothMesh.vertices == null || clothMesh.triangles == null )
{
IssueError( "[AmplifyMotion] Invalid Mesh on Cloth-enabled object " + m_obj.name );
return;
}
base.Initialize();
m_renderer = m_cloth.gameObject.GetComponent<Renderer>();
int meshVertexCount = clothMesh.vertexCount;
Vector3[] meshVertices = clothMesh.vertices;
Vector2[] meshTexcoords = clothMesh.uv;
int[] meshTriangles = clothMesh.triangles;
m_targetRemap = new int[ meshVertexCount ];
if ( m_cloth.vertices.Length == clothMesh.vertices.Length )
{
for ( int i = 0; i < meshVertexCount; i++ )
m_targetRemap[ i ] = i;
}
else
{
// a) May contains duplicated verts, optimization/cleanup is required
Dictionary<Vector3, int> dict = new Dictionary<Vector3, int>();
int original, vertexCount = 0;
for ( int i = 0; i < meshVertexCount; i++ )
{
if ( dict.TryGetValue( meshVertices[ i ], out original ) )
m_targetRemap[ i ] = original;
else
{
m_targetRemap[ i ] = vertexCount;
dict.Add( meshVertices[ i ], vertexCount++ );
}
}
// b) Tear is activated, creates extra verts (NOT SUPPORTED, POOL OF VERTS USED, NO ACCESS TO TRIANGLES)
}
m_targetVertexCount = meshVertexCount;
m_prevVertices = new Vector3[ m_targetVertexCount ];
m_currVertices = new Vector3[ m_targetVertexCount ];
m_clonedMesh = new Mesh();
m_clonedMesh.vertices = meshVertices;
m_clonedMesh.normals = meshVertices;
m_clonedMesh.uv = meshTexcoords;
m_clonedMesh.triangles = meshTriangles;
m_sharedMaterials = ProcessSharedMaterials( m_renderer.sharedMaterials );
m_wasVisible = false;
}
internal override void Shutdown()
{
Mesh.Destroy( m_clonedMesh );
}
#if UNITY_4
internal override void UpdateTransform( bool starting )
#else
internal override void UpdateTransform( CommandBuffer updateCB, bool starting )
#endif
{
if ( !m_initialized )
{
Initialize();
return;
}
Profiler.BeginSample( "Cloth.Update" );
if ( !starting && m_wasVisible )
m_prevLocalToWorld = m_currLocalToWorld;
bool isVisible = m_renderer.isVisible;
if ( !m_error && ( isVisible || starting ) )
{
if ( !starting && m_wasVisible )
Array.Copy( m_currVertices, m_prevVertices, m_targetVertexCount );
}
#if UNITY_4
m_currLocalToWorld = Matrix4x4.identity;
#else
m_currLocalToWorld = Matrix4x4.TRS( m_transform.position, m_transform.rotation, Vector3.one );
#endif
if ( starting || !m_wasVisible )
m_prevLocalToWorld = m_currLocalToWorld;
m_starting = starting;
m_wasVisible = isVisible;
Profiler.EndSample();
}
#if UNITY_4
internal override void RenderVectors( Camera camera, float scale, AmplifyMotion.Quality quality )
{
if ( m_initialized && !m_error && m_renderer.isVisible )
{
Profiler.BeginSample( "Cloth.Render" );
const float rcp255 = 1 / 255.0f;
bool mask = ( m_owner.Instance.CullingMask & ( 1 << m_obj.gameObject.layer ) ) != 0;
int objectId = mask ? m_owner.Instance.GenerateObjectId( m_obj.gameObject ) : 255;
Vector3[] clothVertices = m_cloth.vertices;
for ( int i = 0; i < m_targetVertexCount; i++ )
m_currVertices[ i ] = clothVertices[ m_targetRemap[ i ] ];
if ( m_starting || !m_wasVisible )
Array.Copy( m_currVertices, m_prevVertices, m_targetVertexCount );
m_clonedMesh.vertices = m_currVertices;
m_clonedMesh.normals = m_prevVertices;
Matrix4x4 prevModelViewProj;
if ( m_obj.FixedStep )
prevModelViewProj = m_owner.PrevViewProjMatrixRT * ( Matrix4x4 ) m_currLocalToWorld;
else
prevModelViewProj = m_owner.PrevViewProjMatrixRT * ( Matrix4x4 ) m_prevLocalToWorld;
Shader.SetGlobalMatrix( "_AM_MATRIX_PREV_MVP", prevModelViewProj );
Shader.SetGlobalFloat( "_AM_OBJECT_ID", objectId * rcp255 );
Shader.SetGlobalFloat( "_AM_MOTION_SCALE", mask ? scale : 0 );
int qualityPass = ( quality == AmplifyMotion.Quality.Mobile ) ? 0 : 2;
for ( int i = 0; i < m_sharedMaterials.Length; i++ )
{
MaterialDesc matDesc = m_sharedMaterials[ i ];
int pass = qualityPass + ( matDesc.coverage ? 1 : 0 );
if ( matDesc.coverage )
{
m_owner.Instance.ClothVectorsMaterial.mainTexture = matDesc.material.mainTexture;
if ( matDesc.cutoff )
m_owner.Instance.ClothVectorsMaterial.SetFloat( "_Cutoff", matDesc.material.GetFloat( "_Cutoff" ) );
}
if ( m_owner.Instance.ClothVectorsMaterial.SetPass( pass ) )
{
#if UNITY_4
Graphics.DrawMeshNow( m_clonedMesh, Matrix4x4.identity, i );
#else
Graphics.DrawMeshNow( m_clonedMesh, m_currLocalToWorld, i );
#endif
}
}
Profiler.EndSample();
}
}
#else
internal override void RenderVectors( Camera camera, CommandBuffer renderCB, float scale, AmplifyMotion.Quality quality )
{
if ( m_initialized && !m_error && m_renderer.isVisible )
{
Profiler.BeginSample( "Cloth.Render" );
const float rcp255 = 1 / 255.0f;
bool mask = ( m_owner.Instance.CullingMask & ( 1 << m_obj.gameObject.layer ) ) != 0;
int objectId = mask ? m_owner.Instance.GenerateObjectId( m_obj.gameObject ) : 255;
Vector3[] clothVertices = m_cloth.vertices;
for ( int i = 0; i < m_targetVertexCount; i++ )
m_currVertices[ i ] = clothVertices[ m_targetRemap[ i ] ];
if ( m_starting || !m_wasVisible )
Array.Copy( m_currVertices, m_prevVertices, m_targetVertexCount );
m_clonedMesh.vertices = m_currVertices;
m_clonedMesh.normals = m_prevVertices;
Matrix4x4 prevModelViewProj;
if ( m_obj.FixedStep )
prevModelViewProj = m_owner.PrevViewProjMatrixRT * ( Matrix4x4 ) m_currLocalToWorld;
else
prevModelViewProj = m_owner.PrevViewProjMatrixRT * ( Matrix4x4 ) m_prevLocalToWorld;
renderCB.SetGlobalMatrix( "_AM_MATRIX_PREV_MVP", prevModelViewProj );
renderCB.SetGlobalFloat( "_AM_OBJECT_ID", objectId * rcp255 );
renderCB.SetGlobalFloat( "_AM_MOTION_SCALE", mask ? scale : 0 );
int qualityPass = ( quality == AmplifyMotion.Quality.Mobile ) ? 0 : 2;
for ( int i = 0; i < m_sharedMaterials.Length; i++ )
{
MaterialDesc matDesc = m_sharedMaterials[ i ];
int pass = qualityPass + ( matDesc.coverage ? 1 : 0 );
if ( matDesc.coverage )
{
Texture mainTex = matDesc.material.mainTexture;
if ( mainTex != null )
matDesc.propertyBlock.SetTexture( "_MainTex", mainTex );
if ( matDesc.cutoff )
matDesc.propertyBlock.SetFloat( "_Cutoff", matDesc.material.GetFloat( "_Cutoff" ) );
}
renderCB.DrawMesh( m_clonedMesh, m_currLocalToWorld, m_owner.Instance.ClothVectorsMaterial, i, pass, matDesc.propertyBlock );
}
Profiler.EndSample();
}
}
#endif
}
}
| |
using Bridge.Contract;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Bridge.Translator.Tests
{
internal class Comparence
{
public string Name
{
get;
set;
}
public string File1FullPath
{
get;
set;
}
public string File2FullPath
{
get;
set;
}
public bool InReference
{
get;
set;
}
public string Difference
{
get;
set;
}
public CompareResult Result
{
get;
set;
}
public string ContentMarker
{
get; set;
}
public override string ToString()
{
var fromTo = new string[2];
if (InReference)
{
fromTo[0] = "Output";
fromTo[1] = "Reference";
}
else
{
fromTo[1] = "Output";
fromTo[0] = "Reference";
}
string difference;
switch (Result)
{
case CompareResult.DoesNotExist:
difference = string.Empty;
break;
case CompareResult.HasContentDifferences:
difference = " Difference: " + Difference + ".";
break;
case CompareResult.TheSame:
difference = string.Empty;
break;
default:
difference = string.Empty;
break;
}
return string.Format("{0} file {1} compared with {2} file {3}.{4}", fromTo[0], Name, fromTo[1], Result, difference);
}
}
internal enum CompareMode
{
Default = 0,
Presence = 1,
Content = 2,
MarkedContent = 3
}
internal enum CompareResult
{
DoesNotExist = 0,
HasContentDifferences = 1,
TheSame = 2
}
internal class FolderComparer
{
public ILogger Logger { get; set; }
public List<Comparence> CompareFolders(string referenceFolder, string outputFolder, Dictionary<string, CompareMode> specialFiles)
{
var referenceDirectory = new DirectoryInfo(referenceFolder);
var referenceFiles = referenceDirectory.GetFiles("*", SearchOption.AllDirectories);
var outputDirectory = new DirectoryInfo(outputFolder);
var outputFiles = outputDirectory.GetFiles("*", SearchOption.AllDirectories);
var comparence = new Dictionary<string, Comparence>(referenceFiles.Length > outputFiles.Length ? referenceFiles.Length : outputFiles.Length);
foreach (var file in referenceFiles)
{
HandleFile(referenceFolder, outputFolder, specialFiles, comparence, file, true);
}
foreach (var file in outputFiles)
{
HandleFile(outputFolder, referenceFolder, specialFiles, comparence, file, false);
}
return comparence.Values.Where(x => x.Result != CompareResult.TheSame).ToList();
}
public void LogDifferences(string diffName, List<Comparence> comparence)
{
var differ = new DiffMatchPatch.diff_match_patch();
differ.Diff_Timeout = 10;
var sb = new StringBuilder(diffName);
sb.AppendLine();
foreach (var diff in comparence)
{
if (diff.Result != CompareResult.HasContentDifferences)
{
continue;
}
try
{
var contents = GetFileContents(diff.File1FullPath, diff.File2FullPath, diff.ContentMarker);
if (contents.Item1 != null)
{
sb.AppendLine(string.Format("DIFF Could not get detailed diff " + contents.Item1));
continue;
}
var file1Content = contents.Item2;
if (file1Content == null)
{
sb.AppendLine(string.Format("DIFF Could not get detailed diff for {0}. Content is null.}", diff.File1FullPath));
continue;
}
var file2Content = contents.Item3;
if (file2Content == null)
{
sb.AppendLine(string.Format("DIFF Could not get detailed diff for {0}. Content is null.}", diff.File2FullPath));
continue;
}
var patches = differ.patch_make(file1Content, file2Content);
var patchText = differ.patch_toText(patches);
sb.AppendLine();
sb.AppendLine("DIFF for " + diff.ToString());
sb.AppendLine();
sb.AppendLine(patchText);
//sb.AppendLine();
//sb.AppendLine("|" + diffText + "|");
//sb.AppendLine("-------------------File 1 content:");
//sb.AppendLine(file1Content);
//sb.AppendLine("-------------------File 2 content:");
//sb.AppendLine(file2Content);
}
catch (System.Exception ex)
{
sb.AppendLine(string.Format("DIFF Could not get detailed diff for {0}. Exception: {1}", diff.ToString(), ex.Message));
}
}
Logger.Warn(string.Empty);
Logger.Warn(sb.ToString());
}
private void HandleFile(string folder1, string folder2, Dictionary<string, CompareMode> specialFiles, Dictionary<string, Comparence> comparence, FileInfo file, bool inReference, bool ignoreSame = true)
{
if (comparence.ContainsKey(file.Name))
{
return;
}
var cd = new Comparence
{
Name = file.Name,
File1FullPath = file.FullName,
Result = CompareResult.DoesNotExist,
InReference = inReference
};
var file2FullName = cd.File1FullPath.Replace(folder1, folder2);
if (File.Exists(file2FullName))
{
cd.File2FullPath = file2FullName;
if (specialFiles != null && specialFiles.Count > 0)
{
CompareMode specialFileMode;
if (specialFiles.TryGetValue(file.Name, out specialFileMode))
{
if (specialFileMode == CompareMode.MarkedContent)
{
cd.ContentMarker = Constansts.CONTENT_MARKER;
}
else
{
cd.Result = CompareResult.TheSame;
return;
}
}
}
cd.Result = CompareResult.HasContentDifferences;
cd.Difference = AnyDifference(cd.File1FullPath, cd.File2FullPath, cd.ContentMarker);
if (cd.Difference == null)
{
if (ignoreSame)
{
return;
}
cd.Result = CompareResult.TheSame;
}
}
comparence.Add(file.Name, cd);
}
private static Tuple<string, string, string> GetFileContents(string file1, string file2, string contentMarker = null)
{
var s1 = File.ReadAllText(file1, Constansts.Encoding);
var s2 = File.ReadAllText(file2, Constansts.Encoding);
if (contentMarker != null)
{
var markerPosition1 = s1.IndexOf(contentMarker);
if (markerPosition1 >= 0)
{
s1 = s1.Remove(0, markerPosition1);
}
var markerPosition2 = s2.IndexOf(contentMarker);
if (markerPosition2 >= 0)
{
s2 = s2.Remove(0, markerPosition2);
}
if (markerPosition1 < 0 || markerPosition2 < 0)
{
var error = "Content marker position not found either for file1 or file2:";
error += string.Format(" for file {0} at position {1}", file1, markerPosition1);
error += string.Format(" for file {0} at position {1}", file2, markerPosition2);
return Tuple.Create(error, (string)null, (string)null);
}
}
return Tuple.Create((string)null, s1, s2);
}
private static string AnyDifference(string file1, string file2, string contentMarker = null)
{
var contents = GetFileContents(file1, file2, contentMarker);
if (contents.Item1 != null)
{
return contents.Item1;
}
var s1 = contents.Item2;
var s2 = contents.Item3;
if (s1.Length != s2.Length)
{
return string.Format("Length difference {0} vs {1}", s2.Length, s1.Length);
}
int i = 0;
while (i < s1.Length)
{
var b1 = s1[i];
var b2 = s2[i];
if (b1 != b2)
{
return string.Format("Content difference found at symbol {0} with `{1}` vs `{2}`", i, b2, b1);
}
i++;
}
return null;
}
public static string ReadFile(string fullFileName)
{
if (!File.Exists(fullFileName))
{
return null;
}
using (Stream stream = new FileStream(fullFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// BigInt.cs
//
// 11/06/2002
//
namespace System.Security.Cryptography
{
using System.Security.Cryptography.X509Certificates;
using System.Text;
//
// This is a pretty "crude" implementation of BigInt arithmetic operations.
// This class is used in particular to convert certificate serial numbers from
// hexadecimal representation to decimal format and vice versa.
//
// We are not very concerned about the perf characterestics of this implementation
// for now. We perform all operations up to 128 bytes (which is enough for the current
// purposes although this constant can be increased). Any overflow bytes are going to be lost.
//
// A BigInt is represented as a little endian byte array of size 128 bytes. All
// arithmetic operations are performed in base 0x100 (256). The algorithms used
// are simply the common primary school techniques for doing operations in base 10.
//
internal sealed class BigInt {
private byte[] m_elements;
private const int m_maxbytes = 128; // 128 bytes is the maximum we can handle.
// This means any overflow bits beyond 128 bytes
// will be lost when doing arithmetic operations.
private const int m_base = 0x100;
private int m_size = 0;
internal BigInt () {
m_elements = new byte[m_maxbytes];
}
internal BigInt(byte b) {
m_elements = new byte[m_maxbytes];
SetDigit(0, b);
}
//
// Gets or sets the size of a BigInt.
//
internal int Size {
get {
return m_size;
}
set {
if (value > m_maxbytes)
m_size = m_maxbytes;
if (value < 0)
m_size = 0;
m_size = value;
}
}
//
// Gets the digit at the specified index.
//
internal byte GetDigit (int index) {
if (index < 0 || index >= m_size)
return 0;
return m_elements[index];
}
//
// Sets the digit at the specified index.
//
internal void SetDigit (int index, byte digit) {
if (index >= 0 && index < m_maxbytes) {
m_elements[index] = digit;
if (index >= m_size && digit != 0)
m_size = (index + 1);
if (index == m_size - 1 && digit == 0)
m_size--;
}
}
internal void SetDigit (int index, byte digit, ref int size) {
if (index >= 0 && index < m_maxbytes) {
m_elements[index] = digit;
if (index >= size && digit != 0)
size = (index + 1);
if (index == size - 1 && digit == 0)
size = (size - 1);
}
}
//
// overloaded operators.
//
public static bool operator < (BigInt value1, BigInt value2) {
if (value1 == null)
return true;
else if (value2 == null)
return false;
int Len1 = value1.Size;
int Len2 = value2.Size;
if (Len1 != Len2)
return (Len1 < Len2);
while (Len1-- > 0) {
if (value1.m_elements[Len1] != value2.m_elements[Len1])
return (value1.m_elements[Len1] < value2.m_elements[Len1]);
}
return false;
}
public static bool operator > (BigInt value1, BigInt value2) {
if (value1 == null)
return false;
else if (value2 == null)
return true;
int Len1 = value1.Size;
int Len2 = value2.Size;
if (Len1 != Len2)
return (Len1 > Len2);
while (Len1-- > 0) {
if (value1.m_elements[Len1] != value2.m_elements[Len1])
return (value1.m_elements[Len1] > value2.m_elements[Len1]);
}
return false;
}
public static bool operator == (BigInt value1, BigInt value2) {
if ((Object) value1 == null)
return ((Object) value2 == null);
else if ((Object) value2 == null)
return ((Object) value1 == null);
int Len1 = value1.Size;
int Len2 = value2.Size;
if (Len1 != Len2)
return false;
for (int index = 0; index < Len1; index++) {
if (value1.m_elements[index] != value2.m_elements[index])
return false;
}
return true;
}
public static bool operator != (BigInt value1, BigInt value2) {
return !(value1 == value2);
}
public override bool Equals (Object obj) {
if (obj is BigInt) {
return (this == (BigInt) obj);
}
return false;
}
public override int GetHashCode () {
int hash = 0;
for (int index = 0; index < m_size; index++) {
hash += GetDigit(index);
}
return hash;
}
//
// Adds a and b and outputs the result in c.
//
internal static void Add (BigInt a, byte b, ref BigInt c) {
byte carry = b;
int sum = 0;
int size = a.Size;
int newSize = 0;
for (int index = 0; index < size; index++) {
sum = a.GetDigit(index) + carry;
c.SetDigit(index, (byte) (sum & 0xFF), ref newSize);
carry = (byte) ((sum >> 8) & 0xFF);
}
if (carry != 0)
c.SetDigit(a.Size, carry, ref newSize);
c.Size = newSize;
}
//
// Negates a BigInt value. Each byte is complemented, then we add 1 to it.
//
internal static void Negate (ref BigInt a) {
int newSize = 0;
for (int index = 0; index < m_maxbytes; index++) {
a.SetDigit(index, (byte) (~a.GetDigit(index) & 0xFF), ref newSize);
}
for (int index = 0; index < m_maxbytes; index++) {
a.SetDigit(index, (byte) (a.GetDigit(index) + 1), ref newSize);
if ((a.GetDigit(index) & 0xFF) != 0) break;
a.SetDigit(index, (byte) (a.GetDigit(index) & 0xFF), ref newSize);
}
a.Size = newSize;
}
//
// Subtracts b from a and outputs the result in c.
//
internal static void Subtract (BigInt a, BigInt b, ref BigInt c) {
byte borrow = 0;
int diff = 0;
if (a < b) {
Subtract(b, a, ref c);
Negate(ref c);
return;
}
int index = 0;
int size = a.Size;
int newSize = 0;
for (index = 0; index < size; index++) {
diff = a.GetDigit(index) - b.GetDigit(index) - borrow;
borrow = 0;
if (diff < 0) {
diff += m_base;
borrow = 1;
}
c.SetDigit(index, (byte) (diff & 0xFF), ref newSize);
}
c.Size = newSize;
}
//
// multiplies a BigInt by an integer.
//
private void Multiply (int b) {
if (b == 0) {
Clear();
return;
}
int carry = 0, product = 0;
int size = this.Size;
int newSize = 0;
for (int index = 0; index < size; index++) {
product = b * GetDigit(index) + carry;
carry = product / m_base;
SetDigit(index, (byte) (product % m_base), ref newSize);
}
if (carry != 0) {
byte[] bytes = BitConverter.GetBytes(carry);
for (int index = 0; index < bytes.Length; index++) {
SetDigit(size + index, bytes[index], ref newSize);
}
}
this.Size = newSize;
}
private static void Multiply (BigInt a, int b, ref BigInt c) {
if (b == 0) {
c.Clear();
return;
}
int carry = 0, product = 0;
int size = a.Size;
int newSize = 0;
for (int index = 0; index < size; index++) {
product = b * a.GetDigit(index) + carry;
carry = product / m_base;
c.SetDigit(index, (byte) (product % m_base), ref newSize);
}
if (carry != 0) {
byte[] bytes = BitConverter.GetBytes(carry);
for (int index = 0; index < bytes.Length; index++) {
c.SetDigit(size + index, bytes[index], ref newSize);
}
}
c.Size = newSize;
}
//
// Divides a BigInt by a single byte.
//
private void Divide (int b) {
int carry = 0, quotient = 0;
int bLen = this.Size;
int newSize = 0;
while (bLen-- > 0) {
quotient = m_base * carry + GetDigit(bLen);
carry = quotient % b;
SetDigit(bLen, (byte) (quotient / b), ref newSize);
}
this.Size = newSize;
}
//
// Integer division of one BigInt by another.
//
internal static void Divide (BigInt numerator, BigInt denominator, ref BigInt quotient, ref BigInt remainder) {
// Avoid extra computations in special cases.
if (numerator < denominator) {
quotient.Clear();
remainder.CopyFrom(numerator);
return;
}
if (numerator == denominator) {
quotient.Clear(); quotient.SetDigit(0, 1);
remainder.Clear();
return;
}
BigInt dividend = new BigInt();
dividend.CopyFrom(numerator);
BigInt divisor = new BigInt();
divisor.CopyFrom(denominator);
uint zeroCount = 0;
// We pad the divisor with zeros until its size equals that of the dividend.
while (divisor.Size < dividend.Size) {
divisor.Multiply(m_base);
zeroCount++;
}
if (divisor > dividend) {
divisor.Divide(m_base);
zeroCount--;
}
// Use school division techniques, make a guess for how many times
// divisor goes into dividend, making adjustment if necessary.
int a = 0;
int b = 0;
int c = 0;
BigInt hold = new BigInt();
quotient.Clear();
for (int index = 0; index <= zeroCount; index++) {
a = dividend.Size == divisor.Size ? dividend.GetDigit(dividend.Size - 1) :
m_base * dividend.GetDigit(dividend.Size - 1) + dividend.GetDigit(dividend.Size - 2);
b = divisor.GetDigit(divisor.Size - 1);
c = a / b;
if (c >= m_base)
c = 0xFF;
Multiply(divisor, c, ref hold);
while (hold > dividend) {
c--;
Multiply(divisor, c, ref hold);
}
quotient.Multiply(m_base);
Add(quotient, (byte) c, ref quotient);
Subtract(dividend, hold, ref dividend);
divisor.Divide(m_base);
}
remainder.CopyFrom(dividend);
}
//
// copies a BigInt value.
//
internal void CopyFrom (BigInt a) {
Array.Copy(a.m_elements, m_elements, m_maxbytes);
m_size = a.m_size;
}
//
// This method returns true if the BigInt is equal to 0, false otherwise.
//
internal bool IsZero () {
for (int index = 0; index < m_size; index++) {
if (m_elements[index] != 0)
return false;
}
return true;
}
//
// returns the array in machine format, i.e. little endian format (as an integer).
//
internal byte[] ToByteArray() {
byte[] result = new byte[this.Size];
Array.Copy(m_elements, result, this.Size);
return result;
}
//
// zeroizes the content of the internal array.
//
internal void Clear () {
m_size = 0;
}
//
// Imports a hexadecimal string into a BigInt bit representation.
//
internal void FromHexadecimal (string hexNum) {
byte[] hex = X509Utils.DecodeHexString(hexNum);
Array.Reverse(hex);
int size = X509Utils.GetHexArraySize(hex);
Array.Copy(hex, m_elements, size);
this.Size = size;
}
//
// Imports a decimal string into a BigInt bit representation.
//
internal void FromDecimal (string decNum) {
BigInt c = new BigInt();
BigInt tmp = new BigInt();
int length = decNum.Length;
for (int index = 0; index < length; index++) {
// just ignore invalid characters. No need to raise an exception.
if (decNum[index] > '9' || decNum[index] < '0')
continue;
Multiply(c, 10, ref tmp);
Add(tmp, (byte) (decNum[index] - '0'), ref c);
}
CopyFrom(c);
}
//
// Exports the BigInt representation as a decimal string.
//
private static readonly char[] decValues = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
internal string ToDecimal ()
{
if (IsZero())
return "0";
BigInt ten = new BigInt(0xA);
BigInt numerator = new BigInt();
BigInt quotient = new BigInt();
BigInt remainder = new BigInt();
numerator.CopyFrom(this);
// Each hex digit can account for log(16) = 1.21 decimal digits. Times two hex digits in a byte
// and m_size bytes used in this BigInt, yields the maximum number of characters for the decimal
// representation of the BigInt.
char[] dec = new char[(int)Math.Ceiling(m_size * 2 * 1.21)];
int index = 0;
do
{
Divide(numerator, ten, ref quotient, ref remainder);
dec[index++] = decValues[remainder.IsZero() ? 0 : (int)remainder.m_elements[0]];
numerator.CopyFrom(quotient);
} while (quotient.IsZero() == false);
Array.Reverse(dec, 0, index);
return new String(dec, 0, index);
}
}
}
| |
// <copyright file="IncompleteLU.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra.Solvers;
using MathNet.Numerics.Properties;
namespace MathNet.Numerics.LinearAlgebra.Double.Solvers
{
/// <summary>
/// An incomplete, level 0, LU factorization preconditioner.
/// </summary>
/// <remarks>
/// The ILU(0) algorithm was taken from: <br/>
/// Iterative methods for sparse linear systems <br/>
/// Yousef Saad <br/>
/// Algorithm is described in Chapter 10, section 10.3.2, page 275 <br/>
/// </remarks>
public sealed class ILU0Preconditioner : IPreconditioner<double>
{
/// <summary>
/// The matrix holding the lower (L) and upper (U) matrices. The
/// decomposition matrices are combined to reduce storage.
/// </summary>
SparseMatrix _decompositionLU;
/// <summary>
/// Returns the upper triagonal matrix that was created during the LU decomposition.
/// </summary>
/// <returns>A new matrix containing the upper triagonal elements.</returns>
internal Matrix<double> UpperTriangle()
{
var result = new SparseMatrix(_decompositionLU.RowCount);
for (var i = 0; i < _decompositionLU.RowCount; i++)
{
for (var j = i; j < _decompositionLU.ColumnCount; j++)
{
result[i, j] = _decompositionLU[i, j];
}
}
return result;
}
/// <summary>
/// Returns the lower triagonal matrix that was created during the LU decomposition.
/// </summary>
/// <returns>A new matrix containing the lower triagonal elements.</returns>
internal Matrix<double> LowerTriangle()
{
var result = new SparseMatrix(_decompositionLU.RowCount);
for (var i = 0; i < _decompositionLU.RowCount; i++)
{
for (var j = 0; j <= i; j++)
{
if (i == j)
{
result[i, j] = 1.0;
}
else
{
result[i, j] = _decompositionLU[i, j];
}
}
}
return result;
}
/// <summary>
/// Initializes the preconditioner and loads the internal data structures.
/// </summary>
/// <param name="matrix">The matrix upon which the preconditioner is based. </param>
/// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <see langword="null" />.</exception>
/// <exception cref="ArgumentException">If <paramref name="matrix"/> is not a square matrix.</exception>
public void Initialize(Matrix<double> matrix)
{
if (matrix == null)
{
throw new ArgumentNullException("matrix");
}
if (matrix.RowCount != matrix.ColumnCount)
{
throw new ArgumentException(Resource.ArgumentMatrixSquare, "matrix");
}
_decompositionLU = SparseMatrix.OfMatrix(matrix);
// M == A
// for i = 2, ... , n do
// for k = 1, .... , i - 1 do
// if (i,k) == NZ(Z) then
// compute z(i,k) = z(i,k) / z(k,k);
// for j = k + 1, ...., n do
// if (i,j) == NZ(Z) then
// compute z(i,j) = z(i,j) - z(i,k) * z(k,j)
// end
// end
// end
// end
// end
for (var i = 0; i < _decompositionLU.RowCount; i++)
{
for (var k = 0; k < i; k++)
{
if (_decompositionLU[i, k] != 0.0)
{
var t = _decompositionLU[i, k]/_decompositionLU[k, k];
_decompositionLU[i, k] = t;
if (_decompositionLU[k, i] != 0.0)
{
_decompositionLU[i, i] = _decompositionLU[i, i] - (t*_decompositionLU[k, i]);
}
for (var j = k + 1; j < _decompositionLU.RowCount; j++)
{
if (j == i)
{
continue;
}
if (_decompositionLU[i, j] != 0.0)
{
_decompositionLU[i, j] = _decompositionLU[i, j] - (t*_decompositionLU[k, j]);
}
}
}
}
}
}
/// <summary>
/// Approximates the solution to the matrix equation <b>Ax = b</b>.
/// </summary>
/// <param name="rhs">The right hand side vector.</param>
/// <param name="lhs">The left hand side vector. Also known as the result vector.</param>
public void Approximate(Vector<double> rhs, Vector<double> lhs)
{
if (_decompositionLU == null)
{
throw new ArgumentException(Resource.ArgumentMatrixDoesNotExist);
}
if ((lhs.Count != rhs.Count) || (lhs.Count != _decompositionLU.RowCount))
{
throw new ArgumentException(Resource.ArgumentVectorsSameLength);
}
// Solve:
// Lz = y
// Which gives
// for (int i = 1; i < matrix.RowLength; i++)
// {
// z_i = l_ii^-1 * (y_i - SUM_(j<i) l_ij * z_j)
// }
// NOTE: l_ii should be 1 because u_ii has to be the value
var rowValues = new DenseVector(_decompositionLU.RowCount);
for (var i = 0; i < _decompositionLU.RowCount; i++)
{
// Clear the rowValues
rowValues.Clear();
_decompositionLU.Row(i, rowValues);
var sum = 0.0;
for (var j = 0; j < i; j++)
{
sum += rowValues[j]*lhs[j];
}
lhs[i] = rhs[i] - sum;
}
// Solve:
// Ux = z
// Which gives
// for (int i = matrix.RowLength - 1; i > -1; i--)
// {
// x_i = u_ii^-1 * (z_i - SUM_(j > i) u_ij * x_j)
// }
for (var i = _decompositionLU.RowCount - 1; i > -1; i--)
{
_decompositionLU.Row(i, rowValues);
var sum = 0.0;
for (var j = _decompositionLU.RowCount - 1; j > i; j--)
{
sum += rowValues[j]*lhs[j];
}
lhs[i] = 1/rowValues[i]*(lhs[i] - sum);
}
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.Common.DataStructures
{
using System;
/// <summary>
/// This class contains all the properties which are associated with the elements defined in the MS-ASNOTE protocol
/// </summary>
public class Note
{
/// <summary>
/// Gets or sets note body information of the note, which contains type and content of the note
/// </summary>
public Response.Body Body { get; set; }
/// <summary>
/// Gets or sets Categories information of the note
/// </summary>
public Response.Categories4 Categories { get; set; }
/// <summary>
/// Gets or sets a value indicating whether include LastModifiedDate in the response
/// </summary>
public bool IsLastModifiedDateSpecified { get; set; }
/// <summary>
/// Gets or sets LastModifiedDate information of the note
/// </summary>
public DateTime LastModifiedDate { get; set; }
/// <summary>
/// Gets or sets MessageClass information of the note
/// </summary>
public string MessageClass { get; set; }
/// <summary>
/// Gets or sets subject information of the note
/// </summary>
public string Subject { get; set; }
/// <summary>
/// Gets or sets the value of LastModifiedDate element from the server response
/// </summary>
public string LastModifiedDateString { get; set; }
/// <summary>
/// Deserialize to object instance from Properties
/// </summary>
/// <typeparam name="T">The generic type parameter</typeparam>
/// <param name="properties">The Properties data which contains new added information</param>
/// <returns>The object instance</returns>
public static T DeserializeFromFetchProperties<T>(Response.Properties properties)
{
T obj = Activator.CreateInstance<T>();
if (properties.ItemsElementName.Length > 0)
{
for (int itemIndex = 0; itemIndex < properties.ItemsElementName.Length; itemIndex++)
{
switch (properties.ItemsElementName[itemIndex])
{
case Response.ItemsChoiceType3.Categories:
case Response.ItemsChoiceType3.Categories1:
case Response.ItemsChoiceType3.Categories2:
case Response.ItemsChoiceType3.Categories4:
case Response.ItemsChoiceType3.LastModifiedDate:
case Response.ItemsChoiceType3.Subject:
case Response.ItemsChoiceType3.Subject1:
case Response.ItemsChoiceType3.Subject3:
case Response.ItemsChoiceType3.MessageClass:
break;
case Response.ItemsChoiceType3.Categories3:
Common.SetSpecifiedPropertyValueByName(obj, "Categories", properties.Items[itemIndex]);
break;
case Response.ItemsChoiceType3.Body:
Common.SetSpecifiedPropertyValueByName(obj, "Body", properties.Items[itemIndex]);
break;
case Response.ItemsChoiceType3.LastModifiedDate1:
string lastModifiedDateString = properties.Items[itemIndex].ToString();
if (!string.IsNullOrEmpty(lastModifiedDateString))
{
Common.SetSpecifiedPropertyValueByName(obj, "IsLastModifiedDateSpecified", true);
Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDate", Common.GetNoSeparatorDateTime(lastModifiedDateString));
Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDateString", lastModifiedDateString);
}
break;
case Response.ItemsChoiceType3.Subject2:
Common.SetSpecifiedPropertyValueByName(obj, "Subject", properties.Items[itemIndex]);
break;
case Response.ItemsChoiceType3.MessageClass1:
Common.SetSpecifiedPropertyValueByName(obj, "MessageClass", properties.Items[itemIndex]);
break;
default:
Common.SetSpecifiedPropertyValueByName(obj, properties.ItemsElementName[itemIndex].ToString(), properties.Items[itemIndex]);
break;
}
}
}
return obj;
}
/// <summary>
/// Get note instance from the Properties element of Search response
/// </summary>
/// <typeparam name="T">The generic type parameter</typeparam>
/// <param name="properties">The data which contains information for note</param>
/// <returns>The returned note instance</returns>
public static T DeserializeFromSearchProperties<T>(Response.SearchResponseStoreResultProperties properties)
{
T obj = Activator.CreateInstance<T>();
if (properties.ItemsElementName.Length > 0)
{
for (int itemIndex = 0; itemIndex < properties.ItemsElementName.Length; itemIndex++)
{
switch (properties.ItemsElementName[itemIndex])
{
case Response.ItemsChoiceType6.Categories:
case Response.ItemsChoiceType6.Categories1:
case Response.ItemsChoiceType6.Categories3:
case Response.ItemsChoiceType6.Subject:
case Response.ItemsChoiceType6.Subject1:
case Response.ItemsChoiceType6.Subject3:
case Response.ItemsChoiceType6.LastModifiedDate:
case Response.ItemsChoiceType6.MessageClass:
break;
case Response.ItemsChoiceType6.Categories2:
Common.SetSpecifiedPropertyValueByName(obj, "Categories", (Response.Categories4)properties.Items[itemIndex]);
break;
case Response.ItemsChoiceType6.Subject2:
Common.SetSpecifiedPropertyValueByName(obj, "Subject", properties.Items[itemIndex]);
break;
case Response.ItemsChoiceType6.Body:
Common.SetSpecifiedPropertyValueByName(obj, "Body", (Response.Body)properties.Items[itemIndex]);
break;
case Response.ItemsChoiceType6.LastModifiedDate1:
string lastModifiedDateString = properties.Items[itemIndex].ToString();
if (!string.IsNullOrEmpty(lastModifiedDateString))
{
Common.SetSpecifiedPropertyValueByName(obj, "IsLastModifiedDateSpecified", true);
Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDate", Common.GetNoSeparatorDateTime(lastModifiedDateString));
Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDateString", lastModifiedDateString);
}
break;
case Response.ItemsChoiceType6.MessageClass1:
Common.SetSpecifiedPropertyValueByName(obj, "MessageClass", properties.Items[itemIndex]);
break;
default:
Common.SetSpecifiedPropertyValueByName(obj, properties.ItemsElementName[itemIndex].ToString(), properties.Items[itemIndex]);
break;
}
}
}
return obj;
}
/// <summary>
/// Get note instance from the ApplicationData element of Sync add response
/// </summary>
/// <typeparam name="T">The generic type parameter</typeparam>
/// <param name="applicationData">The data which contains information for note</param>
/// <returns>The returned instance</returns>
public static T DeserializeFromAddApplicationData<T>(Response.SyncCollectionsCollectionCommandsAddApplicationData applicationData)
{
T obj = Activator.CreateInstance<T>();
if (applicationData.ItemsElementName.Length > 0)
{
for (int itemIndex = 0; itemIndex < applicationData.ItemsElementName.Length; itemIndex++)
{
switch (applicationData.ItemsElementName[itemIndex])
{
case Response.ItemsChoiceType8.Categories:
case Response.ItemsChoiceType8.Categories1:
case Response.ItemsChoiceType8.Categories2:
case Response.ItemsChoiceType8.Categories4:
case Response.ItemsChoiceType8.Subject:
case Response.ItemsChoiceType8.Subject1:
case Response.ItemsChoiceType8.Subject3:
case Response.ItemsChoiceType8.LastModifiedDate:
case Response.ItemsChoiceType8.MessageClass:
break;
case Response.ItemsChoiceType8.Categories3:
Common.SetSpecifiedPropertyValueByName(obj, "Categories", applicationData.Items[itemIndex]);
break;
case Response.ItemsChoiceType8.Subject2:
Common.SetSpecifiedPropertyValueByName(obj, "Subject", applicationData.Items[itemIndex]);
break;
case Response.ItemsChoiceType8.Body:
Common.SetSpecifiedPropertyValueByName(obj, "Body", applicationData.Items[itemIndex]);
break;
case Response.ItemsChoiceType8.LastModifiedDate1:
string lastModifiedDateString = applicationData.Items[itemIndex].ToString();
if (!string.IsNullOrEmpty(lastModifiedDateString))
{
Common.SetSpecifiedPropertyValueByName(obj, "IsLastModifiedDateSpecified", true);
Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDate", Common.GetNoSeparatorDateTime(lastModifiedDateString));
Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDateString", lastModifiedDateString);
}
break;
case Response.ItemsChoiceType8.MessageClass1:
Common.SetSpecifiedPropertyValueByName(obj, "MessageClass", applicationData.Items[itemIndex]);
break;
default:
Common.SetSpecifiedPropertyValueByName(obj, applicationData.ItemsElementName[itemIndex].ToString(), applicationData.Items[itemIndex]);
break;
}
}
}
return obj;
}
/// <summary>
/// Get note instance from the ApplicationData element of Sync change response
/// </summary>
/// <typeparam name="T">The generic type parameter</typeparam>
/// <param name="applicationData">The data which contains information for note</param>
/// <returns>The returned instance</returns>
public static T DeserializeFromChangeApplicationData<T>(Response.SyncCollectionsCollectionCommandsChangeApplicationData applicationData)
{
T obj = Activator.CreateInstance<T>();
if (applicationData.ItemsElementName.Length > 0)
{
for (int itemIndex = 0; itemIndex < applicationData.ItemsElementName.Length; itemIndex++)
{
switch (applicationData.ItemsElementName[itemIndex])
{
case Response.ItemsChoiceType7.Categories:
case Response.ItemsChoiceType7.Categories1:
case Response.ItemsChoiceType7.Categories2:
case Response.ItemsChoiceType7.Categories4:
case Response.ItemsChoiceType7.Subject:
case Response.ItemsChoiceType7.Subject1:
case Response.ItemsChoiceType7.Subject3:
case Response.ItemsChoiceType7.LastModifiedDate:
case Response.ItemsChoiceType7.MessageClass:
break;
case Response.ItemsChoiceType7.Categories3:
Common.SetSpecifiedPropertyValueByName(obj, "Categories", applicationData.Items[itemIndex]);
break;
case Response.ItemsChoiceType7.Subject2:
Common.SetSpecifiedPropertyValueByName(obj, "Subject", applicationData.Items[itemIndex]);
break;
case Response.ItemsChoiceType7.Body:
Common.SetSpecifiedPropertyValueByName(obj, "Body", applicationData.Items[itemIndex]);
break;
case Response.ItemsChoiceType7.LastModifiedDate1:
string lastModifiedDateString = applicationData.Items[itemIndex].ToString();
if (!string.IsNullOrEmpty(lastModifiedDateString))
{
Common.SetSpecifiedPropertyValueByName(obj, "IsLastModifiedDateSpecified", true);
Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDate", Common.GetNoSeparatorDateTime(lastModifiedDateString));
Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDateString", lastModifiedDateString);
}
break;
case Response.ItemsChoiceType7.MessageClass1:
Common.SetSpecifiedPropertyValueByName(obj, "MessageClass", applicationData.Items[itemIndex]);
break;
default:
Common.SetSpecifiedPropertyValueByName(obj, applicationData.ItemsElementName[itemIndex].ToString(), applicationData.Items[itemIndex]);
break;
}
}
}
return obj;
}
}
}
| |
/*
* Naiad ver. 0.5
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.Naiad.Serialization;
using Microsoft.Research.Naiad.DataStructures;
using Microsoft.Research.Naiad.Dataflow;
namespace Microsoft.Research.Naiad.Runtime.Progress
{
internal static class PointstampConstructor
{
public static Pointstamp ToPointstamp<T>(this T time, int graphObjectID) where T : Time<T>
{
var pointstamp = new Pointstamp();
pointstamp.Location = graphObjectID;
pointstamp.Timestamp.Length = time.Coordinates;
time.Populate(ref pointstamp);
return pointstamp;
}
}
/// <summary>
/// Represents a combined dataflow graph location and timestamp,
/// for use in progress tracking.
/// </summary>
/// <seealso cref="Computation.OnFrontierChange"/>
public struct Pointstamp : IEquatable<Pointstamp>
{
/// <summary>
/// A fake array implementation to avoid heap allocation
/// </summary>
public struct FakeArray
{
/// <summary>
/// first coordinate
/// </summary>
public int a;
/// <summary>
/// second coordinate
/// </summary>
public int b;
/// <summary>
/// third coordinate
/// </summary>
public int c;
/// <summary>
/// fourth coordinate
/// </summary>
public int d;
/// <summary>
/// "length" of array
/// </summary>
public int Length;
/// <summary>
/// space for anything beyond four coordinates
/// </summary>
public int[] spillover;
/// <summary>
/// Returns the value at the given <paramref name="index"/>.
/// </summary>
/// <param name="index">The index.</param>
/// <returns>The value at the given <paramref name="index"/>.</returns>
public int this[int index]
{
get
{
switch (index)
{
case 0: return a;
case 1: return b;
case 2: return c;
case 3: return d;
default: return spillover[index - 4];
}
}
set
{
switch (index)
{
case 0: a = value; break;
case 1: b = value; break;
case 2: c = value; break;
case 3: d = value; break;
default: spillover[index - 4] = value; break;
}
}
}
/// <summary>
/// Constructs a FakeArray with the specified size.
/// </summary>
/// <param name="size">The size of this FakeArray.</param>
public FakeArray(int size)
{
Length = size;
a = b = c = d = 0;
if (Length > 4)
spillover = new int[Length - 4];
else
spillover = null;
}
/// <summary>
/// Returns a string representation of this array.
/// </summary>
/// <returns>A string representation of this array.</returns>
public override string ToString()
{
var result = new StringBuilder().Append(this[0]);
for (int i = 1; i < this.Length; i++)
result.AppendFormat(", {0}", this[i]);
return result.ToString();
}
}
/// <summary>
/// Dataflow graph location
/// </summary>
public int Location;
/// <summary>
/// Timestamp
/// </summary>
public FakeArray Timestamp;
/// <summary>
/// Returns a hashcode for this pointstamp.
/// </summary>
/// <returns>A hashcode for this pointstamp.</returns>
public override int GetHashCode()
{
var result = Location;
for (int i = 0; i < Timestamp.Length; i++)
result += Timestamp[i];
return result;
}
/// <summary>
/// Returns a string representation of this pointstamp.
/// </summary>
/// <returns>A string representation of this pointstamp.</returns>
public override string ToString()
{
return String.Format("[location = {0}, timestamp = <{1}>]", Location, Timestamp);
}
/// <summary>
/// Returns <c>true</c> if and only if this and the other pointstamps are equal.
/// </summary>
/// <param name="other">The other pointstamp.</param>
/// <returns><c>true</c> if and only if this and the other pointstamps are equal.</returns>
public bool Equals(Pointstamp other)
{
if (this.Location != other.Location)
return false;
if (this.Timestamp.Length != other.Timestamp.Length)
return false;
for (int i = 0; i < this.Timestamp.Length; i++)
if (this.Timestamp[i] != other.Timestamp[i])
return false;
return true;
}
/// <summary>
/// Constructs a Pointstamp copying from another
/// </summary>
/// <param name="that"></param>
internal Pointstamp(Pointstamp that)
{
this.Location = that.Location;
this.Timestamp = that.Timestamp;
}
/// <summary>
/// Constructs a new pointstamp from a location and int array
/// </summary>
/// <param name="location">dataflow graph location</param>
/// <param name="indices">timestamp indices</param>
internal Pointstamp(int location, int[] indices)
{
Location = location;
Timestamp = new FakeArray(indices.Length);
for (int j = 0; j < indices.Length; j++)
Timestamp[j] = indices[j];
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Net.HttpListenerRequest
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo.mono@gmail.com)
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2011-2012 Xamarin, Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Net.WebSockets;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace System.Net
{
public sealed partial class HttpListenerRequest
{
private class Context : TransportContext
{
public override ChannelBinding GetChannelBinding(ChannelBindingKind kind)
{
throw new NotImplementedException();
}
}
private long _contentLength;
private bool _clSet;
private CookieCollection _cookies;
private WebHeaderCollection _headers;
private string _method;
private Stream _inputStream;
private HttpListenerContext _context;
private bool _isChunked;
private bool _kaSet;
private bool _keepAlive;
private static byte[] s_100continue = Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n");
internal HttpListenerRequest(HttpListenerContext context)
{
_context = context;
_headers = new WebHeaderCollection();
_version = HttpVersion.Version10;
}
private static char[] s_separators = new char[] { ' ' };
internal void SetRequestLine(string req)
{
string[] parts = req.Split(s_separators, 3);
if (parts.Length != 3)
{
_context.ErrorMessage = "Invalid request line (parts).";
return;
}
_method = parts[0];
foreach (char c in _method)
{
int ic = (int)c;
if ((ic >= 'A' && ic <= 'Z') ||
(ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
continue;
_context.ErrorMessage = "(Invalid verb)";
return;
}
_rawUrl = parts[1];
if (parts[2].Length != 8 || !parts[2].StartsWith("HTTP/"))
{
_context.ErrorMessage = "Invalid request line (version).";
return;
}
try
{
_version = new Version(parts[2].Substring(5));
if (_version.Major < 1)
throw new Exception();
}
catch
{
_context.ErrorMessage = "Invalid request line (version).";
return;
}
}
private static bool MaybeUri(string s)
{
int p = s.IndexOf(':');
if (p == -1)
return false;
if (p >= 10)
return false;
return IsPredefinedScheme(s.Substring(0, p));
}
private static bool IsPredefinedScheme(string scheme)
{
if (scheme == null || scheme.Length < 3)
return false;
char c = scheme[0];
if (c == 'h')
return (scheme == UriScheme.Http || scheme == UriScheme.Https);
if (c == 'f')
return (scheme == UriScheme.File || scheme == UriScheme.Ftp);
if (c == 'n')
{
c = scheme[1];
if (c == 'e')
return (scheme == UriScheme.News || scheme == UriScheme.NetPipe || scheme == UriScheme.NetTcp);
if (scheme == UriScheme.Nntp)
return true;
return false;
}
if ((c == 'g' && scheme == UriScheme.Gopher) || (c == 'm' && scheme == UriScheme.Mailto))
return true;
return false;
}
internal void FinishInitialization()
{
string host = UserHostName;
if (_version > HttpVersion.Version10 && (host == null || host.Length == 0))
{
_context.ErrorMessage = "Invalid host name";
return;
}
string path;
Uri raw_uri = null;
if (MaybeUri(_rawUrl.ToLowerInvariant()) && Uri.TryCreate(_rawUrl, UriKind.Absolute, out raw_uri))
path = raw_uri.PathAndQuery;
else
path = _rawUrl;
if ((host == null || host.Length == 0))
host = UserHostAddress;
if (raw_uri != null)
host = raw_uri.Host;
int colon = host.IndexOf(':');
if (colon >= 0)
host = host.Substring(0, colon);
string base_uri = string.Format("{0}://{1}:{2}", RequestScheme, host, LocalEndPoint.Port);
if (!Uri.TryCreate(base_uri + path, UriKind.Absolute, out _requestUri))
{
_context.ErrorMessage = WebUtility.HtmlEncode("Invalid url: " + base_uri + path);
return;
}
_requestUri = HttpListenerRequestUriBuilder.GetRequestUri(_rawUrl, _requestUri.Scheme,
_requestUri.Authority, _requestUri.LocalPath, _requestUri.Query);
if (_version >= HttpVersion.Version11)
{
string t_encoding = Headers[HttpKnownHeaderNames.TransferEncoding];
_isChunked = (t_encoding != null && string.Equals(t_encoding, "chunked", StringComparison.OrdinalIgnoreCase));
// 'identity' is not valid!
if (t_encoding != null && !_isChunked)
{
_context.Connection.SendError(null, 501);
return;
}
}
if (!_isChunked && !_clSet)
{
if (string.Equals(_method, "POST", StringComparison.OrdinalIgnoreCase) ||
string.Equals(_method, "PUT", StringComparison.OrdinalIgnoreCase))
{
_context.Connection.SendError(null, 411);
return;
}
}
if (String.Compare(Headers[HttpKnownHeaderNames.Expect], "100-continue", StringComparison.OrdinalIgnoreCase) == 0)
{
HttpResponseStream output = _context.Connection.GetResponseStream();
output.InternalWrite(s_100continue, 0, s_100continue.Length);
}
}
internal static string Unquote(String str)
{
int start = str.IndexOf('\"');
int end = str.LastIndexOf('\"');
if (start >= 0 && end >= 0)
str = str.Substring(start + 1, end - 1);
return str.Trim();
}
internal void AddHeader(string header)
{
int colon = header.IndexOf(':');
if (colon == -1 || colon == 0)
{
_context.ErrorMessage = HttpStatusDescription.Get(400);
_context.ErrorStatus = 400;
return;
}
string name = header.Substring(0, colon).Trim();
string val = header.Substring(colon + 1).Trim();
string lower = name.ToLower(CultureInfo.InvariantCulture);
_headers.Set(name, val);
switch (lower)
{
case "content-length":
try
{
_contentLength = long.Parse(val.Trim());
if (_contentLength < 0)
_context.ErrorMessage = "Invalid Content-Length.";
_clSet = true;
}
catch
{
_context.ErrorMessage = "Invalid Content-Length.";
}
break;
case "cookie":
if (_cookies == null)
_cookies = new CookieCollection();
string[] cookieStrings = val.Split(new char[] { ',', ';' });
Cookie current = null;
int version = 0;
foreach (string cookieString in cookieStrings)
{
string str = cookieString.Trim();
if (str.Length == 0)
continue;
if (str.StartsWith("$Version"))
{
version = Int32.Parse(Unquote(str.Substring(str.IndexOf('=') + 1)));
}
else if (str.StartsWith("$Path"))
{
if (current != null)
current.Path = str.Substring(str.IndexOf('=') + 1).Trim();
}
else if (str.StartsWith("$Domain"))
{
if (current != null)
current.Domain = str.Substring(str.IndexOf('=') + 1).Trim();
}
else if (str.StartsWith("$Port"))
{
if (current != null)
current.Port = str.Substring(str.IndexOf('=') + 1).Trim();
}
else
{
if (current != null)
{
_cookies.Add(current);
}
current = new Cookie();
int idx = str.IndexOf('=');
if (idx > 0)
{
current.Name = str.Substring(0, idx).Trim();
current.Value = str.Substring(idx + 1).Trim();
}
else
{
current.Name = str.Trim();
current.Value = String.Empty;
}
current.Version = version;
}
}
if (current != null)
{
_cookies.Add(current);
}
break;
}
}
// returns true is the stream could be reused.
internal bool FlushInput()
{
if (!HasEntityBody)
return true;
int length = 2048;
if (_contentLength > 0)
length = (int)Math.Min(_contentLength, (long)length);
byte[] bytes = new byte[length];
while (true)
{
try
{
IAsyncResult ares = InputStream.BeginRead(bytes, 0, length, null, null);
if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne(1000))
return false;
if (InputStream.EndRead(ares) <= 0)
return true;
}
catch (ObjectDisposedException)
{
_inputStream = null;
return true;
}
catch
{
return false;
}
}
}
public int ClientCertificateError
{
get
{
HttpConnection cnc = _context.Connection;
if (cnc.ClientCertificate == null)
return 0;
int[] errors = cnc.ClientCertificateErrors;
if (errors != null && errors.Length > 0)
return errors[0];
return 0;
}
}
public long ContentLength64
{
get
{
if (_isChunked)
_contentLength = -1;
return _contentLength;
}
}
public CookieCollection Cookies
{
get
{
if (_cookies == null)
_cookies = new CookieCollection();
return _cookies;
}
}
public bool HasEntityBody => (_contentLength > 0 || _isChunked);
public NameValueCollection Headers => _headers;
public string HttpMethod => _method;
public Stream InputStream
{
get
{
if (_inputStream == null)
{
if (_isChunked || _contentLength > 0)
_inputStream = _context.Connection.GetRequestStream(_isChunked, _contentLength);
else
_inputStream = Stream.Null;
}
return _inputStream;
}
}
public bool IsAuthenticated => false;
public bool IsSecureConnection => _context.Connection.IsSecure;
public bool KeepAlive
{
get
{
if (_kaSet)
return _keepAlive;
_kaSet = true;
// 1. Connection header
// 2. Protocol (1.1 == keep-alive by default)
// 3. Keep-Alive header
string cnc = Headers[HttpKnownHeaderNames.Connection];
if (!String.IsNullOrEmpty(cnc))
{
_keepAlive = string.Equals(cnc, "keep-alive", StringComparison.OrdinalIgnoreCase);
}
else if (_version == HttpVersion.Version11)
{
_keepAlive = true;
}
else
{
cnc = Headers[HttpKnownHeaderNames.KeepAlive];
if (!String.IsNullOrEmpty(cnc))
_keepAlive = !string.Equals(cnc, "closed", StringComparison.OrdinalIgnoreCase);
}
return _keepAlive;
}
}
public IPEndPoint LocalEndPoint => _context.Connection.LocalEndPoint;
public IPEndPoint RemoteEndPoint => _context.Connection.RemoteEndPoint;
public Guid RequestTraceIdentifier => Guid.Empty;
public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, object state)
{
Task<X509Certificate2> getClientCertificate = new Task<X509Certificate2>(() => GetClientCertificate());
return TaskToApm.Begin(getClientCertificate, requestCallback, state);
}
public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
return TaskToApm.End<X509Certificate2>(asyncResult);
}
public X509Certificate2 GetClientCertificate() => _context.Connection.ClientCertificate;
public string ServiceName => null;
public TransportContext TransportContext => new Context();
public Task<X509Certificate2> GetClientCertificateAsync()
{
return Task<X509Certificate2>.Factory.FromAsync(BeginGetClientCertificate, EndGetClientCertificate, null);
}
private Uri RequestUri => _requestUri;
private bool SupportsWebSockets => true;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace HTLib2
{
public partial class HSerialize
{
[Serializable]
class Ver : ISerializable
{
public readonly int ver;
public Ver(int ver)
{
this.ver = ver;
}
public Ver(SerializationInfo info, StreamingContext context)
{
ver = (int)info.GetValue("ver", typeof(int));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ver", ver);
}
public static implicit operator int(Ver ver)
{
return ver.ver;
}
}
public class SerializedVersionException : Exception
{
public SerializedVersionException() { }
public SerializedVersionException(string message) : base(message) { }
public SerializedVersionException(string message, Exception innerException) : base (message,innerException) { }
}
public static void Serialize(string filename, int? ver, object obj0 ) { _Serialize(filename, ver, new object[] { obj0 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1 ) { _Serialize(filename, ver, new object[] { obj0, obj1 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3, object obj4 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3, obj4 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3, object obj4, object obj5 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3, obj4, obj5 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3, obj4, obj5, obj6 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3, obj4, obj5, obj6, obj7 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7, object obj8 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7, object obj8, object obj9) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8, obj9 }); }
public static void SerializeDepreciated(string filename, int? ver, object obj1, params object[] obj234)
{
List<object> objs = new List<object>();
objs.Add(obj1);
foreach(object obj in obj234)
objs.Add(obj);
_Serialize(filename, ver, objs.ToArray());
}
public static void _Serialize(string filename, int? ver, object[] objs)
{
string lockname = "Serializer: "+filename.Replace("\\", "@");
using(new NamedLock(lockname))
{
Stream stream = HFile.Open(filename, FileMode.Create);
BinaryFormatter bFormatter = new BinaryFormatter();
{
if(ver != null)
bFormatter.Serialize(stream, new Ver(ver.Value));
}
{
System.Int32 count = objs.Length;
bFormatter.Serialize(stream, count);
for(int i = 0; i < count; i++)
{
bFormatter.Serialize(stream, objs[i]);
}
}
stream.Flush();
stream.Close();
}
}
public static bool _Deserialize(string filename, int? ver, out object[] objs)
{
string lockname = "Serializer: "+filename.Replace("\\", "@");
using(new NamedLock(lockname))
{
Stream stream = HFile.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryFormatter bFormatter = new BinaryFormatter();
{
if(ver != null)
{
try
{
Ver sver = (Ver)bFormatter.Deserialize(stream);
if(sver.ver != ver.Value)
{
stream.Close();
objs = null;
return false;
}
}
catch(Exception)
{
stream.Close();
objs = null;
return false;
}
}
}
{
System.Int32 count = (System.Int32)bFormatter.Deserialize(stream);
objs = new object[count];
for(int i = 0; i < count; i++)
{
objs[i] = bFormatter.Deserialize(stream);
}
}
stream.Close();
}
return true;
}
public static T Deserialize<T>(string filename, int? ver)
{
object[] objs;
HDebug.Verify(_Deserialize(filename, ver, out objs));
HDebug.Assert(objs.Length == 1);
return (T)objs[0];
}
//public static bool DeserializeIfExist<T>(string filename, int? ver, out T obj)
//{
// if(HFile.Exists(filename) == false)
// {
// obj = default(T);
// return false;
// }
// return Deserialize(filename, ver, out obj);
//}
//public static bool Deserialize<T>(string filename, int? ver, out T obj)
//{
// object[] objs;
// if(Deserialize(filename, ver, out objs) == false)
// {
// obj = default(T);
// return false;
// }
// HDebug.Assert(objs.Length == 1);
// obj = (T)objs[0];
// return true;
//}
//public static bool Deserialize<T1, T2>(string filename, int? ver, out T1 obj1, out T2 obj2)
//{
// object[] objs;
// if(Deserialize(filename, ver, out objs) == false)
// {
// obj1 = default(T1);
// obj2 = default(T2);
// return false;
// }
// HDebug.Assert(objs.Length == 2);
// obj1 = (T1)objs[0];
// obj2 = (T2)objs[1];
// return true;
//}
//public static bool Deserialize<T1, T2, T3>(string filename, int? ver, out T1 obj1, out T2 obj2, out T3 obj3)
//{
// object[] objs;
// if(Deserialize(filename, ver, out objs) == false)
// {
// obj1 = default(T1);
// obj2 = default(T2);
// obj3 = default(T3);
// return false;
// }
// HDebug.Assert(objs.Length == 3);
// obj1 = (T1)objs[0];
// obj2 = (T2)objs[1];
// obj3 = (T3)objs[2];
// return true;
//}
//public static bool Deserialize<T1, T2, T3, T4>(string filename, int? ver, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4)
//{
// object[] objs;
// if(Deserialize(filename, ver, out objs) == false)
// {
// obj1 = default(T1);
// obj2 = default(T2);
// obj3 = default(T3);
// obj4 = default(T4);
// return false;
// }
// HDebug.Assert(objs.Length == 4);
// obj1 = (T1)objs[0];
// obj2 = (T2)objs[1];
// obj3 = (T3)objs[2];
// obj4 = (T4)objs[3];
// return true;
//}
//public static bool Deserialize<T1, T2, T3, T4, T5>(string filename, int? ver, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4, out T5 obj5)
//{
// object[] objs;
// if(Deserialize(filename, ver, out objs) == false)
// {
// obj1 = default(T1);
// obj2 = default(T2);
// obj3 = default(T3);
// obj4 = default(T4);
// obj5 = default(T5);
// return false;
// }
// HDebug.Assert(objs.Length == 5);
// obj1 = (T1)objs[0];
// obj2 = (T2)objs[1];
// obj3 = (T3)objs[2];
// obj4 = (T4)objs[3];
// obj5 = (T5)objs[4];
// return true;
//}
public static bool Deserialize<T0 >(string filename, int? ver, out T0 obj0 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); return false; } HDebug.Assert(objs.Length == 1); obj0 = (T0)objs[0]; return true; }
public static bool Deserialize<T0, T1 >(string filename, int? ver, out T0 obj0, out T1 obj1 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); return false; } HDebug.Assert(objs.Length == 2); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; return true; }
public static bool Deserialize<T0, T1, T2 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); return false; } HDebug.Assert(objs.Length == 3); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; return true; }
public static bool Deserialize<T0, T1, T2, T3 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); return false; } HDebug.Assert(objs.Length == 4); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; return true; }
public static bool Deserialize<T0, T1, T2, T3, T4 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); obj4 = default(T4); return false; } HDebug.Assert(objs.Length == 5); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; obj4 = (T4)objs[4]; return true; }
public static bool Deserialize<T0, T1, T2, T3, T4, T5 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4, out T5 obj5 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); obj4 = default(T4); obj5 = default(T5); return false; } HDebug.Assert(objs.Length == 6); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; obj4 = (T4)objs[4]; obj5 = (T5)objs[5]; return true; }
public static bool Deserialize<T0, T1, T2, T3, T4, T5, T6 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4, out T5 obj5, out T6 obj6 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); obj4 = default(T4); obj5 = default(T5); obj6 = default(T6); return false; } HDebug.Assert(objs.Length == 7); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; obj4 = (T4)objs[4]; obj5 = (T5)objs[5]; obj6 = (T6)objs[6]; return true; }
public static bool Deserialize<T0, T1, T2, T3, T4, T5, T6, T7 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4, out T5 obj5, out T6 obj6, out T7 obj7 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); obj4 = default(T4); obj5 = default(T5); obj6 = default(T6); obj7 = default(T7); return false; } HDebug.Assert(objs.Length == 8); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; obj4 = (T4)objs[4]; obj5 = (T5)objs[5]; obj6 = (T6)objs[6]; obj7 = (T7)objs[7]; return true; }
public static bool Deserialize<T0, T1, T2, T3, T4, T5, T6, T7, T8 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4, out T5 obj5, out T6 obj6, out T7 obj7, out T8 obj8 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); obj4 = default(T4); obj5 = default(T5); obj6 = default(T6); obj7 = default(T7); obj8 = default(T8); return false; } HDebug.Assert(objs.Length == 9); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; obj4 = (T4)objs[4]; obj5 = (T5)objs[5]; obj6 = (T6)objs[6]; obj7 = (T7)objs[7]; obj8 = (T8)objs[8]; return true; }
public static bool Deserialize<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4, out T5 obj5, out T6 obj6, out T7 obj7, out T8 obj8, out T9 obj9) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); obj4 = default(T4); obj5 = default(T5); obj6 = default(T6); obj7 = default(T7); obj8 = default(T8); obj9 = default(T9); return false; } HDebug.Assert(objs.Length == 10); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; obj4 = (T4)objs[4]; obj5 = (T5)objs[5]; obj6 = (T6)objs[6]; obj7 = (T7)objs[7]; obj8 = (T8)objs[8]; obj9 = (T9)objs[9]; return true; }
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.IO;
using IServiceProvider = System.IServiceProvider;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.FSharp.ProjectSystem;
using EnvDTE;
using VSLangProj;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem.Automation
{
/// <summary>
/// Represents an automation friendly version of a language-specific project.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "OAVS")]
[ComVisible(true), CLSCompliant(false)]
public class OAVSProject : VSProject
{
private ProjectNode project;
private OAVSProjectEvents events;
internal OAVSProject(ProjectNode project)
{
this.project = project;
}
public ProjectItem AddWebReference(string bstrUrl)
{
Debug.Fail("VSProject.AddWebReference not implemented");
throw new NotImplementedException();
}
public BuildManager BuildManager
{
get
{
return new OABuildManager(this.project);
}
}
public void CopyProject(string bstrDestFolder, string bstrDestUNCPath, prjCopyProjectOption copyProjectOption, string bstrUsername, string bstrPassword)
{
Debug.Fail("VSProject.CopyProject not implemented");
throw new NotImplementedException();
}
public ProjectItem CreateWebReferencesFolder()
{
Debug.Fail("VSProject.CreateWebReferencesFolder not implemented");
throw new NotImplementedException();
}
public DTE DTE
{
get
{
return (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE));
}
}
public VSProjectEvents Events
{
get
{
if (events == null)
events = new OAVSProjectEvents(this);
return events;
}
}
public void Exec(prjExecCommand command, int bSuppressUI, object varIn, out object pVarOut)
{
Debug.Fail("VSProject.Exec not implemented");
throw new NotImplementedException();
}
public void GenerateKeyPairFiles(string strPublicPrivateFile, string strPublicOnlyFile)
{
Debug.Fail("VSProject.GenerateKeyPairFiles not implemented");
throw new NotImplementedException();
}
public string GetUniqueFilename(object pDispatch, string bstrRoot, string bstrDesiredExt)
{
Debug.Fail("VSProject.GetUniqueFilename not implemented");
throw new NotImplementedException();
}
public Imports Imports
{
get
{
Debug.Fail("VSProject.Imports not implemented");
throw new NotImplementedException();
}
}
public Project Project
{
get
{
return this.project.GetAutomationObject() as Project;
}
}
public References References
{
get
{
ReferenceContainerNode references = project.GetReferenceContainer() as ReferenceContainerNode;
if (null == references)
{
return null;
}
return references.Object as References;
}
}
/// <summary>
/// Automation may call this function but nothing to do here.
/// </summary>
public void Refresh()
{
}
public string TemplatePath
{
get
{
Debug.Fail("VSProject.TemplatePath not implemented");
throw new NotImplementedException();
}
}
public ProjectItem WebReferencesFolder
{
get
{
Debug.Fail("VSProject.WebReferencesFolder not implemented");
throw new NotImplementedException();
}
}
public bool WorkOffline
{
get
{
Debug.Fail("VSProject.WorkOffLine not implemented");
throw new NotImplementedException();
}
set
{
Debug.Fail("VSProject.Set_WorkOffLine not implemented");
throw new NotImplementedException();
}
}
}
/// <summary>
/// Provides access to language-specific project events
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "OAVS")]
[ComVisible(true), CLSCompliant(false)]
public class OAVSProjectEvents : VSProjectEvents
{
private OAVSProject vsProject;
internal OAVSProjectEvents(OAVSProject vsProject)
{
this.vsProject = vsProject;
}
public BuildManagerEvents BuildManagerEvents
{
get
{
return vsProject.BuildManager as BuildManagerEvents;
}
}
public ImportsEvents ImportsEvents
{
get
{
Debug.Fail("VSProjectEvents.ImportsEvents not implemented");
throw new NotImplementedException();
}
}
public ReferencesEvents ReferencesEvents
{
get
{
return vsProject.References as ReferencesEvents;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using hw.DebugFormatter;
namespace hw.Helper
{
/// <summary>
/// Summary description for File.
/// </summary>
[Serializable]
public sealed class File
{
readonly string _name;
Uri _uriCache;
public Uri Uri { get { return _uriCache ?? (_uriCache = new Uri(_name)); } }
public bool IsFTP { get { return Uri.Scheme == Uri.UriSchemeFtp; } }
/// <summary>
/// constructs a FileInfo
/// </summary>
/// <param name="name"> the filename </param>
internal static File Create(string name) { return new File(name); }
File(string name) { _name = name; }
public File() { _name = ""; }
/// <summary>
/// considers the file as a string. If file existe it should be a text file
/// </summary>
/// <value> the content of the file if existing else null. </value>
public string String
{
get
{
if(System.IO.File.Exists(_name))
{
var f = System.IO.File.OpenText(_name);
var result = f.ReadToEnd();
f.Close();
return result;
}
try
{
if(Uri.Scheme == Uri.UriSchemeHttp)
return StringFromHTTP;
}
catch
{}
return null;
}
set
{
var f = System.IO.File.CreateText(_name);
f.Write(value);
f.Close();
}
}
public void AssumeDirectoryOfFileExists()
{
var dn = DirectoryName;
if(dn == null || dn.FileHandle().Exists)
return;
Directory.CreateDirectory(dn);
}
string StringFromHTTP
{
get
{
var req = WebRequest.Create(Uri.AbsoluteUri);
var resp = req.GetResponse();
var stream = resp.GetResponseStream();
Tracer.Assert(stream != null);
var streamReader = new StreamReader(stream);
var result = streamReader.ReadToEnd();
return result;
}
}
public override string ToString() { return FullName; }
/// <summary>
/// considers the file as a byte array
/// </summary>
public byte[] Bytes
{
get
{
var f = Reader;
var result = new byte[Size];
f.Read(result, 0, (int) Size);
f.Close();
return result;
}
set
{
var f = System.IO.File.OpenWrite(_name);
f.Write(value, 0, value.Length);
f.Close();
}
}
public FileStream Reader { get { return System.IO.File.OpenRead(_name); } }
/// <summary>
/// Size of file in bytes
/// </summary>
public long Size { get { return ((FileInfo) FileSystemInfo).Length; } }
/// <summary>
/// Gets the full path of the directory or file.
/// </summary>
public string FullName { get { return FileSystemInfo.FullName; } }
public string DirectoryName { get { return Path.GetDirectoryName(FullName); } }
public string Extension { get { return Path.GetExtension(FullName); } }
/// <summary>
/// Gets the name of the directory or file without path.
/// </summary>
public string Name { get { return FileSystemInfo.Name; } }
/// <summary>
/// Gets a value indicating whether a file exists.
/// </summary>
public bool Exists { get { return FileSystemInfo.Exists; } }
/// <summary>
/// Gets a value indicating whether a file exists.
/// </summary>
public bool IsMounted
{
get
{
if(!Exists)
return false;
if((FileSystemInfo.Attributes & FileAttributes.ReparsePoint) == 0)
return false;
try
{
((DirectoryInfo) FileSystemInfo).GetFileSystemInfos("dummy");
return true;
}
catch(Exception)
{
return false;
}
}
}
/// <summary>
/// Delete the file
/// </summary>
public void Delete(bool recursive = false)
{
if(IsDirectory)
Directory.Delete(_name, recursive);
else
System.IO.File.Delete(_name);
}
/// <summary>
/// Move the file
/// </summary>
public void Move(string newName)
{
if(IsDirectory)
Directory.Move(_name, newName);
else
System.IO.File.Move(_name, newName);
}
/// <summary>
/// returns true if it is a directory
/// </summary>
public bool IsDirectory { get { return Directory.Exists(_name); } }
FileSystemInfo _fileInfoCache;
FileSystemInfo FileSystemInfo
{
get
{
if(_fileInfoCache == null)
if(IsDirectory)
_fileInfoCache = new DirectoryInfo(_name);
else
_fileInfoCache = new FileInfo(_name);
return _fileInfoCache;
}
}
/// <summary>
/// Content of directory, one line for each file
/// </summary>
public string DirectoryString { get { return GetDirectoryString(); } }
string GetDirectoryString()
{
var result = "";
foreach(var fi in GetItems())
{
result += fi.Name;
result += "\n";
}
return result;
}
FileSystemInfo[] GetItems() { return ((DirectoryInfo) FileSystemInfo).GetFileSystemInfos().ToArray(); }
public File[] Items { get { return GetItems().Select(f => Create(f.FullName)).ToArray(); } }
/// <summary>
/// Gets the directory of the source file that called this function
/// </summary>
/// <param name="depth"> The depth. </param>
/// <returns> </returns>
public static string SourcePath(int depth) { return new FileInfo(SourceFileName(depth + 1)).DirectoryName; }
/// <summary>
/// Gets the name of the source file that called this function
/// </summary>
/// <param name="depth"> stack depths of the function used. </param>
/// <returns> </returns>
public static string SourceFileName(int depth)
{
var sf = new StackTrace(true).GetFrame(depth + 1);
return sf.GetFileName();
}
/// <summary>
/// Gets list of files that match given path and pattern
/// </summary>
/// <param name="filePattern"></param>
/// <returns></returns>
public static string[] Select(string filePattern)
{
var namePattern = filePattern.Split('\\').Last();
return Directory
.GetFiles(filePattern.Substring(0, filePattern.Length - namePattern.Length - 1), namePattern);
}
public bool IsLocked
{
get
{
try
{
System.IO.File.OpenRead(_name).Close();
return false;
}
catch(IOException)
{
return true;
}
//file is not locked
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Plugin.Connectivity.Abstractions;
using Windows.Networking.Connectivity;
using System.Threading.Tasks;
using Windows.Networking.Sockets;
using Windows.Networking;
using System.Diagnostics;
using Windows.ApplicationModel.Core;
namespace Plugin.Connectivity
{
/// <summary>
/// Connectivity Implementation for WinRT
/// </summary>
public class ConnectivityImplementation : BaseConnectivity
{
bool isConnected;
/// <summary>
/// Default constructor
/// </summary>
public ConnectivityImplementation()
{
isConnected = IsConnected;
NetworkInformation.NetworkStatusChanged += NetworkStatusChanged;
}
async void NetworkStatusChanged(object sender)
{
var previous = isConnected;
var newConnected = IsConnected;
if (previous == newConnected)
return;
var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
if (dispatcher != null)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
OnConnectivityChanged(new ConnectivityChangedEventArgs { IsConnected = newConnected });
});
}
else
{
OnConnectivityChanged(new ConnectivityChangedEventArgs { IsConnected = newConnected });
}
}
/// <summary>
/// Gets if there is an active internet connection
/// </summary>
public override bool IsConnected =>
(isConnected = NetworkInformation.GetInternetConnectionProfile()?.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess);
/// <summary>
/// Checks if remote is reachable. RT apps cannot do loopback so this will alway return false.
/// You can use it to check remote calls though.
/// </summary>
/// <param name="host"></param>
/// <param name="msTimeout"></param>
/// <returns></returns>
public override async Task<bool> IsReachable(string host, int msTimeout = 5000)
{
if (string.IsNullOrEmpty(host))
throw new ArgumentNullException("host");
if (!IsConnected)
return false;
try
{
var serverHost = new HostName(host);
using (var client = new StreamSocket())
{
await client.ConnectAsync(serverHost, "http");
return true;
}
}
catch (Exception ex)
{
Debug.WriteLine("Unable to reach: " + host + " Error: " + ex);
return false;
}
}
/// <summary>
/// Tests if a remote host name is reachable
/// </summary>
/// <param name="host">Host name can be a remote IP or URL of website (no http:// or www.)</param>
/// <param name="port">Port to attempt to check is reachable.</param>
/// <param name="msTimeout">Timeout in milliseconds.</param>
/// <returns></returns>
public override async Task<bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000)
{
if (string.IsNullOrEmpty(host))
throw new ArgumentNullException("host");
if (!IsConnected)
return false;
host = host.Replace("http://www.", string.Empty).
Replace("http://", string.Empty).
Replace("https://www.", string.Empty).
Replace("https://", string.Empty);
try
{
using (var tcpClient = new StreamSocket())
{
await tcpClient.ConnectAsync(
new Windows.Networking.HostName(host),
port.ToString(),
SocketProtectionLevel.PlainSocket);
var localIp = tcpClient.Information.LocalAddress.DisplayName;
var remoteIp = tcpClient.Information.RemoteAddress.DisplayName;
tcpClient.Dispose();
return true;
}
}
catch (Exception ex)
{
Debug.WriteLine("Unable to reach: " + host + " Error: " + ex);
return false;
}
}
/// <summary>
/// Gets the list of all active connection types.
/// </summary>
public override IEnumerable<ConnectionType> ConnectionTypes
{
get
{
var networkInterfaceList = NetworkInformation.GetConnectionProfiles();
foreach (var networkInterfaceInfo in networkInterfaceList.Where(networkInterfaceInfo => networkInterfaceInfo.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None))
{
var type = ConnectionType.Other;
if (networkInterfaceInfo.NetworkAdapter != null)
{
switch (networkInterfaceInfo.NetworkAdapter.IanaInterfaceType)
{
case 6:
type = ConnectionType.Desktop;
break;
case 71:
type = ConnectionType.WiFi;
break;
case 243:
case 244:
type = ConnectionType.Cellular;
break;
}
}
yield return type;
}
}
}
/// <summary>
/// Retrieves a list of available bandwidths for the platform.
/// Only active connections.
/// </summary>
public override IEnumerable<UInt64> Bandwidths
{
get
{
var networkInterfaceList = NetworkInformation.GetConnectionProfiles();
foreach (var networkInterfaceInfo in networkInterfaceList.Where(networkInterfaceInfo => networkInterfaceInfo.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None))
{
UInt64 speed = 0;
if (networkInterfaceInfo.NetworkAdapter != null)
{
speed = (UInt64)networkInterfaceInfo.NetworkAdapter.OutboundMaxBitsPerSecond;
}
yield return speed;
}
}
}
private bool disposed = false;
/// <summary>
/// Dispose
/// </summary>
/// <param name="disposing"></param>
public override void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
NetworkInformation.NetworkStatusChanged -= NetworkStatusChanged;
}
disposed = true;
}
base.Dispose(disposing);
}
}
}
| |
// 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.Linq;
using Xunit;
namespace System.Collections.Tests
{
public static class BitArray_CtorTests
{
private const int BitsPerByte = 8;
private const int BitsPerInt32 = 32;
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(BitsPerByte)]
[InlineData(BitsPerByte * 2)]
[InlineData(BitsPerInt32)]
[InlineData(BitsPerInt32 * 2)]
[InlineData(200)]
[InlineData(65551)]
public static void Ctor_Int(int length)
{
BitArray bitArray = new BitArray(length);
Assert.Equal(length, bitArray.Length);
for (int i = 0; i < bitArray.Length; i++)
{
Assert.False(bitArray[i]);
Assert.False(bitArray.Get(i));
}
ICollection collection = bitArray;
Assert.Equal(length, collection.Count);
Assert.False(collection.IsSynchronized);
}
[Theory]
[InlineData(0, true)]
[InlineData(0, false)]
[InlineData(1, true)]
[InlineData(1, false)]
[InlineData(BitsPerByte, true)]
[InlineData(BitsPerByte, false)]
[InlineData(BitsPerByte * 2, true)]
[InlineData(BitsPerByte * 2, false)]
[InlineData(BitsPerInt32, true)]
[InlineData(BitsPerInt32, false)]
[InlineData(BitsPerInt32 * 2, true)]
[InlineData(BitsPerInt32 * 2, false)]
[InlineData(200, true)]
[InlineData(200, false)]
[InlineData(65551, true)]
[InlineData(65551, false)]
public static void Ctor_Int_Bool(int length, bool defaultValue)
{
BitArray bitArray = new BitArray(length, defaultValue);
Assert.Equal(length, bitArray.Length);
for (int i = 0; i < bitArray.Length; i++)
{
Assert.Equal(defaultValue, bitArray[i]);
Assert.Equal(defaultValue, bitArray.Get(i));
}
ICollection collection = bitArray;
Assert.Equal(length, collection.Count);
Assert.False(collection.IsSynchronized);
}
[Fact]
public static void Ctor_Int_NegativeLength_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new BitArray(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new BitArray(-1, false));
}
public static IEnumerable<object[]> Ctor_BoolArray_TestData()
{
yield return new object[] { new bool[0] };
foreach (int size in new[] { 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2 })
{
yield return new object[] { Enumerable.Repeat(true, size).ToArray() };
yield return new object[] { Enumerable.Repeat(false, size).ToArray() };
yield return new object[] { Enumerable.Range(0, size).Select(x => x % 2 == 0).ToArray() };
}
}
[Theory]
[MemberData(nameof(Ctor_BoolArray_TestData))]
public static void Ctor_BoolArray(bool[] values)
{
BitArray bitArray = new BitArray(values);
Assert.Equal(values.Length, bitArray.Length);
for (int i = 0; i < bitArray.Length; i++)
{
Assert.Equal(values[i], bitArray[i]);
Assert.Equal(values[i], bitArray.Get(i));
}
ICollection collection = bitArray;
Assert.Equal(values.Length, collection.Count);
Assert.False(collection.IsSynchronized);
}
[Fact]
public static void Ctor_NullBoolArray_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("values", () => new BitArray((bool[])null));
}
public static IEnumerable<object[]> Ctor_BitArray_TestData()
{
yield return new object[] { "bool[](empty)", new BitArray(new bool[0]) };
yield return new object[] { "byte[](empty)", new BitArray(new byte[0]) };
yield return new object[] { "int[](empty)", new BitArray(new int[0]) };
foreach (int size in new[] { 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2 })
{
yield return new object[] { "length", new BitArray(size) };
yield return new object[] { "length|default(true)", new BitArray(size, true) };
yield return new object[] { "length|default(false)", new BitArray(size, false) };
yield return new object[] { "bool[](all)", new BitArray(Enumerable.Repeat(true, size).ToArray()) };
yield return new object[] { "bool[](none)", new BitArray(Enumerable.Repeat(false, size).ToArray()) };
yield return new object[] { "bool[](alternating)", new BitArray(Enumerable.Range(0, size).Select(x => x % 2 == 0).ToArray()) };
if (size >= BitsPerByte)
{
yield return new object[] { "byte[](all)", new BitArray(Enumerable.Repeat((byte)0xff, size / BitsPerByte).ToArray()) };
yield return new object[] { "byte[](none)", new BitArray(Enumerable.Repeat((byte)0x00, size / BitsPerByte).ToArray()) };
yield return new object[] { "byte[](alternating)", new BitArray(Enumerable.Repeat((byte)0xaa, size / BitsPerByte).ToArray()) };
}
if (size >= BitsPerInt32)
{
yield return new object[] { "int[](all)", new BitArray(Enumerable.Repeat(unchecked((int)0xffffffff), size / BitsPerInt32).ToArray()) };
yield return new object[] { "int[](none)", new BitArray(Enumerable.Repeat(0x00000000, size / BitsPerInt32).ToArray()) };
yield return new object[] { "int[](alternating)", new BitArray(Enumerable.Repeat(unchecked((int)0xaaaaaaaa), size / BitsPerInt32).ToArray()) };
}
}
}
[Theory]
[MemberData(nameof(Ctor_BitArray_TestData))]
public static void Ctor_BitArray(string label, BitArray bits)
{
BitArray bitArray = new BitArray(bits);
Assert.Equal(bits.Length, bitArray.Length);
for (int i = 0; i < bitArray.Length; i++)
{
Assert.Equal(bits[i], bitArray[i]);
Assert.Equal(bits[i], bitArray.Get(i));
}
ICollection collection = bitArray;
Assert.Equal(bits.Length, collection.Count);
Assert.False(collection.IsSynchronized);
}
[Fact]
public static void Ctor_NullBitArray_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("bits", () => new BitArray((BitArray)null));
}
public static IEnumerable<object[]> Ctor_IntArray_TestData()
{
yield return new object[] { new int[0], new bool[0] };
foreach (int size in new[] { 1, 10 })
{
yield return new object[] { Enumerable.Repeat(unchecked((int)0xffffffff), size).ToArray(), Enumerable.Repeat(true, size * BitsPerInt32).ToArray() };
yield return new object[] { Enumerable.Repeat(0x00000000, size).ToArray(), Enumerable.Repeat(false, size * BitsPerInt32).ToArray() };
yield return new object[] { Enumerable.Repeat(unchecked((int)0xaaaaaaaa), size).ToArray(), Enumerable.Range(0, size * BitsPerInt32).Select(i => i % 2 == 1).ToArray() };
}
}
[Theory]
[MemberData(nameof(Ctor_IntArray_TestData))]
public static void Ctor_IntArray(int[] array, bool[] expected)
{
BitArray bitArray = new BitArray(array);
Assert.Equal(expected.Length, bitArray.Length);
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], bitArray[i]);
Assert.Equal(expected[i], bitArray.Get(i));
}
ICollection collection = bitArray;
Assert.Equal(expected.Length, collection.Count);
Assert.False(collection.IsSynchronized);
}
[Fact]
public static void Ctor_NullIntArray_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("values", () => new BitArray((int[])null));
}
[Fact]
public static void Ctor_LargeIntArrayOverflowingBitArray_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("values", () => new BitArray(new int[int.MaxValue / BitsPerInt32 + 1 ]));
}
public static IEnumerable<object[]> Ctor_ByteArray_TestData()
{
yield return new object[] { new byte[0], new bool[0] };
foreach (int size in new[] { 1, 2, 3, BitsPerInt32 / BitsPerByte, 2 * BitsPerInt32 / BitsPerByte })
{
yield return new object[] { Enumerable.Repeat((byte)0xff, size).ToArray(), Enumerable.Repeat(true, size * BitsPerByte).ToArray() };
yield return new object[] { Enumerable.Repeat((byte)0x00, size).ToArray(), Enumerable.Repeat(false, size * BitsPerByte).ToArray() };
yield return new object[] { Enumerable.Repeat((byte)0xaa, size).ToArray(), Enumerable.Range(0, size * BitsPerByte).Select(i => i % 2 == 1).ToArray() };
}
}
[Theory]
[MemberData(nameof(Ctor_ByteArray_TestData))]
public static void Ctor_ByteArray(byte[] bytes, bool[] expected)
{
BitArray bitArray = new BitArray(bytes);
Assert.Equal(expected.Length, bitArray.Length);
for (int i = 0; i < bitArray.Length; i++)
{
Assert.Equal(expected[i], bitArray[i]);
Assert.Equal(expected[i], bitArray.Get(i));
}
ICollection collection = bitArray;
Assert.Equal(expected.Length, collection.Count);
Assert.False(collection.IsSynchronized);
}
[Fact]
public static void Ctor_NullByteArray_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("bytes", () => new BitArray((byte[])null));
}
[Fact]
public static void Ctor_LargeByteArrayOverflowingBitArray_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("bytes", () => new BitArray(new byte[int.MaxValue / BitsPerByte + 1 ]));
}
[Fact]
public static void Ctor_Simple_Method_Tests()
{
int length = 0;
BitArray bitArray = new BitArray(length);
Assert.NotNull(bitArray.SyncRoot);
Assert.False(bitArray.IsSynchronized);
Assert.False(bitArray.IsReadOnly);
Assert.Equal(bitArray, bitArray.Clone());
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "A bug in BitArray.Clone() caused an ArgumentExeption to be thrown in this case.")]
[Fact]
public static void Clone_LongLength_Works()
{
BitArray bitArray = new BitArray(int.MaxValue - 30);
BitArray clone = (BitArray)bitArray.Clone();
Assert.Equal(bitArray.Length, clone.Length);
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="EntitySqlQueryState.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
//---------------------------------------------------------------------
namespace System.Data.Objects
{
using System.Collections.Generic;
using System.Data.Common.CommandTrees;
using System.Data.Common.CommandTrees.ExpressionBuilder;
using System.Data.Common.EntitySql;
using System.Data.Common.QueryCache;
using System.Data.Metadata.Edm;
using System.Data.Objects.Internal;
using System.Diagnostics;
/// <summary>
/// ObjectQueryState based on Entity-SQL query text.
/// </summary>
internal sealed class EntitySqlQueryState : ObjectQueryState
{
/// <summary>
/// The Entity-SQL text that defines the query.
/// </summary>
/// <remarks>
/// It is important that this field is readonly for consistency reasons wrt <see cref="_queryExpression"/>.
/// If this field becomes read-write, then write should be allowed only when <see cref="_queryExpression"/> is null,
/// or there should be a mechanism keeping both fields consistent.
/// </remarks>
private readonly string _queryText;
/// <summary>
/// Optional <see cref="DbExpression"/> that defines the query. Must be semantically equal to the <see cref="_queryText"/>.
/// </summary>
/// <remarks>
/// It is important that this field is readonly for consistency reasons wrt <see cref="_queryText"/>.
/// If this field becomes read-write, then there should be a mechanism keeping both fields consistent.
/// </remarks>
private readonly DbExpression _queryExpression;
/// <summary>
/// Can a Limit subclause be appended to the text of this query?
/// </summary>
private readonly bool _allowsLimit;
/// <summary>
/// Initializes a new query EntitySqlQueryState instance.
/// </summary>
/// <param name="context">
/// The ObjectContext containing the metadata workspace the query was
/// built against, the connection on which to execute the query, and the
/// cache to store the results in. Must not be null.
/// </param>
/// <param name="commandText">
/// The Entity-SQL text of the query
/// </param>
/// <param name="mergeOption">
/// The merge option to use when retrieving results if an explicit merge option is not specified
/// </param>
internal EntitySqlQueryState(Type elementType, string commandText, bool allowsLimit, ObjectContext context, ObjectParameterCollection parameters, Span span)
: this(elementType, commandText, /*expression*/ null, allowsLimit, context, parameters, span)
{ }
/// <summary>
/// Initializes a new query EntitySqlQueryState instance.
/// </summary>
/// <param name="context">
/// The ObjectContext containing the metadata workspace the query was
/// built against, the connection on which to execute the query, and the
/// cache to store the results in. Must not be null.
/// </param>
/// <param name="commandText">
/// The Entity-SQL text of the query
/// </param>
/// <param name="expression">
/// Optional <see cref="DbExpression"/> that defines the query. Must be semantically equal to the <paramref name="commandText"/>.
/// </param>
/// <param name="mergeOption">
/// The merge option to use when retrieving results if an explicit merge option is not specified
/// </param>
internal EntitySqlQueryState(Type elementType, string commandText, DbExpression expression, bool allowsLimit, ObjectContext context, ObjectParameterCollection parameters, Span span)
: base(elementType, context, parameters, span)
{
EntityUtil.CheckArgumentNull(commandText, "commandText");
if (string.IsNullOrEmpty(commandText))
{
throw EntityUtil.Argument(System.Data.Entity.Strings.ObjectQuery_InvalidEmptyQuery, "commandText");
}
_queryText = commandText;
_queryExpression = expression;
_allowsLimit = allowsLimit;
}
/// <summary>
/// Determines whether or not the current query is a 'Skip' or 'Sort' operation
/// and so would allow a 'Limit' clause to be appended to the current query text.
/// </summary>
/// <returns>
/// <c>True</c> if the current query is a Skip or Sort expression, or a
/// Project expression with a Skip or Sort expression input.
/// </returns>
internal bool AllowsLimitSubclause { get { return _allowsLimit; } }
/// <summary>
/// Always returns the Entity-SQL text of the implemented ObjectQuery.
/// </summary>
/// <param name="commandText">Always set to the Entity-SQL text of this ObjectQuery.</param>
/// <returns>Always returns <c>true</c>.</returns>
internal override bool TryGetCommandText(out string commandText)
{
commandText = this._queryText;
return true;
}
internal override bool TryGetExpression(out System.Linq.Expressions.Expression expression)
{
expression = null;
return false;
}
protected override TypeUsage GetResultType()
{
DbExpression query = this.Parse();
return query.ResultType;
}
internal override ObjectQueryState Include<TElementType>(ObjectQuery<TElementType> sourceQuery, string includePath)
{
ObjectQueryState retState = new EntitySqlQueryState(this.ElementType, _queryText, _queryExpression, _allowsLimit, this.ObjectContext, ObjectParameterCollection.DeepCopy(this.Parameters), Span.IncludeIn(this.Span, includePath));
this.ApplySettingsTo(retState);
return retState;
}
internal override ObjectQueryExecutionPlan GetExecutionPlan(MergeOption? forMergeOption)
{
// Metadata is required to generate the execution plan or to retrieve it from the cache.
this.ObjectContext.EnsureMetadata();
// Determine the required merge option, with the following precedence:
// 1. The merge option specified to Execute(MergeOption) as forMergeOption.
// 2. The merge option set via ObjectQuery.MergeOption.
// 3. The global default merge option.
MergeOption mergeOption = EnsureMergeOption(forMergeOption, this.UserSpecifiedMergeOption);
// If a cached plan is present, then it can be reused if it has the required merge option
// (since span and parameters cannot change between executions). However, if the cached
// plan does not have the required merge option we proceed as if it were not present.
ObjectQueryExecutionPlan plan = this._cachedPlan;
if (plan != null)
{
if (plan.MergeOption == mergeOption)
{
return plan;
}
else
{
plan = null;
}
}
// There is no cached plan (or it was cleared), so the execution plan must be retrieved from
// the global query cache (if plan caching is enabled) or rebuilt for the required merge option.
QueryCacheManager cacheManager = null;
EntitySqlQueryCacheKey cacheKey = null;
if (this.PlanCachingEnabled)
{
// Create a new cache key that reflects the current state of the Parameters collection
// and the Span object (if any), and uses the specified merge option.
cacheKey = new EntitySqlQueryCacheKey(
this.ObjectContext.DefaultContainerName,
_queryText,
(null == this.Parameters ? 0 : this.Parameters.Count),
(null == this.Parameters ? null : this.Parameters.GetCacheKey()),
(null == this.Span ? null : this.Span.GetCacheKey()),
mergeOption,
this.ElementType);
cacheManager = this.ObjectContext.MetadataWorkspace.GetQueryCacheManager();
ObjectQueryExecutionPlan executionPlan = null;
if (cacheManager.TryCacheLookup(cacheKey, out executionPlan))
{
plan = executionPlan;
}
}
if (plan == null)
{
// Either caching is not enabled or the execution plan was not found in the cache
DbExpression queryExpression = this.Parse();
Debug.Assert(queryExpression != null, "EntitySqlQueryState.Parse returned null expression?");
DbQueryCommandTree tree = DbQueryCommandTree.FromValidExpression(this.ObjectContext.MetadataWorkspace, DataSpace.CSpace, queryExpression);
plan = ObjectQueryExecutionPlan.Prepare(this.ObjectContext, tree, this.ElementType, mergeOption, this.Span, null, DbExpressionBuilder.AliasGenerator);
// If caching is enabled then update the cache now.
// Note: the logic is the same as in ELinqQueryState.
if (cacheKey != null)
{
var newEntry = new QueryCacheEntry(cacheKey, plan);
QueryCacheEntry foundEntry = null;
if (cacheManager.TryLookupAndAdd(newEntry, out foundEntry))
{
// If TryLookupAndAdd returns 'true' then the entry was already present in the cache when the attempt to add was made.
// In this case the existing execution plan should be used.
plan = (ObjectQueryExecutionPlan)foundEntry.GetTarget();
}
}
}
if (this.Parameters != null)
{
this.Parameters.SetReadOnly(true);
}
// Update the cached plan with the newly retrieved/prepared plan
this._cachedPlan = plan;
// Return the execution plan
return plan;
}
internal DbExpression Parse()
{
if (_queryExpression != null)
{
return _queryExpression;
}
List<DbParameterReferenceExpression> parameters = null;
if (this.Parameters != null)
{
parameters = new List<DbParameterReferenceExpression>(this.Parameters.Count);
foreach (ObjectParameter parameter in this.Parameters)
{
TypeUsage typeUsage = parameter.TypeUsage;
if (null == typeUsage)
{
// Since ObjectParameters do not allow users to specify 'facets', make
// sure that the parameter TypeUsage is not populated with the provider
// default facet values.
this.ObjectContext.Perspective.TryGetTypeByName(
parameter.MappableType.FullName,
false /* bIgnoreCase */,
out typeUsage);
}
Debug.Assert(typeUsage != null, "typeUsage != null");
parameters.Add(typeUsage.Parameter(parameter.Name));
}
}
DbLambda lambda =
CqlQuery.CompileQueryCommandLambda(
_queryText, // Command Text
this.ObjectContext.Perspective, // Perspective
null, // Parser options - null indicates 'use default'
parameters, // Parameters
null // Variables
);
Debug.Assert(lambda.Variables == null || lambda.Variables.Count == 0, "lambda.Variables must be empty");
return lambda.Body;
}
}
}
| |
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Text;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Util.Automaton
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Just holds a set of <see cref="T:int[]"/> states, plus a corresponding
/// <see cref="T:int[]"/> count per state. Used by
/// <see cref="BasicOperations.Determinize(Automaton)"/>.
/// <para/>
/// NOTE: This was SortedIntSet in Lucene
/// </summary>
internal sealed class SortedInt32Set : IEquatable<SortedInt32Set>, IEquatable<SortedInt32Set.FrozenInt32Set>
{
internal int[] values;
internal int[] counts;
internal int upto;
private int hashCode;
// If we hold more than this many states, we switch from
// O(N^2) linear ops to O(N log(N)) TreeMap
private const int TREE_MAP_CUTOVER = 30;
private readonly IDictionary<int, int> map = new JCG.SortedDictionary<int, int>();
private bool useTreeMap;
internal State state;
public SortedInt32Set(int capacity)
{
values = new int[capacity];
counts = new int[capacity];
}
// Adds this state to the set
public void Incr(int num)
{
if (useTreeMap)
{
int key = num;
if (!map.TryGetValue(key, out int val))
{
map[key] = 1;
}
else
{
map[key] = 1 + val;
}
return;
}
if (upto == values.Length)
{
values = ArrayUtil.Grow(values, 1 + upto);
counts = ArrayUtil.Grow(counts, 1 + upto);
}
for (int i = 0; i < upto; i++)
{
if (values[i] == num)
{
counts[i]++;
return;
}
else if (num < values[i])
{
// insert here
int j = upto - 1;
while (j >= i)
{
values[1 + j] = values[j];
counts[1 + j] = counts[j];
j--;
}
values[i] = num;
counts[i] = 1;
upto++;
return;
}
}
// append
values[upto] = num;
counts[upto] = 1;
upto++;
if (upto == TREE_MAP_CUTOVER)
{
useTreeMap = true;
for (int i = 0; i < upto; i++)
{
map[values[i]] = counts[i];
}
}
}
// Removes this state from the set, if count decrs to 0
public void Decr(int num)
{
if (useTreeMap)
{
int count = map[num];
if (count == 1)
{
map.Remove(num);
}
else
{
map[num] = count - 1;
}
// Fall back to simple arrays once we touch zero again
if (map.Count == 0)
{
useTreeMap = false;
upto = 0;
}
return;
}
for (int i = 0; i < upto; i++)
{
if (values[i] == num)
{
counts[i]--;
if (counts[i] == 0)
{
int limit = upto - 1;
while (i < limit)
{
values[i] = values[i + 1];
counts[i] = counts[i + 1];
i++;
}
upto = limit;
}
return;
}
}
if (Debugging.AssertsEnabled) Debugging.Assert(false);
}
public void ComputeHash()
{
if (useTreeMap)
{
if (map.Count > values.Length)
{
int size = ArrayUtil.Oversize(map.Count, RamUsageEstimator.NUM_BYTES_INT32);
values = new int[size];
counts = new int[size];
}
hashCode = map.Count;
upto = 0;
foreach (int state in map.Keys)
{
hashCode = 683 * hashCode + state;
values[upto++] = state;
}
}
else
{
hashCode = upto;
for (int i = 0; i < upto; i++)
{
hashCode = 683 * hashCode + values[i];
}
}
}
public FrozenInt32Set ToFrozenInt32Set() // LUCENENET TODO: This didn't exist in the original
{
int[] c = new int[upto];
Array.Copy(values, 0, c, 0, upto);
return new FrozenInt32Set(c, this.hashCode, this.state);
}
public FrozenInt32Set Freeze(State state)
{
int[] c = new int[upto];
Array.Copy(values, 0, c, 0, upto);
return new FrozenInt32Set(c, hashCode, state);
}
public override int GetHashCode()
{
return hashCode;
}
public override bool Equals(object other)
{
if (other == null)
{
return false;
}
if (!(other is FrozenInt32Set))
{
return false;
}
FrozenInt32Set other2 = (FrozenInt32Set)other;
if (hashCode != other2.hashCode)
{
return false;
}
if (other2.values.Length != upto)
{
return false;
}
for (int i = 0; i < upto; i++)
{
if (other2.values[i] != values[i])
{
return false;
}
}
return true;
}
public bool Equals(SortedInt32Set other) // LUCENENET TODO: This didn't exist in the original
{
throw new NotImplementedException("SortedIntSet Equals");
}
public bool Equals(FrozenInt32Set other) // LUCENENET TODO: This didn't exist in the original
{
if (other == null)
{
return false;
}
if (hashCode != other.hashCode)
{
return false;
}
if (other.values.Length != upto)
{
return false;
}
for (int i = 0; i < upto; i++)
{
if (other.values[i] != values[i])
{
return false;
}
}
return true;
}
public override string ToString()
{
StringBuilder sb = (new StringBuilder()).Append('[');
for (int i = 0; i < upto; i++)
{
if (i > 0)
{
sb.Append(' ');
}
sb.Append(values[i]).Append(':').Append(counts[i]);
}
sb.Append(']');
return sb.ToString();
}
/// <summary>
/// NOTE: This was FrozenIntSet in Lucene
/// </summary>
public sealed class FrozenInt32Set : IEquatable<SortedInt32Set>, IEquatable<FrozenInt32Set>
{
internal readonly int[] values;
internal readonly int hashCode;
internal readonly State state;
public FrozenInt32Set(int[] values, int hashCode, State state)
{
this.values = values;
this.hashCode = hashCode;
this.state = state;
}
public FrozenInt32Set(int num, State state)
{
this.values = new int[] { num };
this.state = state;
this.hashCode = 683 + num;
}
public override int GetHashCode()
{
return hashCode;
}
public override bool Equals(object other)
{
if (other == null)
{
return false;
}
if (other is FrozenInt32Set)
{
FrozenInt32Set other2 = (FrozenInt32Set)other;
if (hashCode != other2.hashCode)
{
return false;
}
if (other2.values.Length != values.Length)
{
return false;
}
for (int i = 0; i < values.Length; i++)
{
if (other2.values[i] != values[i])
{
return false;
}
}
return true;
}
else if (other is SortedInt32Set)
{
SortedInt32Set other3 = (SortedInt32Set)other;
if (hashCode != other3.hashCode)
{
return false;
}
if (other3.values.Length != values.Length)
{
return false;
}
for (int i = 0; i < values.Length; i++)
{
if (other3.values[i] != values[i])
{
return false;
}
}
return true;
}
return false;
}
public bool Equals(SortedInt32Set other) // LUCENENET TODO: This didn't exist in the original
{
if (other == null)
{
return false;
}
if (hashCode != other.hashCode)
{
return false;
}
if (other.values.Length != values.Length)
{
return false;
}
for (int i = 0; i < values.Length; i++)
{
if (other.values[i] != values[i])
{
return false;
}
}
return true;
}
public bool Equals(FrozenInt32Set other) // LUCENENET TODO: This didn't exist in the original
{
if (other == null)
{
return false;
}
if (hashCode != other.hashCode)
{
return false;
}
if (other.values.Length != values.Length)
{
return false;
}
for (int i = 0; i < values.Length; i++)
{
if (other.values[i] != values[i])
{
return false;
}
}
return true;
}
public override string ToString()
{
StringBuilder sb = (new StringBuilder()).Append('[');
for (int i = 0; i < values.Length; i++)
{
if (i > 0)
{
sb.Append(' ');
}
sb.Append(values[i]);
}
sb.Append(']');
return sb.ToString();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.Serialization;
namespace System.Collections.Specialized
{
/// <devdoc>
/// <para>
/// OrderedDictionary offers IDictionary syntax with ordering. Objects
/// added or inserted in an IOrderedDictionary must have both a key and an index, and
/// can be retrieved by either.
/// OrderedDictionary is used by the ParameterCollection because MSAccess relies on ordering of
/// parameters, while almost all other DBs do not. DataKeyArray also uses it so
/// DataKeys can be retrieved by either their name or their index.
///
/// OrderedDictionary implements IDeserializationCallback because it needs to have the
/// contained ArrayList and Hashtable deserialized before it tries to get its count and objects.
/// </para>
/// </devdoc>
[Serializable]
public class OrderedDictionary : IOrderedDictionary, ISerializable, IDeserializationCallback
{
private ArrayList _objectsArray;
private Hashtable _objectsTable;
private int _initialCapacity;
private IEqualityComparer _comparer;
private bool _readOnly;
private Object _syncRoot;
private SerializationInfo _siInfo; //A temporary variable which we need during deserialization.
private const string KeyComparerName = "KeyComparer";
private const string ArrayListName = "ArrayList";
private const string ReadOnlyName = "ReadOnly";
private const string InitCapacityName = "InitialCapacity";
public OrderedDictionary() : this(0)
{
}
public OrderedDictionary(int capacity) : this(capacity, null)
{
}
public OrderedDictionary(IEqualityComparer comparer) : this(0, comparer)
{
}
public OrderedDictionary(int capacity, IEqualityComparer comparer)
{
_initialCapacity = capacity;
_comparer = comparer;
}
private OrderedDictionary(OrderedDictionary dictionary)
{
Debug.Assert(dictionary != null);
_readOnly = true;
_objectsArray = dictionary._objectsArray;
_objectsTable = dictionary._objectsTable;
_comparer = dictionary._comparer;
_initialCapacity = dictionary._initialCapacity;
}
protected OrderedDictionary(SerializationInfo info, StreamingContext context)
{
// We can't do anything with the keys and values until the entire graph has been deserialized
// and getting Counts and objects won't fail. For the time being, we'll just cache this.
// The graph is not valid until OnDeserialization has been called.
_siInfo = info;
}
/// <devdoc>
/// Gets the size of the table.
/// </devdoc>
public int Count
{
get
{
return objectsArray.Count;
}
}
/// <devdoc>
/// Indicates that the collection can grow.
/// </devdoc>
bool IDictionary.IsFixedSize
{
get
{
return _readOnly;
}
}
/// <devdoc>
/// Indicates that the collection is not read-only
/// </devdoc>
public bool IsReadOnly
{
get
{
return _readOnly;
}
}
/// <devdoc>
/// Indicates that this class is not synchronized
/// </devdoc>
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
/// <devdoc>
/// Gets the collection of keys in the table in order.
/// </devdoc>
public ICollection Keys
{
get
{
return new OrderedDictionaryKeyValueCollection(objectsArray, true);
}
}
private ArrayList objectsArray
{
get
{
if (_objectsArray == null)
{
_objectsArray = new ArrayList(_initialCapacity);
}
return _objectsArray;
}
}
private Hashtable objectsTable
{
get
{
if (_objectsTable == null)
{
_objectsTable = new Hashtable(_initialCapacity, _comparer);
}
return _objectsTable;
}
}
/// <devdoc>
/// The SyncRoot object. Not used because IsSynchronized is false
/// </devdoc>
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
/// <devdoc>
/// Gets or sets the object at the specified index
/// </devdoc>
public object this[int index]
{
get
{
return ((DictionaryEntry)objectsArray[index]).Value;
}
set
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index < 0 || index >= objectsArray.Count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
object key = ((DictionaryEntry)objectsArray[index]).Key;
objectsArray[index] = new DictionaryEntry(key, value);
objectsTable[key] = value;
}
}
/// <devdoc>
/// Gets or sets the object with the specified key
/// </devdoc>
public object this[object key]
{
get
{
return objectsTable[key];
}
set
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (objectsTable.Contains(key))
{
objectsTable[key] = value;
objectsArray[IndexOfKey(key)] = new DictionaryEntry(key, value);
}
else
{
Add(key, value);
}
}
}
/// <devdoc>
/// Returns an arrayList of the values in the table
/// </devdoc>
public ICollection Values
{
get
{
return new OrderedDictionaryKeyValueCollection(objectsArray, false);
}
}
/// <devdoc>
/// Adds a new entry to the table with the lowest-available index.
/// </devdoc>
public void Add(object key, object value)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
objectsTable.Add(key, value);
objectsArray.Add(new DictionaryEntry(key, value));
}
/// <devdoc>
/// Clears all elements in the table.
/// </devdoc>
public void Clear()
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
objectsTable.Clear();
objectsArray.Clear();
}
/// <devdoc>
/// Returns a readonly OrderedDictionary for the given OrderedDictionary.
/// </devdoc>
public OrderedDictionary AsReadOnly()
{
return new OrderedDictionary(this);
}
/// <devdoc>
/// Returns true if the key exists in the table, false otherwise.
/// </devdoc>
public bool Contains(object key)
{
return objectsTable.Contains(key);
}
/// <devdoc>
/// Copies the table to an array. This will not preserve order.
/// </devdoc>
public void CopyTo(Array array, int index)
{
objectsTable.CopyTo(array, index);
}
private int IndexOfKey(object key)
{
for (int i = 0; i < objectsArray.Count; i++)
{
object o = ((DictionaryEntry)objectsArray[i]).Key;
if (_comparer != null)
{
if (_comparer.Equals(o, key))
{
return i;
}
}
else
{
if (o.Equals(key))
{
return i;
}
}
}
return -1;
}
/// <devdoc>
/// Inserts a new object at the given index with the given key.
/// </devdoc>
public void Insert(int index, object key, object value)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index > Count || index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
objectsTable.Add(key, value);
objectsArray.Insert(index, new DictionaryEntry(key, value));
}
/// <devdoc>
/// Removes the entry at the given index.
/// </devdoc>
public void RemoveAt(int index)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index >= Count || index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
object key = ((DictionaryEntry)objectsArray[index]).Key;
objectsArray.RemoveAt(index);
objectsTable.Remove(key);
}
/// <devdoc>
/// Removes the entry with the given key.
/// </devdoc>
public void Remove(object key)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
int index = IndexOfKey(key);
if (index < 0)
{
return;
}
objectsTable.Remove(key);
objectsArray.RemoveAt(index);
}
#region IDictionary implementation
public virtual IDictionaryEnumerator GetEnumerator()
{
return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry);
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator()
{
return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry);
}
#endregion
#region ISerializable implementation
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
info.AddValue(KeyComparerName, _comparer, typeof(IEqualityComparer));
info.AddValue(ReadOnlyName, _readOnly);
info.AddValue(InitCapacityName, _initialCapacity);
object[] serArray = new object[Count];
_objectsArray.CopyTo(serArray);
info.AddValue(ArrayListName, serArray);
}
#endregion
#region IDeserializationCallback implementation
void IDeserializationCallback.OnDeserialization(object sender) {
OnDeserialization(sender);
}
protected virtual void OnDeserialization(object sender)
{
if (_siInfo == null)
{
throw new SerializationException(SR.Serialization_InvalidOnDeser);
}
_comparer = (IEqualityComparer)_siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer));
_readOnly = _siInfo.GetBoolean(ReadOnlyName);
_initialCapacity = _siInfo.GetInt32(InitCapacityName);
object[] serArray = (object[])_siInfo.GetValue(ArrayListName, typeof(object[]));
if (serArray != null)
{
foreach (object o in serArray)
{
DictionaryEntry entry;
try
{
// DictionaryEntry is a value type, so it can only be casted.
entry = (DictionaryEntry)o;
}
catch
{
throw new SerializationException(SR.OrderedDictionary_SerializationMismatch);
}
objectsArray.Add(entry);
objectsTable.Add(entry.Key, entry.Value);
}
}
}
#endregion
/// <devdoc>
/// OrderedDictionaryEnumerator works just like any other IDictionaryEnumerator, but it retrieves DictionaryEntries
/// in the order by index.
/// </devdoc>
private class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
private int _objectReturnType;
internal const int Keys = 1;
internal const int Values = 2;
internal const int DictionaryEntry = 3;
private IEnumerator _arrayEnumerator;
internal OrderedDictionaryEnumerator(ArrayList array, int objectReturnType)
{
_arrayEnumerator = array.GetEnumerator();
_objectReturnType = objectReturnType;
}
/// <devdoc>
/// Retrieves the current DictionaryEntry. This is the same as Entry, but not strongly-typed.
/// </devdoc>
public object Current
{
get
{
if (_objectReturnType == Keys)
{
return ((DictionaryEntry)_arrayEnumerator.Current).Key;
}
if (_objectReturnType == Values)
{
return ((DictionaryEntry)_arrayEnumerator.Current).Value;
}
return Entry;
}
}
/// <devdoc>
/// Retrieves the current DictionaryEntry
/// </devdoc>
public DictionaryEntry Entry
{
get
{
return new DictionaryEntry(((DictionaryEntry)_arrayEnumerator.Current).Key, ((DictionaryEntry)_arrayEnumerator.Current).Value);
}
}
/// <devdoc>
/// Retrieves the key of the current DictionaryEntry
/// </devdoc>
public object Key
{
get
{
return ((DictionaryEntry)_arrayEnumerator.Current).Key;
}
}
/// <devdoc>
/// Retrieves the value of the current DictionaryEntry
/// </devdoc>
public object Value
{
get
{
return ((DictionaryEntry)_arrayEnumerator.Current).Value;
}
}
/// <devdoc>
/// Moves the enumerator pointer to the next member
/// </devdoc>
public bool MoveNext()
{
return _arrayEnumerator.MoveNext();
}
/// <devdoc>
/// Resets the enumerator pointer to the beginning.
/// </devdoc>
public void Reset()
{
_arrayEnumerator.Reset();
}
}
/// <devdoc>
/// OrderedDictionaryKeyValueCollection implements a collection for the Values and Keys properties
/// that is "live"- it will reflect changes to the OrderedDictionary on the collection made after the getter
/// was called.
/// </devdoc>
private class OrderedDictionaryKeyValueCollection : ICollection
{
private ArrayList _objects;
private bool _isKeys;
public OrderedDictionaryKeyValueCollection(ArrayList array, bool isKeys)
{
_objects = array;
_isKeys = isKeys;
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
foreach (object o in _objects)
{
array.SetValue(_isKeys ? ((DictionaryEntry)o).Key : ((DictionaryEntry)o).Value, index);
index++;
}
}
int ICollection.Count
{
get
{
return _objects.Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return _objects.SyncRoot;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return new OrderedDictionaryEnumerator(_objects, _isKeys == true ? OrderedDictionaryEnumerator.Keys : OrderedDictionaryEnumerator.Values);
}
}
}
}
| |
#region License
/*
* Copyright 2009- Marko Lahma
*
* 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.Concurrent;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Quartz.Util
{
/// <summary>
/// Utility methods that are used to convert objects from one type into another.
/// </summary>
/// <author>Aleksandar Seovic</author>
/// <author>Marko Lahma</author>
public static class ObjectUtils
{
/// <summary>
/// Convert the value to the required <see cref="System.Type"/> (if necessary from a string).
/// </summary>
/// <param name="newValue">The proposed change value.</param>
/// <param name="requiredType">
/// The <see cref="System.Type"/> we must convert to.
/// </param>
/// <returns>The new value, possibly the result of type conversion.</returns>
public static object? ConvertValueIfNecessary(Type requiredType, object? newValue)
{
if (newValue != null)
{
// if it is assignable, return the value right away
if (requiredType.IsInstanceOfType(newValue))
{
return newValue;
}
// try to convert using type converter
TypeConverter typeConverter = TypeDescriptor.GetConverter(requiredType);
if (typeConverter.CanConvertFrom(newValue.GetType()))
{
return typeConverter.ConvertFrom(null, CultureInfo.InvariantCulture, newValue);
}
typeConverter = TypeDescriptor.GetConverter(newValue.GetType());
if (typeConverter.CanConvertTo(requiredType))
{
return typeConverter.ConvertTo(null, CultureInfo.InvariantCulture, newValue, requiredType);
}
if (requiredType == typeof(Type))
{
return Type.GetType(newValue.ToString()!, true);
}
if (newValue.GetType().GetTypeInfo().IsEnum)
{
// If we couldn't convert the type, but it's an enum type, try convert it as an int
return ConvertValueIfNecessary(requiredType, Convert.ChangeType(newValue, Convert.GetTypeCode(newValue), null));
}
if (requiredType.IsEnum)
{
// if JSON serializer creates numbers from enums, be prepared for that
try
{
return Enum.ToObject(requiredType, newValue);
}
catch
{
}
}
throw new NotSupportedException($"{newValue} is no a supported value for a target of type {requiredType}");
}
if (requiredType.GetTypeInfo().IsValueType)
{
return Activator.CreateInstance(requiredType);
}
// return default
return null;
}
/// <summary>
/// Instantiates an instance of the type specified.
/// </summary>
public static T InstantiateType<T>(Type? type)
{
if (type == null)
{
ExceptionHelper.ThrowArgumentNullException(nameof(type), "Cannot instantiate null");
}
var ci = type.GetConstructor(Type.EmptyTypes);
if (ci == null)
{
ExceptionHelper.ThrowArgumentException("Cannot instantiate type which has no empty constructor", type.Name);
}
return (T) ci.Invoke(Array.Empty<object>());
}
/// <summary>
/// Sets the object properties using reflection.
/// </summary>
public static void SetObjectProperties(object obj, string[] propertyNames, object[] propertyValues)
{
for (int i = 0; i < propertyNames.Length; i++)
{
string name = propertyNames[i];
try
{
SetPropertyValue(obj, name, propertyValues[i]);
}
catch (Exception nfe)
{
throw new SchedulerConfigException(
$"Could not parse property '{name}' into correct data type: {nfe.Message}", nfe);
}
}
}
/// <summary>
/// Sets the object properties using reflection.
/// </summary>
/// <param name="obj">The object to set values to.</param>
/// <param name="props">The properties to set to object.</param>
public static void SetObjectProperties(object obj, NameValueCollection props)
{
// remove the type
props.Remove("type");
foreach (string name in props.Keys)
{
try
{
var value = props[name];
SetPropertyValue(obj, name, value);
}
catch (Exception nfe)
{
throw new SchedulerConfigException(
$"Could not parse property '{name}' into correct data type: {nfe.Message}", nfe);
}
}
}
private static readonly ConcurrentDictionary<(Type ObjectType, string PropertyName), PropertyInfo?> propertyResolutionCache = new ();
public static void SetPropertyValue(object target, string propertyName, object? value)
{
var pi = propertyResolutionCache.GetOrAdd((target.GetType(), propertyName), tuple =>
{
string name = char.IsLower(tuple.PropertyName[0])
? char.ToUpper(tuple.PropertyName[0]) + tuple.PropertyName.Substring(1)
: tuple.PropertyName;
Type t = tuple.ObjectType;
var propertyInfo = t.GetProperty(name);
if (propertyInfo == null || !propertyInfo.CanWrite)
{
// try to find from interfaces
foreach (var interfaceType in target.GetType().GetInterfaces())
{
propertyInfo = interfaceType.GetProperty(name);
if (propertyInfo != null && propertyInfo.CanWrite)
{
// found suitable
break;
}
}
}
return propertyInfo;
});
if (pi == null)
{
// not match from anywhere
throw new MemberAccessException($"No writable property '{propertyName}' found");
}
var mi = pi.GetSetMethod();
if (mi == null)
{
throw new MemberAccessException($"Property '{propertyName}' has no setter");
}
if (mi.GetParameters()[0].ParameterType == typeof(TimeSpan))
{
// special handling
value = GetTimeSpanValueForProperty(pi, value);
}
else
{
value = ConvertValueIfNecessary(mi.GetParameters()[0].ParameterType, value);
}
mi.Invoke(target, new[] {value});
}
public static TimeSpan GetTimeSpanValueForProperty(PropertyInfo pi, object? value)
{
object[] attributes = pi.GetCustomAttributes(typeof(TimeSpanParseRuleAttribute), false).ToArray();
if (attributes.Length == 0)
{
return (TimeSpan) ConvertValueIfNecessary(typeof(TimeSpan), value)!;
}
TimeSpanParseRuleAttribute attribute = (TimeSpanParseRuleAttribute) attributes[0];
long longValue = Convert.ToInt64(value);
switch (attribute.Rule)
{
case TimeSpanParseRule.Milliseconds:
return TimeSpan.FromMilliseconds(longValue);
case TimeSpanParseRule.Seconds:
return TimeSpan.FromSeconds(longValue);
case TimeSpanParseRule.Minutes:
return TimeSpan.FromMinutes(longValue);
case TimeSpanParseRule.Hours:
return TimeSpan.FromHours(longValue);
default:
throw new ArgumentOutOfRangeException();
}
}
public static bool IsAttributePresent(Type typeToExamine, Type attributeType)
{
return typeToExamine.GetTypeInfo().GetCustomAttributes(attributeType, true).Any();
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dialogflow.V2.Tests
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using apis = Google.Cloud.Dialogflow.V2;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Moq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
/// <summary>Generated unit tests</summary>
public class GeneratedIntentsClientTest
{
[Fact]
public void GetIntent()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetIntentRequest expectedRequest = new GetIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.GetIntent(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
IntentName name = new IntentName("[PROJECT]", "[INTENT]");
Intent response = client.GetIntent(name);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetIntentAsync()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetIntentRequest expectedRequest = new GetIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.GetIntentAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Intent>(Task.FromResult(expectedResponse), null, null, null, null));
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
IntentName name = new IntentName("[PROJECT]", "[INTENT]");
Intent response = await client.GetIntentAsync(name);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetIntent2()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetIntentRequest expectedRequest = new GetIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
LanguageCode = "languageCode-412800396",
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.GetIntent(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
IntentName name = new IntentName("[PROJECT]", "[INTENT]");
string languageCode = "languageCode-412800396";
Intent response = client.GetIntent(name, languageCode);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetIntentAsync2()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetIntentRequest expectedRequest = new GetIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
LanguageCode = "languageCode-412800396",
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.GetIntentAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Intent>(Task.FromResult(expectedResponse), null, null, null, null));
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
IntentName name = new IntentName("[PROJECT]", "[INTENT]");
string languageCode = "languageCode-412800396";
Intent response = await client.GetIntentAsync(name, languageCode);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetIntent3()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetIntentRequest request = new GetIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.GetIntent(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
Intent response = client.GetIntent(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetIntentAsync3()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetIntentRequest request = new GetIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.GetIntentAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Intent>(Task.FromResult(expectedResponse), null, null, null, null));
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
Intent response = await client.GetIntentAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateIntent()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
CreateIntentRequest expectedRequest = new CreateIntentRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
Intent = new Intent(),
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.CreateIntent(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
Intent intent = new Intent();
Intent response = client.CreateIntent(parent, intent);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateIntentAsync()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
CreateIntentRequest expectedRequest = new CreateIntentRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
Intent = new Intent(),
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.CreateIntentAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Intent>(Task.FromResult(expectedResponse), null, null, null, null));
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
Intent intent = new Intent();
Intent response = await client.CreateIntentAsync(parent, intent);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateIntent2()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
CreateIntentRequest expectedRequest = new CreateIntentRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
Intent = new Intent(),
LanguageCode = "languageCode-412800396",
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.CreateIntent(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
Intent intent = new Intent();
string languageCode = "languageCode-412800396";
Intent response = client.CreateIntent(parent, intent, languageCode);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateIntentAsync2()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
CreateIntentRequest expectedRequest = new CreateIntentRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
Intent = new Intent(),
LanguageCode = "languageCode-412800396",
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.CreateIntentAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Intent>(Task.FromResult(expectedResponse), null, null, null, null));
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
Intent intent = new Intent();
string languageCode = "languageCode-412800396";
Intent response = await client.CreateIntentAsync(parent, intent, languageCode);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateIntent3()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
CreateIntentRequest request = new CreateIntentRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
Intent = new Intent(),
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.CreateIntent(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
Intent response = client.CreateIntent(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateIntentAsync3()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
CreateIntentRequest request = new CreateIntentRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
Intent = new Intent(),
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.CreateIntentAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Intent>(Task.FromResult(expectedResponse), null, null, null, null));
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
Intent response = await client.CreateIntentAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void UpdateIntent()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
UpdateIntentRequest expectedRequest = new UpdateIntentRequest
{
Intent = new Intent(),
LanguageCode = "languageCode-412800396",
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.UpdateIntent(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
Intent intent = new Intent();
string languageCode = "languageCode-412800396";
Intent response = client.UpdateIntent(intent, languageCode);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task UpdateIntentAsync()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
UpdateIntentRequest expectedRequest = new UpdateIntentRequest
{
Intent = new Intent(),
LanguageCode = "languageCode-412800396",
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.UpdateIntentAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Intent>(Task.FromResult(expectedResponse), null, null, null, null));
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
Intent intent = new Intent();
string languageCode = "languageCode-412800396";
Intent response = await client.UpdateIntentAsync(intent, languageCode);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void UpdateIntent2()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
UpdateIntentRequest expectedRequest = new UpdateIntentRequest
{
Intent = new Intent(),
LanguageCode = "languageCode-412800396",
UpdateMask = new FieldMask(),
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.UpdateIntent(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
Intent intent = new Intent();
string languageCode = "languageCode-412800396";
FieldMask updateMask = new FieldMask();
Intent response = client.UpdateIntent(intent, languageCode, updateMask);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task UpdateIntentAsync2()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
UpdateIntentRequest expectedRequest = new UpdateIntentRequest
{
Intent = new Intent(),
LanguageCode = "languageCode-412800396",
UpdateMask = new FieldMask(),
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.UpdateIntentAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Intent>(Task.FromResult(expectedResponse), null, null, null, null));
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
Intent intent = new Intent();
string languageCode = "languageCode-412800396";
FieldMask updateMask = new FieldMask();
Intent response = await client.UpdateIntentAsync(intent, languageCode, updateMask);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void UpdateIntent3()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
UpdateIntentRequest request = new UpdateIntentRequest
{
Intent = new Intent(),
LanguageCode = "languageCode-412800396",
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.UpdateIntent(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
Intent response = client.UpdateIntent(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task UpdateIntentAsync3()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
UpdateIntentRequest request = new UpdateIntentRequest
{
Intent = new Intent(),
LanguageCode = "languageCode-412800396",
};
Intent expectedResponse = new Intent
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
DisplayName = "displayName1615086568",
Priority = 1165461084,
IsFallback = false,
MlDisabled = true,
Action = "action-1422950858",
ResetContexts = true,
RootFollowupIntentName = "rootFollowupIntentName402253784",
ParentFollowupIntentName = "parentFollowupIntentName-1131901680",
};
mockGrpcClient.Setup(x => x.UpdateIntentAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Intent>(Task.FromResult(expectedResponse), null, null, null, null));
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
Intent response = await client.UpdateIntentAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteIntent()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteIntentRequest expectedRequest = new DeleteIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteIntent(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
IntentName name = new IntentName("[PROJECT]", "[INTENT]");
client.DeleteIntent(name);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteIntentAsync()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteIntentRequest expectedRequest = new DeleteIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteIntentAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
IntentName name = new IntentName("[PROJECT]", "[INTENT]");
await client.DeleteIntentAsync(name);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteIntent2()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteIntentRequest request = new DeleteIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteIntent(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
client.DeleteIntent(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteIntentAsync2()
{
Mock<Intents.IntentsClient> mockGrpcClient = new Mock<Intents.IntentsClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteIntentRequest request = new DeleteIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteIntentAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
IntentsClient client = new IntentsClientImpl(mockGrpcClient.Object, null);
await client.DeleteIntentAsync(request);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.2.16. Identifies the type of entity, including kind of entity, domain (surface, subsurface, air, etc) country, category, etc.
/// </summary>
[Serializable]
[XmlRoot]
public partial class EntityType
{
/// <summary>
/// Kind of entity
/// </summary>
private byte _entityKind;
/// <summary>
/// Domain of entity (air, surface, subsurface, space, etc)
/// </summary>
private byte _domain;
/// <summary>
/// country to which the design of the entity is attributed
/// </summary>
private ushort _country;
/// <summary>
/// category of entity
/// </summary>
private byte _category;
/// <summary>
/// subcategory of entity
/// </summary>
private byte _subcategory;
/// <summary>
/// specific info based on subcategory field
/// </summary>
private byte _specific;
private byte _extra;
/// <summary>
/// Initializes a new instance of the <see cref="EntityType"/> class.
/// </summary>
public EntityType()
{
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(EntityType left, EntityType right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(EntityType left, EntityType right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public virtual int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize += 1; // this._entityKind
marshalSize += 1; // this._domain
marshalSize += 2; // this._country
marshalSize += 1; // this._category
marshalSize += 1; // this._subcategory
marshalSize += 1; // this._specific
marshalSize += 1; // this._extra
return marshalSize;
}
/// <summary>
/// Gets or sets the Kind of entity
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "entityKind")]
public byte EntityKind
{
get
{
return this._entityKind;
}
set
{
this._entityKind = value;
}
}
/// <summary>
/// Gets or sets the Domain of entity (air, surface, subsurface, space, etc)
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "domain")]
public byte Domain
{
get
{
return this._domain;
}
set
{
this._domain = value;
}
}
/// <summary>
/// Gets or sets the country to which the design of the entity is attributed
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "country")]
public ushort Country
{
get
{
return this._country;
}
set
{
this._country = value;
}
}
/// <summary>
/// Gets or sets the category of entity
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "category")]
public byte Category
{
get
{
return this._category;
}
set
{
this._category = value;
}
}
/// <summary>
/// Gets or sets the subcategory of entity
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "subcategory")]
public byte Subcategory
{
get
{
return this._subcategory;
}
set
{
this._subcategory = value;
}
}
/// <summary>
/// Gets or sets the specific info based on subcategory field
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "specific")]
public byte Specific
{
get
{
return this._specific;
}
set
{
this._specific = value;
}
}
/// <summary>
/// Gets or sets the extra
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "extra")]
public byte Extra
{
get
{
return this._extra;
}
set
{
this._extra = value;
}
}
/// <summary>
/// Occurs when exception when processing PDU is caught.
/// </summary>
public event EventHandler<PduExceptionEventArgs> ExceptionOccured;
/// <summary>
/// Called when exception occurs (raises the <see cref="Exception"/> event).
/// </summary>
/// <param name="e">The exception.</param>
protected void RaiseExceptionOccured(Exception e)
{
if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
{
this.ExceptionOccured(this, new PduExceptionEventArgs(e));
}
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Marshal(DataOutputStream dos)
{
if (dos != null)
{
try
{
dos.WriteUnsignedByte((byte)this._entityKind);
dos.WriteUnsignedByte((byte)this._domain);
dos.WriteUnsignedShort((ushort)this._country);
dos.WriteUnsignedByte((byte)this._category);
dos.WriteUnsignedByte((byte)this._subcategory);
dos.WriteUnsignedByte((byte)this._specific);
dos.WriteUnsignedByte((byte)this._extra);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Unmarshal(DataInputStream dis)
{
if (dis != null)
{
try
{
this._entityKind = dis.ReadUnsignedByte();
this._domain = dis.ReadUnsignedByte();
this._country = dis.ReadUnsignedShort();
this._category = dis.ReadUnsignedByte();
this._subcategory = dis.ReadUnsignedByte();
this._specific = dis.ReadUnsignedByte();
this._extra = dis.ReadUnsignedByte();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Reflection(StringBuilder sb)
{
sb.AppendLine("<EntityType>");
try
{
sb.AppendLine("<entityKind type=\"byte\">" + this._entityKind.ToString(CultureInfo.InvariantCulture) + "</entityKind>");
sb.AppendLine("<domain type=\"byte\">" + this._domain.ToString(CultureInfo.InvariantCulture) + "</domain>");
sb.AppendLine("<country type=\"ushort\">" + this._country.ToString(CultureInfo.InvariantCulture) + "</country>");
sb.AppendLine("<category type=\"byte\">" + this._category.ToString(CultureInfo.InvariantCulture) + "</category>");
sb.AppendLine("<subcategory type=\"byte\">" + this._subcategory.ToString(CultureInfo.InvariantCulture) + "</subcategory>");
sb.AppendLine("<specific type=\"byte\">" + this._specific.ToString(CultureInfo.InvariantCulture) + "</specific>");
sb.AppendLine("<extra type=\"byte\">" + this._extra.ToString(CultureInfo.InvariantCulture) + "</extra>");
sb.AppendLine("</EntityType>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as EntityType;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(EntityType obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
if (this._entityKind != obj._entityKind)
{
ivarsEqual = false;
}
if (this._domain != obj._domain)
{
ivarsEqual = false;
}
if (this._country != obj._country)
{
ivarsEqual = false;
}
if (this._category != obj._category)
{
ivarsEqual = false;
}
if (this._subcategory != obj._subcategory)
{
ivarsEqual = false;
}
if (this._specific != obj._specific)
{
ivarsEqual = false;
}
if (this._extra != obj._extra)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ this._entityKind.GetHashCode();
result = GenerateHash(result) ^ this._domain.GetHashCode();
result = GenerateHash(result) ^ this._country.GetHashCode();
result = GenerateHash(result) ^ this._category.GetHashCode();
result = GenerateHash(result) ^ this._subcategory.GetHashCode();
result = GenerateHash(result) ^ this._specific.GetHashCode();
result = GenerateHash(result) ^ this._extra.GetHashCode();
return result;
}
}
}
| |
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Threading.Tasks;
using Prism.Interfaces;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Resources;
using Windows.ApplicationModel.Search;
using Windows.UI.ApplicationSettings;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace Prism
{
/// <summary>
/// Provides MvvmAppBase-specific behavior to supplement the default Application class.
/// </summary>
// Documentation on using the MVVM pattern is at http://go.microsoft.com/fwlink/?LinkID=288814&clcid=0x409
public abstract class MvvmAppBase : Application
{
private bool _isRestoringFromTermination;
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
protected MvvmAppBase()
{
this.Suspending += OnSuspending;
}
/// <summary>
/// Gets or sets the session state service.
/// </summary>
/// <value>
/// The session state service.
/// </value>
protected ISessionStateService SessionStateService { get; set; }
/// <summary>
/// Gets or sets the navigation service.
/// </summary>
/// <value>
/// The navigation service.
/// </value>
protected INavigationService NavigationService { get; set; }
/// <summary>
/// Factory for creating the ExtendedSplashScreen instance.
/// </summary>
/// <value>
/// The Func that creates the ExtendedSplashScreen. It requires a SplashScreen parameter,
/// and must return a Page instance.
/// </value>
protected Func<SplashScreen, Page> ExtendedSplashScreenFactory { get; set; }
/// <summary>
/// Gets a value indicating whether the application is suspending.
/// </summary>
/// <value>
/// <c>true</c> if the application is suspending; otherwise, <c>false</c>.
/// </value>
public bool IsSuspending { get; private set; }
/// <summary>
/// Override this method with logic that will be performed after the application is initialized. For example, navigating to the application's home page.
/// </summary>
/// <param name="args">The <see cref="LaunchActivatedEventArgs"/> instance containing the event data.</param>
protected abstract Task OnLaunchApplication(LaunchActivatedEventArgs args);
/// <summary>
/// Gets the type of the page based on a page token.
/// </summary>
/// <param name="pageToken">The page token.</param>
/// <returns>The type of the page which corresponds to the specified token.</returns>
protected virtual Type GetPageType(string pageToken)
{
var assemblyQualifiedAppType = this.GetType().GetTypeInfo().AssemblyQualifiedName;
var pageNameWithParameter = assemblyQualifiedAppType.Replace(this.GetType().FullName, this.GetType().Namespace + ".Views.{0}Page");
var viewFullName = string.Format(CultureInfo.InvariantCulture, pageNameWithParameter, pageToken);
var viewType = Type.GetType(viewFullName);
if (viewType == null)
{
var resourceLoader = ResourceLoader.GetForCurrentView(Constants.PrismInfrastructureResourceMapId);
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture, resourceLoader.GetString("DefaultPageTypeLookupErrorMessage"), pageToken, this.GetType().Namespace + ".Views"),
"pageToken");
}
return viewType;
}
/// <summary>
/// Used for setting up the list of known types for the SessionStateService, using the RegisterKnownType method.
/// </summary>
protected virtual void OnRegisterKnownTypesForSerialization() { }
/// <summary>
/// Override this method with the initialization logic of your application. Here you can initialize services, repositories, and so on.
/// </summary>
/// <param name="args">The <see cref="IActivatedEventArgs"/> instance containing the event data.</param>
protected virtual void OnInitialize(IActivatedEventArgs args) { }
/// <summary>
/// Gets the Settings charm action items.
/// </summary>
/// <returns>The list of Setting charm action items that will populate the Settings pane.</returns>
protected virtual IList<SettingsCommand> GetSettingsCommands()
{
return null;
}
/// <summary>
/// Resolves the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>A concrete instance of the specified type.</returns>
protected virtual object Resolve(Type type)
{
return Activator.CreateInstance(type);
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
var rootFrame = await InitializeFrameAsync(args);
// If the app is launched via the app's primary tile, the args.TileId property
// will have the same value as the AppUserModelId, which is set in the Package.appxmanifest.
// See http://go.microsoft.com/fwlink/?LinkID=288842
string tileId = AppManifestHelper.GetApplicationId();
if (rootFrame != null && (!_isRestoringFromTermination || (args != null && args.TileId != tileId)))
{
await OnLaunchApplication(args);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Initializes the Frame and its content.
/// </summary>
/// <param name="args">The <see cref="IActivatedEventArgs"/> instance containing the event data.</param>
/// <returns>A task of a Frame that holds the app content.</returns>
protected async Task<Frame> InitializeFrameAsync(IActivatedEventArgs args)
{
var rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
if (ExtendedSplashScreenFactory != null)
{
Page extendedSplashScreen = this.ExtendedSplashScreenFactory.Invoke(args.SplashScreen);
rootFrame.Content = extendedSplashScreen;
}
var frameFacade = new FrameFacadeAdapter(rootFrame);
//Initialize MvvmAppBase common services
SessionStateService = new SessionStateService();
//Configure VisualStateAwarePage with the ability to get the session state for its frame
VisualStateAwarePage.GetSessionStateForFrame =
frame => SessionStateService.GetSessionStateForFrame(frameFacade);
//Associate the frame with a key
SessionStateService.RegisterFrame(frameFacade, "AppFrame");
NavigationService = CreateNavigationService(frameFacade, SessionStateService);
SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;
// Set a factory for the ViewModelLocator to use the default resolution mechanism to construct view models
ViewModelLocator.SetDefaultViewModelFactory(Resolve);
OnRegisterKnownTypesForSerialization();
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
await SessionStateService.RestoreSessionStateAsync();
}
OnInitialize(args);
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// Restore the saved session state and navigate to the last page visited
try
{
SessionStateService.RestoreFrameState();
NavigationService.RestoreSavedNavigation();
_isRestoringFromTermination = true;
}
catch (SessionStateServiceException)
{
// Something went wrong restoring state.
// Assume there is no state and continue
}
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
return rootFrame;
}
/// <summary>
/// Creates the navigation service.
/// </summary>
/// <param name="rootFrame">The root frame.</param>
/// <param name="sessionStateService">The session state service.</param>
/// <returns>The initialized navigation service.</returns>
private INavigationService CreateNavigationService(IFrameFacade rootFrame, ISessionStateService sessionStateService)
{
var navigationService = new FrameNavigationService(rootFrame, GetPageType, sessionStateService);
return navigationService;
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
IsSuspending = true;
try
{
var deferral = e.SuspendingOperation.GetDeferral();
//Bootstrap inform navigation service that app is suspending.
NavigationService.Suspending();
// Save application state
await SessionStateService.SaveAsync();
deferral.Complete();
}
finally
{
IsSuspending = false;
}
}
/// <summary>
/// Called when the Settings charm is invoked, this handler populates the Settings charm with the charm items returned by the GetSettingsCommands function.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="SettingsPaneCommandsRequestedEventArgs"/> instance containing the event data.</param>
private void OnCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
{
if (args == null || args.Request == null || args.Request.ApplicationCommands == null)
{
return;
}
var applicationCommands = args.Request.ApplicationCommands;
var settingsCommands = GetSettingsCommands();
foreach (var settingsCommand in settingsCommands)
{
applicationCommands.Add(settingsCommand);
}
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Decrypted data IMPORT Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class A_DECRYPDataSet : EduHubDataSet<A_DECRYP>
{
/// <inheritdoc />
public override string Name { get { return "A_DECRYP"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal A_DECRYPDataSet(EduHubContext Context)
: base(Context)
{
Index_TID = new Lazy<Dictionary<int, A_DECRYP>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="A_DECRYP" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="A_DECRYP" /> fields for each CSV column header</returns>
internal override Action<A_DECRYP, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<A_DECRYP, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "LINE_TYPE":
mapper[i] = (e, v) => e.LINE_TYPE = v;
break;
case "RECORD":
mapper[i] = (e, v) => e.RECORD = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="A_DECRYP" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="A_DECRYP" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="A_DECRYP" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{A_DECRYP}"/> of entities</returns>
internal override IEnumerable<A_DECRYP> ApplyDeltaEntities(IEnumerable<A_DECRYP> Entities, List<A_DECRYP> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.TID;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.TID.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<int, A_DECRYP>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find A_DECRYP by TID field
/// </summary>
/// <param name="TID">TID value used to find A_DECRYP</param>
/// <returns>Related A_DECRYP entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public A_DECRYP FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find A_DECRYP by TID field
/// </summary>
/// <param name="TID">TID value used to find A_DECRYP</param>
/// <param name="Value">Related A_DECRYP entity</param>
/// <returns>True if the related A_DECRYP entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out A_DECRYP Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find A_DECRYP by TID field
/// </summary>
/// <param name="TID">TID value used to find A_DECRYP</param>
/// <returns>Related A_DECRYP entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public A_DECRYP TryFindByTID(int TID)
{
A_DECRYP value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a A_DECRYP table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[A_DECRYP]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[A_DECRYP](
[TID] int IDENTITY NOT NULL,
[LINE_TYPE] varchar(10) NULL,
[RECORD] varchar(200) NULL,
[LW_DATE] datetime NULL,
CONSTRAINT [A_DECRYP_Index_TID] PRIMARY KEY CLUSTERED (
[TID] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="A_DECRYPDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="A_DECRYPDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="A_DECRYP"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="A_DECRYP"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<A_DECRYP> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[A_DECRYP] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the A_DECRYP data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the A_DECRYP data set</returns>
public override EduHubDataSetDataReader<A_DECRYP> GetDataSetDataReader()
{
return new A_DECRYPDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the A_DECRYP data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the A_DECRYP data set</returns>
public override EduHubDataSetDataReader<A_DECRYP> GetDataSetDataReader(List<A_DECRYP> Entities)
{
return new A_DECRYPDataReader(new EduHubDataSetLoadedReader<A_DECRYP>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class A_DECRYPDataReader : EduHubDataSetDataReader<A_DECRYP>
{
public A_DECRYPDataReader(IEduHubDataSetReader<A_DECRYP> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 4; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // LINE_TYPE
return Current.LINE_TYPE;
case 2: // RECORD
return Current.RECORD;
case 3: // LW_DATE
return Current.LW_DATE;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // LINE_TYPE
return Current.LINE_TYPE == null;
case 2: // RECORD
return Current.RECORD == null;
case 3: // LW_DATE
return Current.LW_DATE == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // LINE_TYPE
return "LINE_TYPE";
case 2: // RECORD
return "RECORD";
case 3: // LW_DATE
return "LW_DATE";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "LINE_TYPE":
return 1;
case "RECORD":
return 2;
case "LW_DATE":
return 3;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
namespace Ocelot.IntegrationTests
{
public class ThreadSafeHeadersTests : IDisposable
{
private readonly HttpClient _httpClient;
private IWebHost _builder;
private IWebHostBuilder _webHostBuilder;
private readonly string _ocelotBaseUrl;
private IWebHost _downstreamBuilder;
private readonly Random _random;
private readonly ConcurrentBag<ThreadSafeHeadersTestResult> _results;
public ThreadSafeHeadersTests()
{
_results = new ConcurrentBag<ThreadSafeHeadersTestResult>();
_random = new Random();
_httpClient = new HttpClient();
_ocelotBaseUrl = "http://localhost:5001";
_httpClient.BaseAddress = new Uri(_ocelotBaseUrl);
}
[Fact]
public void should_return_same_response_for_each_different_header_under_load_to_downsteam_service()
{
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 51879,
}
},
UpstreamPathTemplate = "/",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => GivenThereIsAConfiguration(configuration))
.And(x => GivenThereIsAServiceRunningOn("http://localhost:51879"))
.And(x => GivenOcelotIsRunning())
.When(x => WhenIGetUrlOnTheApiGatewayMultipleTimesWithDifferentHeaderValues("/", 300))
.Then(x => ThenTheSameHeaderValuesAreReturnedByTheDownstreamService())
.BDDfy();
}
private void GivenThereIsAServiceRunningOn(string url)
{
_downstreamBuilder = new WebHostBuilder()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseUrls(url)
.Configure(app =>
{
app.Run(async context =>
{
var header = context.Request.Headers["ThreadSafeHeadersTest"];
context.Response.StatusCode = 200;
await context.Response.WriteAsync(header[0]);
});
})
.Build();
_downstreamBuilder.Start();
}
private void GivenOcelotIsRunning()
{
_webHostBuilder = new WebHostBuilder()
.UseUrls(_ocelotBaseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false);
config.AddJsonFile("ocelot.json", false, false);
config.AddEnvironmentVariables();
})
.ConfigureServices(x =>
{
x.AddOcelot();
})
.Configure(app =>
{
app.UseOcelot().Wait();
});
_builder = _webHostBuilder.Build();
_builder.Start();
}
private void GivenThereIsAConfiguration(FileConfiguration fileConfiguration)
{
var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json";
var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration);
if (File.Exists(configurationPath))
{
File.Delete(configurationPath);
}
File.WriteAllText(configurationPath, jsonConfiguration);
var text = File.ReadAllText(configurationPath);
configurationPath = $"{AppContext.BaseDirectory}/ocelot.json";
if (File.Exists(configurationPath))
{
File.Delete(configurationPath);
}
File.WriteAllText(configurationPath, jsonConfiguration);
text = File.ReadAllText(configurationPath);
}
private void WhenIGetUrlOnTheApiGatewayMultipleTimesWithDifferentHeaderValues(string url, int times)
{
var tasks = new Task[times];
for (int i = 0; i < times; i++)
{
var urlCopy = url;
var random = _random.Next(0, 50);
tasks[i] = GetForThreadSafeHeadersTest(urlCopy, random);
}
Task.WaitAll(tasks);
}
private async Task GetForThreadSafeHeadersTest(string url, int random)
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("ThreadSafeHeadersTest", new List<string> { random.ToString() });
var response = await _httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
int result = int.Parse(content);
var tshtr = new ThreadSafeHeadersTestResult(result, random);
_results.Add(tshtr);
}
private void ThenTheSameHeaderValuesAreReturnedByTheDownstreamService()
{
foreach(var result in _results)
{
result.Result.ShouldBe(result.Random);
}
}
public void Dispose()
{
_builder?.Dispose();
_httpClient?.Dispose();
_downstreamBuilder?.Dispose();
}
class ThreadSafeHeadersTestResult
{
public ThreadSafeHeadersTestResult(int result, int random)
{
Result = result;
Random = random;
}
public int Result { get; private set; }
public int Random { get; private set; }
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2016, George Sedov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
******************************************************************************/
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
namespace KSPPreciseManeuver.UI {
[RequireComponent (typeof (RectTransform))]
public class SaverControl : MonoBehaviour {
[SerializeField]
private Button m_ButtonSave = null;
[SerializeField]
private Button m_ButtonDel = null;
[SerializeField]
private Button m_ButtonOk = null;
[SerializeField]
private PreciseManeuverDropdown m_Chooser = null;
private UnityAction<string> chooserText = null;
[SerializeField]
private InputField m_NameInput = null;
[SerializeField]
private GameObject m_ChooserPanel = null;
[SerializeField]
private GameObject m_SaverPanel = null;
private int savedChooserValue = 0;
private System.Collections.Generic.List<string> presetCache = new System.Collections.Generic.List<string> ();
private ISaverControl m_Control = null;
public void SetControl (ISaverControl control) {
m_Control = control;
m_Chooser.UpdateDropdownCaption = SetChooserText;
m_Chooser.UpdateDropdownOption = SetChooserOption;
chooserText = m_Control.ReplaceTextComponentWithTMPro (m_Chooser.CaptionArea.GetComponent<Text> ());
m_Control.ReplaceInputFieldWithTMPro (m_NameInput, InputFieldSubmit, InputFieldChange);
SwitchChooser ();
RepopulateChooser ();
}
public void OnDestroy () {
m_Chooser.Hide ();
m_Control = null;
}
public void SaveButtonAction () {
if (m_Chooser.Value != 0)
m_Control.AddPreset (presetCache[m_Chooser.Value - 1]);
}
public void SaveAsButtonAction () {
SwitchSaver ();
var text = m_Control.suggestPresetName ();
m_Control.TMProText = text;
m_Control.TMProActivateInputField ();
m_Control.TMProSelectAllText ();
InputFieldChange (text);
}
public void DelButtonAction () {
if (m_Chooser.Value != 0)
m_Control.RemovePreset (presetCache[m_Chooser.Value - 1]);
RepopulateChooser ();
}
public void OKButtonAction () {
var text = m_Control.TMProText;
if (text.Length > 0) {
m_Control.AddPreset (text);
RepopulateChooser ();
var items = presetCache.FindAll (a => (a == text));
if (items.Count == 1)
m_Chooser.SetValueWithoutNotify (presetCache.FindIndex (a => (a == text)) + 1);
SwitchChooser ();
UpdateControls ();
}
}
public void CancelButtonAction () {
SwitchChooser ();
UpdateControls ();
}
public void InputFieldChange (string text) {
if (text.Length > 0) {
m_ButtonOk.interactable = true;
m_ButtonOk.GetComponent<Image> ().color = new Color (1.0f, 1.0f, 1.0f, 1.0f);
} else {
m_ButtonOk.interactable = false;
m_ButtonOk.GetComponent<Image> ().color = new Color (0.0f, 0.0f, 0.0f, 0.25f);
}
}
public void InputFieldSubmit (string text) {
if (Input.GetKeyDown (KeyCode.Return) || Input.GetKeyDown (KeyCode.KeypadEnter)) {
OKButtonAction ();
}
}
private void SwitchSaver () {
var canvasgroup = m_ChooserPanel.GetComponent<CanvasGroup> ();
canvasgroup.interactable = false;
canvasgroup.blocksRaycasts = false;
m_ChooserPanel.GetComponent<CanvasGroupFader> ().FadeOut ();
m_SaverPanel.GetComponent<CanvasGroupFader> ().FadeIn ();
canvasgroup = m_SaverPanel.GetComponent<CanvasGroup> ();
canvasgroup.interactable = true;
canvasgroup.blocksRaycasts = true;
}
private void SwitchChooser () {
var canvasgroup = m_SaverPanel.GetComponent<CanvasGroup> ();
canvasgroup.interactable = false;
canvasgroup.blocksRaycasts = false;
m_SaverPanel.GetComponent<CanvasGroupFader> ().FadeOut ();
m_ChooserPanel.GetComponent<CanvasGroupFader> ().FadeIn ();
canvasgroup = m_ChooserPanel.GetComponent<CanvasGroup> ();
canvasgroup.interactable = true;
canvasgroup.blocksRaycasts = true;
}
public void UpdateControls () {
if (m_Chooser.Value > 0) {
m_ButtonSave.interactable = true;
m_ButtonSave.GetComponent<Image> ().color = new Color (1.0f, 1.0f, 1.0f, 1.0f);
m_ButtonDel.interactable = true;
m_ButtonDel.GetComponent<Image> ().color = new Color (1.0f, 1.0f, 1.0f, 1.0f);
} else {
m_ButtonSave.interactable = false;
m_ButtonSave.GetComponent<Image> ().color = new Color (0.0f, 0.0f, 0.0f, 0.25f);
m_ButtonDel.interactable = false;
m_ButtonDel.GetComponent<Image> ().color = new Color (0.0f, 0.0f, 0.0f, 0.25f);
}
}
public void RepopulateChooser () {
presetCache = m_Control.presetNames ();
m_Chooser.OptionsCount = 1 + presetCache.Count;
m_Chooser.SetValueWithoutNotify (0);
UpdateControls ();
}
private void SetChooserText (int index, GameObject caption) {
if (index < 0 || index > presetCache.Count)
return;
if (index == 0)
chooserText (m_Control.newPresetLocalized);
else
chooserText (presetCache[index - 1]);
}
private void SetChooserOption (PreciseManeuverDropdownItem item) {
if (item.Index == 0)
m_Control.ReplaceTextComponentWithTMPro (item.GetComponentInChildren<Text> ())?.Invoke (m_Control.newPresetLocalized);
else
m_Control.ReplaceTextComponentWithTMPro (item.GetComponentInChildren<Text> ())?.Invoke (presetCache[item.Index - 1]);
}
public void ChooserValueChange (int value) {
if (value == 0) {
SaveAsButtonAction ();
} else {
m_Control.loadPreset (presetCache[value - 1]);
}
UpdateControls ();
}
public void ItemClicked () {
if (savedChooserValue != m_Chooser.Value) {
savedChooserValue = m_Chooser.Value;
} else {
ChooserValueChange (savedChooserValue);
}
}
public void InputFieldSelected () {
m_Control.lockKeyboard ();
}
public void InputFieldDeselected () {
m_Control.unlockKeyboard ();
}
}
}
| |
// 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.Net.Http.Headers;
using Xunit;
namespace System.Net.Http.Tests
{
public class AuthenticationHeaderValueTest
{
[Fact]
public void Ctor_SetBothSchemeAndParameters_MatchExpectation()
{
AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Basic", "realm=\"contoso.com\"");
Assert.Equal("Basic", auth.Scheme);
Assert.Equal("realm=\"contoso.com\"", auth.Parameter);
AssertExtensions.Throws<ArgumentException>("scheme", () => { new AuthenticationHeaderValue(null, "x"); });
AssertExtensions.Throws<ArgumentException>("scheme", () => { new AuthenticationHeaderValue("", "x"); });
Assert.Throws<FormatException>(() => { new AuthenticationHeaderValue(" x", "x"); });
Assert.Throws<FormatException>(() => { new AuthenticationHeaderValue("x ", "x"); });
Assert.Throws<FormatException>(() => { new AuthenticationHeaderValue("x y", "x"); });
}
[Fact]
public void Ctor_SetSchemeOnly_MatchExpectation()
{
// Just verify that this ctor forwards the call to the overload taking 2 parameters.
AuthenticationHeaderValue auth = new AuthenticationHeaderValue("NTLM");
Assert.Equal("NTLM", auth.Scheme);
Assert.Null(auth.Parameter);
}
[Fact]
public void ToString_UseBothNoParameterAndSetParameter_AllSerializedCorrectly()
{
using (HttpResponseMessage response = new HttpResponseMessage())
{
string input = string.Empty;
AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Digest",
"qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"");
Assert.Equal(
"Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"",
auth.ToString());
response.Headers.ProxyAuthenticate.Add(auth);
input += auth.ToString();
auth = new AuthenticationHeaderValue("Negotiate");
Assert.Equal("Negotiate", auth.ToString());
response.Headers.ProxyAuthenticate.Add(auth);
input += ", " + auth.ToString();
auth = new AuthenticationHeaderValue("Custom", ""); // empty string should be treated like 'null'.
Assert.Equal("Custom", auth.ToString());
response.Headers.ProxyAuthenticate.Add(auth);
input += ", " + auth.ToString();
string result = response.Headers.ProxyAuthenticate.ToString();
Assert.Equal(input, result);
}
}
[Fact]
public void Parse_GoodValues_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
string input = " Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8 ";
request.Headers.Authorization = AuthenticationHeaderValue.Parse(input);
Assert.Equal(input.Trim(), request.Headers.Authorization.ToString());
}
[Fact]
public void TryParse_GoodValues_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
string input = " Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",realm=\"Digest\" ";
AuthenticationHeaderValue parsedValue;
Assert.True(AuthenticationHeaderValue.TryParse(input, out parsedValue));
request.Headers.Authorization = parsedValue;
Assert.Equal(input.Trim(), request.Headers.Authorization.ToString());
}
[Fact]
public void Parse_BadValues_Throws()
{
string input = "D\rigest qop=\"auth\",algorithm=MD5-sess,charset=utf-8,realm=\"Digest\"";
Assert.Throws<FormatException>(() => { AuthenticationHeaderValue.Parse(input); });
}
[Fact]
public void TryParse_BadValues_False()
{
string input = ", Digest qop=\"auth\",nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"";
AuthenticationHeaderValue parsedValue;
Assert.False(AuthenticationHeaderValue.TryParse(input, out parsedValue));
}
[Fact]
public void Add_BadValues_Throws()
{
string x = SR.net_http_message_not_success_statuscode;
string input = "Digest algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\", ";
HttpRequestMessage request = new HttpRequestMessage();
Assert.Throws<FormatException>(() => { request.Headers.Add(HttpKnownHeaderNames.Authorization, input); });
}
[Fact]
public void GetHashCode_UseSameAndDifferentAuth_SameOrDifferentHashCodes()
{
AuthenticationHeaderValue auth1 = new AuthenticationHeaderValue("A", "b");
AuthenticationHeaderValue auth2 = new AuthenticationHeaderValue("a", "b");
AuthenticationHeaderValue auth3 = new AuthenticationHeaderValue("A", "B");
AuthenticationHeaderValue auth4 = new AuthenticationHeaderValue("A");
AuthenticationHeaderValue auth5 = new AuthenticationHeaderValue("A", "");
AuthenticationHeaderValue auth6 = new AuthenticationHeaderValue("X", "b");
Assert.Equal(auth1.GetHashCode(), auth2.GetHashCode());
Assert.NotEqual(auth1.GetHashCode(), auth3.GetHashCode());
Assert.NotEqual(auth1.GetHashCode(), auth4.GetHashCode());
Assert.Equal(auth4.GetHashCode(), auth5.GetHashCode());
Assert.NotEqual(auth1.GetHashCode(), auth6.GetHashCode());
}
[Fact]
public void Equals_UseSameAndDifferentAuth_EqualOrNotEqualNoExceptions()
{
AuthenticationHeaderValue auth1 = new AuthenticationHeaderValue("A", "b");
AuthenticationHeaderValue auth2 = new AuthenticationHeaderValue("a", "b");
AuthenticationHeaderValue auth3 = new AuthenticationHeaderValue("A", "B");
AuthenticationHeaderValue auth4 = new AuthenticationHeaderValue("A");
AuthenticationHeaderValue auth5 = new AuthenticationHeaderValue("A", "");
AuthenticationHeaderValue auth6 = new AuthenticationHeaderValue("X", "b");
Assert.False(auth1.Equals(null));
Assert.True(auth1.Equals(auth2));
Assert.False(auth1.Equals(auth3));
Assert.False(auth1.Equals(auth4));
Assert.False(auth4.Equals(auth1));
Assert.False(auth1.Equals(auth5));
Assert.False(auth5.Equals(auth1));
Assert.True(auth4.Equals(auth5));
Assert.True(auth5.Equals(auth4));
Assert.False(auth1.Equals(auth6));
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
AuthenticationHeaderValue source = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
AuthenticationHeaderValue clone = (AuthenticationHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Scheme, clone.Scheme);
Assert.Equal(source.Parameter, clone.Parameter);
source = new AuthenticationHeaderValue("Kerberos");
clone = (AuthenticationHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Scheme, clone.Scheme);
Assert.Null(clone.Parameter);
}
[Fact]
public void GetAuthenticationLength_DifferentValidScenarios_AllReturnNonZero()
{
CallGetAuthenticationLength(" Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== ", 1, 37,
new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="));
CallGetAuthenticationLength(" Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== , ", 1, 37,
new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="));
CallGetAuthenticationLength(" Basic realm=\"example.com\"", 1, 25,
new AuthenticationHeaderValue("Basic", "realm=\"example.com\""));
CallGetAuthenticationLength(" Basic realm=\"exam,,ple.com\",", 1, 27,
new AuthenticationHeaderValue("Basic", "realm=\"exam,,ple.com\""));
CallGetAuthenticationLength(" Basic realm=\"exam,ple.com\",", 1, 26,
new AuthenticationHeaderValue("Basic", "realm=\"exam,ple.com\""));
CallGetAuthenticationLength("NTLM ", 0, 7, new AuthenticationHeaderValue("NTLM"));
CallGetAuthenticationLength("Digest", 0, 6, new AuthenticationHeaderValue("Digest"));
CallGetAuthenticationLength("Digest,,", 0, 6, new AuthenticationHeaderValue("Digest"));
CallGetAuthenticationLength("Digest a=b, c=d,,", 0, 15, new AuthenticationHeaderValue("Digest", "a=b, c=d"));
CallGetAuthenticationLength("Kerberos,", 0, 8, new AuthenticationHeaderValue("Kerberos"));
CallGetAuthenticationLength("Basic,NTLM", 0, 5, new AuthenticationHeaderValue("Basic"));
CallGetAuthenticationLength("Digest a=b,c=\"d\", e=f, NTLM", 0, 21,
new AuthenticationHeaderValue("Digest", "a=b,c=\"d\", e=f"));
CallGetAuthenticationLength("Digest a = b , c = \"d\" , e = f ,NTLM", 0, 32,
new AuthenticationHeaderValue("Digest", "a = b , c = \"d\" , e = f"));
CallGetAuthenticationLength("Digest a = b , c = \"d\" , e = f , NTLM AbCdEf==", 0, 32,
new AuthenticationHeaderValue("Digest", "a = b , c = \"d\" , e = f"));
CallGetAuthenticationLength("Digest a = \"b\", c= \"d\" , e = f,NTLM AbC=,", 0, 31,
new AuthenticationHeaderValue("Digest", "a = \"b\", c= \"d\" , e = f"));
CallGetAuthenticationLength("Digest a=\"b\", c=d", 0, 17,
new AuthenticationHeaderValue("Digest", "a=\"b\", c=d"));
CallGetAuthenticationLength("Digest a=\"b\", c=d,", 0, 17,
new AuthenticationHeaderValue("Digest", "a=\"b\", c=d"));
CallGetAuthenticationLength("Digest a=\"b\", c=d ,", 0, 18,
new AuthenticationHeaderValue("Digest", "a=\"b\", c=d"));
CallGetAuthenticationLength("Digest a=\"b\", c=d ", 0, 19,
new AuthenticationHeaderValue("Digest", "a=\"b\", c=d"));
CallGetAuthenticationLength("Custom \"blob\", c=d,Custom2 \"blob\"", 0, 18,
new AuthenticationHeaderValue("Custom", "\"blob\", c=d"));
CallGetAuthenticationLength("Custom \"blob\", a=b,,,c=d,Custom2 \"blob\"", 0, 24,
new AuthenticationHeaderValue("Custom", "\"blob\", a=b,,,c=d"));
CallGetAuthenticationLength("Custom \"blob\", a=b,c=d,,,Custom2 \"blob\"", 0, 22,
new AuthenticationHeaderValue("Custom", "\"blob\", a=b,c=d"));
CallGetAuthenticationLength("Custom a=b, c=d,,,InvalidNextScheme\u670D", 0, 15,
new AuthenticationHeaderValue("Custom", "a=b, c=d"));
}
[Fact]
public void GetAuthenticationLength_DifferentInvalidScenarios_AllReturnZero()
{
CheckInvalidGetAuthenticationLength(" NTLM", 0); // no leading whitespace allowed
CheckInvalidGetAuthenticationLength("Basic=", 0);
CheckInvalidGetAuthenticationLength("=Basic", 0);
CheckInvalidGetAuthenticationLength("Digest a=b, \u670D", 0);
CheckInvalidGetAuthenticationLength("Digest a=b, c=d, \u670D", 0);
CheckInvalidGetAuthenticationLength("Digest a=b, c=", 0);
CheckInvalidGetAuthenticationLength("Digest a=\"b, c", 0);
CheckInvalidGetAuthenticationLength("Digest a=\"b", 0);
CheckInvalidGetAuthenticationLength("Digest a=b, c=\u670D", 0);
CheckInvalidGetAuthenticationLength("", 0);
CheckInvalidGetAuthenticationLength(null, 0);
}
#region Helper methods
private static void CallGetAuthenticationLength(string input, int startIndex, int expectedLength,
AuthenticationHeaderValue expectedResult)
{
object result = null;
Assert.Equal(expectedLength, AuthenticationHeaderValue.GetAuthenticationLength(input, startIndex, out result));
Assert.Equal(expectedResult, result);
}
private static void CheckInvalidGetAuthenticationLength(string input, int startIndex)
{
object result = null;
Assert.Equal(0, AuthenticationHeaderValue.GetAuthenticationLength(input, startIndex, out result));
Assert.Null(result);
}
#endregion
}
}
| |
/*
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 System.Text;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
using Orleans.Storage;
using Orleans.CodeGeneration;
namespace Orleans.Runtime
{
/// <summary>
/// Maintains additional per-activation state that is required for Orleans internal operations.
/// MUST lock this object for any concurrent access
/// Consider: compartmentalize by usage, e.g., using separate interfaces for data for catalog, etc.
/// </summary>
internal class ActivationData : IActivationData, IInvokable
{
// This class is used for activations that have extension invokers. It keeps a dictionary of
// invoker objects to use with the activation, and extend the default invoker
// defined for the grain class.
// Note that in all cases we never have more than one copy of an actual invoker;
// we may have a ExtensionInvoker per activation, in the worst case.
private class ExtensionInvoker : IGrainMethodInvoker
{
// Because calls to ExtensionInvoker are allways made within the activation context,
// we rely on the single-threading guarantee of the runtime and do not protect the map with a lock.
private Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>> extensionMap; // key is the extension interface ID
/// <summary>
/// Try to add an extension for the specific interface ID.
/// Fail and return false if there is already an extension for that interface ID.
/// Note that if an extension invoker handles multiple interface IDs, it can only be associated
/// with one of those IDs when added, and so only conflicts on that one ID will be detected and prevented.
/// </summary>
/// <param name="invoker"></param>
/// <param name="handler"></param>
/// <returns></returns>
internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension handler)
{
if (extensionMap == null)
{
extensionMap = new Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>>(1);
}
if (extensionMap.ContainsKey(invoker.InterfaceId)) return false;
extensionMap.Add(invoker.InterfaceId, new Tuple<IGrainExtension, IGrainExtensionMethodInvoker>(handler, invoker));
return true;
}
/// <summary>
/// Removes all extensions for the specified interface id.
/// Returns true if the chained invoker no longer has any extensions and may be safely retired.
/// </summary>
/// <param name="extension"></param>
/// <returns>true if the chained invoker is now empty, false otherwise</returns>
public bool Remove(IGrainExtension extension)
{
int interfaceId = 0;
foreach(int iface in extensionMap.Keys)
if (extensionMap[iface].Item1 == extension)
{
interfaceId = iface;
break;
}
if (interfaceId == 0) // not found
throw new InvalidOperationException(String.Format("Extension {0} is not installed",
extension.GetType().FullName));
extensionMap.Remove(interfaceId);
return extensionMap.Count == 0;
}
public bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result)
{
result = null;
if (extensionMap == null) return false;
foreach (var ext in extensionMap.Values)
if (extensionType == ext.Item1.GetType())
{
result = ext.Item1;
return true;
}
return false;
}
/// <summary>
/// Invokes the appropriate grain or extension method for the request interface ID and method ID.
/// First each extension invoker is tried; if no extension handles the request, then the base
/// invoker is used to handle the request.
/// The base invoker will throw an appropriate exception if the request is not recognized.
/// </summary>
/// <param name="grain"></param>
/// <param name="interfaceId"></param>
/// <param name="methodId"></param>
/// <param name="arguments"></param>
/// <returns></returns>
public Task<object> Invoke(IAddressable grain, int interfaceId, int methodId, object[] arguments)
{
if (extensionMap == null || !extensionMap.ContainsKey(interfaceId))
throw new InvalidOperationException(
String.Format("Extension invoker invoked with an unknown inteface ID:{0}.", interfaceId));
var invoker = extensionMap[interfaceId].Item2;
var extension = extensionMap[interfaceId].Item1;
return invoker.Invoke(extension, interfaceId, methodId, arguments);
}
public bool IsExtensionInstalled(int interfaceId)
{
return extensionMap != null && extensionMap.ContainsKey(interfaceId);
}
public int InterfaceId
{
get { return 0; } // 0 indicates an extension invoker that may have multiple intefaces inplemented by extensions.
}
}
// This is the maximum amount of time we expect a request to continue processing
private static TimeSpan maxRequestProcessingTime;
private static NodeConfiguration nodeConfiguration;
public readonly TimeSpan CollectionAgeLimit;
private IGrainMethodInvoker lastInvoker;
// This is the maximum number of enqueued request messages for a single activation before we write a warning log or reject new requests.
private LimitValue maxEnqueuedRequestsLimit;
private HashSet<GrainTimer> timers;
private readonly TraceLogger logger;
public static void Init(ClusterConfiguration config, NodeConfiguration nodeConfig)
{
// Consider adding a config parameter for this
maxRequestProcessingTime = config.Globals.ResponseTimeout.Multiply(5);
nodeConfiguration = nodeConfig;
}
public ActivationData(ActivationAddress addr, string genericArguments, PlacementStrategy placedUsing, IActivationCollector collector, TimeSpan ageLimit)
{
if (null == addr) throw new ArgumentNullException("addr");
if (null == placedUsing) throw new ArgumentNullException("placedUsing");
if (null == collector) throw new ArgumentNullException("collector");
logger = TraceLogger.GetLogger("ActivationData", TraceLogger.LoggerType.Runtime);
ResetKeepAliveRequest();
Address = addr;
State = ActivationState.Create;
PlacedUsing = placedUsing;
if (!Grain.IsSystemTarget && !Constants.IsSystemGrain(Grain))
{
this.collector = collector;
}
CollectionAgeLimit = ageLimit;
GrainReference = GrainReference.FromGrainId(addr.Grain, genericArguments,
Grain.IsSystemTarget ? addr.Silo : null);
}
#region Method invocation
private ExtensionInvoker extensionInvoker;
public IGrainMethodInvoker GetInvoker(int interfaceId, string genericGrainType=null)
{
// Return previous cached invoker, if applicable
if (lastInvoker != null && interfaceId == lastInvoker.InterfaceId) // extension invoker returns InterfaceId==0, so this condition will never be true if an extension is installed
return lastInvoker;
if (extensionInvoker != null && extensionInvoker.IsExtensionInstalled(interfaceId)) // HasExtensionInstalled(interfaceId)
// Shared invoker for all extensions installed on this grain
lastInvoker = extensionInvoker;
else
// Find the specific invoker for this interface / grain type
lastInvoker = RuntimeClient.Current.GetInvoker(interfaceId, genericGrainType);
return lastInvoker;
}
internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension extension)
{
if(extensionInvoker == null)
extensionInvoker = new ExtensionInvoker();
return extensionInvoker.TryAddExtension(invoker, extension);
}
internal void RemoveExtension(IGrainExtension extension)
{
if (extensionInvoker != null)
{
if (extensionInvoker.Remove(extension))
extensionInvoker = null;
}
else
throw new InvalidOperationException("Grain extensions not installed.");
}
internal bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result)
{
result = null;
return extensionInvoker != null && extensionInvoker.TryGetExtensionHandler(extensionType, out result);
}
#endregion
public string GrainTypeName
{
get
{
if (GrainInstanceType == null)
{
throw new ArgumentNullException("GrainInstanceType", "GrainInstanceType has not been set.");
}
return GrainInstanceType.FullName;
}
}
internal Type GrainInstanceType { get; private set; }
internal void SetGrainInstance(Grain grainInstance)
{
GrainInstance = grainInstance;
if (grainInstance != null)
{
GrainInstanceType = grainInstance.GetType();
// Don't ever collect system grains or reminder table grain or memory store grains.
bool doNotCollect = typeof(IReminderTable).IsAssignableFrom(GrainInstanceType) || typeof(IMemoryStorageGrain).IsAssignableFrom(GrainInstanceType);
if (doNotCollect)
{
this.collector = null;
}
}
}
public IStorageProvider StorageProvider { get; set; }
private Streams.StreamDirectory streamDirectory;
internal Streams.StreamDirectory GetStreamDirectory()
{
return streamDirectory ?? (streamDirectory = new Streams.StreamDirectory());
}
internal bool IsUsingStreams
{
get { return streamDirectory != null; }
}
internal async Task DeactivateStreamResources()
{
if (streamDirectory == null) return; // No streams - Nothing to do.
if (extensionInvoker == null) return; // No installed extensions - Nothing to do.
if (StreamResourceTestControl.TestOnlySuppressStreamCleanupOnDeactivate)
{
logger.Warn(0, "Suppressing cleanup of stream resources during tests for {0}", this);
return;
}
await streamDirectory.Cleanup(true, false);
}
#region IActivationData
GrainReference IActivationData.GrainReference
{
get { return GrainReference; }
}
public GrainId Identity
{
get { return Grain; }
}
public Grain GrainInstance { get; private set; }
public ActivationId ActivationId { get { return Address.Activation; } }
public ActivationAddress Address { get; private set; }
public IDisposable RegisterTimer(Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period)
{
var timer = GrainTimer.FromTaskCallback(asyncCallback, state, dueTime, period);
AddTimer(timer);
timer.Start();
return timer;
}
#endregion
#region Catalog
internal readonly GrainReference GrainReference;
public SiloAddress Silo { get { return Address.Silo; } }
public GrainId Grain { get { return Address.Grain; } }
public ActivationState State { get; private set; }
public void SetState(ActivationState state)
{
State = state;
}
// Don't accept any new messages and stop all timers.
public void PrepareForDeactivation()
{
SetState(ActivationState.Deactivating);
StopAllTimers();
}
/// <summary>
/// If State == Invalid, this may contain a forwarding address for incoming messages
/// </summary>
public ActivationAddress ForwardingAddress { get; set; }
private IActivationCollector collector;
internal bool IsExemptFromCollection
{
get { return collector == null; }
}
public DateTime CollectionTicket { get; private set; }
private bool collectionCancelledFlag;
public bool TrySetCollectionCancelledFlag()
{
lock (this)
{
if (default(DateTime) == CollectionTicket || collectionCancelledFlag) return false;
collectionCancelledFlag = true;
return true;
}
}
public void ResetCollectionCancelledFlag()
{
lock (this)
{
collectionCancelledFlag = false;
}
}
public void ResetCollectionTicket()
{
CollectionTicket = default(DateTime);
}
public void SetCollectionTicket(DateTime ticket)
{
if (ticket == default(DateTime)) throw new ArgumentException("default(DateTime) is disallowed", "ticket");
if (CollectionTicket != default(DateTime))
{
throw new InvalidOperationException("call ResetCollectionTicket before calling SetCollectionTicket.");
}
CollectionTicket = ticket;
}
#endregion
#region Dispatcher
public PlacementStrategy PlacedUsing { get; private set; }
// currently, the only supported multi-activation grain is one using the StatelessWorkerPlacement strategy.
internal bool IsStatelessWorker { get { return PlacedUsing is StatelessWorkerPlacement; } }
public Message Running { get; private set; }
// the number of requests that are currently executing on this activation.
// includes reentrant and non-reentrant requests.
private int numRunning;
private DateTime currentRequestStartTime;
private DateTime becameIdle;
public void RecordRunning(Message message)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
numRunning++;
if (Running != null) return;
// This logic only works for non-reentrant activations
// Consider: Handle long request detection for reentrant activations.
Running = message;
currentRequestStartTime = DateTime.UtcNow;
}
public void ResetRunning(Message message)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
numRunning--;
if (numRunning == 0)
{
becameIdle = DateTime.UtcNow;
if (!IsExemptFromCollection)
{
collector.TryRescheduleCollection(this);
}
}
// The below logic only works for non-reentrant activations.
if (Running != null && !message.Equals(Running)) return;
Running = null;
currentRequestStartTime = DateTime.MinValue;
}
private long inFlightCount;
private long enqueuedOnDispatcherCount;
/// <summary>
/// Number of messages that are actively being processed [as opposed to being in the Waiting queue].
/// In most cases this will be 0 or 1, but for Reentrant grains can be >1.
/// </summary>
public long InFlightCount { get { return Interlocked.Read(ref inFlightCount); } }
/// <summary>
/// Number of messages that are being received [as opposed to being in the scheduler queue or actively processed].
/// </summary>
public long EnqueuedOnDispatcherCount { get { return Interlocked.Read(ref enqueuedOnDispatcherCount); } }
/// <summary>Increment the number of in-flight messages currently being processed.</summary>
public void IncrementInFlightCount() { Interlocked.Increment(ref inFlightCount); }
/// <summary>Decrement the number of in-flight messages currently being processed.</summary>
public void DecrementInFlightCount() { Interlocked.Decrement(ref inFlightCount); }
/// <summary>Increment the number of messages currently in the prcess of being received.</summary>
public void IncrementEnqueuedOnDispatcherCount() { Interlocked.Increment(ref enqueuedOnDispatcherCount); }
/// <summary>Decrement the number of messages currently in the prcess of being received.</summary>
public void DecrementEnqueuedOnDispatcherCount() { Interlocked.Decrement(ref enqueuedOnDispatcherCount); }
/// <summary>
/// grouped by sending activation: responses first, then sorted by id
/// </summary>
private List<Message> waiting;
public int WaitingCount
{
get
{
return waiting == null ? 0 : waiting.Count;
}
}
/// <summary>
/// Insert in a FIFO order
/// </summary>
/// <param name="message"></param>
public bool EnqueueMessage(Message message)
{
lock (this)
{
if (State == ActivationState.Invalid)
{
logger.Warn(ErrorCode.Dispatcher_InvalidActivation,
"Cannot enqueue message to invalid activation {0} : {1}", this.ToDetailedString(), message);
return false;
}
// If maxRequestProcessingTime is never set, then we will skip this check
if (maxRequestProcessingTime.TotalMilliseconds > 0 && Running != null)
{
// Consider: Handle long request detection for reentrant activations -- this logic only works for non-reentrant activations
var currentRequestActiveTime = DateTime.UtcNow - currentRequestStartTime;
if (currentRequestActiveTime > maxRequestProcessingTime)
{
logger.Warn(ErrorCode.Dispatcher_ExtendedMessageProcessing,
"Current request has been active for {0} for activation {1}. Currently executing {2}. Trying to enqueue {3}.",
currentRequestActiveTime, this.ToDetailedString(), Running, message);
}
}
waiting = waiting ?? new List<Message>();
waiting.Add(message);
return true;
}
}
/// <summary>
/// Check whether this activation is overloaded.
/// Returns LimitExceededException if overloaded, otherwise <c>null</c>c>
/// </summary>
/// <param name="log">TraceLogger to use for reporting any overflow condition</param>
/// <returns>Returns LimitExceededException if overloaded, otherwise <c>null</c>c></returns>
public LimitExceededException CheckOverloaded(TraceLogger log)
{
LimitValue limitValue = GetMaxEnqueuedRequestLimit();
int maxRequestsHardLimit = limitValue.HardLimitThreshold;
int maxRequestsSoftLimit = limitValue.SoftLimitThreshold;
if (maxRequestsHardLimit <= 0 && maxRequestsSoftLimit <= 0) return null; // No limits are set
int count = GetRequestCount();
if (maxRequestsHardLimit > 0 && count > maxRequestsHardLimit) // Hard limit
{
log.Warn(ErrorCode.Catalog_Reject_ActivationTooManyRequests,
String.Format("Overload - {0} enqueued requests for activation {1}, exceeding hard limit rejection threshold of {2}",
count, this, maxRequestsHardLimit));
return new LimitExceededException(limitValue.Name, count, maxRequestsHardLimit, this.ToString());
}
if (maxRequestsSoftLimit > 0 && count > maxRequestsSoftLimit) // Soft limit
{
log.Warn(ErrorCode.Catalog_Warn_ActivationTooManyRequests,
String.Format("Hot - {0} enqueued requests for activation {1}, exceeding soft limit warning threshold of {2}",
count, this, maxRequestsSoftLimit));
return null;
}
return null;
}
internal int GetRequestCount()
{
lock (this)
{
long numInDispatcher = EnqueuedOnDispatcherCount;
long numActive = InFlightCount;
long numWaiting = WaitingCount;
return (int)(numInDispatcher + numActive + numWaiting);
}
}
private LimitValue GetMaxEnqueuedRequestLimit()
{
if (maxEnqueuedRequestsLimit != null) return maxEnqueuedRequestsLimit;
if (GrainInstanceType != null)
{
string limitName = CodeGeneration.GrainInterfaceData.IsStatelessWorker(GrainInstanceType)
? LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER
: LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS;
maxEnqueuedRequestsLimit = nodeConfiguration.LimitManager.GetLimit(limitName); // Cache for next time
return maxEnqueuedRequestsLimit;
}
return nodeConfiguration.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS);
}
public Message PeekNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0) return waiting[0];
return null;
}
public void DequeueNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0)
waiting.RemoveAt(0);
}
internal List<Message> DequeueAllWaitingMessages()
{
lock (this)
{
if (waiting == null) return null;
List<Message> tmp = waiting;
waiting = null;
return tmp;
}
}
#endregion
#region Activation collection
public bool IsInactive
{
get
{
return !IsCurrentlyExecuting && (waiting == null || waiting.Count == 0);
}
}
public bool IsCurrentlyExecuting
{
get
{
return numRunning > 0 ;
}
}
/// <summary>
/// Returns how long this activation has been idle.
/// </summary>
public TimeSpan GetIdleness(DateTime now)
{
if (now == default(DateTime))
throw new ArgumentException("default(DateTime) is not allowed; Use DateTime.UtcNow instead.", "now");
return now - becameIdle;
}
/// <summary>
/// Returns whether this activation has been idle long enough to be collected.
/// </summary>
public bool IsStale(DateTime now)
{
return GetIdleness(now) >= CollectionAgeLimit;
}
private DateTime keepAliveUntil;
public bool ShouldBeKeptAlive { get { return keepAliveUntil >= DateTime.UtcNow; } }
public void DelayDeactivation(TimeSpan timespan)
{
if (timespan <= TimeSpan.Zero)
{
// reset any current keepAliveUntill
ResetKeepAliveRequest();
}
else if (timespan == TimeSpan.MaxValue)
{
// otherwise creates negative time.
keepAliveUntil = DateTime.MaxValue;
}
else
{
keepAliveUntil = DateTime.UtcNow + timespan;
}
}
public void ResetKeepAliveRequest()
{
keepAliveUntil = DateTime.MinValue;
}
public List<Action> OnInactive { get; set; } // ActivationData
public void AddOnInactive(Action action) // ActivationData
{
lock (this)
{
if (OnInactive == null)
{
OnInactive = new List<Action>();
}
OnInactive.Add(action);
}
}
public void RunOnInactive()
{
lock (this)
{
if (OnInactive == null) return;
var actions = OnInactive;
OnInactive = null;
foreach (var action in actions)
{
action();
}
}
}
#endregion
#region In-grain Timers
internal void AddTimer(GrainTimer timer)
{
lock(this)
{
if (timers == null)
{
timers = new HashSet<GrainTimer>();
}
timers.Add(timer);
}
}
private void StopAllTimers()
{
lock (this)
{
if (timers == null) return;
foreach (var timer in timers)
{
timer.Stop();
}
}
}
internal void OnTimerDisposed(GrainTimer orleansTimerInsideGrain)
{
lock (this) // need to lock since dispose can be called on finalizer thread, outside garin context (not single threaded).
{
timers.Remove(orleansTimerInsideGrain);
}
}
internal Task WaitForAllTimersToFinish()
{
lock(this)
{
if (timers == null)
{
return TaskDone.Done;
}
var tasks = new List<Task>();
var timerCopy = timers.ToList(); // need to copy since OnTimerDisposed will change the timers set.
foreach (var timer in timerCopy)
{
// first call dispose, then wait to finish.
Utils.SafeExecute(timer.Dispose, logger, "timer.Dispose has thrown");
tasks.Add(timer.GetCurrentlyExecutingTickTask());
}
return Task.WhenAll(tasks);
}
}
#endregion
#region Printing functions
public string DumpStatus()
{
var sb = new StringBuilder();
lock (this)
{
sb.AppendFormat(" {0}", ToDetailedString());
if (Running != null)
{
sb.AppendFormat(" Processing message: {0}", Running);
}
if (waiting!=null && waiting.Count > 0)
{
sb.AppendFormat(" Messages queued within ActivationData: {0}", PrintWaitingQueue());
}
}
return sb.ToString();
}
public override string ToString()
{
return String.Format("[Activation: {0}{1}{2}{3} State={4}]",
Silo,
Grain,
ActivationId,
GetActivationInfoString(),
State);
}
internal string ToDetailedString()
{
return
String.Format(
"[Activation: {0}{1}{2}{3} State={4} NonReentrancyQueueSize={5} EnqueuedOnDispatcher={6} InFlightCount={7} NumRunning={8} IdlenessTimeSpan={9} CollectionAgeLimit={10}]",
Silo.ToLongString(),
Grain.ToDetailedString(),
ActivationId,
GetActivationInfoString(),
State, // 4
WaitingCount, // 5 NonReentrancyQueueSize
EnqueuedOnDispatcherCount, // 6 EnqueuedOnDispatcher
InFlightCount, // 7 InFlightCount
numRunning, // 8 NumRunning
GetIdleness(DateTime.UtcNow), // 9 IdlenessTimeSpan
CollectionAgeLimit); // 10 CollectionAgeLimit
}
public string Name
{
get
{
return String.Format("[Activation: {0}{1}{2}{3}]",
Silo,
Grain,
ActivationId,
GetActivationInfoString());
}
}
/// <summary>
/// Return string containing dump of the queue of waiting work items
/// </summary>
/// <returns></returns>
/// <remarks>Note: Caller must be holding lock on this activation while calling this method.</remarks>
internal string PrintWaitingQueue()
{
return Utils.EnumerableToString(waiting);
}
private string GetActivationInfoString()
{
var placement = PlacedUsing != null ? PlacedUsing.GetType().Name : String.Empty;
return GrainInstanceType == null ? placement :
String.Format(" #GrainType={0} Placement={1}", GrainInstanceType.FullName, placement);
}
#endregion
}
internal static class StreamResourceTestControl
{
internal static bool TestOnlySuppressStreamCleanupOnDeactivate;
}
}
| |
//
// Copyright 2014 Gustavo J Knuppe (https://github.com/knuppe)
//
// 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.
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - May you do good and not evil. -
// - May you find forgiveness for yourself and forgive others. -
// - May you share freely, never taking more than you give. -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
/*
Copyright (c) 2001, Dr Martin Porter
Copyright (c) 2002, Richard Boulton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holders 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.
*/
// This file was generated automatically by the Snowball to OpenNLP and
// ported to SharpNL
namespace SharpNL.Stemmer.Snowball {
public class RomanianStemmer : SnowballStemmer {
private static RomanianStemmer instance;
/// <summary>
/// Gets the <see cref="RomanianStemmer"/> instance.
/// </summary>
/// <value>The <see cref="RomanianStemmer"/> instance.</value>
public static RomanianStemmer Instance => instance ?? (instance = new RomanianStemmer());
private RomanianStemmer() { }
/// <summary>
/// Reduces the given word into its stem.
/// </summary>
/// <param name="word">The word.</param>
/// <returns>The stemmed word.</returns>
public override string Stem(string word) {
Current = word.ToLowerInvariant();
CanStem();
return Current;
}
private static readonly Among[] a_0 = {
new Among("", -1, 3, null),
new Among("I", 0, 1, null),
new Among("U", 0, 2, null)
};
private static readonly Among[] a_1 = {
new Among("ea", -1, 3, null),
new Among("a\u0163ia", -1, 7, null),
new Among("aua", -1, 2, null),
new Among("iua", -1, 4, null),
new Among("a\u0163ie", -1, 7, null),
new Among("ele", -1, 3, null),
new Among("ile", -1, 5, null),
new Among("iile", 6, 4, null),
new Among("iei", -1, 4, null),
new Among("atei", -1, 6, null),
new Among("ii", -1, 4, null),
new Among("ului", -1, 1, null),
new Among("ul", -1, 1, null),
new Among("elor", -1, 3, null),
new Among("ilor", -1, 4, null),
new Among("iilor", 14, 4, null)
};
private static readonly Among[] a_2 = {
new Among("icala", -1, 4, null),
new Among("iciva", -1, 4, null),
new Among("ativa", -1, 5, null),
new Among("itiva", -1, 6, null),
new Among("icale", -1, 4, null),
new Among("a\u0163iune", -1, 5, null),
new Among("i\u0163iune", -1, 6, null),
new Among("atoare", -1, 5, null),
new Among("itoare", -1, 6, null),
new Among("\u0103toare", -1, 5, null),
new Among("icitate", -1, 4, null),
new Among("abilitate", -1, 1, null),
new Among("ibilitate", -1, 2, null),
new Among("ivitate", -1, 3, null),
new Among("icive", -1, 4, null),
new Among("ative", -1, 5, null),
new Among("itive", -1, 6, null),
new Among("icali", -1, 4, null),
new Among("atori", -1, 5, null),
new Among("icatori", 18, 4, null),
new Among("itori", -1, 6, null),
new Among("\u0103tori", -1, 5, null),
new Among("icitati", -1, 4, null),
new Among("abilitati", -1, 1, null),
new Among("ivitati", -1, 3, null),
new Among("icivi", -1, 4, null),
new Among("ativi", -1, 5, null),
new Among("itivi", -1, 6, null),
new Among("icit\u0103i", -1, 4, null),
new Among("abilit\u0103i", -1, 1, null),
new Among("ivit\u0103i", -1, 3, null),
new Among("icit\u0103\u0163i", -1, 4, null),
new Among("abilit\u0103\u0163i", -1, 1, null),
new Among("ivit\u0103\u0163i", -1, 3, null),
new Among("ical", -1, 4, null),
new Among("ator", -1, 5, null),
new Among("icator", 35, 4, null),
new Among("itor", -1, 6, null),
new Among("\u0103tor", -1, 5, null),
new Among("iciv", -1, 4, null),
new Among("ativ", -1, 5, null),
new Among("itiv", -1, 6, null),
new Among("ical\u0103", -1, 4, null),
new Among("iciv\u0103", -1, 4, null),
new Among("ativ\u0103", -1, 5, null),
new Among("itiv\u0103", -1, 6, null)
};
private static readonly Among[] a_3 = {
new Among("ica", -1, 1, null),
new Among("abila", -1, 1, null),
new Among("ibila", -1, 1, null),
new Among("oasa", -1, 1, null),
new Among("ata", -1, 1, null),
new Among("ita", -1, 1, null),
new Among("anta", -1, 1, null),
new Among("ista", -1, 3, null),
new Among("uta", -1, 1, null),
new Among("iva", -1, 1, null),
new Among("ic", -1, 1, null),
new Among("ice", -1, 1, null),
new Among("abile", -1, 1, null),
new Among("ibile", -1, 1, null),
new Among("isme", -1, 3, null),
new Among("iune", -1, 2, null),
new Among("oase", -1, 1, null),
new Among("ate", -1, 1, null),
new Among("itate", 17, 1, null),
new Among("ite", -1, 1, null),
new Among("ante", -1, 1, null),
new Among("iste", -1, 3, null),
new Among("ute", -1, 1, null),
new Among("ive", -1, 1, null),
new Among("ici", -1, 1, null),
new Among("abili", -1, 1, null),
new Among("ibili", -1, 1, null),
new Among("iuni", -1, 2, null),
new Among("atori", -1, 1, null),
new Among("osi", -1, 1, null),
new Among("ati", -1, 1, null),
new Among("itati", 30, 1, null),
new Among("iti", -1, 1, null),
new Among("anti", -1, 1, null),
new Among("isti", -1, 3, null),
new Among("uti", -1, 1, null),
new Among("i\u015Fti", -1, 3, null),
new Among("ivi", -1, 1, null),
new Among("it\u0103i", -1, 1, null),
new Among("o\u015Fi", -1, 1, null),
new Among("it\u0103\u0163i", -1, 1, null),
new Among("abil", -1, 1, null),
new Among("ibil", -1, 1, null),
new Among("ism", -1, 3, null),
new Among("ator", -1, 1, null),
new Among("os", -1, 1, null),
new Among("at", -1, 1, null),
new Among("it", -1, 1, null),
new Among("ant", -1, 1, null),
new Among("ist", -1, 3, null),
new Among("ut", -1, 1, null),
new Among("iv", -1, 1, null),
new Among("ic\u0103", -1, 1, null),
new Among("abil\u0103", -1, 1, null),
new Among("ibil\u0103", -1, 1, null),
new Among("oas\u0103", -1, 1, null),
new Among("at\u0103", -1, 1, null),
new Among("it\u0103", -1, 1, null),
new Among("ant\u0103", -1, 1, null),
new Among("ist\u0103", -1, 3, null),
new Among("ut\u0103", -1, 1, null),
new Among("iv\u0103", -1, 1, null)
};
private static readonly Among[] a_4 = {
new Among("ea", -1, 1, null),
new Among("ia", -1, 1, null),
new Among("esc", -1, 1, null),
new Among("\u0103sc", -1, 1, null),
new Among("ind", -1, 1, null),
new Among("\u00E2nd", -1, 1, null),
new Among("are", -1, 1, null),
new Among("ere", -1, 1, null),
new Among("ire", -1, 1, null),
new Among("\u00E2re", -1, 1, null),
new Among("se", -1, 2, null),
new Among("ase", 10, 1, null),
new Among("sese", 10, 2, null),
new Among("ise", 10, 1, null),
new Among("use", 10, 1, null),
new Among("\u00E2se", 10, 1, null),
new Among("e\u015Fte", -1, 1, null),
new Among("\u0103\u015Fte", -1, 1, null),
new Among("eze", -1, 1, null),
new Among("ai", -1, 1, null),
new Among("eai", 19, 1, null),
new Among("iai", 19, 1, null),
new Among("sei", -1, 2, null),
new Among("e\u015Fti", -1, 1, null),
new Among("\u0103\u015Fti", -1, 1, null),
new Among("ui", -1, 1, null),
new Among("ezi", -1, 1, null),
new Among("\u00E2i", -1, 1, null),
new Among("a\u015Fi", -1, 1, null),
new Among("se\u015Fi", -1, 2, null),
new Among("ase\u015Fi", 29, 1, null),
new Among("sese\u015Fi", 29, 2, null),
new Among("ise\u015Fi", 29, 1, null),
new Among("use\u015Fi", 29, 1, null),
new Among("\u00E2se\u015Fi", 29, 1, null),
new Among("i\u015Fi", -1, 1, null),
new Among("u\u015Fi", -1, 1, null),
new Among("\u00E2\u015Fi", -1, 1, null),
new Among("a\u0163i", -1, 2, null),
new Among("ea\u0163i", 38, 1, null),
new Among("ia\u0163i", 38, 1, null),
new Among("e\u0163i", -1, 2, null),
new Among("i\u0163i", -1, 2, null),
new Among("\u00E2\u0163i", -1, 2, null),
new Among("ar\u0103\u0163i", -1, 1, null),
new Among("ser\u0103\u0163i", -1, 2, null),
new Among("aser\u0103\u0163i", 45, 1, null),
new Among("seser\u0103\u0163i", 45, 2, null),
new Among("iser\u0103\u0163i", 45, 1, null),
new Among("user\u0103\u0163i", 45, 1, null),
new Among("\u00E2ser\u0103\u0163i", 45, 1, null),
new Among("ir\u0103\u0163i", -1, 1, null),
new Among("ur\u0103\u0163i", -1, 1, null),
new Among("\u00E2r\u0103\u0163i", -1, 1, null),
new Among("am", -1, 1, null),
new Among("eam", 54, 1, null),
new Among("iam", 54, 1, null),
new Among("em", -1, 2, null),
new Among("asem", 57, 1, null),
new Among("sesem", 57, 2, null),
new Among("isem", 57, 1, null),
new Among("usem", 57, 1, null),
new Among("\u00E2sem", 57, 1, null),
new Among("im", -1, 2, null),
new Among("\u00E2m", -1, 2, null),
new Among("\u0103m", -1, 2, null),
new Among("ar\u0103m", 65, 1, null),
new Among("ser\u0103m", 65, 2, null),
new Among("aser\u0103m", 67, 1, null),
new Among("seser\u0103m", 67, 2, null),
new Among("iser\u0103m", 67, 1, null),
new Among("user\u0103m", 67, 1, null),
new Among("\u00E2ser\u0103m", 67, 1, null),
new Among("ir\u0103m", 65, 1, null),
new Among("ur\u0103m", 65, 1, null),
new Among("\u00E2r\u0103m", 65, 1, null),
new Among("au", -1, 1, null),
new Among("eau", 76, 1, null),
new Among("iau", 76, 1, null),
new Among("indu", -1, 1, null),
new Among("\u00E2ndu", -1, 1, null),
new Among("ez", -1, 1, null),
new Among("easc\u0103", -1, 1, null),
new Among("ar\u0103", -1, 1, null),
new Among("ser\u0103", -1, 2, null),
new Among("aser\u0103", 84, 1, null),
new Among("seser\u0103", 84, 2, null),
new Among("iser\u0103", 84, 1, null),
new Among("user\u0103", 84, 1, null),
new Among("\u00E2ser\u0103", 84, 1, null),
new Among("ir\u0103", -1, 1, null),
new Among("ur\u0103", -1, 1, null),
new Among("\u00E2r\u0103", -1, 1, null),
new Among("eaz\u0103", -1, 1, null)
};
private static readonly Among[] a_5 = {
new Among("a", -1, 1, null),
new Among("e", -1, 1, null),
new Among("ie", 1, 1, null),
new Among("i", -1, 1, null),
new Among("\u0103", -1, 1, null)
};
private static readonly char[] g_v = {
(char) 17, (char) 65, (char) 16, (char) 0, (char) 0, (char) 0,
(char) 0, (char) 0, (char) 0, (char) 0, (char) 0, (char) 0,
(char) 0, (char) 0, (char) 0, (char) 0, (char) 2, (char) 32,
(char) 0, (char) 0, (char) 4
};
private bool B_standard_suffix_removed;
private int I_p2;
private int I_p1;
private int I_pV;
private void copy_from(RomanianStemmer other) {
B_standard_suffix_removed = other.B_standard_suffix_removed;
I_p2 = other.I_p2;
I_p1 = other.I_p1;
I_pV = other.I_pV;
base.copy_from(other);
}
private bool r_prelude() {
bool subroot = false;
int v_1;
int v_2;
int v_3;
// (, line 31
// repeat, line 32
replab0:
while (true) {
v_1 = cursor;
do {
// goto, line 32
while (true) {
v_2 = cursor;
do {
// (, line 32
if (!(in_grouping(g_v, 97, 259))) {
break;
}
// [, line 33
bra = cursor;
// or, line 33
do {
v_3 = cursor;
do {
// (, line 33
// literal, line 33
if (!(eq_s(1, "u"))) {
break;
}
// ], line 33
ket = cursor;
if (!(in_grouping(g_v, 97, 259))) {
break;
}
// <-, line 33
slice_from("U");
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = v_3;
// (, line 34
// literal, line 34
if (!(eq_s(1, "i"))) {
subroot = true;
break;
}
// ], line 34
ket = cursor;
if (!(in_grouping(g_v, 97, 259))) {
subroot = true;
break;
}
// <-, line 34
slice_from("I");
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = v_2;
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = v_2;
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
}
if (subroot) {
subroot = false;
break;
}
if (!subroot) {
goto replab0;
}
} while (false);
cursor = v_1;
break;
}
return true;
}
private bool r_mark_regions() {
bool subroot = false;
int v_1;
int v_2;
int v_3;
int v_6;
int v_8;
// (, line 38
I_pV = limit;
I_p1 = limit;
I_p2 = limit;
// do, line 44
v_1 = cursor;
do {
// (, line 44
// or, line 46
do {
v_2 = cursor;
do {
// (, line 45
if (!(in_grouping(g_v, 97, 259))) {
break;
}
// or, line 45
do {
v_3 = cursor;
do {
// (, line 45
if (!(out_grouping(g_v, 97, 259))) {
break;
}
// gopast, line 45
while (true) {
do {
if (!(in_grouping(g_v, 97, 259))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
}
if (subroot) {
subroot = false;
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = v_3;
// (, line 45
if (!(in_grouping(g_v, 97, 259))) {
subroot = true;
break;
}
// gopast, line 45
while (true) {
do {
if (!(out_grouping(g_v, 97, 259))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
}
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = v_2;
// (, line 47
if (!(out_grouping(g_v, 97, 259))) {
subroot = true;
break;
}
// or, line 47
do {
v_6 = cursor;
do {
// (, line 47
if (!(out_grouping(g_v, 97, 259))) {
break;
}
// gopast, line 47
while (true) {
do {
if (!(in_grouping(g_v, 97, 259))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
}
if (subroot) {
subroot = false;
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = v_6;
// (, line 47
if (!(in_grouping(g_v, 97, 259))) {
subroot = true;
break;
}
// next, line 47
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
} while (false);
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
// setmark pV, line 48
I_pV = cursor;
} while (false);
cursor = v_1;
// do, line 50
v_8 = cursor;
do {
// (, line 50
// gopast, line 51
while (true) {
do {
if (!(in_grouping(g_v, 97, 259))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
}
if (subroot) {
subroot = false;
break;
}
// gopast, line 51
while (true) {
do {
if (!(out_grouping(g_v, 97, 259))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
}
if (subroot) {
subroot = false;
break;
}
// setmark p1, line 51
I_p1 = cursor;
// gopast, line 52
while (true) {
do {
if (!(in_grouping(g_v, 97, 259))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
}
if (subroot) {
subroot = false;
break;
}
// gopast, line 52
while (true) {
do {
if (!(out_grouping(g_v, 97, 259))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
}
if (subroot) {
subroot = false;
break;
}
// setmark p2, line 52
I_p2 = cursor;
} while (false);
cursor = v_8;
return true;
}
private bool r_postlude() {
bool subroot = false;
int among_var;
int v_1;
// repeat, line 56
replab0:
while (true) {
v_1 = cursor;
do {
// (, line 56
// [, line 58
bra = cursor;
// substring, line 58
among_var = find_among(a_0, 3);
if (among_var == 0) {
break;
}
// ], line 58
ket = cursor;
switch (among_var) {
case 0:
subroot = true;
break;
case 1:
// (, line 59
// <-, line 59
slice_from("i");
break;
case 2:
// (, line 60
// <-, line 60
slice_from("u");
break;
case 3:
// (, line 61
// next, line 61
if (cursor >= limit) {
subroot = true;
break;
}
cursor++;
break;
}
if (subroot) {
subroot = false;
break;
}
if (!subroot) {
goto replab0;
}
} while (false);
cursor = v_1;
break;
}
return true;
}
private bool r_RV() {
if (!(I_pV <= cursor)) {
return false;
}
return true;
}
private bool r_R1() {
if (!(I_p1 <= cursor)) {
return false;
}
return true;
}
private bool r_R2() {
if (!(I_p2 <= cursor)) {
return false;
}
return true;
}
private bool r_step_0() {
bool returnn = false;
int among_var;
int v_1;
// (, line 72
// [, line 73
ket = cursor;
// substring, line 73
among_var = find_among_b(a_1, 16);
if (among_var == 0) {
return false;
}
// ], line 73
bra = cursor;
// call R1, line 73
if (!r_R1()) {
return false;
}
switch (among_var) {
case 0:
return false;
case 1:
// (, line 75
// delete, line 75
slice_del();
break;
case 2:
// (, line 77
// <-, line 77
slice_from("a");
break;
case 3:
// (, line 79
// <-, line 79
slice_from("e");
break;
case 4:
// (, line 81
// <-, line 81
slice_from("i");
break;
case 5:
// (, line 83
// not, line 83
{
v_1 = limit - cursor;
do {
// literal, line 83
returnn = true;
if (!(eq_s_b(2, "ab"))) {
returnn = false;
break;
} else if (returnn) {
return false;
}
} while (false);
cursor = limit - v_1;
}
// <-, line 83
slice_from("i");
break;
case 6:
// (, line 85
// <-, line 85
slice_from("at");
break;
case 7:
// (, line 87
// <-, line 87
slice_from("a\u0163i");
break;
}
return true;
}
private bool r_combo_suffix() {
int among_var;
int v_1;
// test, line 91
v_1 = limit - cursor;
// (, line 91
// [, line 92
ket = cursor;
// substring, line 92
among_var = find_among_b(a_2, 46);
if (among_var == 0) {
return false;
}
// ], line 92
bra = cursor;
// call R1, line 92
if (!r_R1()) {
return false;
}
// (, line 92
switch (among_var) {
case 0:
return false;
case 1:
// (, line 100
// <-, line 101
slice_from("abil");
break;
case 2:
// (, line 103
// <-, line 104
slice_from("ibil");
break;
case 3:
// (, line 106
// <-, line 107
slice_from("iv");
break;
case 4:
// (, line 112
// <-, line 113
slice_from("ic");
break;
case 5:
// (, line 117
// <-, line 118
slice_from("at");
break;
case 6:
// (, line 121
// <-, line 122
slice_from("it");
break;
}
// set standard_suffix_removed, line 125
B_standard_suffix_removed = true;
cursor = limit - v_1;
return true;
}
private bool r_standard_suffix() {
int among_var;
int v_1;
// (, line 129
// unset standard_suffix_removed, line 130
B_standard_suffix_removed = false;
// repeat, line 131
replab0:
while (true) {
v_1 = limit - cursor;
do {
// call combo_suffix, line 131
if (!r_combo_suffix()) {
break;
} else if (r_combo_suffix()) {
goto replab0;
}
} while (false);
cursor = limit - v_1;
break;
}
// [, line 132
ket = cursor;
// substring, line 132
among_var = find_among_b(a_3, 62);
if (among_var == 0) {
return false;
}
// ], line 132
bra = cursor;
// call R2, line 132
if (!r_R2()) {
return false;
}
// (, line 132
switch (among_var) {
case 0:
return false;
case 1:
// (, line 148
// delete, line 149
slice_del();
break;
case 2:
// (, line 151
// literal, line 152
if (!(eq_s_b(1, "\u0163"))) {
return false;
}
// ], line 152
bra = cursor;
// <-, line 152
slice_from("t");
break;
case 3:
// (, line 155
// <-, line 156
slice_from("ist");
break;
}
// set standard_suffix_removed, line 160
B_standard_suffix_removed = true;
return true;
}
private bool r_verb_suffix() {
bool subroot = false;
int among_var;
int v_1;
int v_2;
int v_3;
// setlimit, line 164
v_1 = limit - cursor;
// tomark, line 164
if (cursor < I_pV) {
return false;
}
cursor = I_pV;
v_2 = limit_backward;
limit_backward = cursor;
cursor = limit - v_1;
// (, line 164
// [, line 165
ket = cursor;
// substring, line 165
among_var = find_among_b(a_4, 94);
if (among_var == 0) {
limit_backward = v_2;
return false;
}
// ], line 165
bra = cursor;
switch (among_var) {
case 0:
limit_backward = v_2;
return false;
case 1:
// (, line 200
// or, line 200
do {
v_3 = limit - cursor;
do {
if (!(out_grouping_b(g_v, 97, 259))) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = limit - v_3;
// literal, line 200
if (!(eq_s_b(1, "u"))) {
limit_backward = v_2;
return false;
}
} while (false);
// delete, line 200
slice_del();
break;
case 2:
// (, line 214
// delete, line 214
slice_del();
break;
}
limit_backward = v_2;
return true;
}
private bool r_vowel_suffix() {
int among_var;
// (, line 218
// [, line 219
ket = cursor;
// substring, line 219
among_var = find_among_b(a_5, 5);
if (among_var == 0) {
return false;
}
// ], line 219
bra = cursor;
// call RV, line 219
if (!r_RV()) {
return false;
}
switch (among_var) {
case 0:
return false;
case 1:
// (, line 220
// delete, line 220
slice_del();
break;
}
return true;
}
private bool CanStem() {
bool subroot = false;
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
int v_6;
int v_7;
int v_8;
// (, line 225
// do, line 226
v_1 = cursor;
do {
// call prelude, line 226
if (!r_prelude()) {
break;
}
} while (false);
cursor = v_1;
// do, line 227
v_2 = cursor;
do {
// call mark_regions, line 227
if (!r_mark_regions()) {
break;
}
} while (false);
cursor = v_2;
// backwards, line 228
limit_backward = cursor;
cursor = limit;
// (, line 228
// do, line 229
v_3 = limit - cursor;
do {
// call step_0, line 229
if (!r_step_0()) {
break;
}
} while (false);
cursor = limit - v_3;
// do, line 230
v_4 = limit - cursor;
do {
// call standard_suffix, line 230
if (!r_standard_suffix()) {
break;
}
} while (false);
cursor = limit - v_4;
// do, line 231
v_5 = limit - cursor;
do {
// (, line 231
// or, line 231
do {
v_6 = limit - cursor;
do {
// Boolean test standard_suffix_removed, line 231
if (!(B_standard_suffix_removed)) {
break;
}
subroot = true;
if (subroot) break;
} while (false);
if (subroot) {
subroot = false;
break;
}
cursor = limit - v_6;
// call verb_suffix, line 231
if (!r_verb_suffix()) {
subroot = true;
break;
}
} while (false);
if (subroot) {
subroot = false;
break;
}
} while (false);
cursor = limit - v_5;
// do, line 232
v_7 = limit - cursor;
do {
// call vowel_suffix, line 232
if (!r_vowel_suffix()) {
break;
}
} while (false);
cursor = limit - v_7;
cursor = limit_backward; // do, line 234
v_8 = cursor;
do {
// call postlude, line 234
if (!r_postlude()) {
break;
}
} while (false);
cursor = v_8;
return true;
}
}
}
| |
//
// NoradSDP4.cs
//
// Copyright (c) 2003-2010 Michael F. Henry
//
using System;
namespace OrbitTools
{
/// <summary>
/// NORAD SDP4 implementation.
/// </summary>
internal class NoradSDP4 : NoradBase
{
const double zns = 1.19459E-5;
const double zes = 0.01675;
const double znl = 1.5835218E-4;
const double zel = 0.05490;
const double thdt = 4.3752691E-3;
double dp_e3; double dp_ee2; double dp_se2;
double dp_se3; double dp_sgh2; double dp_sgh3; double dp_sgh4;
double dp_sh2; double dp_sh3; double dp_si2;
double dp_si3; double dp_sl2; double dp_sl3; double dp_sl4;
double dp_xgh2; double dp_xgh3; double dp_xgh4; double dp_xh2;
double dp_xh3; double dp_xi2; double dp_xi3; double dp_xl2;
double dp_xl3; double dp_xl4; double dp_xqncl; double dp_zmol;
double dp_zmos;
double dp_atime; double dp_d2201; double dp_d2211; double dp_d3210;
double dp_d3222; double dp_d4410; double dp_d4422; double dp_d5220;
double dp_d5232; double dp_d5421; double dp_d5433; double dp_del1;
double dp_del2; double dp_del3; double dp_omegaq; double dp_sse;
double dp_ssg; double dp_ssh; double dp_ssi; double dp_ssl;
double dp_step2; double dp_stepn; double dp_stepp; double dp_thgr;
double dp_xfact; double dp_xlamo; double dp_xli; double dp_xni;
bool gp_reso; // geopotential resonant
bool gp_sync; // geopotential synchronous
// ///////////////////////////////////////////////////////////////////////////
public NoradSDP4(Orbit orbit) :
base(orbit)
{
double sinarg = Math.Sin(Orbit.ArgPerigee);
double cosarg = Math.Cos(Orbit.ArgPerigee);
// Deep space initialization
Julian jd = Orbit.Epoch;
dp_thgr = jd.ToGmst();
double eq = Orbit.Eccentricity;
double aqnv = 1.0 / Orbit.SemiMajor;
dp_xqncl = Orbit.Inclination;
double xmao = Orbit.MeanAnomaly;
double xpidot = m_omgdot + m_xnodot;
double sinq = Math.Sin(Orbit.RAAN);
double cosq = Math.Cos(Orbit.RAAN);
dp_omegaq = Orbit.ArgPerigee;
#region Lunar / Solar terms
// Initialize lunar solar terms
double day = jd.FromJan0_12h_1900();
double dpi_xnodce = 4.5236020 - 9.2422029E-4 * day;
double dpi_stem = Math.Sin(dpi_xnodce);
double dpi_ctem = Math.Cos(dpi_xnodce);
double dpi_zcosil = 0.91375164 - 0.03568096 * dpi_ctem;
double dpi_zsinil = Math.Sqrt(1.0 - dpi_zcosil * dpi_zcosil);
double dpi_zsinhl = 0.089683511 * dpi_stem / dpi_zsinil;
double dpi_zcoshl = Math.Sqrt(1.0 - dpi_zsinhl * dpi_zsinhl);
double dpi_c = 4.7199672 + 0.22997150 * day;
double dpi_gam = 5.8351514 + 0.0019443680 * day;
dp_zmol = Globals.Fmod2p(dpi_c - dpi_gam);
double dpi_zx = 0.39785416 * dpi_stem / dpi_zsinil;
double dpi_zy = dpi_zcoshl * dpi_ctem + 0.91744867 * dpi_zsinhl * dpi_stem;
dpi_zx = Globals.AcTan(dpi_zx, dpi_zy) + dpi_gam - dpi_xnodce;
double dpi_zcosgl = Math.Cos(dpi_zx);
double dpi_zsingl = Math.Sin(dpi_zx);
dp_zmos = 6.2565837 + 0.017201977 * day;
dp_zmos = Globals.Fmod2p(dp_zmos);
const double zcosis = 0.91744867;
const double zsinis = 0.39785416;
const double zsings = -0.98088458;
const double zcosgs = 0.1945905;
const double c1ss = 2.9864797E-6;
double zcosg = zcosgs;
double zsing = zsings;
double zcosi = zcosis;
double zsini = zsinis;
double zcosh = cosq;
double zsinh = sinq;
double cc = c1ss;
double zn = zns;
double ze = zes;
double xnoi = 1.0 / Orbit.MeanMotion;
double a1; double a3; double a7; double a8; double a9; double a10;
double a2; double a4; double a5; double a6; double x1; double x2;
double x3; double x4; double x5; double x6; double x7; double x8;
double z31; double z32; double z33; double z1; double z2; double z3;
double z11; double z12; double z13; double z21; double z22; double z23;
double s3; double s2; double s4; double s1; double s5; double s6;
double s7;
double se = 0.0;
double si = 0.0;
double sl = 0.0;
double sgh = 0.0;
double sh = 0.0;
double eosq = Globals.Sqr(Orbit.Eccentricity);
// Apply the solar and lunar terms on the first pass, then re-apply the
// solar terms again on the second pass.
for (int pass = 1; pass <= 2; pass++)
{
// Do solar terms
a1 = zcosg * zcosh + zsing * zcosi * zsinh;
a3 = -zsing * zcosh + zcosg * zcosi * zsinh;
a7 = -zcosg * zsinh + zsing * zcosi * zcosh;
a8 = zsing * zsini;
a9 = zsing * zsinh + zcosg * zcosi * zcosh;
a10 = zcosg * zsini;
a2 = m_cosio * a7 + m_sinio * a8;
a4 = m_cosio * a9 + m_sinio * a10;
a5 = -m_sinio * a7 + m_cosio * a8;
a6 = -m_sinio * a9 + m_cosio * a10;
x1 = a1 * cosarg + a2 * sinarg;
x2 = a3 * cosarg + a4 * sinarg;
x3 = -a1 * sinarg + a2 * cosarg;
x4 = -a3 * sinarg + a4 * cosarg;
x5 = a5 * sinarg;
x6 = a6 * sinarg;
x7 = a5 * cosarg;
x8 = a6 * cosarg;
z31 = 12.0 * x1 * x1 - 3.0 * x3 * x3;
z32 = 24.0 * x1 * x2 - 6.0 * x3 * x4;
z33 = 12.0 * x2 * x2 - 3.0 * x4 * x4;
z1 = 3.0 * (a1 * a1 + a2 * a2) + z31 * eosq;
z2 = 6.0 * (a1 * a3 + a2 * a4) + z32 * eosq;
z3 = 3.0 * (a3 * a3 + a4 * a4) + z33 * eosq;
z11 = -6.0 * a1 * a5 + eosq * (-24.0 * x1 * x7 - 6.0 * x3 * x5);
z12 = -6.0 * (a1 * a6 + a3 * a5) +
eosq * (-24.0 * (x2 * x7 + x1 * x8) - 6.0 * (x3 * x6 + x4 * x5));
z13 = -6.0 * a3 * a6 + eosq * (-24.0 * x2 * x8 - 6.0 * x4 * x6);
z21 = 6.0 * a2 * a5 + eosq * (24.0 * x1 * x5 - 6.0 * x3 * x7);
z22 = 6.0 * (a4 * a5 + a2 * a6) +
eosq * (24.0 * (x2 * x5 + x1 * x6) - 6.0 * (x4 * x7 + x3 * x8));
z23 = 6.0 * a4 * a6 + eosq * (24.0 * x2 * x6 - 6.0 * x4 * x8);
z1 = z1 + z1 + m_betao2 * z31;
z2 = z2 + z2 + m_betao2 * z32;
z3 = z3 + z3 + m_betao2 * z33;
s3 = cc * xnoi;
s2 = -0.5 * s3 / m_betao;
s4 = s3 * m_betao;
s1 = -15.0 * eq * s4;
s5 = x1 * x3 + x2 * x4;
s6 = x2 * x3 + x1 * x4;
s7 = x2 * x4 - x1 * x3;
se = s1 * zn * s5;
si = s2 * zn * (z11 + z13);
sl = -zn * s3 * (z1 + z3 - 14.0 - 6.0 * eosq);
sgh = s4 * zn * (z31 + z33 - 6.0);
if (Orbit.Inclination < 5.2359877E-2)
{
sh = 0.0;
}
else
{
sh = -zn * s2 * (z21 + z23);
}
dp_ee2 = 2.0 * s1 * s6;
dp_e3 = 2.0 * s1 * s7;
dp_xi2 = 2.0 * s2 * z12;
dp_xi3 = 2.0 * s2 * (z13 - z11);
dp_xl2 = -2.0 * s3 * z2;
dp_xl3 = -2.0 * s3 * (z3 - z1);
dp_xl4 = -2.0 * s3 * (-21.0 - 9.0 * eosq) * ze;
dp_xgh2 = 2.0 * s4 * z32;
dp_xgh3 = 2.0 * s4 * (z33 - z31);
dp_xgh4 = -18.0 * s4 * ze;
dp_xh2 = -2.0 * s2 * z22;
dp_xh3 = -2.0 * s2 * (z23 - z21);
if (pass == 1)
{
// Do lunar terms
dp_sse = se;
dp_ssi = si;
dp_ssl = sl;
dp_ssh = sh / m_sinio;
dp_ssg = sgh - m_cosio * dp_ssh;
dp_se2 = dp_ee2;
dp_si2 = dp_xi2;
dp_sl2 = dp_xl2;
dp_sgh2 = dp_xgh2;
dp_sh2 = dp_xh2;
dp_se3 = dp_e3;
dp_si3 = dp_xi3;
dp_sl3 = dp_xl3;
dp_sgh3 = dp_xgh3;
dp_sh3 = dp_xh3;
dp_sl4 = dp_xl4;
dp_sgh4 = dp_xgh4;
zcosg = dpi_zcosgl;
zsing = dpi_zsingl;
zcosi = dpi_zcosil;
zsini = dpi_zsinil;
zcosh = dpi_zcoshl * cosq + dpi_zsinhl * sinq;
zsinh = sinq * dpi_zcoshl - cosq * dpi_zsinhl;
zn = znl;
const double c1l = 4.7968065E-7;
cc = c1l;
ze = zel;
}
}
#endregion
dp_sse = dp_sse + se;
dp_ssi = dp_ssi + si;
dp_ssl = dp_ssl + sl;
dp_ssg = dp_ssg + sgh - m_cosio / m_sinio * sh;
dp_ssh = dp_ssh + sh / m_sinio;
// Geopotential resonance initialization for 12 hour orbits
gp_reso = false;
gp_sync = false;
double g310;
double f220;
double bfact = 0.0;
// Determine if orbit is 12- or 24-hour resonant.
// Mean motion is given in radians per minute.
if ((Orbit.MeanMotion > 0.0034906585) && (Orbit.MeanMotion < 0.0052359877))
{
// Orbit is within the Clarke Belt (period is 24-hour resonant).
// Synchronous resonance terms initialization
gp_reso = true;
gp_sync = true;
#region 24-hour resonant
double g200 = 1.0 + eosq * (-2.5 + 0.8125 * eosq);
g310 = 1.0 + 2.0 * eosq;
double g300 = 1.0 + eosq * (-6.0 + 6.60937 * eosq);
f220 = 0.75 * (1.0 + m_cosio) * (1.0 + m_cosio);
double f311 = 0.9375 * m_sinio * m_sinio * (1.0 + 3 * m_cosio) - 0.75 * (1.0 + m_cosio);
double f330 = 1.0 + m_cosio;
f330 = 1.875 * f330 * f330 * f330;
const double q22 = 1.7891679e-06;
const double q33 = 2.2123015e-07;
const double q31 = 2.1460748e-06;
dp_del1 = 3.0 * m_xnodp * m_xnodp * aqnv * aqnv;
dp_del2 = 2.0 * dp_del1 * f220 * g200 * q22;
dp_del3 = 3.0 * dp_del1 * f330 * g300 * q33 * aqnv;
dp_del1 = dp_del1 * f311 * g310 * q31 * aqnv;
dp_xlamo = xmao + Orbit.RAAN + Orbit.ArgPerigee - dp_thgr;
bfact = m_xmdot + xpidot - thdt;
bfact = bfact + dp_ssl + dp_ssg + dp_ssh;
#endregion
}
else if (((Orbit.MeanMotion >= 8.26E-3) && (Orbit.MeanMotion <= 9.24E-3)) && (eq >= 0.5))
{
// Period is 12-hour resonant
gp_reso = true;
#region 12-hour resonant
double eoc = eq * eosq;
double g201 = -0.306 - (eq - 0.64) * 0.440;
double g211; double g322;
double g410; double g422;
double g520;
if (eq <= 0.65)
{
g211 = 3.616 - 13.247 * eq + 16.290 * eosq;
g310 = -19.302 + 117.390 * eq - 228.419 * eosq + 156.591 * eoc;
g322 = -18.9068 + 109.7927 * eq - 214.6334 * eosq + 146.5816 * eoc;
g410 = -41.122 + 242.694 * eq - 471.094 * eosq + 313.953 * eoc;
g422 = -146.407 + 841.880 * eq - 1629.014 * eosq + 1083.435 * eoc;
g520 = -532.114 + 3017.977 * eq - 5740.0 * eosq + 3708.276 * eoc;
}
else
{
g211 = -72.099 + 331.819 * eq - 508.738 * eosq + 266.724 * eoc;
g310 = -346.844 + 1582.851 * eq - 2415.925 * eosq + 1246.113 * eoc;
g322 = -342.585 + 1554.908 * eq - 2366.899 * eosq + 1215.972 * eoc;
g410 = -1052.797 + 4758.686 * eq - 7193.992 * eosq + 3651.957 * eoc;
g422 = -3581.69 + 16178.11 * eq - 24462.77 * eosq + 12422.52 * eoc;
if (eq <= 0.715)
{
g520 = 1464.74 - 4664.75 * eq + 3763.64 * eosq;
}
else
{
g520 = -5149.66 + 29936.92 * eq - 54087.36 * eosq + 31324.56 * eoc;
}
}
double g533;
double g521;
double g532;
if (eq < 0.7)
{
g533 = -919.2277 + 4988.61 * eq - 9064.77 * eosq + 5542.21 * eoc;
g521 = -822.71072 + 4568.6173 * eq - 8491.4146 * eosq + 5337.524 * eoc;
g532 = -853.666 + 4690.25 * eq - 8624.77 * eosq + 5341.4 * eoc;
}
else
{
g533 = -37995.78 + 161616.52 * eq - 229838.2 * eosq + 109377.94 * eoc;
g521 = -51752.104 + 218913.95 * eq - 309468.16 * eosq + 146349.42 * eoc;
g532 = -40023.88 + 170470.89 * eq - 242699.48 * eosq + 115605.82 * eoc;
}
double sini2 = m_sinio * m_sinio;
double cosi2 = m_cosio * m_cosio;
f220 = 0.75 * (1.0 + 2.0 * m_cosio + cosi2);
double f221 = 1.5 * sini2;
double f321 = 1.875 * m_sinio * (1.0 - 2.0 * m_cosio - 3.0 * cosi2);
double f322 = -1.875 * m_sinio * (1.0 + 2.0 * m_cosio - 3.0 * cosi2);
double f441 = 35.0 * sini2 * f220;
double f442 = 39.3750 * sini2 * sini2;
double f522 = 9.84375 * m_sinio * (sini2 * (1.0 - 2.0 * m_cosio - 5.0 * cosi2) +
0.33333333 * (-2.0 + 4.0 * m_cosio + 6.0 * cosi2));
double f523 = m_sinio * (4.92187512 * sini2 * (-2.0 - 4.0 * m_cosio + 10.0 * cosi2) +
6.56250012 * (1.0 + 2.0 * m_cosio - 3.0 * cosi2));
double f542 = 29.53125 * m_sinio * (2.0 - 8.0 * m_cosio + cosi2 * (-12.0 + 8.0 * m_cosio + 10.0 * cosi2));
double f543 = 29.53125 * m_sinio * (-2.0 - 8.0 * m_cosio + cosi2 * (12.0 + 8.0 * m_cosio - 10.0 * cosi2));
double xno2 = m_xnodp * m_xnodp;
double ainv2 = aqnv * aqnv;
double temp1 = 3.0 * xno2 * ainv2;
const double root22 = 1.7891679E-6;
const double root32 = 3.7393792E-7;
const double root44 = 7.3636953E-9;
const double root52 = 1.1428639E-7;
const double root54 = 2.1765803E-9;
double temp = temp1 * root22;
dp_d2201 = temp * f220 * g201;
dp_d2211 = temp * f221 * g211;
temp1 = temp1 * aqnv;
temp = temp1 * root32;
dp_d3210 = temp * f321 * g310;
dp_d3222 = temp * f322 * g322;
temp1 = temp1 * aqnv;
temp = 2.0 * temp1 * root44;
dp_d4410 = temp * f441 * g410;
dp_d4422 = temp * f442 * g422;
temp1 = temp1 * aqnv;
temp = temp1 * root52;
dp_d5220 = temp * f522 * g520;
dp_d5232 = temp * f523 * g532;
temp = 2.0 * temp1 * root54;
dp_d5421 = temp * f542 * g521;
dp_d5433 = temp * f543 * g533;
dp_xlamo = xmao + Orbit.RAAN + Orbit.RAAN - dp_thgr - dp_thgr;
bfact = m_xmdot + m_xnodot + m_xnodot - thdt - thdt;
bfact = bfact + dp_ssl + dp_ssh + dp_ssh;
#endregion
}
if (gp_reso || gp_sync)
{
dp_xfact = bfact - m_xnodp;
// Initialize integrator
dp_xli = dp_xlamo;
dp_xni = m_xnodp;
// dp_atime = 0.0; // performed by runtime
dp_stepp = 720.0;
dp_stepn = -720.0;
dp_step2 = 259200.0;
}
}
// ///////////////////////////////////////////////////////////////////////////
private bool DeepCalcDotTerms(ref double pxndot, ref double pxnddt, ref double pxldot)
{
// Dot terms calculated
if (gp_sync)
{
const double fasx2 = 0.13130908;
const double fasx4 = 2.8843198;
const double fasx6 = 0.37448087;
pxndot = dp_del1 * Math.Sin(dp_xli - fasx2) +
dp_del2 * Math.Sin(2.0 * (dp_xli - fasx4)) +
dp_del3 * Math.Sin(3.0 * (dp_xli - fasx6));
pxnddt = dp_del1 * Math.Cos(dp_xli - fasx2) +
2.0 * dp_del2 * Math.Cos(2.0 * (dp_xli - fasx4)) +
3.0 * dp_del3 * Math.Cos(3.0 * (dp_xli - fasx6));
}
else
{
const double g54 = 4.4108898;
const double g52 = 1.0508330;
const double g44 = 1.8014998;
const double g22 = 5.7686396;
const double g32 = 0.95240898;
double xomi = dp_omegaq + m_omgdot * dp_atime;
double x2omi = xomi + xomi;
double x2li = dp_xli + dp_xli;
pxndot = dp_d2201 * Math.Sin(x2omi + dp_xli - g22) +
dp_d2211 * Math.Sin(dp_xli - g22) +
dp_d3210 * Math.Sin( xomi + dp_xli - g32) +
dp_d3222 * Math.Sin(-xomi + dp_xli - g32) +
dp_d4410 * Math.Sin(x2omi + x2li - g44) +
dp_d4422 * Math.Sin(x2li - g44) +
dp_d5220 * Math.Sin( xomi + dp_xli - g52) +
dp_d5232 * Math.Sin(-xomi + dp_xli - g52) +
dp_d5421 * Math.Sin( xomi + x2li - g54) +
dp_d5433 * Math.Sin(-xomi + x2li - g54);
pxnddt = dp_d2201 * Math.Cos(x2omi + dp_xli - g22) +
dp_d2211 * Math.Cos(dp_xli - g22) +
dp_d3210 * Math.Cos( xomi + dp_xli - g32) +
dp_d3222 * Math.Cos(-xomi + dp_xli - g32) +
dp_d5220 * Math.Cos( xomi + dp_xli - g52) +
dp_d5232 * Math.Cos(-xomi + dp_xli - g52) +
2.0 * (dp_d4410 * Math.Cos(x2omi + x2li - g44) +
dp_d4422 * Math.Cos(x2li - g44) +
dp_d5421 * Math.Cos( xomi + x2li - g54) +
dp_d5433 * Math.Cos(-xomi + x2li - g54));
}
pxldot = dp_xni + dp_xfact;
pxnddt = pxnddt * pxldot;
return true;
}
// ///////////////////////////////////////////////////////////////////////////
private void DeepCalcIntegrator(ref double pxndot, ref double pxnddt,
ref double pxldot, double delta)
{
DeepCalcDotTerms(ref pxndot, ref pxnddt, ref pxldot);
dp_xli = dp_xli + pxldot * delta + pxndot * dp_step2;
dp_xni = dp_xni + pxndot * delta + pxnddt * dp_step2;
dp_atime = dp_atime + delta;
}
// ///////////////////////////////////////////////////////////////////////////
private bool DeepSecular(ref double xmdf, ref double omgadf, ref double xnode,
ref double emm, ref double xincc, ref double xnn,
ref double tsince)
{
// Deep space secular effects
xmdf = xmdf + dp_ssl * tsince;
omgadf = omgadf + dp_ssg * tsince;
xnode = xnode + dp_ssh * tsince;
emm = Orbit.Eccentricity + dp_sse * tsince;
xincc = Orbit.Inclination + dp_ssi * tsince;
if (xincc < 0.0)
{
xincc = -xincc;
xnode = xnode + Globals.Pi;
omgadf = omgadf - Globals.Pi;
}
double xnddt = 0.0;
double xndot = 0.0;
double xldot = 0.0;
double ft = 0.0;
double delt = 0.0;
bool fDone = false;
if (gp_reso)
{
while (!fDone)
{
if ((dp_atime == 0.0) ||
((tsince >= 0.0) && (dp_atime < 0.0)) ||
((tsince < 0.0) && (dp_atime >= 0.0)))
{
delt = (tsince < 0) ? dp_stepn : dp_stepp;
// Epoch restart
dp_atime = 0.0;
dp_xni = m_xnodp;
dp_xli = dp_xlamo;
fDone = true;
}
else
{
if (Math.Abs(tsince) < Math.Abs(dp_atime))
{
delt = dp_stepp;
if (tsince >= 0.0)
{
delt = dp_stepn;
}
DeepCalcIntegrator(ref xndot, ref xnddt, ref xldot, delt);
}
else
{
delt = dp_stepn;
if (tsince > 0.0)
{
delt = dp_stepp;
}
fDone = true;
}
}
}
while (Math.Abs(tsince - dp_atime) >= dp_stepp)
{
DeepCalcIntegrator(ref xndot, ref xnddt, ref xldot, delt);
}
ft = tsince - dp_atime;
DeepCalcDotTerms(ref xndot, ref xnddt, ref xldot);
xnn = dp_xni + xndot * ft + xnddt * ft * ft * 0.5;
double xl = dp_xli + xldot * ft + xndot * ft * ft * 0.5;
double temp = -xnode + dp_thgr + tsince * thdt;
xmdf = xl - omgadf + temp;
if (!gp_sync)
{
xmdf = xl + temp + temp;
}
}
return true;
}
// ///////////////////////////////////////////////////////////////////////////
private bool DeepPeriodics(ref double e, ref double xincc,
ref double omgadf, ref double xnode,
ref double xmam, double tsince)
{
// Lunar-solar periodics
double sinis = Math.Sin(xincc);
double cosis = Math.Cos(xincc);
double sghs = 0.0;
double shs = 0.0;
double sh1 = 0.0;
double pe = 0.0;
double pinc = 0.0;
double pl = 0.0;
double sghl = 0.0;
double zm = dp_zmos + zns * tsince;
double zf = zm + 2.0 * zes * Math.Sin(zm);
double sinzf = Math.Sin(zf);
double f2 = 0.5 * sinzf * sinzf - 0.25;
double f3 = -0.5 * sinzf * Math.Cos(zf);
double ses = dp_se2 * f2 + dp_se3 * f3;
double sis = dp_si2 * f2 + dp_si3 * f3;
double sls = dp_sl2 * f2 + dp_sl3 * f3 + dp_sl4 * sinzf;
sghs = dp_sgh2 * f2 + dp_sgh3 * f3 + dp_sgh4 * sinzf;
shs = dp_sh2 * f2 + dp_sh3 * f3;
zm = dp_zmol + znl * tsince;
zf = zm + 2.0 * zel * Math.Sin(zm);
sinzf = Math.Sin(zf);
f2 = 0.5 * sinzf * sinzf - 0.25;
f3 = -0.5 * sinzf * Math.Cos(zf);
double sel = dp_ee2 * f2 + dp_e3 * f3;
double sil = dp_xi2 * f2 + dp_xi3 * f3;
double sll = dp_xl2 * f2 + dp_xl3 * f3 + dp_xl4 * sinzf;
sghl = dp_xgh2 * f2 + dp_xgh3 * f3 + dp_xgh4 * sinzf;
sh1 = dp_xh2 * f2 + dp_xh3 * f3;
pe = ses + sel;
pinc = sis + sil;
pl = sls + sll;
double pgh = sghs + sghl;
double ph = shs + sh1;
xincc = xincc + pinc;
e = e + pe;
if (dp_xqncl >= 0.2)
{
// Apply periodics directly
ph = ph / m_sinio;
pgh = pgh - m_cosio * ph;
omgadf = omgadf + pgh;
xnode = xnode + ph;
xmam = xmam + pl;
}
else
{
// Apply periodics with Lyddane modification
double sinok = Math.Sin(xnode);
double cosok = Math.Cos(xnode);
double alfdp = sinis * sinok;
double betdp = sinis * cosok;
double dalf = ph * cosok + pinc * cosis * sinok;
double dbet = -ph * sinok + pinc * cosis * cosok;
alfdp = alfdp + dalf;
betdp = betdp + dbet;
double xls = xmam + omgadf + cosis * xnode;
double dls = pl + pgh - pinc * xnode * sinis;
xls = xls + dls;
xnode = Globals.AcTan(alfdp, betdp);
xmam = xmam + pl;
omgadf = xls - xmam - Math.Cos(xincc) * xnode;
}
return true;
}
/// <summary>
/// Calculate satellite ECI position/velocity for a given time.
/// </summary>
/// <param name="tsince">Target time, in minutes-past-epoch format.</param>
/// <returns>AU-based position/velocity ECI coordinates.</returns>
/// <remarks>
/// This procedure returns the ECI position and velocity for the satellite
/// in the orbit at the given number of minutes since the TLE epoch time.
/// The algorithm uses NORAD's Simplified General Perturbation 4 deep space
/// orbit model.
/// </remarks>
public override EciTime GetPosition(double tsince)
{
// Update for secular gravity and atmospheric drag
double xmdf = Orbit.MeanAnomaly + m_xmdot * tsince;
double omgadf = Orbit.ArgPerigee + m_omgdot * tsince;
double xnoddf = Orbit.RAAN + m_xnodot * tsince;
double tsq = tsince * tsince;
double xnode = xnoddf + m_xnodcf * tsq;
double tempa = 1.0 - m_c1 * tsince;
double tempe = Orbit.BStar * m_c4 * tsince;
double templ = m_t2cof * tsq;
double xn = m_xnodp;
double em = 0.0;
double xinc = 0.0;
DeepSecular(ref xmdf, ref omgadf, ref xnode, ref em, ref xinc, ref xn, ref tsince);
double a = Math.Pow(Globals.Xke / xn, 2.0 / 3.0) * Globals.Sqr(tempa);
double e = em - tempe;
double xmam = xmdf + m_xnodp * templ;
DeepPeriodics(ref e, ref xinc, ref omgadf, ref xnode, ref xmam, tsince);
double xl = xmam + omgadf + xnode;
xn = Globals.Xke / Math.Pow(a, 1.5);
return FinalPosition(xinc, omgadf, e, a, xl, xnode, xn, tsince);
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.Dlp.V2Beta1;
using Google.LongRunning;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Dlp.V2Beta1.Snippets
{
/// <summary>Generated snippets</summary>
public class GeneratedDlpServiceClientSnippets
{
/// <summary>Snippet for InspectContentAsync</summary>
public async Task InspectContentAsync()
{
// Snippet: InspectContentAsync(InspectConfig,IEnumerable<ContentItem>,CallSettings)
// Additional: InspectContentAsync(InspectConfig,IEnumerable<ContentItem>,CancellationToken)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
InspectConfig inspectConfig = new InspectConfig
{
InfoTypes = {
new InfoType
{
Name = "EMAIL_ADDRESS",
},
},
};
IEnumerable<ContentItem> items = new[]
{
new ContentItem
{
Type = "text/plain",
Value = "My email is example@example.com.",
},
};
// Make the request
InspectContentResponse response = await dlpServiceClient.InspectContentAsync(inspectConfig, items);
// End snippet
}
/// <summary>Snippet for InspectContent</summary>
public void InspectContent()
{
// Snippet: InspectContent(InspectConfig,IEnumerable<ContentItem>,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
InspectConfig inspectConfig = new InspectConfig
{
InfoTypes = {
new InfoType
{
Name = "EMAIL_ADDRESS",
},
},
};
IEnumerable<ContentItem> items = new[]
{
new ContentItem
{
Type = "text/plain",
Value = "My email is example@example.com.",
},
};
// Make the request
InspectContentResponse response = dlpServiceClient.InspectContent(inspectConfig, items);
// End snippet
}
/// <summary>Snippet for InspectContentAsync</summary>
public async Task InspectContentAsync_RequestObject()
{
// Snippet: InspectContentAsync(InspectContentRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
InspectContentRequest request = new InspectContentRequest
{
InspectConfig = new InspectConfig
{
InfoTypes = {
new InfoType
{
Name = "EMAIL_ADDRESS",
},
},
},
Items = {
new ContentItem
{
Type = "text/plain",
Value = "My email is example@example.com.",
},
},
};
// Make the request
InspectContentResponse response = await dlpServiceClient.InspectContentAsync(request);
// End snippet
}
/// <summary>Snippet for InspectContent</summary>
public void InspectContent_RequestObject()
{
// Snippet: InspectContent(InspectContentRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
InspectContentRequest request = new InspectContentRequest
{
InspectConfig = new InspectConfig
{
InfoTypes = {
new InfoType
{
Name = "EMAIL_ADDRESS",
},
},
},
Items = {
new ContentItem
{
Type = "text/plain",
Value = "My email is example@example.com.",
},
},
};
// Make the request
InspectContentResponse response = dlpServiceClient.InspectContent(request);
// End snippet
}
/// <summary>Snippet for RedactContentAsync</summary>
public async Task RedactContentAsync_RequestObject()
{
// Snippet: RedactContentAsync(RedactContentRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
RedactContentRequest request = new RedactContentRequest
{
InspectConfig = new InspectConfig
{
InfoTypes = {
new InfoType
{
Name = "EMAIL_ADDRESS",
},
},
},
Items = {
new ContentItem
{
Type = "text/plain",
Value = "My email is example@example.com.",
},
},
ReplaceConfigs = {
new RedactContentRequest.Types.ReplaceConfig
{
InfoType = new InfoType
{
Name = "EMAIL_ADDRESS",
},
ReplaceWith = "REDACTED",
},
},
};
// Make the request
RedactContentResponse response = await dlpServiceClient.RedactContentAsync(request);
// End snippet
}
/// <summary>Snippet for RedactContent</summary>
public void RedactContent_RequestObject()
{
// Snippet: RedactContent(RedactContentRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
RedactContentRequest request = new RedactContentRequest
{
InspectConfig = new InspectConfig
{
InfoTypes = {
new InfoType
{
Name = "EMAIL_ADDRESS",
},
},
},
Items = {
new ContentItem
{
Type = "text/plain",
Value = "My email is example@example.com.",
},
},
ReplaceConfigs = {
new RedactContentRequest.Types.ReplaceConfig
{
InfoType = new InfoType
{
Name = "EMAIL_ADDRESS",
},
ReplaceWith = "REDACTED",
},
},
};
// Make the request
RedactContentResponse response = dlpServiceClient.RedactContent(request);
// End snippet
}
/// <summary>Snippet for DeidentifyContentAsync</summary>
public async Task DeidentifyContentAsync()
{
// Snippet: DeidentifyContentAsync(DeidentifyConfig,InspectConfig,IEnumerable<ContentItem>,CallSettings)
// Additional: DeidentifyContentAsync(DeidentifyConfig,InspectConfig,IEnumerable<ContentItem>,CancellationToken)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
DeidentifyConfig deidentifyConfig = new DeidentifyConfig();
InspectConfig inspectConfig = new InspectConfig();
IEnumerable<ContentItem> items = new List<ContentItem>();
// Make the request
DeidentifyContentResponse response = await dlpServiceClient.DeidentifyContentAsync(deidentifyConfig, inspectConfig, items);
// End snippet
}
/// <summary>Snippet for DeidentifyContent</summary>
public void DeidentifyContent()
{
// Snippet: DeidentifyContent(DeidentifyConfig,InspectConfig,IEnumerable<ContentItem>,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
DeidentifyConfig deidentifyConfig = new DeidentifyConfig();
InspectConfig inspectConfig = new InspectConfig();
IEnumerable<ContentItem> items = new List<ContentItem>();
// Make the request
DeidentifyContentResponse response = dlpServiceClient.DeidentifyContent(deidentifyConfig, inspectConfig, items);
// End snippet
}
/// <summary>Snippet for DeidentifyContentAsync</summary>
public async Task DeidentifyContentAsync_RequestObject()
{
// Snippet: DeidentifyContentAsync(DeidentifyContentRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
DeidentifyContentRequest request = new DeidentifyContentRequest
{
DeidentifyConfig = new DeidentifyConfig(),
InspectConfig = new InspectConfig(),
Items = { },
};
// Make the request
DeidentifyContentResponse response = await dlpServiceClient.DeidentifyContentAsync(request);
// End snippet
}
/// <summary>Snippet for DeidentifyContent</summary>
public void DeidentifyContent_RequestObject()
{
// Snippet: DeidentifyContent(DeidentifyContentRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
DeidentifyContentRequest request = new DeidentifyContentRequest
{
DeidentifyConfig = new DeidentifyConfig(),
InspectConfig = new InspectConfig(),
Items = { },
};
// Make the request
DeidentifyContentResponse response = dlpServiceClient.DeidentifyContent(request);
// End snippet
}
/// <summary>Snippet for AnalyzeDataSourceRiskAsync</summary>
public async Task AnalyzeDataSourceRiskAsync()
{
// Snippet: AnalyzeDataSourceRiskAsync(PrivacyMetric,BigQueryTable,CallSettings)
// Additional: AnalyzeDataSourceRiskAsync(PrivacyMetric,BigQueryTable,CancellationToken)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
PrivacyMetric privacyMetric = new PrivacyMetric();
BigQueryTable sourceTable = new BigQueryTable();
// Make the request
Operation<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata> response =
await dlpServiceClient.AnalyzeDataSourceRiskAsync(privacyMetric, sourceTable);
// Poll until the returned long-running operation is complete
Operation<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata> completedResponse =
await response.PollUntilCompletedAsync();
// Retrieve the operation result
RiskAnalysisOperationResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata> retrievedResponse =
await dlpServiceClient.PollOnceAnalyzeDataSourceRiskAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
RiskAnalysisOperationResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AnalyzeDataSourceRisk</summary>
public void AnalyzeDataSourceRisk()
{
// Snippet: AnalyzeDataSourceRisk(PrivacyMetric,BigQueryTable,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
PrivacyMetric privacyMetric = new PrivacyMetric();
BigQueryTable sourceTable = new BigQueryTable();
// Make the request
Operation<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata> response =
dlpServiceClient.AnalyzeDataSourceRisk(privacyMetric, sourceTable);
// Poll until the returned long-running operation is complete
Operation<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata> completedResponse =
response.PollUntilCompleted();
// Retrieve the operation result
RiskAnalysisOperationResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata> retrievedResponse =
dlpServiceClient.PollOnceAnalyzeDataSourceRisk(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
RiskAnalysisOperationResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AnalyzeDataSourceRiskAsync</summary>
public async Task AnalyzeDataSourceRiskAsync_RequestObject()
{
// Snippet: AnalyzeDataSourceRiskAsync(AnalyzeDataSourceRiskRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeDataSourceRiskRequest request = new AnalyzeDataSourceRiskRequest
{
PrivacyMetric = new PrivacyMetric(),
SourceTable = new BigQueryTable(),
};
// Make the request
Operation<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata> response =
await dlpServiceClient.AnalyzeDataSourceRiskAsync(request);
// Poll until the returned long-running operation is complete
Operation<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata> completedResponse =
await response.PollUntilCompletedAsync();
// Retrieve the operation result
RiskAnalysisOperationResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata> retrievedResponse =
await dlpServiceClient.PollOnceAnalyzeDataSourceRiskAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
RiskAnalysisOperationResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AnalyzeDataSourceRisk</summary>
public void AnalyzeDataSourceRisk_RequestObject()
{
// Snippet: AnalyzeDataSourceRisk(AnalyzeDataSourceRiskRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
AnalyzeDataSourceRiskRequest request = new AnalyzeDataSourceRiskRequest
{
PrivacyMetric = new PrivacyMetric(),
SourceTable = new BigQueryTable(),
};
// Make the request
Operation<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata> response =
dlpServiceClient.AnalyzeDataSourceRisk(request);
// Poll until the returned long-running operation is complete
Operation<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata> completedResponse =
response.PollUntilCompleted();
// Retrieve the operation result
RiskAnalysisOperationResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata> retrievedResponse =
dlpServiceClient.PollOnceAnalyzeDataSourceRisk(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
RiskAnalysisOperationResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateInspectOperationAsync</summary>
public async Task CreateInspectOperationAsync()
{
// Snippet: CreateInspectOperationAsync(InspectConfig,StorageConfig,OutputStorageConfig,CallSettings)
// Additional: CreateInspectOperationAsync(InspectConfig,StorageConfig,OutputStorageConfig,CancellationToken)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
InspectConfig inspectConfig = new InspectConfig
{
InfoTypes = {
new InfoType
{
Name = "EMAIL_ADDRESS",
},
},
};
StorageConfig storageConfig = new StorageConfig
{
CloudStorageOptions = new CloudStorageOptions
{
FileSet = new CloudStorageOptions.Types.FileSet
{
Url = "gs://example_bucket/example_file.png",
},
},
};
OutputStorageConfig outputConfig = new OutputStorageConfig();
// Make the request
Operation<InspectOperationResult, InspectOperationMetadata> response =
await dlpServiceClient.CreateInspectOperationAsync(inspectConfig, storageConfig, outputConfig);
// Poll until the returned long-running operation is complete
Operation<InspectOperationResult, InspectOperationMetadata> completedResponse =
await response.PollUntilCompletedAsync();
// Retrieve the operation result
InspectOperationResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<InspectOperationResult, InspectOperationMetadata> retrievedResponse =
await dlpServiceClient.PollOnceCreateInspectOperationAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
InspectOperationResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateInspectOperation</summary>
public void CreateInspectOperation()
{
// Snippet: CreateInspectOperation(InspectConfig,StorageConfig,OutputStorageConfig,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
InspectConfig inspectConfig = new InspectConfig
{
InfoTypes = {
new InfoType
{
Name = "EMAIL_ADDRESS",
},
},
};
StorageConfig storageConfig = new StorageConfig
{
CloudStorageOptions = new CloudStorageOptions
{
FileSet = new CloudStorageOptions.Types.FileSet
{
Url = "gs://example_bucket/example_file.png",
},
},
};
OutputStorageConfig outputConfig = new OutputStorageConfig();
// Make the request
Operation<InspectOperationResult, InspectOperationMetadata> response =
dlpServiceClient.CreateInspectOperation(inspectConfig, storageConfig, outputConfig);
// Poll until the returned long-running operation is complete
Operation<InspectOperationResult, InspectOperationMetadata> completedResponse =
response.PollUntilCompleted();
// Retrieve the operation result
InspectOperationResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<InspectOperationResult, InspectOperationMetadata> retrievedResponse =
dlpServiceClient.PollOnceCreateInspectOperation(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
InspectOperationResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateInspectOperationAsync</summary>
public async Task CreateInspectOperationAsync_RequestObject()
{
// Snippet: CreateInspectOperationAsync(CreateInspectOperationRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
CreateInspectOperationRequest request = new CreateInspectOperationRequest
{
InspectConfig = new InspectConfig
{
InfoTypes = {
new InfoType
{
Name = "EMAIL_ADDRESS",
},
},
},
StorageConfig = new StorageConfig
{
CloudStorageOptions = new CloudStorageOptions
{
FileSet = new CloudStorageOptions.Types.FileSet
{
Url = "gs://example_bucket/example_file.png",
},
},
},
OutputConfig = new OutputStorageConfig(),
};
// Make the request
Operation<InspectOperationResult, InspectOperationMetadata> response =
await dlpServiceClient.CreateInspectOperationAsync(request);
// Poll until the returned long-running operation is complete
Operation<InspectOperationResult, InspectOperationMetadata> completedResponse =
await response.PollUntilCompletedAsync();
// Retrieve the operation result
InspectOperationResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<InspectOperationResult, InspectOperationMetadata> retrievedResponse =
await dlpServiceClient.PollOnceCreateInspectOperationAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
InspectOperationResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateInspectOperation</summary>
public void CreateInspectOperation_RequestObject()
{
// Snippet: CreateInspectOperation(CreateInspectOperationRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
CreateInspectOperationRequest request = new CreateInspectOperationRequest
{
InspectConfig = new InspectConfig
{
InfoTypes = {
new InfoType
{
Name = "EMAIL_ADDRESS",
},
},
},
StorageConfig = new StorageConfig
{
CloudStorageOptions = new CloudStorageOptions
{
FileSet = new CloudStorageOptions.Types.FileSet
{
Url = "gs://example_bucket/example_file.png",
},
},
},
OutputConfig = new OutputStorageConfig(),
};
// Make the request
Operation<InspectOperationResult, InspectOperationMetadata> response =
dlpServiceClient.CreateInspectOperation(request);
// Poll until the returned long-running operation is complete
Operation<InspectOperationResult, InspectOperationMetadata> completedResponse =
response.PollUntilCompleted();
// Retrieve the operation result
InspectOperationResult result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<InspectOperationResult, InspectOperationMetadata> retrievedResponse =
dlpServiceClient.PollOnceCreateInspectOperation(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
InspectOperationResult retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ListInspectFindingsAsync</summary>
public async Task ListInspectFindingsAsync()
{
// Snippet: ListInspectFindingsAsync(ResultName,CallSettings)
// Additional: ListInspectFindingsAsync(ResultName,CancellationToken)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
ResultName name = new ResultName("[RESULT]");
// Make the request
ListInspectFindingsResponse response = await dlpServiceClient.ListInspectFindingsAsync(name);
// End snippet
}
/// <summary>Snippet for ListInspectFindings</summary>
public void ListInspectFindings()
{
// Snippet: ListInspectFindings(ResultName,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
ResultName name = new ResultName("[RESULT]");
// Make the request
ListInspectFindingsResponse response = dlpServiceClient.ListInspectFindings(name);
// End snippet
}
/// <summary>Snippet for ListInspectFindingsAsync</summary>
public async Task ListInspectFindingsAsync_RequestObject()
{
// Snippet: ListInspectFindingsAsync(ListInspectFindingsRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
ListInspectFindingsRequest request = new ListInspectFindingsRequest
{
ResultName = new ResultName("[RESULT]"),
};
// Make the request
ListInspectFindingsResponse response = await dlpServiceClient.ListInspectFindingsAsync(request);
// End snippet
}
/// <summary>Snippet for ListInspectFindings</summary>
public void ListInspectFindings_RequestObject()
{
// Snippet: ListInspectFindings(ListInspectFindingsRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
ListInspectFindingsRequest request = new ListInspectFindingsRequest
{
ResultName = new ResultName("[RESULT]"),
};
// Make the request
ListInspectFindingsResponse response = dlpServiceClient.ListInspectFindings(request);
// End snippet
}
/// <summary>Snippet for ListInfoTypesAsync</summary>
public async Task ListInfoTypesAsync()
{
// Snippet: ListInfoTypesAsync(string,string,CallSettings)
// Additional: ListInfoTypesAsync(string,string,CancellationToken)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
string category = "PII";
string languageCode = "en";
// Make the request
ListInfoTypesResponse response = await dlpServiceClient.ListInfoTypesAsync(category, languageCode);
// End snippet
}
/// <summary>Snippet for ListInfoTypes</summary>
public void ListInfoTypes()
{
// Snippet: ListInfoTypes(string,string,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
string category = "PII";
string languageCode = "en";
// Make the request
ListInfoTypesResponse response = dlpServiceClient.ListInfoTypes(category, languageCode);
// End snippet
}
/// <summary>Snippet for ListInfoTypesAsync</summary>
public async Task ListInfoTypesAsync_RequestObject()
{
// Snippet: ListInfoTypesAsync(ListInfoTypesRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
ListInfoTypesRequest request = new ListInfoTypesRequest
{
Category = "PII",
LanguageCode = "en",
};
// Make the request
ListInfoTypesResponse response = await dlpServiceClient.ListInfoTypesAsync(request);
// End snippet
}
/// <summary>Snippet for ListInfoTypes</summary>
public void ListInfoTypes_RequestObject()
{
// Snippet: ListInfoTypes(ListInfoTypesRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
ListInfoTypesRequest request = new ListInfoTypesRequest
{
Category = "PII",
LanguageCode = "en",
};
// Make the request
ListInfoTypesResponse response = dlpServiceClient.ListInfoTypes(request);
// End snippet
}
/// <summary>Snippet for ListRootCategoriesAsync</summary>
public async Task ListRootCategoriesAsync()
{
// Snippet: ListRootCategoriesAsync(string,CallSettings)
// Additional: ListRootCategoriesAsync(string,CancellationToken)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
string languageCode = "en";
// Make the request
ListRootCategoriesResponse response = await dlpServiceClient.ListRootCategoriesAsync(languageCode);
// End snippet
}
/// <summary>Snippet for ListRootCategories</summary>
public void ListRootCategories()
{
// Snippet: ListRootCategories(string,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
string languageCode = "en";
// Make the request
ListRootCategoriesResponse response = dlpServiceClient.ListRootCategories(languageCode);
// End snippet
}
/// <summary>Snippet for ListRootCategoriesAsync</summary>
public async Task ListRootCategoriesAsync_RequestObject()
{
// Snippet: ListRootCategoriesAsync(ListRootCategoriesRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
// Initialize request argument(s)
ListRootCategoriesRequest request = new ListRootCategoriesRequest
{
LanguageCode = "en",
};
// Make the request
ListRootCategoriesResponse response = await dlpServiceClient.ListRootCategoriesAsync(request);
// End snippet
}
/// <summary>Snippet for ListRootCategories</summary>
public void ListRootCategories_RequestObject()
{
// Snippet: ListRootCategories(ListRootCategoriesRequest,CallSettings)
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
ListRootCategoriesRequest request = new ListRootCategoriesRequest
{
LanguageCode = "en",
};
// Make the request
ListRootCategoriesResponse response = dlpServiceClient.ListRootCategories(request);
// End snippet
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Editor.CSharp.QuickInfo;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo
{
public class SyntacticQuickInfoSourceTests : AbstractQuickInfoSourceTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Brackets_0()
{
await TestInMethodAndScriptAsync(
@"
switch (true)
{
}$$
",
@"switch (true)
{");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Brackets_1()
{
await TestInClassAsync("int Property { get; }$$ ", "int Property {");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Brackets_2()
{
await TestInClassAsync("void M()\r\n{ }$$ ", "void M()\r\n{");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Brackets_3()
{
await TestInMethodAndScriptAsync("var a = new int[] { }$$ ", "new int[] {");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Brackets_4()
{
await TestInMethodAndScriptAsync(
@"
if (true)
{
}$$
",
@"if (true)
{");
}
[WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")]
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ScopeBrackets_0()
{
await TestInMethodAndScriptAsync(
@"if (true)
{
{
}$$
}",
"{");
}
[WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")]
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ScopeBrackets_1()
{
await TestInMethodAndScriptAsync(
@"while (true)
{
// some
// comment
{
}$$
}",
@"// some
// comment
{");
}
[WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")]
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ScopeBrackets_2()
{
await TestInMethodAndScriptAsync(
@"do
{
/* comment */
{
}$$
}
while (true);",
@"/* comment */
{");
}
[WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")]
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ScopeBrackets_3()
{
await TestInMethodAndScriptAsync(
@"if (true)
{
}
else
{
{
// some
// comment
}$$
}",
@"{
// some
// comment");
}
[WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")]
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ScopeBrackets_4()
{
await TestInMethodAndScriptAsync(
@"using (var x = new X())
{
{
/* comment */
}$$
}",
@"{
/* comment */");
}
[WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")]
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ScopeBrackets_5()
{
await TestInMethodAndScriptAsync(
@"foreach (var x in xs)
{
// above
{
/* below */
}$$
}",
@"// above
{");
}
[WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")]
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ScopeBrackets_6()
{
await TestInMethodAndScriptAsync(
@"for (;;)
{
/*************/
// part 1
// part 2
{
}$$
}",
@"/*************/
// part 1
// part 2
{");
}
[WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")]
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ScopeBrackets_7()
{
await TestInMethodAndScriptAsync(
@"try
{
/*************/
// part 1
// part 2
{
}$$
}
catch { throw; }",
@"/*************/
// part 1
// part 2
{");
}
[WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")]
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ScopeBrackets_8()
{
await TestInMethodAndScriptAsync(
@"
{
/*************/
// part 1
// part 2
}$$
",
@"{
/*************/
// part 1
// part 2");
}
[WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")]
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ScopeBrackets_9()
{
await TestInClassAsync(
@"int Property
{
set
{
{
}$$
}
}",
"{");
}
[WorkItem(325, "https://github.com/dotnet/roslyn/issues/325")]
[WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ScopeBrackets_10()
{
await TestInMethodAndScriptAsync(
@"switch (true)
{
default:
// comment
{
}$$
break;
}",
@"// comment
{");
}
private IQuickInfoProvider CreateProvider(TestWorkspace workspace)
{
return new SyntacticQuickInfoProvider(
workspace.GetService<IProjectionBufferFactoryService>(),
workspace.GetService<IEditorOptionsFactoryService>(),
workspace.GetService<ITextEditorFactoryService>(),
workspace.GetService<IGlyphService>(),
workspace.GetService<ClassificationTypeMap>());
}
protected override async Task AssertNoContentAsync(
TestWorkspace workspace,
Document document,
int position)
{
var provider = CreateProvider(workspace);
Assert.Null(await provider.GetItemAsync(document, position, CancellationToken.None));
}
protected override async Task AssertContentIsAsync(
TestWorkspace workspace,
Document document,
int position,
string expectedContent,
string expectedDocumentationComment = null)
{
var provider = CreateProvider(workspace);
var state = await provider.GetItemAsync(document, position, cancellationToken: CancellationToken.None);
Assert.NotNull(state);
var viewHostingControl = (ViewHostingControl)((ElisionBufferDeferredContent)state.Content).Create();
try
{
var actualContent = viewHostingControl.ToString();
Assert.Equal(expectedContent, actualContent);
}
finally
{
viewHostingControl.TextView_TestOnly.Close();
}
}
protected override Task TestInMethodAsync(string code, string expectedContent, string expectedDocumentationComment = null)
{
return TestInClassAsync(
@"void M()
{" + code + "}", expectedContent, expectedDocumentationComment);
}
protected override Task TestInClassAsync(string code, string expectedContent, string expectedDocumentationComment = null)
{
return TestAsync(
@"class C
{" + code + "}", expectedContent, expectedDocumentationComment);
}
protected override Task TestInScriptAsync(string code, string expectedContent, string expectedDocumentationComment = null)
{
return TestAsync(code, expectedContent, expectedContent, Options.Script);
}
protected override async Task TestAsync(
string code,
string expectedContent,
string expectedDocumentationComment = null,
CSharpParseOptions parseOptions = null)
{
using (var workspace = TestWorkspace.CreateCSharp(code, parseOptions))
{
var testDocument = workspace.Documents.Single();
var position = testDocument.CursorPosition.Value;
var document = workspace.CurrentSolution.Projects.First().Documents.First();
if (string.IsNullOrEmpty(expectedContent))
{
await AssertNoContentAsync(workspace, document, position);
}
else
{
await AssertContentIsAsync(workspace, document, position, expectedContent, expectedDocumentationComment);
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="_NegotiateClient.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System.Security.Authentication.ExtendedProtection;
internal class NegotiateClient : ISessionAuthenticationModule {
internal const string AuthType = "Negotiate";
private const string negotiateHeader = "Negotiate";
private const string negotiateSignature = "negotiate";
private const string nego2Header = "Nego2";
private const string nego2Signature = "nego2";
public Authorization Authenticate(string challenge, WebRequest webRequest, ICredentials credentials) {
GlobalLog.Print("NegotiateClient::Authenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " calling DoAuthenticate()");
return DoAuthenticate(challenge, webRequest, credentials, false);
}
private Authorization DoAuthenticate(string challenge, WebRequest webRequest, ICredentials credentials, bool preAuthenticate) {
GlobalLog.Print("NegotiateClient::DoAuthenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " preAuthenticate:" + preAuthenticate.ToString());
GlobalLog.Assert(credentials != null, "NegotiateClient::DoAuthenticate()|credentials == null");
if (credentials == null) {
return null;
}
HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;
GlobalLog.Assert(httpWebRequest != null, "NegotiateClient::DoAuthenticate()|httpWebRequest == null");
GlobalLog.Assert(httpWebRequest.ChallengedUri != null, "NegotiateClient::DoAuthenticate()|httpWebRequest.ChallengedUri == null");
NTAuthentication authSession = null;
string incoming = null;
bool useNego2 = false; // In case of pre-auth we always use "Negotiate", never "Nego2".
if (!preAuthenticate) {
int index = GetSignatureIndex(challenge, out useNego2);
if (index < 0) {
return null;
}
int blobBegin = index + (useNego2 ? nego2Signature.Length : negotiateSignature.Length);
//
// there may be multiple challenges. If the next character after the
// package name is not a comma then it is challenge data
//
if (challenge.Length > blobBegin && challenge[blobBegin] != ',') {
++blobBegin;
}
else {
index = -1;
}
if (index >= 0 && challenge.Length > blobBegin)
{
// Strip other modules information in case of multiple challenges
// i.e do not take ", NTLM" as part of the following Negotiate blob
// Negotiate TlRMTVNTUAACAAAADgAOADgAAAA1wo ... MAbwBmAHQALgBjAG8AbQAAAAAA,NTLM
index = challenge.IndexOf(',', blobBegin);
if (index != -1)
incoming = challenge.Substring(blobBegin, index - blobBegin);
else
incoming = challenge.Substring(blobBegin);
}
authSession = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this);
GlobalLog.Print("NegotiateClient::DoAuthenticate() key:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " retrieved authSession:" + ValidationHelper.HashString(authSession));
}
if (authSession==null)
{
// Credentials are always set for "Negotiate", never for "Nego2". A customer shouldn't even know
// about "Nego2".
NetworkCredential NC = credentials.GetCredential(httpWebRequest.ChallengedUri, negotiateSignature);
GlobalLog.Print("NegotiateClient::DoAuthenticate() GetCredential() returns:" + ValidationHelper.ToString(NC));
string username = string.Empty;
if (NC == null || (!(NC is SystemNetworkCredential) && (username = NC.InternalGetUserName()).Length == 0))
{
return null;
}
ICredentialPolicy policy = AuthenticationManager.CredentialPolicy;
if (policy != null && !policy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, NC, this))
return null;
SpnToken spn = httpWebRequest.CurrentAuthenticationState.GetComputeSpn(httpWebRequest);
GlobalLog.Print("NegotiateClient::Authenticate() ChallengedSpn:" + ValidationHelper.ToString(spn));
ChannelBinding binding = null;
if (httpWebRequest.CurrentAuthenticationState.TransportContext != null)
{
binding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint);
}
authSession =
new NTAuthentication(
AuthType,
NC,
spn,
httpWebRequest,
binding);
GlobalLog.Print("NegotiateClient::DoAuthenticate() setting SecurityContext for:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " to authSession:" + ValidationHelper.HashString(authSession));
httpWebRequest.CurrentAuthenticationState.SetSecurityContext(authSession, this);
}
string clientResponse = authSession.GetOutgoingBlob(incoming);
if (clientResponse==null) {
return null;
}
bool canShareConnection = httpWebRequest.UnsafeOrProxyAuthenticatedConnectionSharing;
if (canShareConnection) {
httpWebRequest.LockConnection = true;
}
// this is the first leg of an NTLM handshake,
// set the NtlmKeepAlive override *STRICTLY* only in this case.
httpWebRequest.NtlmKeepAlive = incoming==null && authSession.IsValidContext && !authSession.IsKerberos;
// If we received a "Nego2" header value from the server, we'll respond with "Nego2" in the "Authorization"
// header. If the server sent a "Negotiate" header value or if pre-authenticate is used (i.e. the auth blob
// is sent with the first request), we send "Negotiate" in the "Authorization" header.
return AuthenticationManager.GetGroupAuthorization(this, (useNego2 ? nego2Header : negotiateHeader) +
" " + clientResponse, authSession.IsCompleted, authSession, canShareConnection, authSession.IsKerberos);
}
public bool CanPreAuthenticate {
get {
return true;
}
}
public Authorization PreAuthenticate(WebRequest webRequest, ICredentials credentials) {
GlobalLog.Print("NegotiateClient::PreAuthenticate() webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " calling DoAuthenticate()");
return DoAuthenticate(null, webRequest, credentials, true);
}
public string AuthenticationType {
get {
return AuthType;
}
}
//
// called when getting the final blob on the 200 OK from the server
//
public bool Update(string challenge, WebRequest webRequest) {
GlobalLog.Print("NegotiateClient::Update(): " + challenge);
HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;
GlobalLog.Assert(httpWebRequest != null, "NegotiateClient::Update()|httpWebRequest == null");
GlobalLog.Assert(httpWebRequest.ChallengedUri != null, "NegotiateClient::Update()|httpWebRequest.ChallengedUri == null");
//
// try to retrieve the state of the ongoing handshake
//
NTAuthentication authSession = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this);
GlobalLog.Print("NegotiateClient::Update() key:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " retrieved authSession:" + ValidationHelper.HashString(authSession));
if (authSession==null) {
GlobalLog.Print("NegotiateClient::Update() null session returning true");
return true;
}
GlobalLog.Print("NegotiateClient::Update() authSession.IsCompleted:" + authSession.IsCompleted.ToString());
if (!authSession.IsCompleted && httpWebRequest.CurrentAuthenticationState.StatusCodeMatch==httpWebRequest.ResponseStatusCode) {
GlobalLog.Print("NegotiateClient::Update() still handshaking (based on status code) returning false");
return false;
}
// now possibly close the ConnectionGroup after authentication is done.
if (!httpWebRequest.UnsafeOrProxyAuthenticatedConnectionSharing) {
GlobalLog.Print("NegotiateClient::Update() releasing ConnectionGroup:" + httpWebRequest.GetConnectionGroupLine());
httpWebRequest.ServicePoint.ReleaseConnectionGroup(httpWebRequest.GetConnectionGroupLine());
}
//
// the whole point here is to close the Security Context (this will complete the authentication handshake
// with server authentication for schemese that support it such as Kerberos)
//
bool useNego2 = true;
int index = challenge==null ? -1 : GetSignatureIndex(challenge, out useNego2);
if (index>=0) {
int blobBegin = index + (useNego2 ? nego2Signature.Length : negotiateSignature.Length);
string incoming = null;
//
// there may be multiple challenges. If the next character after the
// package name is not a comma then it is challenge data
//
if (challenge.Length > blobBegin && challenge[blobBegin] != ',') {
++blobBegin;
} else {
index = -1;
}
if (index >= 0 && challenge.Length > blobBegin) {
incoming = challenge.Substring(blobBegin);
}
GlobalLog.Print("NegotiateClient::Update() this must be a final incoming blob:[" + ValidationHelper.ToString(incoming) + "]");
string clientResponse = authSession.GetOutgoingBlob(incoming);
httpWebRequest.CurrentAuthenticationState.Authorization.MutuallyAuthenticated = authSession.IsMutualAuthFlag;
GlobalLog.Print("NegotiateClient::Update() GetOutgoingBlob() returns clientResponse:[" + ValidationHelper.ToString(clientResponse) + "] IsCompleted:" + authSession.IsCompleted.ToString());
}
// Extract the CBT we used and cache it for future requests that want to do preauth
httpWebRequest.ServicePoint.SetCachedChannelBinding(httpWebRequest.ChallengedUri, authSession.ChannelBinding);
GlobalLog.Print("NegotiateClient::Update() session removed and ConnectionGroup released returning true");
ClearSession(httpWebRequest);
return true;
}
public void ClearSession(WebRequest webRequest) {
HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;
GlobalLog.Assert(httpWebRequest != null, "NegotiateClient::ClearSession()|httpWebRequest == null");
httpWebRequest.CurrentAuthenticationState.ClearSession();
}
public bool CanUseDefaultCredentials {
get {
return true;
}
}
private static int GetSignatureIndex(string challenge, out bool useNego2) {
// Negotiate supports two header fields "Nego2" and "Negotiate". If we find "Nego2" we use it,
// otherwise we fall back to "Negotiate" (if available).
useNego2 = true;
int index = -1;
// Consider Nego2 headers only on Win7 and later. Older OS version don't support LiveSSP.
if (ComNetOS.IsWin7orLater) {
index = AuthenticationManager.FindSubstringNotInQuotes(challenge, nego2Signature);
}
if (index < 0) {
useNego2 = false;
index = AuthenticationManager.FindSubstringNotInQuotes(challenge, negotiateSignature);
}
return index;
}
}; // class NegotiateClient
} // namespace System.Net
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Xml;
using System.Xml.XPath;
using NUnit.Framework;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.CoreXml
{
[TestFixture]
public class FrameworkXmlTests
{
private const string Xml1 = @"<root>
<items>
<item1 />
<item2>
<item21>text21</item21>
</item2>
<item3>
<item31>text31</item31>
</item3>
<item4 />
<item5 />
<item6 />
</items>
</root>";
// Umbraco : the following test shows that when legacy imports the whole tree in a
// "contentAll" xslt macro parameter, the entire collection of nodes is cloned ie is
// duplicated.
//
// What is the impact on memory?
// What happens for non-xslt macros?
[Test]
public void ImportNodeClonesImportedNode()
{
var doc1 = new XmlDocument();
doc1.LoadXml(Xml1);
XmlNode node1 = doc1.SelectSingleNode("//item2");
Assert.IsNotNull(node1);
var doc2 = new XmlDocument();
doc2.LoadXml("<nodes />");
XmlNode node2 = doc2.ImportNode(node1, true);
XmlElement root2 = doc2.DocumentElement;
Assert.IsNotNull(root2);
root2.AppendChild(node2);
XmlNode node3 = doc2.SelectSingleNode("//item2");
Assert.AreNotSame(node1, node2); // has been cloned
Assert.AreSame(node2, node3); // has been appended
Assert.AreNotSame(node1.FirstChild, node2.FirstChild); // deep clone
}
// Umbraco: the CanRemove...NodeAndNavigate tests shows that if the underlying XmlDocument
// is modified while navigating, then strange situations can be created. For xslt macros,
// the result depends on what the xslt engine is doing at the moment = unpredictable.
//
// What happens for non-xslt macros?
[Test]
public void CanRemoveCurrentNodeAndNavigate()
{
var doc1 = new XmlDocument();
doc1.LoadXml(Xml1);
XPathNavigator nav1 = doc1.CreateNavigator();
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("root", nav1.Name);
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("items", nav1.Name);
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("item1", nav1.Name);
Assert.IsTrue(nav1.MoveToNext());
Assert.AreEqual("item2", nav1.Name);
XmlNode node1 = doc1.SelectSingleNode("//item2");
Assert.IsNotNull(node1);
XmlNode parent1 = node1.ParentNode;
Assert.IsNotNull(parent1);
parent1.RemoveChild(node1);
// navigator now navigates on an isolated fragment
// that is rooted on the node that was removed
Assert.AreEqual("item2", nav1.Name);
Assert.IsFalse(nav1.MoveToPrevious());
Assert.IsFalse(nav1.MoveToNext());
Assert.IsFalse(nav1.MoveToParent());
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("item21", nav1.Name);
Assert.IsTrue(nav1.MoveToParent());
Assert.AreEqual("item2", nav1.Name);
nav1.MoveToRoot();
Assert.AreEqual("item2", nav1.Name);
}
[Test]
public void CanRemovePathNodeAndNavigate()
{
var doc1 = new XmlDocument();
doc1.LoadXml(Xml1);
XPathNavigator nav1 = doc1.CreateNavigator();
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("root", nav1.Name);
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("items", nav1.Name);
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("item1", nav1.Name);
Assert.IsTrue(nav1.MoveToNext());
Assert.AreEqual("item2", nav1.Name);
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("item21", nav1.Name);
XmlNode node1 = doc1.SelectSingleNode("//item2");
Assert.IsNotNull(node1);
XmlNode parent1 = node1.ParentNode;
Assert.IsNotNull(parent1);
parent1.RemoveChild(node1);
// navigator now navigates on an isolated fragment
// that is rooted on the node that was removed
Assert.AreEqual("item21", nav1.Name);
Assert.IsTrue(nav1.MoveToParent());
Assert.AreEqual("item2", nav1.Name);
Assert.IsFalse(nav1.MoveToPrevious());
Assert.IsFalse(nav1.MoveToNext());
Assert.IsFalse(nav1.MoveToParent());
nav1.MoveToRoot();
Assert.AreEqual("item2", nav1.Name);
}
[Test]
public void CanRemoveOutOfPathNodeAndNavigate()
{
var doc1 = new XmlDocument();
doc1.LoadXml(Xml1);
XPathNavigator nav1 = doc1.CreateNavigator();
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("root", nav1.Name);
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("items", nav1.Name);
Assert.IsTrue(nav1.MoveToFirstChild());
Assert.AreEqual("item1", nav1.Name);
Assert.IsTrue(nav1.MoveToNext());
Assert.AreEqual("item2", nav1.Name);
Assert.IsTrue(nav1.MoveToNext());
Assert.AreEqual("item3", nav1.Name);
Assert.IsTrue(nav1.MoveToNext());
Assert.AreEqual("item4", nav1.Name);
XmlNode node1 = doc1.SelectSingleNode("//item2");
Assert.IsNotNull(node1);
XmlNode parent1 = node1.ParentNode;
Assert.IsNotNull(parent1);
parent1.RemoveChild(node1);
// navigator sees the change
Assert.AreEqual("item4", nav1.Name);
Assert.IsTrue(nav1.MoveToPrevious());
Assert.AreEqual("item3", nav1.Name);
Assert.IsTrue(nav1.MoveToPrevious());
Assert.AreEqual("item1", nav1.Name);
}
// Umbraco: the following test shows that if the underlying XmlDocument is modified while
// iterating, then strange situations can be created. For xslt macros, the result depends
// on what the xslt engine is doing at the moment = unpredictable.
//
// What happens for non-xslt macros?
[Test]
public void CanRemoveNodeAndIterate()
{
var doc1 = new XmlDocument();
doc1.LoadXml(Xml1);
XPathNavigator nav1 = doc1.CreateNavigator();
XPathNodeIterator iter1 = nav1.Select("//items/*");
XPathNodeIterator iter2 = nav1.Select("//items/*");
Assert.AreEqual(6, iter1.Count);
XmlNode node1 = doc1.SelectSingleNode("//item2");
Assert.IsNotNull(node1);
XmlNode parent1 = node1.ParentNode;
Assert.IsNotNull(parent1);
parent1.RemoveChild(node1);
// iterator partially sees the change
Assert.AreEqual(6, iter1.Count); // has been cached, not updated
Assert.AreEqual(5, iter2.Count); // not calculated yet, correct value
int count = 0;
while (iter1.MoveNext())
{
count++;
}
Assert.AreEqual(5, count);
}
[Test]
public void OldFrameworkXPathBugIsFixed()
{
// see http://bytes.com/topic/net/answers/177129-reusing-xpathexpression-multiple-iterations
var doc = new XmlDocument();
doc.LoadXml("<root><a><a1/><a2/></a><b/></root>");
XPathNavigator nav = doc.CreateNavigator();
XPathExpression expr = nav.Compile("*");
nav.MoveToFirstChild(); // root
XPathNodeIterator iter1 = nav.Select(expr);
iter1.MoveNext(); // root/a
XPathNodeIterator iter2 = iter1.Current.Select(expr);
iter2.MoveNext(); // /root/a/a1
iter2.MoveNext(); // /root/a/a2
// used to fail because iter1 and iter2 would conflict
Assert.IsTrue(iter1.MoveNext()); // root/b
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.ResultObjects;
using WebsitePanel.Providers.Common;
namespace WebsitePanel.Portal
{
public partial class SettingsExchangeMailboxPlansPolicy : WebsitePanelControlBase, IUserSettingsEditorControl
{
private bool RetentionPolicy
{
get
{
return Request["SettingsName"].ToLower().Contains("retentionpolicy");
}
}
private string MainValidationGroup
{
get { return RetentionPolicy ? "CreateRetentionPolicy" : "CreateMailboxPlan"; }
}
public void BindSettings(UserSettings settings)
{
secMailboxPlan.Text = RetentionPolicy ? GetLocalizedString("secRetentionPolicy.Text") : GetLocalizedString("secMailboxPlan.Text");
BindMailboxPlans();
txtStatus.Visible = false;
secMailboxFeatures.Visible = !RetentionPolicy;
secMailboxGeneral.Visible = !RetentionPolicy;
secStorageQuotas.Visible = !RetentionPolicy;
secDeleteRetention.Visible = !RetentionPolicy;
secLitigationHold.Visible = !RetentionPolicy;
secArchiving.Visible = !RetentionPolicy;
secRetentionPolicyTags.Visible = RetentionPolicy;
gvMailboxPlans.Columns[4].Visible = !RetentionPolicy;
gvMailboxPlans.Columns[5].Visible = !RetentionPolicy;
btnAddMailboxPlan.ValidationGroup = MainValidationGroup;
btnUpdateMailboxPlan.ValidationGroup = MainValidationGroup;
valRequireMailboxPlan.ValidationGroup = MainValidationGroup;
UpdateTags();
}
private void BindMailboxPlans()
{
Providers.HostedSolution.Organization[] orgs = GetOrganizations();
if ((orgs != null) & (orgs.GetLength(0) > 0))
{
ExchangeMailboxPlan[] list = ES.Services.ExchangeServer.GetExchangeMailboxPlans(orgs[0].Id, RetentionPolicy);
gvMailboxPlans.DataSource = list;
gvMailboxPlans.DataBind();
}
// enable set default plan button if organization has two or more plans
btnSetDefaultMailboxPlan.Enabled = gvMailboxPlans.Rows.Count > 1;
btnUpdateMailboxPlan.Enabled = (string.IsNullOrEmpty(txtMailboxPlan.Text)) ? false : true;
}
public void btnAddMailboxPlan_Click(object sender, EventArgs e)
{
if (!RetentionPolicy)
Page.Validate(MainValidationGroup);
if (!Page.IsValid)
return;
Providers.HostedSolution.ExchangeMailboxPlan plan = new Providers.HostedSolution.ExchangeMailboxPlan();
plan.MailboxPlan = txtMailboxPlan.Text;
plan.Archiving = RetentionPolicy;
if (RetentionPolicy)
{
}
else
{
plan.MailboxSizeMB = mailboxSize.QuotaValue;
plan.IsDefault = false;
plan.MaxRecipients = maxRecipients.QuotaValue;
plan.MaxSendMessageSizeKB = maxSendMessageSizeKB.QuotaValue;
plan.MaxReceiveMessageSizeKB = maxReceiveMessageSizeKB.QuotaValue;
plan.EnablePOP = chkPOP3.Checked;
plan.EnableIMAP = chkIMAP.Checked;
plan.EnableOWA = chkOWA.Checked;
plan.EnableMAPI = chkMAPI.Checked;
plan.EnableActiveSync = chkActiveSync.Checked;
plan.IssueWarningPct = sizeIssueWarning.ValueKB;
if ((plan.IssueWarningPct == 0)) plan.IssueWarningPct = 100;
plan.ProhibitSendPct = sizeProhibitSend.ValueKB;
if ((plan.ProhibitSendPct == 0)) plan.ProhibitSendPct = 100;
plan.ProhibitSendReceivePct = sizeProhibitSendReceive.ValueKB;
if ((plan.ProhibitSendReceivePct == 0)) plan.ProhibitSendReceivePct = 100;
plan.KeepDeletedItemsDays = daysKeepDeletedItems.ValueDays;
plan.HideFromAddressBook = chkHideFromAddressBook.Checked;
plan.AllowLitigationHold = chkEnableLitigationHold.Checked;
plan.RecoverableItemsSpace = recoverableItemsSpace.QuotaValue;
plan.RecoverableItemsWarningPct = recoverableItemsWarning.ValueKB;
if ((plan.RecoverableItemsWarningPct == 0)) plan.RecoverableItemsWarningPct = 100;
plan.LitigationHoldMsg = txtLitigationHoldMsg.Text.Trim();
plan.LitigationHoldUrl = txtLitigationHoldUrl.Text.Trim();
plan.EnableArchiving = chkEnableArchiving.Checked;
plan.ArchiveSizeMB = archiveQuota.QuotaValue;
plan.ArchiveWarningPct = archiveWarningQuota.ValueKB;
if ((plan.ArchiveWarningPct == 0)) plan.ArchiveWarningPct = 100;
}
if (PanelSecurity.SelectedUser.Role == UserRole.Administrator)
plan.MailboxPlanType = (int)ExchangeMailboxPlanType.Administrator;
else
if (PanelSecurity.SelectedUser.Role == UserRole.Reseller)
plan.MailboxPlanType = (int)ExchangeMailboxPlanType.Reseller;
Providers.HostedSolution.Organization[] orgs = GetOrganizations();
if ((orgs != null) & (orgs.GetLength(0) > 0))
{
int planId = ES.Services.ExchangeServer.AddExchangeMailboxPlan(orgs[0].Id, plan);
if (planId < 0)
{
messageBox.ShowResultMessage(planId);
return;
}
if (RetentionPolicy)
SaveTags(orgs[0].Id, planId);
}
BindMailboxPlans();
}
protected void gvMailboxPlan_RowCommand(object sender, GridViewCommandEventArgs e)
{
int mailboxPlanId = Utils.ParseInt(e.CommandArgument.ToString(), 0);
Providers.HostedSolution.Organization[] orgs = null;
Providers.HostedSolution.ExchangeMailboxPlan plan;
switch (e.CommandName)
{
case "DeleteItem":
try
{
orgs = GetOrganizations();
plan = ES.Services.ExchangeServer.GetExchangeMailboxPlan(orgs[0].Id, mailboxPlanId);
if (plan.ItemId != orgs[0].Id)
{
messageBox.ShowErrorMessage("EXCHANGE_UNABLE_USE_SYSTEMPLAN");
BindMailboxPlans();
return;
}
int result = ES.Services.ExchangeServer.DeleteExchangeMailboxPlan(orgs[0].Id, mailboxPlanId);
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
ViewState["MailboxPlanID"] = null;
txtMailboxPlan.Text = string.Empty;
mailboxSize.QuotaValue = 0;
maxRecipients.QuotaValue = 0;
maxSendMessageSizeKB.QuotaValue = 0;
maxReceiveMessageSizeKB.QuotaValue = 0;
chkPOP3.Checked = false;
chkIMAP.Checked = false;
chkOWA.Checked = false;
chkMAPI.Checked = false;
chkActiveSync.Checked = false;
sizeIssueWarning.ValueKB = -1;
sizeProhibitSend.ValueKB = -1;
sizeProhibitSendReceive.ValueKB = -1;
daysKeepDeletedItems.ValueDays = -1;
chkHideFromAddressBook.Checked = false;
chkEnableLitigationHold.Checked = false;
recoverableItemsSpace.QuotaValue = 0;
recoverableItemsWarning.ValueKB = -1;
txtLitigationHoldMsg.Text = string.Empty;
txtLitigationHoldUrl.Text = string.Empty;
chkEnableArchiving.Checked = false;
archiveQuota.QuotaValue = 0;
archiveWarningQuota.ValueKB = 0;
ViewState["Tags"] = null;
gvPolicy.DataSource = null;
gvPolicy.DataBind();
UpdateTags();
btnUpdateMailboxPlan.Enabled = (string.IsNullOrEmpty(txtMailboxPlan.Text)) ? false : true;
}
catch (Exception)
{
messageBox.ShowErrorMessage("EXCHANGE_DELETE_MAILBOXPLAN");
}
BindMailboxPlans();
break;
case "EditItem":
ViewState["MailboxPlanID"] = mailboxPlanId;
orgs = GetOrganizations();
plan = ES.Services.ExchangeServer.GetExchangeMailboxPlan(orgs[0].Id, mailboxPlanId);
txtMailboxPlan.Text = plan.MailboxPlan;
if (RetentionPolicy)
{
List<ExchangeMailboxPlanRetentionPolicyTag> tags = new List<ExchangeMailboxPlanRetentionPolicyTag>();
tags.AddRange(ES.Services.ExchangeServer.GetExchangeMailboxPlanRetentionPolicyTags(plan.MailboxPlanId));
ViewState["Tags"] = tags;
gvPolicy.DataSource = tags;
gvPolicy.DataBind();
UpdateTags();
}
else
{
mailboxSize.QuotaValue = plan.MailboxSizeMB;
maxRecipients.QuotaValue = plan.MaxRecipients;
maxSendMessageSizeKB.QuotaValue = plan.MaxSendMessageSizeKB;
maxReceiveMessageSizeKB.QuotaValue = plan.MaxReceiveMessageSizeKB;
chkPOP3.Checked = plan.EnablePOP;
chkIMAP.Checked = plan.EnableIMAP;
chkOWA.Checked = plan.EnableOWA;
chkMAPI.Checked = plan.EnableMAPI;
chkActiveSync.Checked = plan.EnableActiveSync;
sizeIssueWarning.ValueKB = plan.IssueWarningPct;
sizeProhibitSend.ValueKB = plan.ProhibitSendPct;
sizeProhibitSendReceive.ValueKB = plan.ProhibitSendReceivePct;
if (plan.KeepDeletedItemsDays != -1)
daysKeepDeletedItems.ValueDays = plan.KeepDeletedItemsDays;
chkHideFromAddressBook.Checked = plan.HideFromAddressBook;
chkEnableLitigationHold.Checked = plan.AllowLitigationHold;
recoverableItemsSpace.QuotaValue = plan.RecoverableItemsSpace;
recoverableItemsWarning.ValueKB = plan.RecoverableItemsWarningPct;
txtLitigationHoldMsg.Text = plan.LitigationHoldMsg;
txtLitigationHoldUrl.Text = plan.LitigationHoldUrl;
chkEnableArchiving.Checked = plan.EnableArchiving;
archiveQuota.QuotaValue = plan.ArchiveSizeMB;
archiveWarningQuota.ValueKB = plan.ArchiveWarningPct;
}
btnUpdateMailboxPlan.Enabled = (string.IsNullOrEmpty(txtMailboxPlan.Text)) ? false : true;
break;
case "RestampItem":
RestampMailboxes(mailboxPlanId, mailboxPlanId);
break;
case "StampUnassigned":
RestampMailboxes(-1, mailboxPlanId);
break;
}
}
public string GetPlanType(int mailboxPlanType)
{
string imgName = string.Empty;
ExchangeMailboxPlanType planType = (ExchangeMailboxPlanType)mailboxPlanType;
switch (planType)
{
case ExchangeMailboxPlanType.Reseller:
imgName = "company24.png";
break;
case ExchangeMailboxPlanType.Administrator:
imgName = "company24.png";
break;
default:
imgName = "admin_16.png";
break;
}
return GetThemedImage("Exchange/" + imgName);
}
public void SaveSettings(UserSettings settings)
{
settings["ExchangeMailboxPlansPolicy"] = "";
}
protected void btnUpdateMailboxPlan_Click(object sender, EventArgs e)
{
Page.Validate(MainValidationGroup);
if (!Page.IsValid)
return;
if (ViewState["MailboxPlanID"] == null)
return;
int mailboxPlanId = (int)ViewState["MailboxPlanID"];
Providers.HostedSolution.Organization[] orgs = GetOrganizations();
Providers.HostedSolution.ExchangeMailboxPlan plan;
plan = ES.Services.ExchangeServer.GetExchangeMailboxPlan(orgs[0].Id, mailboxPlanId);
if (plan.ItemId != orgs[0].Id)
{
messageBox.ShowErrorMessage("EXCHANGE_UNABLE_USE_SYSTEMPLAN");
BindMailboxPlans();
return;
}
plan = new Providers.HostedSolution.ExchangeMailboxPlan();
plan.MailboxPlanId = (int)ViewState["MailboxPlanID"];
plan.MailboxPlan = txtMailboxPlan.Text;
plan.Archiving = RetentionPolicy;
if (RetentionPolicy)
{
}
else
{
plan.MailboxSizeMB = mailboxSize.QuotaValue;
plan.IsDefault = false;
plan.MaxRecipients = maxRecipients.QuotaValue;
plan.MaxSendMessageSizeKB = maxSendMessageSizeKB.QuotaValue;
plan.MaxReceiveMessageSizeKB = maxReceiveMessageSizeKB.QuotaValue;
plan.EnablePOP = chkPOP3.Checked;
plan.EnableIMAP = chkIMAP.Checked;
plan.EnableOWA = chkOWA.Checked;
plan.EnableMAPI = chkMAPI.Checked;
plan.EnableActiveSync = chkActiveSync.Checked;
plan.IssueWarningPct = sizeIssueWarning.ValueKB;
if ((plan.IssueWarningPct == 0)) plan.IssueWarningPct = 100;
plan.ProhibitSendPct = sizeProhibitSend.ValueKB;
if ((plan.ProhibitSendPct == 0)) plan.ProhibitSendPct = 100;
plan.ProhibitSendReceivePct = sizeProhibitSendReceive.ValueKB;
if ((plan.ProhibitSendReceivePct == 0)) plan.ProhibitSendReceivePct = 100;
plan.KeepDeletedItemsDays = daysKeepDeletedItems.ValueDays;
plan.HideFromAddressBook = chkHideFromAddressBook.Checked;
plan.AllowLitigationHold = chkEnableLitigationHold.Checked;
plan.RecoverableItemsSpace = recoverableItemsSpace.QuotaValue;
plan.RecoverableItemsWarningPct = recoverableItemsWarning.ValueKB;
if ((plan.RecoverableItemsWarningPct == 0)) plan.RecoverableItemsWarningPct = 100;
plan.LitigationHoldMsg = txtLitigationHoldMsg.Text.Trim();
plan.LitigationHoldUrl = txtLitigationHoldUrl.Text.Trim();
plan.EnableArchiving = chkEnableArchiving.Checked;
plan.ArchiveSizeMB = archiveQuota.QuotaValue;
plan.ArchiveWarningPct = archiveWarningQuota.ValueKB;
if ((plan.ArchiveWarningPct == 0)) plan.ArchiveWarningPct = 100;
}
if (PanelSecurity.SelectedUser.Role == UserRole.Administrator)
plan.MailboxPlanType = (int)ExchangeMailboxPlanType.Administrator;
else
if (PanelSecurity.SelectedUser.Role == UserRole.Reseller)
plan.MailboxPlanType = (int)ExchangeMailboxPlanType.Reseller;
if ((orgs != null) & (orgs.GetLength(0) > 0))
{
int result = ES.Services.ExchangeServer.UpdateExchangeMailboxPlan(orgs[0].Id, plan);
if (result < 0)
{
messageBox.ShowErrorMessage("EXCHANGE_UPDATEPLANS");
}
else
{
if (RetentionPolicy)
{
if (SaveTags(orgs[0].Id, mailboxPlanId))
messageBox.ShowSuccessMessage("EXCHANGE_UPDATEPLANS");
}
else
messageBox.ShowSuccessMessage("EXCHANGE_UPDATEPLANS");
}
}
BindMailboxPlans();
}
private bool PlanExists(ExchangeMailboxPlan plan, ExchangeMailboxPlan[] plans)
{
bool result = false;
foreach (ExchangeMailboxPlan p in plans)
{
if (p.MailboxPlan.ToLower() == plan.MailboxPlan.ToLower())
{
result = true;
break;
}
}
return result;
}
protected void txtMailboxPlan_TextChanged(object sender, EventArgs e)
{
btnUpdateMailboxPlan.Enabled = (string.IsNullOrEmpty(txtMailboxPlan.Text)) ? false : true;
}
private void RestampMailboxes(int sourceMailboxPlanId, int destinationMailboxPlanId)
{
UserInfo[] UsersInfo = ES.Services.Users.GetUsers(PanelSecurity.SelectedUserId, true);
try
{
foreach (UserInfo ui in UsersInfo)
{
PackageInfo[] Packages = ES.Services.Packages.GetPackages(ui.UserId);
if ((Packages != null) & (Packages.GetLength(0) > 0))
{
foreach (PackageInfo Package in Packages)
{
Providers.HostedSolution.Organization[] orgs = null;
orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(Package.PackageId, false);
if ((orgs != null) & (orgs.GetLength(0) > 0))
{
foreach (Organization org in orgs)
{
if (!string.IsNullOrEmpty(org.GlobalAddressList))
{
ExchangeAccount[] Accounts = ES.Services.ExchangeServer.GetExchangeAccountByMailboxPlanId(org.Id, sourceMailboxPlanId);
foreach (ExchangeAccount a in Accounts)
{
txtStatus.Text = "Completed";
int result = ES.Services.ExchangeServer.SetExchangeMailboxPlan(org.Id, a.AccountId, destinationMailboxPlanId, a.ArchivingMailboxPlanId, a.EnableArchiving);
if (result < 0)
{
BindMailboxPlans();
txtStatus.Text = "Error: " + a.AccountName;
messageBox.ShowErrorMessage("EXCHANGE_STAMPMAILBOXES");
return;
}
}
}
}
}
}
}
}
messageBox.ShowSuccessMessage("EXCHANGE_STAMPMAILBOXES");
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("EXCHANGE_FAILED_TO_STAMP", ex);
}
BindMailboxPlans();
}
protected void gvPolicy_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "DeleteItem":
try
{
int tagId;
if (!int.TryParse(e.CommandArgument.ToString(), out tagId))
return;
List<ExchangeMailboxPlanRetentionPolicyTag> tags = ViewState["Tags"] as List<ExchangeMailboxPlanRetentionPolicyTag>;
if (tags == null) return;
int i = tags.FindIndex(x => x.TagID == tagId);
if (i >= 0) tags.RemoveAt(i);
ViewState["Tags"] = tags;
gvPolicy.DataSource = tags;
gvPolicy.DataBind();
UpdateTags();
}
catch (Exception)
{
}
break;
}
}
protected void bntAddTag_Click(object sender, EventArgs e)
{
int addTagId;
if (!int.TryParse(ddTags.SelectedValue, out addTagId))
return;
Providers.HostedSolution.ExchangeRetentionPolicyTag tag = ES.Services.ExchangeServer.GetExchangeRetentionPolicyTag(PanelRequest.ItemID, addTagId);
if (tag == null) return;
List<ExchangeMailboxPlanRetentionPolicyTag> res = ViewState["Tags"] as List<ExchangeMailboxPlanRetentionPolicyTag>;
if (res == null) res = new List<ExchangeMailboxPlanRetentionPolicyTag>();
ExchangeMailboxPlanRetentionPolicyTag add = new ExchangeMailboxPlanRetentionPolicyTag();
add.MailboxPlanId = PanelRequest.GetInt("MailboxPlanId");
add.TagID = tag.TagID;
add.TagName = tag.TagName;
res.Add(add);
ViewState["Tags"] = res;
gvPolicy.DataSource = res;
gvPolicy.DataBind();
UpdateTags();
}
protected void UpdateTags()
{
if (RetentionPolicy)
{
ddTags.Items.Clear();
Organization[] orgs = GetOrganizations();
if ((orgs != null) && (orgs.GetLength(0) > 0))
{
Providers.HostedSolution.ExchangeRetentionPolicyTag[] allTags = ES.Services.ExchangeServer.GetExchangeRetentionPolicyTags(orgs[0].Id);
List<ExchangeMailboxPlanRetentionPolicyTag> selectedTags = ViewState["Tags"] as List<ExchangeMailboxPlanRetentionPolicyTag>;
foreach (Providers.HostedSolution.ExchangeRetentionPolicyTag tag in allTags)
{
if (selectedTags != null)
{
if (selectedTags.Find(x => x.TagID == tag.TagID) != null)
continue;
}
ddTags.Items.Add(new System.Web.UI.WebControls.ListItem(tag.TagName, tag.TagID.ToString()));
}
}
}
}
protected bool SaveTags(int ItemId, int planId)
{
ExchangeMailboxPlanRetentionPolicyTag[] currenttags = ES.Services.ExchangeServer.GetExchangeMailboxPlanRetentionPolicyTags(planId);
foreach (ExchangeMailboxPlanRetentionPolicyTag tag in currenttags)
{
ResultObject res = ES.Services.ExchangeServer.DeleteExchangeMailboxPlanRetentionPolicyTag(ItemId, planId, tag.PlanTagID);
if (!res.IsSuccess)
{
messageBox.ShowMessage(res, "EXCHANGE_UPDATEPLANS", null);
return false;
}
}
List<ExchangeMailboxPlanRetentionPolicyTag> tags = ViewState["Tags"] as List<ExchangeMailboxPlanRetentionPolicyTag>;
if (tags != null)
{
foreach (ExchangeMailboxPlanRetentionPolicyTag tag in tags)
{
tag.MailboxPlanId = planId;
IntResult res = ES.Services.ExchangeServer.AddExchangeMailboxPlanRetentionPolicyTag(ItemId, tag);
if (!res.IsSuccess)
{
messageBox.ShowMessage(res, "EXCHANGE_UPDATEPLANS", null);
return false;
}
}
}
return true;
}
protected Organization[] GetOrganizations()
{
Organization[] orgs = null;
if (PanelSecurity.SelectedUserId != 1)
{
PackageInfo[] Packages = ES.Services.Packages.GetPackages(PanelSecurity.SelectedUserId);
if ((Packages != null) & (Packages.GetLength(0) > 0))
{
orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(Packages[0].PackageId, false);
}
}
else
{
orgs = ES.Services.ExchangeServer.GetExchangeOrganizations(1, false);
}
return orgs;
}
protected void btnSetDefaultMailboxPlan_Click(object sender, EventArgs e)
{
// get domain
int mailboxPlanId = Utils.ParseInt(Request.Form["DefaultMailboxPlan"], 0);
try
{
var orgs = GetOrganizations();
if ((orgs != null) && (orgs.GetLength(0) > 0))
{
ES.Services.ExchangeServer.SetOrganizationDefaultExchangeMailboxPlan(orgs[0].Id, mailboxPlanId);
messageBox.ShowSuccessMessage("EXCHANGE_SET_DEFAULT_MAILBOXPLAN");
// rebind domains
BindMailboxPlans();
}
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("EXCHANGE_SET_DEFAULT_MAILBOXPLAN", ex);
}
}
protected string IsChecked(bool val)
{
return val ? "checked" : "";
}
}
}
| |
#region License
//
// Author: Nate Kohari <nkohari@gmail.com>
// Copyright (c) 2007-2008, Enkari, Ltd.
//
// 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
#region Using Directives
using System;
using System.Collections.Generic;
#endregion
namespace Ninject.Core.Infrastructure
{
/// <summary>
/// A collection that organizes items by type.
/// </summary>
/// <typeparam name="TKey">The type of key.</typeparam>
/// <typeparam name="TBase">The base type of items stored in the collection.</typeparam>
public abstract class TypedCollection<TKey, TBase> : ITypedCollection<TKey, TBase>
where TBase : class
{
/*----------------------------------------------------------------------------------------*/
#region Fields
private readonly Dictionary<Type, Dictionary<TKey, TBase>> _items = new Dictionary<Type, Dictionary<TKey, TBase>>();
#endregion
/*----------------------------------------------------------------------------------------*/
#region Public Methods
/// <summary>
/// Adds the specified item to the collection.
/// </summary>
/// <typeparam name="T">The type to organize the item under.</typeparam>
/// <param name="item">The item to add.</param>
public void Add<T>(T item)
where T : TBase
{
DoAdd(typeof(T), item);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Adds the specified item to the collection.
/// </summary>
/// <param name="type">The type to organize the item under.</param>
/// <param name="item">The item to add.</param>
public void Add(Type type, TBase item)
{
DoAdd(type, item);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Adds the specified items to the collection.
/// </summary>
/// <typeparam name="T">The type to organize the items under.</typeparam>
/// <param name="items">The items to add.</param>
public void AddRange<T>(IEnumerable<T> items)
where T : TBase
{
DoAddRange(typeof(T), items);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Adds the specified items to the collection.
/// </summary>
/// <param name="type">The type to organize the items under.</param>
/// <param name="items">The items to add.</param>
public void AddRange(Type type, IEnumerable<TBase> items)
{
DoAddRange(type, items);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets a value indicating whether an item with the specified key has been organized under
/// the specified type.
/// </summary>
/// <typeparam name="T">The type the item is organized under.</typeparam>
/// <param name="key">The item's key.</param>
/// <returns><see langword="True"/> if the item has been defined, otherwise <see langword="false"/>.</returns>
public bool Has<T>(TKey key)
where T : TBase
{
return DoHas(typeof(T), key);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets a value indicating whether an item with the specified key has been organized under
/// the specified type.
/// </summary>
/// <param name="type">The type the item is organized under.</param>
/// <param name="key">The item's key.</param>
/// <returns><see langword="True"/> if the item has been defined, otherwise <see langword="false"/>.</returns>
public bool Has(Type type, TKey key)
{
return DoHas(type, key);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets a value indicating whether one or more items organized under the specified type.
/// </summary>
/// <typeparam name="T">The type to check.</typeparam>
/// <returns><see langword="True"/> if there are such items, otherwise <see langword="false"/>.</returns>
public bool HasOneOrMore<T>()
where T : TBase
{
return DoHasOneOrMore(typeof(T));
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets a value indicating whether one or more items organized under the specified type.
/// </summary>
/// <param name="type">The type check.</param>
/// <returns><see langword="True"/> if there are such items, otherwise <see langword="false"/>.</returns>
public bool HasOneOrMore(Type type)
{
return DoHasOneOrMore(type);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets the item with the specified key, organized under the specified type, if one has been defined.
/// </summary>
/// <typeparam name="T">The type the item is organized under.</typeparam>
/// <param name="key">The item's key.</param>
/// <returns>The item, or <see langword="null"/> if none has been defined.</returns>
public T Get<T>(TKey key)
where T : TBase
{
return (T)DoGet(typeof(T), key);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets the item with the specified key, organized under the specified type, if one has been defined.
/// </summary>
/// <param name="type">The type the item is organized under.</param>
/// <param name="key">The item's key.</param>
/// <returns>The item, or <see langword="null"/> if none has been defined.</returns>
public TBase Get(Type type, TKey key)
{
return DoGet(type, key);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets the first item in the collection that is organized under the specified type.
/// </summary>
/// <typeparam name="T">The type to check.</typeparam>
/// <returns>The item, or <see langword="null"/> if none has been defined.</returns>
public T GetOne<T>()
where T : TBase
{
return (T)DoGetOne(typeof(T));
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets the first item in the collection that is organized under the specified type.
/// </summary>
/// <param name="type">The type the item is organized under.</param>
/// <returns>The item, or <see langword="null"/> if none has been defined.</returns>
public TBase GetOne(Type type)
{
return DoGetOne(type);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets all items organized under the specified type.
/// </summary>
/// <typeparam name="T">The type the items are organized under.</typeparam>
/// <returns>A collection of items organized under the specified type.</returns>
public IList<T> GetAll<T>()
where T : TBase
{
return DoGetAll<T>(typeof(T));
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets all items organized under the specified type.
/// </summary>
/// <param name="type">The type the items are organized under.</param>
/// <returns>A collection of items organized under the specified type.</returns>
public IList<TBase> GetAll(Type type)
{
return DoGetAll<TBase>(type);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets the types that items are organized under.
/// </summary>
/// <returns>A collection of types that items are organized under.</returns>
public IList<Type> GetTypes()
{
return _items.Keys.ToList();
}
#endregion
/*----------------------------------------------------------------------------------------*/
#region Protected Methods
/// <summary>
/// Adds the specified item to the collection.
/// </summary>
/// <param name="type">The type to organize the item under.</param>
/// <param name="item">The item to add.</param>
protected virtual void DoAdd(Type type, TBase item)
{
Ensure.ArgumentNotNull(item, "item");
TKey key = GetKeyForItem(item);
if (!_items.ContainsKey(type))
_items.Add(type, new Dictionary<TKey, TBase>());
bool shouldAdd = true;
if (_items[type].ContainsKey(key))
shouldAdd = OnKeyCollision(type, key, item, _items[type][key]);
if (shouldAdd)
_items[type][key] = item;
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Adds the specified items to the collection.
/// </summary>
/// <param name="type">The type to organize the items under.</param>
/// <param name="items">The items to add.</param>
protected virtual void DoAddRange<T>(Type type, IEnumerable<T> items)
where T : TBase
{
Ensure.ArgumentNotNull(items, "items");
foreach (T item in items)
DoAdd(type, item);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets a value indicating whether an item with the specified key has been organized under
/// the specified type.
/// </summary>
/// <param name="type">The type the item is organized under.</param>
/// <param name="key">The item's key.</param>
/// <returns><see langword="True"/> if the item has been defined, otherwise <see langword="false"/>.</returns>
protected virtual bool DoHas(Type type, TKey key)
{
return _items.ContainsKey(type) && _items[type].ContainsKey(key);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets a value indicating whether one or more items organized under the specified type.
/// </summary>
/// <param name="type">The type check.</param>
/// <returns><see langword="True"/> if there are such items, otherwise <see langword="false"/>.</returns>
protected virtual bool DoHasOneOrMore(Type type)
{
return _items.ContainsKey(type);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets the item with the specified key, organized under the specified type, if one has been defined.
/// </summary>
/// <param name="type">The type the item is organized under.</param>
/// <param name="key">The item's key.</param>
/// <returns>The item, or <see langword="null"/> if none has been defined.</returns>
protected virtual TBase DoGet(Type type, TKey key)
{
return DoHas(type, key) ? _items[type][key] : null;
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets the first item in the collection that is organized under the specified type.
/// </summary>
/// <param name="type">The type the item is organized under.</param>
/// <returns>The item, or <see langword="null"/> if none has been defined.</returns>
protected virtual TBase DoGetOne(Type type)
{
return DoHasOneOrMore(type) ? _items[type].Values.First() : null;
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets all items organized under the specified type.
/// </summary>
/// <param name="type">The type the items are organized under.</param>
/// <returns>A collection of items organized under the specified type.</returns>
protected virtual IList<T> DoGetAll<T>(Type type)
where T : TBase
{
var matches = new List<T>();
if (_items.ContainsKey(type))
{
foreach (T item in _items[type].Values)
matches.Add(item);
}
return matches;
}
#endregion
/*----------------------------------------------------------------------------------------*/
#region Abstract Methods
/// <summary>
/// Gets the key for the specified item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>The key for the item.</returns>
protected abstract TKey GetKeyForItem(TBase item);
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Called when an item is added to the collection when an item with the same key already
/// exists in the collection, organized under the same type.
/// </summary>
/// <param name="type">The type the items are organized under.</param>
/// <param name="key">The key the items share.</param>
/// <param name="newItem">The new item that was added.</param>
/// <param name="existingItem">The item that already existed in the collection.</param>
/// <returns><see langword="True"/> if the new item should replace the existing item, otherwise <see langword="false"/>.</returns>
protected abstract bool OnKeyCollision(Type type, TKey key, TBase newItem, TBase existingItem);
#endregion
/*----------------------------------------------------------------------------------------*/
}
}
| |
/**
*--------------------------------------------------------------------+
* MersenneTwister.cs
*--------------------------------------------------------------------+
* Copyright DarkOverlordOfData (c) 2015
*--------------------------------------------------------------------+
*
* This file is a part of Bosco
*
* Bosco is free software; you can copy, modify, and distribute
* it under the terms of the MIT License
*
* MersenneTwister:
* Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
* All rights reserved.
*
*--------------------------------------------------------------------+
* MT19937 - An alternative PRNG
*
*/
using System;
using UnityEngine;
namespace Bosco.Utils {
public class MersenneTwister : IRandum {
private static int N = 624;
private static int M = 397;
private static int MATRIX_A = -1727483681;
private static int UPPER_MASK = -2147483648;
private static int LOWER_MASK = 2147483647;
public int[] mt = new int[N];
public int mti = N+1;
public MersenneTwister(int seed) {
Debug.Log("seed = "+seed);
init_genrand(seed);
}
public MersenneTwister(int[] init_key, int key_length) {
init_by_array(init_key, key_length);
}
public MersenneTwister() : this((int)((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds*100) & LOWER_MASK) {}
/*
* Generates a random boolean value.
*/
public bool NextBool() {
return (genrand_int32() & 1) == 1;
}
/*
* Generates a random real value from 0.0, inclusive, to 1.0, exclusive.
*/
public double NextDouble() {
return genrand_res53();
}
/*
* Generates a random int value from 0, inclusive, to max, exclusive.
*/
public int NextInt(int max) {
return (int)Math.Abs(genrand_res53() * (max*2));
}
public void init_genrand(int s) {
mt[0] = s & -1;
mti = 1;
while (mti < N) {
mt[mti] = 1812433253 * (mt[mti - 1] ^ (mt[mti - 1] >> 30)) + mti;
/*
# See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. #
# In the previous versions, MSBs of the seed affect #
# only MSBs of the array mt[]. #
# 2002/01/09 modified by Makoto Matsumoto #
*/
mt[mti] = (mt[mti] & -1) >> 0;
/*
# for >32 bit machines #
*/
mti++;
}
}
public void init_by_array(int[] init_key, int key_length) {
int i, j, k;
init_genrand(19650218);
i = 1;
j = 0;
k = N > key_length ? N : key_length;
while (k > 0) {
mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1664525)) + init_key[j] + j;
mt[i] &= -1;
i++;
j++;
if (i >= N) {
mt[0] = mt[N - 1];
i = 1;
}
if (j >= key_length) {
j = 0;
}
k--;
}
k = N - 1;
while (k > 0) {
mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1566083941)) - i;
mt[i] &= -1;
i++;
if (i >= N) {
mt[0] = mt[N - 1];
i = 1;
}
k--;
}
mt[0] = UPPER_MASK;
}
public int genrand_int32() {
int kk;
int y;
var mag01 = new int[]{0, MATRIX_A};
if (mti >= N) {
if (mti == N + 1) {
init_genrand(5489);
}
kk = 0;
while (kk < N - M) {
y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
mt[kk] = mt[kk + M] ^ (y >> 1) ^ mag01[y & 1];
kk++;
}
while (kk < N - 1) {
y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
mt[kk] = mt[kk + (M - N)] ^ (y >> 1) ^ mag01[y & 1];
kk++;
}
y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
mt[N - 1] = mt[M - 1] ^ (y >> 1) ^ mag01[y & 1];
mti = 0;
}
y = mt[mti++];
y ^= y >> 11;
y ^= (y << 7) & -1658038656;
y ^= (y << 15) & -272236544;
y ^= y >> 18;
return y >> 0;
}
/*
* generates a random number on [0,0x7fffffff]-interval
*/
public int genrand_int31() {
return genrand_int32() >> 1;
}
/*
* generates a random number on [0,1]-real-interval
*/
public double genrand_real1() {
return genrand_int32() * 2.32830643653869629e-10;
}
/*
* generates a random number on [0,1)-real-interval
*/
public double genrand_real2() {
return genrand_int32() * 2.32830643653869629e-10;
}
/*
* generates a random number on (0,1)-real-interval
*/
public double genrand_real3() {
return (genrand_int32() + 0.5) * 2.32830643653869629e-10;
}
/*
* generates a random number on [0,1] 53-bit resolution
*/
public double genrand_res53() {
int a, b;
a = genrand_int32() >> 5;
b = genrand_int32() >> 6;
return (a * 67108864.0 + b) * 1.11022302462515654e-16;
}
}
}
/*
# These real versions are due to Isaku Wada, 2002/01/09 added
*/
/**
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not 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.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
| |
using System;
using Org.BouncyCastle.Crypto.Parameters;
namespace Org.BouncyCastle.Crypto.Engines
{
/**
* Serpent is a 128-bit 32-round block cipher with variable key lengths,
* including 128, 192 and 256 bit keys conjectured to be at least as
* secure as three-key triple-DES.
* <p>
* Serpent was designed by Ross Anderson, Eli Biham and Lars Knudsen as a
* candidate algorithm for the NIST AES Quest.>
* </p>
* <p>
* For full details see the <a href="http://www.cl.cam.ac.uk/~rja14/serpent.html">The Serpent home page</a>
* </p>
*/
public class SerpentEngine
: IBlockCipher
{
private const int BLOCK_SIZE = 16;
static readonly int ROUNDS = 32;
static readonly int PHI = unchecked((int)0x9E3779B9); // (Sqrt(5) - 1) * 2**31
private bool encrypting;
private int[] wKey;
private int X0, X1, X2, X3; // registers
/**
* initialise a Serpent cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public virtual void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is KeyParameter))
throw new ArgumentException("invalid parameter passed to Serpent init - " + parameters.GetType().ToString());
this.encrypting = forEncryption;
this.wKey = MakeWorkingKey(((KeyParameter)parameters).GetKey());
}
public virtual string AlgorithmName
{
get { return "Serpent"; }
}
public virtual bool IsPartialBlockOkay
{
get { return false; }
}
public virtual int GetBlockSize()
{
return BLOCK_SIZE;
}
/**
* Process one block of input from the array in and write it to
* the out array.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public virtual int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (wKey == null)
throw new InvalidOperationException("Serpent not initialised");
Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short");
Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short");
if (encrypting)
{
EncryptBlock(input, inOff, output, outOff);
}
else
{
DecryptBlock(input, inOff, output, outOff);
}
return BLOCK_SIZE;
}
public virtual void Reset()
{
}
/**
* Expand a user-supplied key material into a session key.
*
* @param key The user-key bytes (multiples of 4) to use.
* @exception ArgumentException
*/
private int[] MakeWorkingKey(
byte[] key)
{
//
// pad key to 256 bits
//
int[] kPad = new int[16];
int off = 0;
int length = 0;
for (off = key.Length - 4; off > 0; off -= 4)
{
kPad[length++] = BytesToWord(key, off);
}
if (off == 0)
{
kPad[length++] = BytesToWord(key, 0);
if (length < 8)
{
kPad[length] = 1;
}
}
else
{
throw new ArgumentException("key must be a multiple of 4 bytes");
}
//
// expand the padded key up to 33 x 128 bits of key material
//
int amount = (ROUNDS + 1) * 4;
int[] w = new int[amount];
//
// compute w0 to w7 from w-8 to w-1
//
for (int i = 8; i < 16; i++)
{
kPad[i] = RotateLeft(kPad[i - 8] ^ kPad[i - 5] ^ kPad[i - 3] ^ kPad[i - 1] ^ PHI ^ (i - 8), 11);
}
Array.Copy(kPad, 8, w, 0, 8);
//
// compute w8 to w136
//
for (int i = 8; i < amount; i++)
{
w[i] = RotateLeft(w[i - 8] ^ w[i - 5] ^ w[i - 3] ^ w[i - 1] ^ PHI ^ i, 11);
}
//
// create the working keys by processing w with the Sbox and IP
//
Sb3(w[0], w[1], w[2], w[3]);
w[0] = X0; w[1] = X1; w[2] = X2; w[3] = X3;
Sb2(w[4], w[5], w[6], w[7]);
w[4] = X0; w[5] = X1; w[6] = X2; w[7] = X3;
Sb1(w[8], w[9], w[10], w[11]);
w[8] = X0; w[9] = X1; w[10] = X2; w[11] = X3;
Sb0(w[12], w[13], w[14], w[15]);
w[12] = X0; w[13] = X1; w[14] = X2; w[15] = X3;
Sb7(w[16], w[17], w[18], w[19]);
w[16] = X0; w[17] = X1; w[18] = X2; w[19] = X3;
Sb6(w[20], w[21], w[22], w[23]);
w[20] = X0; w[21] = X1; w[22] = X2; w[23] = X3;
Sb5(w[24], w[25], w[26], w[27]);
w[24] = X0; w[25] = X1; w[26] = X2; w[27] = X3;
Sb4(w[28], w[29], w[30], w[31]);
w[28] = X0; w[29] = X1; w[30] = X2; w[31] = X3;
Sb3(w[32], w[33], w[34], w[35]);
w[32] = X0; w[33] = X1; w[34] = X2; w[35] = X3;
Sb2(w[36], w[37], w[38], w[39]);
w[36] = X0; w[37] = X1; w[38] = X2; w[39] = X3;
Sb1(w[40], w[41], w[42], w[43]);
w[40] = X0; w[41] = X1; w[42] = X2; w[43] = X3;
Sb0(w[44], w[45], w[46], w[47]);
w[44] = X0; w[45] = X1; w[46] = X2; w[47] = X3;
Sb7(w[48], w[49], w[50], w[51]);
w[48] = X0; w[49] = X1; w[50] = X2; w[51] = X3;
Sb6(w[52], w[53], w[54], w[55]);
w[52] = X0; w[53] = X1; w[54] = X2; w[55] = X3;
Sb5(w[56], w[57], w[58], w[59]);
w[56] = X0; w[57] = X1; w[58] = X2; w[59] = X3;
Sb4(w[60], w[61], w[62], w[63]);
w[60] = X0; w[61] = X1; w[62] = X2; w[63] = X3;
Sb3(w[64], w[65], w[66], w[67]);
w[64] = X0; w[65] = X1; w[66] = X2; w[67] = X3;
Sb2(w[68], w[69], w[70], w[71]);
w[68] = X0; w[69] = X1; w[70] = X2; w[71] = X3;
Sb1(w[72], w[73], w[74], w[75]);
w[72] = X0; w[73] = X1; w[74] = X2; w[75] = X3;
Sb0(w[76], w[77], w[78], w[79]);
w[76] = X0; w[77] = X1; w[78] = X2; w[79] = X3;
Sb7(w[80], w[81], w[82], w[83]);
w[80] = X0; w[81] = X1; w[82] = X2; w[83] = X3;
Sb6(w[84], w[85], w[86], w[87]);
w[84] = X0; w[85] = X1; w[86] = X2; w[87] = X3;
Sb5(w[88], w[89], w[90], w[91]);
w[88] = X0; w[89] = X1; w[90] = X2; w[91] = X3;
Sb4(w[92], w[93], w[94], w[95]);
w[92] = X0; w[93] = X1; w[94] = X2; w[95] = X3;
Sb3(w[96], w[97], w[98], w[99]);
w[96] = X0; w[97] = X1; w[98] = X2; w[99] = X3;
Sb2(w[100], w[101], w[102], w[103]);
w[100] = X0; w[101] = X1; w[102] = X2; w[103] = X3;
Sb1(w[104], w[105], w[106], w[107]);
w[104] = X0; w[105] = X1; w[106] = X2; w[107] = X3;
Sb0(w[108], w[109], w[110], w[111]);
w[108] = X0; w[109] = X1; w[110] = X2; w[111] = X3;
Sb7(w[112], w[113], w[114], w[115]);
w[112] = X0; w[113] = X1; w[114] = X2; w[115] = X3;
Sb6(w[116], w[117], w[118], w[119]);
w[116] = X0; w[117] = X1; w[118] = X2; w[119] = X3;
Sb5(w[120], w[121], w[122], w[123]);
w[120] = X0; w[121] = X1; w[122] = X2; w[123] = X3;
Sb4(w[124], w[125], w[126], w[127]);
w[124] = X0; w[125] = X1; w[126] = X2; w[127] = X3;
Sb3(w[128], w[129], w[130], w[131]);
w[128] = X0; w[129] = X1; w[130] = X2; w[131] = X3;
return w;
}
private int RotateLeft(
int x,
int bits)
{
return ((x << bits) | (int) ((uint)x >> (32 - bits)));
}
private int RotateRight(
int x,
int bits)
{
return ( (int)((uint)x >> bits) | (x << (32 - bits)));
}
private int BytesToWord(
byte[] src,
int srcOff)
{
return (((src[srcOff] & 0xff) << 24) | ((src[srcOff + 1] & 0xff) << 16) |
((src[srcOff + 2] & 0xff) << 8) | ((src[srcOff + 3] & 0xff)));
}
private void WordToBytes(
int word,
byte[] dst,
int dstOff)
{
dst[dstOff + 3] = (byte)(word);
dst[dstOff + 2] = (byte)((uint)word >> 8);
dst[dstOff + 1] = (byte)((uint)word >> 16);
dst[dstOff] = (byte)((uint)word >> 24);
}
/**
* Encrypt one block of plaintext.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
*/
private void EncryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
X3 = BytesToWord(input, inOff);
X2 = BytesToWord(input, inOff + 4);
X1 = BytesToWord(input, inOff + 8);
X0 = BytesToWord(input, inOff + 12);
Sb0(wKey[0] ^ X0, wKey[1] ^ X1, wKey[2] ^ X2, wKey[3] ^ X3); LT();
Sb1(wKey[4] ^ X0, wKey[5] ^ X1, wKey[6] ^ X2, wKey[7] ^ X3); LT();
Sb2(wKey[8] ^ X0, wKey[9] ^ X1, wKey[10] ^ X2, wKey[11] ^ X3); LT();
Sb3(wKey[12] ^ X0, wKey[13] ^ X1, wKey[14] ^ X2, wKey[15] ^ X3); LT();
Sb4(wKey[16] ^ X0, wKey[17] ^ X1, wKey[18] ^ X2, wKey[19] ^ X3); LT();
Sb5(wKey[20] ^ X0, wKey[21] ^ X1, wKey[22] ^ X2, wKey[23] ^ X3); LT();
Sb6(wKey[24] ^ X0, wKey[25] ^ X1, wKey[26] ^ X2, wKey[27] ^ X3); LT();
Sb7(wKey[28] ^ X0, wKey[29] ^ X1, wKey[30] ^ X2, wKey[31] ^ X3); LT();
Sb0(wKey[32] ^ X0, wKey[33] ^ X1, wKey[34] ^ X2, wKey[35] ^ X3); LT();
Sb1(wKey[36] ^ X0, wKey[37] ^ X1, wKey[38] ^ X2, wKey[39] ^ X3); LT();
Sb2(wKey[40] ^ X0, wKey[41] ^ X1, wKey[42] ^ X2, wKey[43] ^ X3); LT();
Sb3(wKey[44] ^ X0, wKey[45] ^ X1, wKey[46] ^ X2, wKey[47] ^ X3); LT();
Sb4(wKey[48] ^ X0, wKey[49] ^ X1, wKey[50] ^ X2, wKey[51] ^ X3); LT();
Sb5(wKey[52] ^ X0, wKey[53] ^ X1, wKey[54] ^ X2, wKey[55] ^ X3); LT();
Sb6(wKey[56] ^ X0, wKey[57] ^ X1, wKey[58] ^ X2, wKey[59] ^ X3); LT();
Sb7(wKey[60] ^ X0, wKey[61] ^ X1, wKey[62] ^ X2, wKey[63] ^ X3); LT();
Sb0(wKey[64] ^ X0, wKey[65] ^ X1, wKey[66] ^ X2, wKey[67] ^ X3); LT();
Sb1(wKey[68] ^ X0, wKey[69] ^ X1, wKey[70] ^ X2, wKey[71] ^ X3); LT();
Sb2(wKey[72] ^ X0, wKey[73] ^ X1, wKey[74] ^ X2, wKey[75] ^ X3); LT();
Sb3(wKey[76] ^ X0, wKey[77] ^ X1, wKey[78] ^ X2, wKey[79] ^ X3); LT();
Sb4(wKey[80] ^ X0, wKey[81] ^ X1, wKey[82] ^ X2, wKey[83] ^ X3); LT();
Sb5(wKey[84] ^ X0, wKey[85] ^ X1, wKey[86] ^ X2, wKey[87] ^ X3); LT();
Sb6(wKey[88] ^ X0, wKey[89] ^ X1, wKey[90] ^ X2, wKey[91] ^ X3); LT();
Sb7(wKey[92] ^ X0, wKey[93] ^ X1, wKey[94] ^ X2, wKey[95] ^ X3); LT();
Sb0(wKey[96] ^ X0, wKey[97] ^ X1, wKey[98] ^ X2, wKey[99] ^ X3); LT();
Sb1(wKey[100] ^ X0, wKey[101] ^ X1, wKey[102] ^ X2, wKey[103] ^ X3); LT();
Sb2(wKey[104] ^ X0, wKey[105] ^ X1, wKey[106] ^ X2, wKey[107] ^ X3); LT();
Sb3(wKey[108] ^ X0, wKey[109] ^ X1, wKey[110] ^ X2, wKey[111] ^ X3); LT();
Sb4(wKey[112] ^ X0, wKey[113] ^ X1, wKey[114] ^ X2, wKey[115] ^ X3); LT();
Sb5(wKey[116] ^ X0, wKey[117] ^ X1, wKey[118] ^ X2, wKey[119] ^ X3); LT();
Sb6(wKey[120] ^ X0, wKey[121] ^ X1, wKey[122] ^ X2, wKey[123] ^ X3); LT();
Sb7(wKey[124] ^ X0, wKey[125] ^ X1, wKey[126] ^ X2, wKey[127] ^ X3);
WordToBytes(wKey[131] ^ X3, outBytes, outOff);
WordToBytes(wKey[130] ^ X2, outBytes, outOff + 4);
WordToBytes(wKey[129] ^ X1, outBytes, outOff + 8);
WordToBytes(wKey[128] ^ X0, outBytes, outOff + 12);
}
/**
* Decrypt one block of ciphertext.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
*/
private void DecryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
X3 = wKey[131] ^ BytesToWord(input, inOff);
X2 = wKey[130] ^ BytesToWord(input, inOff + 4);
X1 = wKey[129] ^ BytesToWord(input, inOff + 8);
X0 = wKey[128] ^ BytesToWord(input, inOff + 12);
Ib7(X0, X1, X2, X3);
X0 ^= wKey[124]; X1 ^= wKey[125]; X2 ^= wKey[126]; X3 ^= wKey[127];
InverseLT(); Ib6(X0, X1, X2, X3);
X0 ^= wKey[120]; X1 ^= wKey[121]; X2 ^= wKey[122]; X3 ^= wKey[123];
InverseLT(); Ib5(X0, X1, X2, X3);
X0 ^= wKey[116]; X1 ^= wKey[117]; X2 ^= wKey[118]; X3 ^= wKey[119];
InverseLT(); Ib4(X0, X1, X2, X3);
X0 ^= wKey[112]; X1 ^= wKey[113]; X2 ^= wKey[114]; X3 ^= wKey[115];
InverseLT(); Ib3(X0, X1, X2, X3);
X0 ^= wKey[108]; X1 ^= wKey[109]; X2 ^= wKey[110]; X3 ^= wKey[111];
InverseLT(); Ib2(X0, X1, X2, X3);
X0 ^= wKey[104]; X1 ^= wKey[105]; X2 ^= wKey[106]; X3 ^= wKey[107];
InverseLT(); Ib1(X0, X1, X2, X3);
X0 ^= wKey[100]; X1 ^= wKey[101]; X2 ^= wKey[102]; X3 ^= wKey[103];
InverseLT(); Ib0(X0, X1, X2, X3);
X0 ^= wKey[96]; X1 ^= wKey[97]; X2 ^= wKey[98]; X3 ^= wKey[99];
InverseLT(); Ib7(X0, X1, X2, X3);
X0 ^= wKey[92]; X1 ^= wKey[93]; X2 ^= wKey[94]; X3 ^= wKey[95];
InverseLT(); Ib6(X0, X1, X2, X3);
X0 ^= wKey[88]; X1 ^= wKey[89]; X2 ^= wKey[90]; X3 ^= wKey[91];
InverseLT(); Ib5(X0, X1, X2, X3);
X0 ^= wKey[84]; X1 ^= wKey[85]; X2 ^= wKey[86]; X3 ^= wKey[87];
InverseLT(); Ib4(X0, X1, X2, X3);
X0 ^= wKey[80]; X1 ^= wKey[81]; X2 ^= wKey[82]; X3 ^= wKey[83];
InverseLT(); Ib3(X0, X1, X2, X3);
X0 ^= wKey[76]; X1 ^= wKey[77]; X2 ^= wKey[78]; X3 ^= wKey[79];
InverseLT(); Ib2(X0, X1, X2, X3);
X0 ^= wKey[72]; X1 ^= wKey[73]; X2 ^= wKey[74]; X3 ^= wKey[75];
InverseLT(); Ib1(X0, X1, X2, X3);
X0 ^= wKey[68]; X1 ^= wKey[69]; X2 ^= wKey[70]; X3 ^= wKey[71];
InverseLT(); Ib0(X0, X1, X2, X3);
X0 ^= wKey[64]; X1 ^= wKey[65]; X2 ^= wKey[66]; X3 ^= wKey[67];
InverseLT(); Ib7(X0, X1, X2, X3);
X0 ^= wKey[60]; X1 ^= wKey[61]; X2 ^= wKey[62]; X3 ^= wKey[63];
InverseLT(); Ib6(X0, X1, X2, X3);
X0 ^= wKey[56]; X1 ^= wKey[57]; X2 ^= wKey[58]; X3 ^= wKey[59];
InverseLT(); Ib5(X0, X1, X2, X3);
X0 ^= wKey[52]; X1 ^= wKey[53]; X2 ^= wKey[54]; X3 ^= wKey[55];
InverseLT(); Ib4(X0, X1, X2, X3);
X0 ^= wKey[48]; X1 ^= wKey[49]; X2 ^= wKey[50]; X3 ^= wKey[51];
InverseLT(); Ib3(X0, X1, X2, X3);
X0 ^= wKey[44]; X1 ^= wKey[45]; X2 ^= wKey[46]; X3 ^= wKey[47];
InverseLT(); Ib2(X0, X1, X2, X3);
X0 ^= wKey[40]; X1 ^= wKey[41]; X2 ^= wKey[42]; X3 ^= wKey[43];
InverseLT(); Ib1(X0, X1, X2, X3);
X0 ^= wKey[36]; X1 ^= wKey[37]; X2 ^= wKey[38]; X3 ^= wKey[39];
InverseLT(); Ib0(X0, X1, X2, X3);
X0 ^= wKey[32]; X1 ^= wKey[33]; X2 ^= wKey[34]; X3 ^= wKey[35];
InverseLT(); Ib7(X0, X1, X2, X3);
X0 ^= wKey[28]; X1 ^= wKey[29]; X2 ^= wKey[30]; X3 ^= wKey[31];
InverseLT(); Ib6(X0, X1, X2, X3);
X0 ^= wKey[24]; X1 ^= wKey[25]; X2 ^= wKey[26]; X3 ^= wKey[27];
InverseLT(); Ib5(X0, X1, X2, X3);
X0 ^= wKey[20]; X1 ^= wKey[21]; X2 ^= wKey[22]; X3 ^= wKey[23];
InverseLT(); Ib4(X0, X1, X2, X3);
X0 ^= wKey[16]; X1 ^= wKey[17]; X2 ^= wKey[18]; X3 ^= wKey[19];
InverseLT(); Ib3(X0, X1, X2, X3);
X0 ^= wKey[12]; X1 ^= wKey[13]; X2 ^= wKey[14]; X3 ^= wKey[15];
InverseLT(); Ib2(X0, X1, X2, X3);
X0 ^= wKey[8]; X1 ^= wKey[9]; X2 ^= wKey[10]; X3 ^= wKey[11];
InverseLT(); Ib1(X0, X1, X2, X3);
X0 ^= wKey[4]; X1 ^= wKey[5]; X2 ^= wKey[6]; X3 ^= wKey[7];
InverseLT(); Ib0(X0, X1, X2, X3);
WordToBytes(X3 ^ wKey[3], outBytes, outOff);
WordToBytes(X2 ^ wKey[2], outBytes, outOff + 4);
WordToBytes(X1 ^ wKey[1], outBytes, outOff + 8);
WordToBytes(X0 ^ wKey[0], outBytes, outOff + 12);
}
/*
* The sboxes below are based on the work of Brian Gladman and
* Sam Simpson, whose original notice appears below.
* <p>
* For further details see:
* http://fp.gladman.plus.com/cryptography_technology/serpent/
* </p>
*/
/* Partially optimised Serpent S Box bool functions derived */
/* using a recursive descent analyser but without a full search */
/* of all subtrees. This set of S boxes is the result of work */
/* by Sam Simpson and Brian Gladman using the spare time on a */
/* cluster of high capacity servers to search for S boxes with */
/* this customised search engine. There are now an average of */
/* 15.375 terms per S box. */
/* */
/* Copyright: Dr B. R Gladman (gladman@seven77.demon.co.uk) */
/* and Sam Simpson (s.simpson@mia.co.uk) */
/* 17th December 1998 */
/* */
/* We hereby give permission for information in this file to be */
/* used freely subject only to acknowledgement of its origin. */
/**
* S0 - { 3, 8,15, 1,10, 6, 5,11,14,13, 4, 2, 7, 0, 9,12 } - 15 terms.
*/
private void Sb0(int a, int b, int c, int d)
{
int t1 = a ^ d;
int t3 = c ^ t1;
int t4 = b ^ t3;
X3 = (a & d) ^ t4;
int t7 = a ^ (b & t1);
X2 = t4 ^ (c | t7);
int t12 = X3 & (t3 ^ t7);
X1 = (~t3) ^ t12;
X0 = t12 ^ (~t7);
}
/**
* InvSO - {13, 3,11, 0,10, 6, 5,12, 1,14, 4, 7,15, 9, 8, 2 } - 15 terms.
*/
private void Ib0(int a, int b, int c, int d)
{
int t1 = ~a;
int t2 = a ^ b;
int t4 = d ^ (t1 | t2);
int t5 = c ^ t4;
X2 = t2 ^ t5;
int t8 = t1 ^ (d & t2);
X1 = t4 ^ (X2 & t8);
X3 = (a & t4) ^ (t5 | X1);
X0 = X3 ^ (t5 ^ t8);
}
/**
* S1 - {15,12, 2, 7, 9, 0, 5,10, 1,11,14, 8, 6,13, 3, 4 } - 14 terms.
*/
private void Sb1(int a, int b, int c, int d)
{
int t2 = b ^ (~a);
int t5 = c ^ (a | t2);
X2 = d ^ t5;
int t7 = b ^ (d | t2);
int t8 = t2 ^ X2;
X3 = t8 ^ (t5 & t7);
int t11 = t5 ^ t7;
X1 = X3 ^ t11;
X0 = t5 ^ (t8 & t11);
}
/**
* InvS1 - { 5, 8, 2,14,15, 6,12, 3,11, 4, 7, 9, 1,13,10, 0 } - 14 steps.
*/
private void Ib1(int a, int b, int c, int d)
{
int t1 = b ^ d;
int t3 = a ^ (b & t1);
int t4 = t1 ^ t3;
X3 = c ^ t4;
int t7 = b ^ (t1 & t3);
int t8 = X3 | t7;
X1 = t3 ^ t8;
int t10 = ~X1;
int t11 = X3 ^ t7;
X0 = t10 ^ t11;
X2 = t4 ^ (t10 | t11);
}
/**
* S2 - { 8, 6, 7, 9, 3,12,10,15,13, 1,14, 4, 0,11, 5, 2 } - 16 terms.
*/
private void Sb2(int a, int b, int c, int d)
{
int t1 = ~a;
int t2 = b ^ d;
int t3 = c & t1;
X0 = t2 ^ t3;
int t5 = c ^ t1;
int t6 = c ^ X0;
int t7 = b & t6;
X3 = t5 ^ t7;
X2 = a ^ ((d | t7) & (X0 | t5));
X1 = (t2 ^ X3) ^ (X2 ^ (d | t1));
}
/**
* InvS2 - {12, 9,15, 4,11,14, 1, 2, 0, 3, 6,13, 5, 8,10, 7 } - 16 steps.
*/
private void Ib2(int a, int b, int c, int d)
{
int t1 = b ^ d;
int t2 = ~t1;
int t3 = a ^ c;
int t4 = c ^ t1;
int t5 = b & t4;
X0 = t3 ^ t5;
int t7 = a | t2;
int t8 = d ^ t7;
int t9 = t3 | t8;
X3 = t1 ^ t9;
int t11 = ~t4;
int t12 = X0 | X3;
X1 = t11 ^ t12;
X2 = (d & t11) ^ (t3 ^ t12);
}
/**
* S3 - { 0,15,11, 8,12, 9, 6, 3,13, 1, 2, 4,10, 7, 5,14 } - 16 terms.
*/
private void Sb3(int a, int b, int c, int d)
{
int t1 = a ^ b;
int t2 = a & c;
int t3 = a | d;
int t4 = c ^ d;
int t5 = t1 & t3;
int t6 = t2 | t5;
X2 = t4 ^ t6;
int t8 = b ^ t3;
int t9 = t6 ^ t8;
int t10 = t4 & t9;
X0 = t1 ^ t10;
int t12 = X2 & X0;
X1 = t9 ^ t12;
X3 = (b | d) ^ (t4 ^ t12);
}
/**
* InvS3 - { 0, 9,10, 7,11,14, 6,13, 3, 5,12, 2, 4, 8,15, 1 } - 15 terms
*/
private void Ib3(int a, int b, int c, int d)
{
int t1 = a | b;
int t2 = b ^ c;
int t3 = b & t2;
int t4 = a ^ t3;
int t5 = c ^ t4;
int t6 = d | t4;
X0 = t2 ^ t6;
int t8 = t2 | t6;
int t9 = d ^ t8;
X2 = t5 ^ t9;
int t11 = t1 ^ t9;
int t12 = X0 & t11;
X3 = t4 ^ t12;
X1 = X3 ^ (X0 ^ t11);
}
/**
* S4 - { 1,15, 8, 3,12, 0,11, 6, 2, 5, 4,10, 9,14, 7,13 } - 15 terms.
*/
private void Sb4(int a, int b, int c, int d)
{
int t1 = a ^ d;
int t2 = d & t1;
int t3 = c ^ t2;
int t4 = b | t3;
X3 = t1 ^ t4;
int t6 = ~b;
int t7 = t1 | t6;
X0 = t3 ^ t7;
int t9 = a & X0;
int t10 = t1 ^ t6;
int t11 = t4 & t10;
X2 = t9 ^ t11;
X1 = (a ^ t3) ^ (t10 & X2);
}
/**
* InvS4 - { 5, 0, 8, 3,10, 9, 7,14, 2,12,11, 6, 4,15,13, 1 } - 15 terms.
*/
private void Ib4(int a, int b, int c, int d)
{
int t1 = c | d;
int t2 = a & t1;
int t3 = b ^ t2;
int t4 = a & t3;
int t5 = c ^ t4;
X1 = d ^ t5;
int t7 = ~a;
int t8 = t5 & X1;
X3 = t3 ^ t8;
int t10 = X1 | t7;
int t11 = d ^ t10;
X0 = X3 ^ t11;
X2 = (t3 & t11) ^ (X1 ^ t7);
}
/**
* S5 - {15, 5, 2,11, 4,10, 9,12, 0, 3,14, 8,13, 6, 7, 1 } - 16 terms.
*/
private void Sb5(int a, int b, int c, int d)
{
int t1 = ~a;
int t2 = a ^ b;
int t3 = a ^ d;
int t4 = c ^ t1;
int t5 = t2 | t3;
X0 = t4 ^ t5;
int t7 = d & X0;
int t8 = t2 ^ X0;
X1 = t7 ^ t8;
int t10 = t1 | X0;
int t11 = t2 | t7;
int t12 = t3 ^ t10;
X2 = t11 ^ t12;
X3 = (b ^ t7) ^ (X1 & t12);
}
/**
* InvS5 - { 8,15, 2, 9, 4, 1,13,14,11, 6, 5, 3, 7,12,10, 0 } - 16 terms.
*/
private void Ib5(int a, int b, int c, int d)
{
int t1 = ~c;
int t2 = b & t1;
int t3 = d ^ t2;
int t4 = a & t3;
int t5 = b ^ t1;
X3 = t4 ^ t5;
int t7 = b | X3;
int t8 = a & t7;
X1 = t3 ^ t8;
int t10 = a | d;
int t11 = t1 ^ t7;
X0 = t10 ^ t11;
X2 = (b & t10) ^ (t4 | (a ^ c));
}
/**
* S6 - { 7, 2,12, 5, 8, 4, 6,11,14, 9, 1,15,13, 3,10, 0 } - 15 terms.
*/
private void Sb6(int a, int b, int c, int d)
{
int t1 = ~a;
int t2 = a ^ d;
int t3 = b ^ t2;
int t4 = t1 | t2;
int t5 = c ^ t4;
X1 = b ^ t5;
int t7 = t2 | X1;
int t8 = d ^ t7;
int t9 = t5 & t8;
X2 = t3 ^ t9;
int t11 = t5 ^ t8;
X0 = X2 ^ t11;
X3 = (~t5) ^ (t3 & t11);
}
/**
* InvS6 - {15,10, 1,13, 5, 3, 6, 0, 4, 9,14, 7, 2,12, 8,11 } - 15 terms.
*/
private void Ib6(int a, int b, int c, int d)
{
int t1 = ~a;
int t2 = a ^ b;
int t3 = c ^ t2;
int t4 = c | t1;
int t5 = d ^ t4;
X1 = t3 ^ t5;
int t7 = t3 & t5;
int t8 = t2 ^ t7;
int t9 = b | t8;
X3 = t5 ^ t9;
int t11 = b | X3;
X0 = t8 ^ t11;
X2 = (d & t1) ^ (t3 ^ t11);
}
/**
* S7 - { 1,13,15, 0,14, 8, 2,11, 7, 4,12,10, 9, 3, 5, 6 } - 16 terms.
*/
private void Sb7(int a, int b, int c, int d)
{
int t1 = b ^ c;
int t2 = c & t1;
int t3 = d ^ t2;
int t4 = a ^ t3;
int t5 = d | t1;
int t6 = t4 & t5;
X1 = b ^ t6;
int t8 = t3 | X1;
int t9 = a & t4;
X3 = t1 ^ t9;
int t11 = t4 ^ t8;
int t12 = X3 & t11;
X2 = t3 ^ t12;
X0 = (~t11) ^ (X3 & X2);
}
/**
* InvS7 - { 3, 0, 6,13, 9,14,15, 8, 5,12,11, 7,10, 1, 4, 2 } - 17 terms.
*/
private void Ib7(int a, int b, int c, int d)
{
int t3 = c | (a & b);
int t4 = d & (a | b);
X3 = t3 ^ t4;
int t6 = ~d;
int t7 = b ^ t4;
int t9 = t7 | (X3 ^ t6);
X1 = a ^ t9;
X0 = (c ^ t7) ^ (d | X1);
X2 = (t3 ^ X1) ^ (X0 ^ (a & X3));
}
/**
* Apply the linear transformation to the register set.
*/
private void LT()
{
int x0 = RotateLeft(X0, 13);
int x2 = RotateLeft(X2, 3);
int x1 = X1 ^ x0 ^ x2 ;
int x3 = X3 ^ x2 ^ x0 << 3;
X1 = RotateLeft(x1, 1);
X3 = RotateLeft(x3, 7);
X0 = RotateLeft(x0 ^ X1 ^ X3, 5);
X2 = RotateLeft(x2 ^ X3 ^ (X1 << 7), 22);
}
/**
* Apply the inverse of the linear transformation to the register set.
*/
private void InverseLT()
{
int x2 = RotateRight(X2, 22) ^ X3 ^ (X1 << 7);
int x0 = RotateRight(X0, 5) ^ X1 ^ X3;
int x3 = RotateRight(X3, 7);
int x1 = RotateRight(X1, 1);
X3 = x3 ^ x2 ^ x0 << 3;
X1 = x1 ^ x0 ^ x2;
X2 = RotateRight(x2, 3);
X0 = RotateRight(x0, 13);
}
}
}
| |
using Lucene.Net.Codecs.Lucene40;
using Lucene.Net.Support;
using System;
using System.Diagnostics;
using System.Reflection;
namespace Lucene.Net.Codecs.Compressing
{
/*
* 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 ArrayUtil = Lucene.Net.Util.ArrayUtil;
using BufferedChecksumIndexInput = Lucene.Net.Store.BufferedChecksumIndexInput;
using ByteArrayDataInput = Lucene.Net.Store.ByteArrayDataInput;
using BytesRef = Lucene.Net.Util.BytesRef;
using ChecksumIndexInput = Lucene.Net.Store.ChecksumIndexInput;
using CorruptIndexException = Lucene.Net.Index.CorruptIndexException;
using DataInput = Lucene.Net.Store.DataInput;
using DataOutput = Lucene.Net.Store.DataOutput;
using Directory = Lucene.Net.Store.Directory;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexInput = Lucene.Net.Store.IndexInput;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
using SegmentInfo = Lucene.Net.Index.SegmentInfo;
using StoredFieldVisitor = Lucene.Net.Index.StoredFieldVisitor;
/// <summary>
/// <see cref="StoredFieldsReader"/> impl for <see cref="CompressingStoredFieldsFormat"/>.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class CompressingStoredFieldsReader : StoredFieldsReader
{
// Do not reuse the decompression buffer when there is more than 32kb to decompress
private static readonly int BUFFER_REUSE_THRESHOLD = 1 << 15;
private readonly int version;
private readonly FieldInfos fieldInfos;
private readonly CompressingStoredFieldsIndexReader indexReader;
private readonly long maxPointer;
private readonly IndexInput fieldsStream;
private readonly int chunkSize;
private readonly int packedIntsVersion;
private readonly CompressionMode compressionMode;
private readonly Decompressor decompressor;
private readonly BytesRef bytes;
private readonly int numDocs;
private bool closed;
// used by clone
private CompressingStoredFieldsReader(CompressingStoredFieldsReader reader)
{
this.version = reader.version;
this.fieldInfos = reader.fieldInfos;
this.fieldsStream = (IndexInput)reader.fieldsStream.Clone();
this.indexReader = (CompressingStoredFieldsIndexReader)reader.indexReader.Clone();
this.maxPointer = reader.maxPointer;
this.chunkSize = reader.chunkSize;
this.packedIntsVersion = reader.packedIntsVersion;
this.compressionMode = reader.compressionMode;
this.decompressor = (Decompressor)reader.decompressor.Clone();
this.numDocs = reader.numDocs;
this.bytes = new BytesRef(reader.bytes.Bytes.Length);
this.closed = false;
}
/// <summary>
/// Sole constructor. </summary>
public CompressingStoredFieldsReader(Directory d, SegmentInfo si, string segmentSuffix, FieldInfos fn, IOContext context, string formatName, CompressionMode compressionMode)
{
this.compressionMode = compressionMode;
string segment = si.Name;
bool success = false;
fieldInfos = fn;
numDocs = si.DocCount;
ChecksumIndexInput indexStream = null;
try
{
string indexStreamFN = IndexFileNames.SegmentFileName(segment, segmentSuffix, Lucene40StoredFieldsWriter.FIELDS_INDEX_EXTENSION);
string fieldsStreamFN = IndexFileNames.SegmentFileName(segment, segmentSuffix, Lucene40StoredFieldsWriter.FIELDS_EXTENSION);
// Load the index into memory
indexStream = d.OpenChecksumInput(indexStreamFN, context);
string codecNameIdx = formatName + CompressingStoredFieldsWriter.CODEC_SFX_IDX;
version = CodecUtil.CheckHeader(indexStream, codecNameIdx, CompressingStoredFieldsWriter.VERSION_START, CompressingStoredFieldsWriter.VERSION_CURRENT);
Debug.Assert(CodecUtil.HeaderLength(codecNameIdx) == indexStream.GetFilePointer());
indexReader = new CompressingStoredFieldsIndexReader(indexStream, si);
long maxPointer = -1;
if (version >= CompressingStoredFieldsWriter.VERSION_CHECKSUM)
{
maxPointer = indexStream.ReadVInt64();
CodecUtil.CheckFooter(indexStream);
}
else
{
#pragma warning disable 612, 618
CodecUtil.CheckEOF(indexStream);
#pragma warning restore 612, 618
}
indexStream.Dispose();
indexStream = null;
// Open the data file and read metadata
fieldsStream = d.OpenInput(fieldsStreamFN, context);
if (version >= CompressingStoredFieldsWriter.VERSION_CHECKSUM)
{
if (maxPointer + CodecUtil.FooterLength() != fieldsStream.Length)
{
throw new CorruptIndexException("Invalid fieldsStream maxPointer (file truncated?): maxPointer=" + maxPointer + ", length=" + fieldsStream.Length);
}
}
else
{
maxPointer = fieldsStream.Length;
}
this.maxPointer = maxPointer;
string codecNameDat = formatName + CompressingStoredFieldsWriter.CODEC_SFX_DAT;
int fieldsVersion = CodecUtil.CheckHeader(fieldsStream, codecNameDat, CompressingStoredFieldsWriter.VERSION_START, CompressingStoredFieldsWriter.VERSION_CURRENT);
if (version != fieldsVersion)
{
throw new CorruptIndexException("Version mismatch between stored fields index and data: " + version + " != " + fieldsVersion);
}
Debug.Assert(CodecUtil.HeaderLength(codecNameDat) == fieldsStream.GetFilePointer());
if (version >= CompressingStoredFieldsWriter.VERSION_BIG_CHUNKS)
{
chunkSize = fieldsStream.ReadVInt32();
}
else
{
chunkSize = -1;
}
packedIntsVersion = fieldsStream.ReadVInt32();
decompressor = compressionMode.NewDecompressor();
this.bytes = new BytesRef();
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(this, indexStream);
}
}
}
/// <exception cref="ObjectDisposedException"> If this FieldsReader is disposed. </exception>
private void EnsureOpen()
{
if (closed)
{
throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, "this FieldsReader is closed");
}
}
/// <summary>
/// Dispose the underlying <see cref="IndexInput"/>s.
/// </summary>
protected override void Dispose(bool disposing)
{
if (!closed)
{
IOUtils.Dispose(fieldsStream);
closed = true;
}
}
private static void ReadField(DataInput @in, StoredFieldVisitor visitor, FieldInfo info, int bits)
{
switch (bits & CompressingStoredFieldsWriter.TYPE_MASK)
{
case CompressingStoredFieldsWriter.BYTE_ARR:
int length = @in.ReadVInt32();
var data = new byte[length];
@in.ReadBytes(data, 0, length);
visitor.BinaryField(info, data);
break;
case CompressingStoredFieldsWriter.STRING:
length = @in.ReadVInt32();
data = new byte[length];
@in.ReadBytes(data, 0, length);
#pragma warning disable 612, 618
visitor.StringField(info, IOUtils.CHARSET_UTF_8.GetString(data));
#pragma warning restore 612, 618
break;
case CompressingStoredFieldsWriter.NUMERIC_INT32:
visitor.Int32Field(info, @in.ReadInt32());
break;
case CompressingStoredFieldsWriter.NUMERIC_SINGLE:
visitor.SingleField(info, Number.Int32BitsToSingle(@in.ReadInt32()));
break;
case CompressingStoredFieldsWriter.NUMERIC_INT64:
visitor.Int64Field(info, @in.ReadInt64());
break;
case CompressingStoredFieldsWriter.NUMERIC_DOUBLE:
visitor.DoubleField(info, BitConverter.Int64BitsToDouble(@in.ReadInt64()));
break;
default:
throw new InvalidOperationException("Unknown type flag: " + bits.ToString("x"));
}
}
private static void SkipField(DataInput @in, int bits)
{
switch (bits & CompressingStoredFieldsWriter.TYPE_MASK)
{
case CompressingStoredFieldsWriter.BYTE_ARR:
case CompressingStoredFieldsWriter.STRING:
int length = @in.ReadVInt32();
@in.SkipBytes(length);
break;
case CompressingStoredFieldsWriter.NUMERIC_INT32:
case CompressingStoredFieldsWriter.NUMERIC_SINGLE:
@in.ReadInt32();
break;
case CompressingStoredFieldsWriter.NUMERIC_INT64:
case CompressingStoredFieldsWriter.NUMERIC_DOUBLE:
@in.ReadInt64();
break;
default:
throw new InvalidOperationException("Unknown type flag: " + bits.ToString("x"));
}
}
public override void VisitDocument(int docID, StoredFieldVisitor visitor)
{
fieldsStream.Seek(indexReader.GetStartPointer(docID));
int docBase = fieldsStream.ReadVInt32();
int chunkDocs = fieldsStream.ReadVInt32();
if (docID < docBase || docID >= docBase + chunkDocs || docBase + chunkDocs > numDocs)
{
throw new CorruptIndexException("Corrupted: docID=" + docID + ", docBase=" + docBase + ", chunkDocs=" + chunkDocs + ", numDocs=" + numDocs + " (resource=" + fieldsStream + ")");
}
int numStoredFields, offset, length, totalLength;
if (chunkDocs == 1)
{
numStoredFields = fieldsStream.ReadVInt32();
offset = 0;
length = fieldsStream.ReadVInt32();
totalLength = length;
}
else
{
int bitsPerStoredFields = fieldsStream.ReadVInt32();
if (bitsPerStoredFields == 0)
{
numStoredFields = fieldsStream.ReadVInt32();
}
else if (bitsPerStoredFields > 31)
{
throw new CorruptIndexException("bitsPerStoredFields=" + bitsPerStoredFields + " (resource=" + fieldsStream + ")");
}
else
{
long filePointer = fieldsStream.GetFilePointer();
PackedInt32s.Reader reader = PackedInt32s.GetDirectReaderNoHeader(fieldsStream, PackedInt32s.Format.PACKED, packedIntsVersion, chunkDocs, bitsPerStoredFields);
numStoredFields = (int)(reader.Get(docID - docBase));
fieldsStream.Seek(filePointer + PackedInt32s.Format.PACKED.ByteCount(packedIntsVersion, chunkDocs, bitsPerStoredFields));
}
int bitsPerLength = fieldsStream.ReadVInt32();
if (bitsPerLength == 0)
{
length = fieldsStream.ReadVInt32();
offset = (docID - docBase) * length;
totalLength = chunkDocs * length;
}
else if (bitsPerStoredFields > 31)
{
throw new CorruptIndexException("bitsPerLength=" + bitsPerLength + " (resource=" + fieldsStream + ")");
}
else
{
PackedInt32s.IReaderIterator it = PackedInt32s.GetReaderIteratorNoHeader(fieldsStream, PackedInt32s.Format.PACKED, packedIntsVersion, chunkDocs, bitsPerLength, 1);
int off = 0;
for (int i = 0; i < docID - docBase; ++i)
{
off += (int)it.Next();
}
offset = off;
length = (int)it.Next();
off += length;
for (int i = docID - docBase + 1; i < chunkDocs; ++i)
{
off += (int)it.Next();
}
totalLength = off;
}
}
if ((length == 0) != (numStoredFields == 0))
{
throw new CorruptIndexException("length=" + length + ", numStoredFields=" + numStoredFields + " (resource=" + fieldsStream + ")");
}
if (numStoredFields == 0)
{
// nothing to do
return;
}
DataInput documentInput;
if (version >= CompressingStoredFieldsWriter.VERSION_BIG_CHUNKS && totalLength >= 2 * chunkSize)
{
Debug.Assert(chunkSize > 0);
Debug.Assert(offset < chunkSize);
decompressor.Decompress(fieldsStream, chunkSize, offset, Math.Min(length, chunkSize - offset), bytes);
documentInput = new DataInputAnonymousInnerClassHelper(this, offset, length);
}
else
{
BytesRef bytes = totalLength <= BUFFER_REUSE_THRESHOLD ? this.bytes : new BytesRef();
decompressor.Decompress(fieldsStream, totalLength, offset, length, bytes);
Debug.Assert(bytes.Length == length);
documentInput = new ByteArrayDataInput(bytes.Bytes, bytes.Offset, bytes.Length);
}
for (int fieldIDX = 0; fieldIDX < numStoredFields; fieldIDX++)
{
long infoAndBits = documentInput.ReadVInt64();
int fieldNumber = (int)((long)((ulong)infoAndBits >> CompressingStoredFieldsWriter.TYPE_BITS));
FieldInfo fieldInfo = fieldInfos.FieldInfo(fieldNumber);
int bits = (int)(infoAndBits & CompressingStoredFieldsWriter.TYPE_MASK);
Debug.Assert(bits <= CompressingStoredFieldsWriter.NUMERIC_DOUBLE, "bits=" + bits.ToString("x"));
switch (visitor.NeedsField(fieldInfo))
{
case StoredFieldVisitor.Status.YES:
ReadField(documentInput, visitor, fieldInfo, bits);
break;
case StoredFieldVisitor.Status.NO:
SkipField(documentInput, bits);
break;
case StoredFieldVisitor.Status.STOP:
return;
}
}
}
private class DataInputAnonymousInnerClassHelper : DataInput
{
private readonly CompressingStoredFieldsReader outerInstance;
private int offset;
private int length;
public DataInputAnonymousInnerClassHelper(CompressingStoredFieldsReader outerInstance, int offset, int length)
{
this.outerInstance = outerInstance;
this.offset = offset;
this.length = length;
decompressed = outerInstance.bytes.Length;
}
internal int decompressed;
internal virtual void FillBuffer()
{
Debug.Assert(decompressed <= length);
if (decompressed == length)
{
throw new Exception();
}
int toDecompress = Math.Min(length - decompressed, outerInstance.chunkSize);
outerInstance.decompressor.Decompress(outerInstance.fieldsStream, toDecompress, 0, toDecompress, outerInstance.bytes);
decompressed += toDecompress;
}
public override byte ReadByte()
{
if (outerInstance.bytes.Length == 0)
{
FillBuffer();
}
--outerInstance.bytes.Length;
return (byte)outerInstance.bytes.Bytes[outerInstance.bytes.Offset++];
}
public override void ReadBytes(byte[] b, int offset, int len)
{
while (len > outerInstance.bytes.Length)
{
Array.Copy(outerInstance.bytes.Bytes, outerInstance.bytes.Offset, b, offset, outerInstance.bytes.Length);
len -= outerInstance.bytes.Length;
offset += outerInstance.bytes.Length;
FillBuffer();
}
Array.Copy(outerInstance.bytes.Bytes, outerInstance.bytes.Offset, b, offset, len);
outerInstance.bytes.Offset += len;
outerInstance.bytes.Length -= len;
}
}
public override object Clone()
{
EnsureOpen();
return new CompressingStoredFieldsReader(this);
}
internal int Version
{
get
{
return version;
}
}
internal CompressionMode CompressionMode
{
get
{
return compressionMode;
}
}
internal int ChunkSize
{
get
{
return chunkSize;
}
}
internal ChunkIterator GetChunkIterator(int startDocID)
{
EnsureOpen();
return new ChunkIterator(this, startDocID);
}
internal sealed class ChunkIterator
{
private readonly CompressingStoredFieldsReader outerInstance;
internal readonly ChecksumIndexInput fieldsStream;
internal readonly BytesRef spare;
internal readonly BytesRef bytes;
internal int docBase;
internal int chunkDocs;
internal int[] numStoredFields;
internal int[] lengths;
internal ChunkIterator(CompressingStoredFieldsReader outerInstance, int startDocId)
{
this.outerInstance = outerInstance;
this.docBase = -1;
bytes = new BytesRef();
spare = new BytesRef();
numStoredFields = new int[1];
lengths = new int[1];
IndexInput @in = outerInstance.fieldsStream;
@in.Seek(0);
fieldsStream = new BufferedChecksumIndexInput(@in);
fieldsStream.Seek(outerInstance.indexReader.GetStartPointer(startDocId));
}
/// <summary>
/// Return the decompressed size of the chunk
/// </summary>
internal int ChunkSize()
{
int sum = 0;
for (int i = 0; i < chunkDocs; ++i)
{
sum += lengths[i];
}
return sum;
}
/// <summary>
/// Go to the chunk containing the provided <paramref name="doc"/> ID.
/// </summary>
internal void Next(int doc)
{
Debug.Assert(doc >= this.docBase + this.chunkDocs, doc + " " + this.docBase + " " + this.chunkDocs);
fieldsStream.Seek(outerInstance.indexReader.GetStartPointer(doc));
int docBase = fieldsStream.ReadVInt32();
int chunkDocs = fieldsStream.ReadVInt32();
if (docBase < this.docBase + this.chunkDocs || docBase + chunkDocs > outerInstance.numDocs)
{
throw new CorruptIndexException("Corrupted: current docBase=" + this.docBase + ", current numDocs=" + this.chunkDocs + ", new docBase=" + docBase + ", new numDocs=" + chunkDocs + " (resource=" + fieldsStream + ")");
}
this.docBase = docBase;
this.chunkDocs = chunkDocs;
if (chunkDocs > numStoredFields.Length)
{
int newLength = ArrayUtil.Oversize(chunkDocs, 4);
numStoredFields = new int[newLength];
lengths = new int[newLength];
}
if (chunkDocs == 1)
{
numStoredFields[0] = fieldsStream.ReadVInt32();
lengths[0] = fieldsStream.ReadVInt32();
}
else
{
int bitsPerStoredFields = fieldsStream.ReadVInt32();
if (bitsPerStoredFields == 0)
{
Arrays.Fill(numStoredFields, 0, chunkDocs, fieldsStream.ReadVInt32());
}
else if (bitsPerStoredFields > 31)
{
throw new CorruptIndexException("bitsPerStoredFields=" + bitsPerStoredFields + " (resource=" + fieldsStream + ")");
}
else
{
PackedInt32s.IReaderIterator it = PackedInt32s.GetReaderIteratorNoHeader(fieldsStream, PackedInt32s.Format.PACKED, outerInstance.packedIntsVersion, chunkDocs, bitsPerStoredFields, 1);
for (int i = 0; i < chunkDocs; ++i)
{
numStoredFields[i] = (int)it.Next();
}
}
int bitsPerLength = fieldsStream.ReadVInt32();
if (bitsPerLength == 0)
{
Arrays.Fill(lengths, 0, chunkDocs, fieldsStream.ReadVInt32());
}
else if (bitsPerLength > 31)
{
throw new CorruptIndexException("bitsPerLength=" + bitsPerLength);
}
else
{
PackedInt32s.IReaderIterator it = PackedInt32s.GetReaderIteratorNoHeader(fieldsStream, PackedInt32s.Format.PACKED, outerInstance.packedIntsVersion, chunkDocs, bitsPerLength, 1);
for (int i = 0; i < chunkDocs; ++i)
{
lengths[i] = (int)it.Next();
}
}
}
}
/// <summary>
/// Decompress the chunk.
/// </summary>
internal void Decompress()
{
// decompress data
int chunkSize = ChunkSize();
if (outerInstance.version >= CompressingStoredFieldsWriter.VERSION_BIG_CHUNKS && chunkSize >= 2 * outerInstance.chunkSize)
{
bytes.Offset = bytes.Length = 0;
for (int decompressed = 0; decompressed < chunkSize; )
{
int toDecompress = Math.Min(chunkSize - decompressed, outerInstance.chunkSize);
outerInstance.decompressor.Decompress(fieldsStream, toDecompress, 0, toDecompress, spare);
bytes.Bytes = ArrayUtil.Grow(bytes.Bytes, bytes.Length + spare.Length);
Array.Copy(spare.Bytes, spare.Offset, bytes.Bytes, bytes.Length, spare.Length);
bytes.Length += spare.Length;
decompressed += toDecompress;
}
}
else
{
outerInstance.decompressor.Decompress(fieldsStream, chunkSize, 0, chunkSize, bytes);
}
if (bytes.Length != chunkSize)
{
throw new CorruptIndexException("Corrupted: expected chunk size = " + ChunkSize() + ", got " + bytes.Length + " (resource=" + fieldsStream + ")");
}
}
/// <summary>
/// Copy compressed data.
/// </summary>
internal void CopyCompressedData(DataOutput @out)
{
Debug.Assert(outerInstance.Version == CompressingStoredFieldsWriter.VERSION_CURRENT);
long chunkEnd = docBase + chunkDocs == outerInstance.numDocs ? outerInstance.maxPointer : outerInstance.indexReader.GetStartPointer(docBase + chunkDocs);
@out.CopyBytes(fieldsStream, chunkEnd - fieldsStream.GetFilePointer());
}
/// <summary>
/// Check integrity of the data. The iterator is not usable after this method has been called.
/// </summary>
internal void CheckIntegrity()
{
if (outerInstance.version >= CompressingStoredFieldsWriter.VERSION_CHECKSUM)
{
fieldsStream.Seek(fieldsStream.Length - CodecUtil.FooterLength());
CodecUtil.CheckFooter(fieldsStream);
}
}
}
public override long RamBytesUsed()
{
return indexReader.RamBytesUsed();
}
public override void CheckIntegrity()
{
if (version >= CompressingStoredFieldsWriter.VERSION_CHECKSUM)
{
CodecUtil.ChecksumEntireFile(fieldsStream);
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Algorithm.Framework;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algortihm for testing <see cref="ScheduledUniverseSelectionModel"/> scheduling functions
/// </summary>
public class ScheduledUniverseSelectionModelRegressionAlgorithm : QCAlgorithmFramework, IRegressionAlgorithmDefinition
{
public override void Initialize()
{
UniverseSettings.Resolution = Resolution.Hour;
SetStartDate(2017, 01, 01);
SetEndDate(2017, 02, 01);
// selection will run on mon/tues/thurs at 00:00/06:00/12:00/18:00
SetUniverseSelection(new ScheduledUniverseSelectionModel(
DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Thursday),
TimeRules.Every(TimeSpan.FromHours(12)),
SelectSymbols
));
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1)));
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
}
private IEnumerable<Symbol> SelectSymbols(DateTime dateTime)
{
if (dateTime.DayOfWeek == DayOfWeek.Monday || dateTime.DayOfWeek == DayOfWeek.Tuesday)
{
yield return QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
}
else if (dateTime.DayOfWeek == DayOfWeek.Wednesday)
{
// given the date/time rules specified in Initialize, this symbol will never be selected (not invoked on wednesdays)
yield return QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
}
else
{
yield return QuantConnect.Symbol.Create("IBM", SecurityType.Equity, Market.USA);
}
if (dateTime.DayOfWeek == DayOfWeek.Tuesday || dateTime.DayOfWeek == DayOfWeek.Thursday)
{
yield return QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM);
}
else if (dateTime.DayOfWeek == DayOfWeek.Friday)
{
// given the date/time rules specified in Initialize, this symbol will never be selected (every 6 hours never lands on hour==1)
yield return QuantConnect.Symbol.Create("EURGBP", SecurityType.Forex, Market.FXCM);
}
else
{
yield return QuantConnect.Symbol.Create("NZDUSD", SecurityType.Forex, Market.FXCM);
}
}
// some days of the week have different behavior the first time -- less securities to remove
private readonly HashSet<DayOfWeek> _seenDays = new HashSet<DayOfWeek>();
public override void OnSecuritiesChanged(SecurityChanges changes)
{
Console.WriteLine($"{Time}: {changes}");
switch (Time.DayOfWeek)
{
case DayOfWeek.Monday:
ExpectAdditions(changes, "SPY", "NZDUSD");
if (_seenDays.Add(DayOfWeek.Monday))
{
ExpectRemovals(changes, null);
}
else
{
ExpectRemovals(changes, "EURUSD", "IBM");
}
break;
case DayOfWeek.Tuesday:
ExpectAdditions(changes, "EURUSD");
if (_seenDays.Add(DayOfWeek.Tuesday))
{
ExpectRemovals(changes, "NZDUSD");
}
else
{
ExpectRemovals(changes, "NZDUSD");
}
break;
case DayOfWeek.Wednesday:
// selection function not invoked on wednesdays
ExpectAdditions(changes, null);
ExpectRemovals(changes, null);
break;
case DayOfWeek.Thursday:
ExpectAdditions(changes, "IBM");
ExpectRemovals(changes, "SPY");
break;
case DayOfWeek.Friday:
// selection function not invoked on fridays
ExpectAdditions(changes, null);
ExpectRemovals(changes, null);
break;
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Console.WriteLine($"{Time}: {orderEvent}");
}
private void ExpectAdditions(SecurityChanges changes, params string[] tickers)
{
if (tickers == null && changes.AddedSecurities.Count > 0)
{
throw new Exception($"{Time}: Expected no additions: {Time.DayOfWeek}");
}
if (tickers == null)
{
return;
}
foreach (var ticker in tickers)
{
if (changes.AddedSecurities.All(s => s.Symbol.Value != ticker))
{
throw new Exception($"{Time}: Expected {ticker} to be added: {Time.DayOfWeek}");
}
}
}
private void ExpectRemovals(SecurityChanges changes, params string[] tickers)
{
if (tickers == null && changes.RemovedSecurities.Count > 0)
{
throw new Exception($"{Time}: Expected no removals: {Time.DayOfWeek}");
}
if (tickers == null)
{
return;
}
foreach (var ticker in tickers)
{
if (changes.RemovedSecurities.All(s => s.Symbol.Value != ticker))
{
throw new Exception($"{Time}: Expected {ticker} to be removed: {Time.DayOfWeek}");
}
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "44"},
{"Average Win", "0.28%"},
{"Average Loss", "-0.15%"},
{"Compounding Annual Return", "47.960%"},
{"Drawdown", "0.700%"},
{"Expectancy", "1.106"},
{"Net Profit", "3.494%"},
{"Sharpe Ratio", "5.594"},
{"Loss Rate", "26%"},
{"Win Rate", "74%"},
{"Profit-Loss Ratio", "1.86"},
{"Alpha", "0.526"},
{"Beta", "-14.85"},
{"Annual Standard Deviation", "0.054"},
{"Annual Variance", "0.003"},
{"Information Ratio", "5.307"},
{"Tracking Error", "0.054"},
{"Treynor Ratio", "-0.02"},
{"Total Fees", "$31.96"},
{"Total Insights Generated", "54"},
{"Total Insights Closed", "52"},
{"Total Insights Analysis Completed", "52"},
{"Long Insight Count", "54"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$598654.7604"},
{"Total Accumulated Estimated Alpha Value", "$642722.4025"},
{"Mean Population Estimated Insight Value", "$12360.0462"},
{"Mean Population Direction", "61.5385%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "65.1281%"},
{"Rolling Averaged Population Magnitude", "0%"}
};
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using NUnit.Util;
using NUnit.UiKit;
namespace NUnit.Gui
{
/// <summary>
/// Summary description for OptionsDialog.
/// </summary>
public class OptionsDialog : System.Windows.Forms.Form
{
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.HelpProvider helpProvider1;
private System.Windows.Forms.CheckBox clearResultsCheckBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ComboBox initialDisplayComboBox;
private System.Windows.Forms.CheckBox reloadOnChangeCheckBox;
private System.Windows.Forms.CheckBox reloadOnRunCheckBox;
private System.Windows.Forms.CheckBox loadLastProjectCheckBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox recentFilesCountTextBox;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.ComponentModel.IContainer components = null;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.GroupBox groupBox6;
private System.Windows.Forms.RadioButton multiDomainRadioButton;
private System.Windows.Forms.RadioButton singleDomainRadioButton;
private System.Windows.Forms.CheckBox mergeAssembliesCheckBox;
private System.Windows.Forms.GroupBox groupBox7;
private System.Windows.Forms.RadioButton autoNamespaceSuites;
private System.Windows.Forms.RadioButton flatTestList;
private System.Windows.Forms.CheckBox rerunOnChangeCheckBox;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.GroupBox groupBox8;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.CheckBox visualStudioSupportCheckBox;
private System.Windows.Forms.CheckBox labelTestOutputCheckBox;
private System.Windows.Forms.CheckBox enableWordWrap;
private System.Windows.Forms.CheckBox failureToolTips;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.CheckBox errorsTabCheckBox;
private System.Windows.Forms.CheckBox notRunTabCheckBox;
private System.Windows.Forms.CheckBox consoleOutputCheckBox;
private System.Windows.Forms.CheckBox traceOutputCheckBox;
private System.Windows.Forms.CheckBox consoleErrrorCheckBox;
private System.Windows.Forms.RadioButton separateErrors;
private System.Windows.Forms.RadioButton mergeErrors;
private System.Windows.Forms.RadioButton mergeTrace;
private System.Windows.Forms.RadioButton separateTrace;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.GroupBox groupBox9;
private System.Windows.Forms.CheckBox shadowCopyCheckBox;
private ISettings settings;
public OptionsDialog()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(OptionsDialog));
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.helpProvider1 = new System.Windows.Forms.HelpProvider();
this.loadLastProjectCheckBox = new System.Windows.Forms.CheckBox();
this.clearResultsCheckBox = new System.Windows.Forms.CheckBox();
this.reloadOnChangeCheckBox = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.initialDisplayComboBox = new System.Windows.Forms.ComboBox();
this.reloadOnRunCheckBox = new System.Windows.Forms.CheckBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.recentFilesCountTextBox = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.rerunOnChangeCheckBox = new System.Windows.Forms.CheckBox();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.groupBox9 = new System.Windows.Forms.GroupBox();
this.shadowCopyCheckBox = new System.Windows.Forms.CheckBox();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.visualStudioSupportCheckBox = new System.Windows.Forms.CheckBox();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.groupBox7 = new System.Windows.Forms.GroupBox();
this.flatTestList = new System.Windows.Forms.RadioButton();
this.autoNamespaceSuites = new System.Windows.Forms.RadioButton();
this.groupBox6 = new System.Windows.Forms.GroupBox();
this.mergeAssembliesCheckBox = new System.Windows.Forms.CheckBox();
this.singleDomainRadioButton = new System.Windows.Forms.RadioButton();
this.multiDomainRadioButton = new System.Windows.Forms.RadioButton();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.panel2 = new System.Windows.Forms.Panel();
this.separateTrace = new System.Windows.Forms.RadioButton();
this.traceOutputCheckBox = new System.Windows.Forms.CheckBox();
this.mergeTrace = new System.Windows.Forms.RadioButton();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.errorsTabCheckBox = new System.Windows.Forms.CheckBox();
this.failureToolTips = new System.Windows.Forms.CheckBox();
this.enableWordWrap = new System.Windows.Forms.CheckBox();
this.notRunTabCheckBox = new System.Windows.Forms.CheckBox();
this.groupBox8 = new System.Windows.Forms.GroupBox();
this.consoleOutputCheckBox = new System.Windows.Forms.CheckBox();
this.labelTestOutputCheckBox = new System.Windows.Forms.CheckBox();
this.panel1 = new System.Windows.Forms.Panel();
this.consoleErrrorCheckBox = new System.Windows.Forms.CheckBox();
this.mergeErrors = new System.Windows.Forms.RadioButton();
this.separateErrors = new System.Windows.Forms.RadioButton();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.groupBox9.SuspendLayout();
this.groupBox4.SuspendLayout();
this.groupBox5.SuspendLayout();
this.tabPage2.SuspendLayout();
this.groupBox7.SuspendLayout();
this.groupBox6.SuspendLayout();
this.tabPage3.SuspendLayout();
this.panel2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox8.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// okButton
//
this.okButton.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.okButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.okButton.Location = new System.Drawing.Point(77, 434);
this.okButton.Name = "okButton";
this.helpProvider1.SetShowHelp(this.okButton, false);
this.okButton.Size = new System.Drawing.Size(76, 23);
this.okButton.TabIndex = 15;
this.okButton.Text = "OK";
this.okButton.Click += new System.EventHandler(this.okButton_Click);
//
// cancelButton
//
this.cancelButton.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.cancelButton.CausesValidation = false;
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.cancelButton.Location = new System.Drawing.Point(173, 434);
this.cancelButton.Name = "cancelButton";
this.helpProvider1.SetShowHelp(this.cancelButton, false);
this.cancelButton.Size = new System.Drawing.Size(68, 23);
this.cancelButton.TabIndex = 16;
this.cancelButton.Text = "Cancel";
//
// loadLastProjectCheckBox
//
this.helpProvider1.SetHelpString(this.loadLastProjectCheckBox, "If checked, most recent project is loaded at startup.");
this.loadLastProjectCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.loadLastProjectCheckBox.Location = new System.Drawing.Point(19, 65);
this.loadLastProjectCheckBox.Name = "loadLastProjectCheckBox";
this.helpProvider1.SetShowHelp(this.loadLastProjectCheckBox, true);
this.loadLastProjectCheckBox.Size = new System.Drawing.Size(250, 24);
this.loadLastProjectCheckBox.TabIndex = 4;
this.loadLastProjectCheckBox.Text = "Load most recent project at startup.";
//
// clearResultsCheckBox
//
this.helpProvider1.SetHelpString(this.clearResultsCheckBox, "If checked, any prior results are cleared when reloading.");
this.clearResultsCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.clearResultsCheckBox.Location = new System.Drawing.Point(19, 65);
this.clearResultsCheckBox.Name = "clearResultsCheckBox";
this.helpProvider1.SetShowHelp(this.clearResultsCheckBox, true);
this.clearResultsCheckBox.Size = new System.Drawing.Size(232, 24);
this.clearResultsCheckBox.TabIndex = 10;
this.clearResultsCheckBox.Text = "Clear results when reloading.";
//
// reloadOnChangeCheckBox
//
this.helpProvider1.SetHelpString(this.reloadOnChangeCheckBox, "If checked, the assembly is reloaded whenever it changes. Changes to this setting" +
" do not take effect until the next time an assembly is loaded.");
this.reloadOnChangeCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.reloadOnChangeCheckBox.Location = new System.Drawing.Point(19, 55);
this.reloadOnChangeCheckBox.Name = "reloadOnChangeCheckBox";
this.helpProvider1.SetShowHelp(this.reloadOnChangeCheckBox, true);
this.reloadOnChangeCheckBox.Size = new System.Drawing.Size(245, 25);
this.reloadOnChangeCheckBox.TabIndex = 9;
this.reloadOnChangeCheckBox.Text = "Reload when test assembly changes";
this.reloadOnChangeCheckBox.CheckedChanged += new System.EventHandler(this.reloadOnChangeCheckBox_CheckedChanged);
//
// label1
//
this.helpProvider1.SetHelpString(this.label1, "");
this.label1.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.label1.Location = new System.Drawing.Point(19, 28);
this.label1.Name = "label1";
this.helpProvider1.SetShowHelp(this.label1, true);
this.label1.Size = new System.Drawing.Size(144, 24);
this.label1.TabIndex = 5;
this.label1.Text = "Initial display on load:";
//
// initialDisplayComboBox
//
this.initialDisplayComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.helpProvider1.SetHelpString(this.initialDisplayComboBox, "Selects the initial display style of the tree when an assembly is loaded");
this.initialDisplayComboBox.ItemHeight = 16;
this.initialDisplayComboBox.Items.AddRange(new object[] {
"Auto",
"Expand",
"Collapse",
"HideTests"});
this.initialDisplayComboBox.Location = new System.Drawing.Point(173, 28);
this.initialDisplayComboBox.Name = "initialDisplayComboBox";
this.helpProvider1.SetShowHelp(this.initialDisplayComboBox, true);
this.initialDisplayComboBox.Size = new System.Drawing.Size(87, 24);
this.initialDisplayComboBox.TabIndex = 6;
//
// reloadOnRunCheckBox
//
this.helpProvider1.SetHelpString(this.reloadOnRunCheckBox, "If checked, the assembly is reloaded before each run.");
this.reloadOnRunCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.reloadOnRunCheckBox.Location = new System.Drawing.Point(19, 28);
this.reloadOnRunCheckBox.Name = "reloadOnRunCheckBox";
this.helpProvider1.SetShowHelp(this.reloadOnRunCheckBox, true);
this.reloadOnRunCheckBox.Size = new System.Drawing.Size(237, 23);
this.reloadOnRunCheckBox.TabIndex = 8;
this.reloadOnRunCheckBox.Text = "Reload before each test run";
//
// label2
//
this.label2.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.label2.Location = new System.Drawing.Point(19, 28);
this.label2.Name = "label2";
this.helpProvider1.SetShowHelp(this.label2, false);
this.label2.Size = new System.Drawing.Size(55, 16);
this.label2.TabIndex = 1;
this.label2.Text = "Display";
//
// label3
//
this.label3.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.label3.Location = new System.Drawing.Point(144, 28);
this.label3.Name = "label3";
this.helpProvider1.SetShowHelp(this.label3, false);
this.label3.Size = new System.Drawing.Size(96, 24);
this.label3.TabIndex = 3;
this.label3.Text = "files in list";
//
// recentFilesCountTextBox
//
this.recentFilesCountTextBox.Location = new System.Drawing.Point(86, 28);
this.recentFilesCountTextBox.Name = "recentFilesCountTextBox";
this.helpProvider1.SetShowHelp(this.recentFilesCountTextBox, false);
this.recentFilesCountTextBox.Size = new System.Drawing.Size(40, 22);
this.recentFilesCountTextBox.TabIndex = 2;
this.recentFilesCountTextBox.Text = "";
this.recentFilesCountTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.recentFilesCountTextBox_Validating);
this.recentFilesCountTextBox.Validated += new System.EventHandler(this.recentFilesCountTextBox_Validated);
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.recentFilesCountTextBox);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.loadLastProjectCheckBox);
this.groupBox1.Location = new System.Drawing.Point(10, 9);
this.groupBox1.Name = "groupBox1";
this.helpProvider1.SetShowHelp(this.groupBox1, false);
this.groupBox1.Size = new System.Drawing.Size(283, 102);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Recent Files";
//
// groupBox2
//
this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox2.Controls.Add(this.rerunOnChangeCheckBox);
this.groupBox2.Controls.Add(this.reloadOnRunCheckBox);
this.groupBox2.Controls.Add(this.reloadOnChangeCheckBox);
this.groupBox2.Location = new System.Drawing.Point(10, 208);
this.groupBox2.Name = "groupBox2";
this.helpProvider1.SetShowHelp(this.groupBox2, false);
this.groupBox2.Size = new System.Drawing.Size(283, 120);
this.groupBox2.TabIndex = 7;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Assembly Reload";
//
// rerunOnChangeCheckBox
//
this.rerunOnChangeCheckBox.Enabled = false;
this.rerunOnChangeCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.rerunOnChangeCheckBox.Location = new System.Drawing.Point(40, 80);
this.rerunOnChangeCheckBox.Name = "rerunOnChangeCheckBox";
this.helpProvider1.SetShowHelp(this.rerunOnChangeCheckBox, false);
this.rerunOnChangeCheckBox.Size = new System.Drawing.Size(200, 24);
this.rerunOnChangeCheckBox.TabIndex = 10;
this.rerunOnChangeCheckBox.Text = "Re-run last tests run";
//
// tabControl1
//
this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.ItemSize = new System.Drawing.Size(46, 18);
this.tabControl1.Location = new System.Drawing.Point(10, 9);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.helpProvider1.SetShowHelp(this.tabControl1, false);
this.tabControl1.Size = new System.Drawing.Size(310, 420);
this.tabControl1.TabIndex = 2;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.groupBox9);
this.tabPage1.Controls.Add(this.groupBox4);
this.tabPage1.Controls.Add(this.groupBox5);
this.tabPage1.Controls.Add(this.groupBox1);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.helpProvider1.SetShowHelp(this.tabPage1, false);
this.tabPage1.Size = new System.Drawing.Size(302, 394);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "General";
//
// groupBox9
//
this.groupBox9.Controls.Add(this.shadowCopyCheckBox);
this.groupBox9.Location = new System.Drawing.Point(8, 296);
this.groupBox9.Name = "groupBox9";
this.groupBox9.Size = new System.Drawing.Size(280, 48);
this.groupBox9.TabIndex = 15;
this.groupBox9.TabStop = false;
this.groupBox9.Text = "Shadow Copy";
//
// shadowCopyCheckBox
//
this.shadowCopyCheckBox.Location = new System.Drawing.Point(19, 18);
this.shadowCopyCheckBox.Name = "shadowCopyCheckBox";
this.shadowCopyCheckBox.Size = new System.Drawing.Size(240, 22);
this.shadowCopyCheckBox.TabIndex = 0;
this.shadowCopyCheckBox.Text = "Enable Shadow Copy";
//
// groupBox4
//
this.groupBox4.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox4.Controls.Add(this.visualStudioSupportCheckBox);
this.groupBox4.Location = new System.Drawing.Point(10, 240);
this.groupBox4.Name = "groupBox4";
this.helpProvider1.SetShowHelp(this.groupBox4, false);
this.groupBox4.Size = new System.Drawing.Size(283, 47);
this.groupBox4.TabIndex = 14;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Visual Studio";
//
// visualStudioSupportCheckBox
//
this.helpProvider1.SetHelpString(this.visualStudioSupportCheckBox, "If checked, Visual Studio projects and solutions may be opened or added to existi" +
"ng test projects.");
this.visualStudioSupportCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.visualStudioSupportCheckBox.Location = new System.Drawing.Point(19, 18);
this.visualStudioSupportCheckBox.Name = "visualStudioSupportCheckBox";
this.helpProvider1.SetShowHelp(this.visualStudioSupportCheckBox, true);
this.visualStudioSupportCheckBox.Size = new System.Drawing.Size(264, 25);
this.visualStudioSupportCheckBox.TabIndex = 14;
this.visualStudioSupportCheckBox.Text = "Enable Visual Studio Support";
//
// groupBox5
//
this.groupBox5.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox5.Controls.Add(this.label1);
this.groupBox5.Controls.Add(this.initialDisplayComboBox);
this.groupBox5.Controls.Add(this.clearResultsCheckBox);
this.groupBox5.Location = new System.Drawing.Point(10, 120);
this.groupBox5.Name = "groupBox5";
this.helpProvider1.SetShowHelp(this.groupBox5, false);
this.groupBox5.Size = new System.Drawing.Size(283, 102);
this.groupBox5.TabIndex = 1;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Tree View";
//
// tabPage2
//
this.tabPage2.Controls.Add(this.groupBox7);
this.tabPage2.Controls.Add(this.groupBox6);
this.tabPage2.Controls.Add(this.groupBox2);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.helpProvider1.SetShowHelp(this.tabPage2, false);
this.tabPage2.Size = new System.Drawing.Size(302, 394);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Test Load";
//
// groupBox7
//
this.groupBox7.Controls.Add(this.flatTestList);
this.groupBox7.Controls.Add(this.autoNamespaceSuites);
this.groupBox7.Location = new System.Drawing.Point(8, 8);
this.groupBox7.Name = "groupBox7";
this.helpProvider1.SetShowHelp(this.groupBox7, false);
this.groupBox7.Size = new System.Drawing.Size(288, 80);
this.groupBox7.TabIndex = 16;
this.groupBox7.TabStop = false;
this.groupBox7.Text = "Test Structure";
//
// flatTestList
//
this.flatTestList.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.flatTestList.Location = new System.Drawing.Point(24, 48);
this.flatTestList.Name = "flatTestList";
this.helpProvider1.SetShowHelp(this.flatTestList, false);
this.flatTestList.Size = new System.Drawing.Size(216, 24);
this.flatTestList.TabIndex = 1;
this.flatTestList.Text = "Flat list of TestFixtures";
//
// autoNamespaceSuites
//
this.autoNamespaceSuites.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.autoNamespaceSuites.Location = new System.Drawing.Point(24, 16);
this.autoNamespaceSuites.Name = "autoNamespaceSuites";
this.helpProvider1.SetShowHelp(this.autoNamespaceSuites, false);
this.autoNamespaceSuites.Size = new System.Drawing.Size(224, 24);
this.autoNamespaceSuites.TabIndex = 0;
this.autoNamespaceSuites.Text = "Automatic Namespace suites";
//
// groupBox6
//
this.groupBox6.Controls.Add(this.mergeAssembliesCheckBox);
this.groupBox6.Controls.Add(this.singleDomainRadioButton);
this.groupBox6.Controls.Add(this.multiDomainRadioButton);
this.groupBox6.Location = new System.Drawing.Point(8, 96);
this.groupBox6.Name = "groupBox6";
this.helpProvider1.SetShowHelp(this.groupBox6, false);
this.groupBox6.Size = new System.Drawing.Size(288, 104);
this.groupBox6.TabIndex = 14;
this.groupBox6.TabStop = false;
this.groupBox6.Text = "Multiple Assemblies";
//
// mergeAssembliesCheckBox
//
this.mergeAssembliesCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.mergeAssembliesCheckBox.Location = new System.Drawing.Point(40, 72);
this.mergeAssembliesCheckBox.Name = "mergeAssembliesCheckBox";
this.helpProvider1.SetShowHelp(this.mergeAssembliesCheckBox, false);
this.mergeAssembliesCheckBox.Size = new System.Drawing.Size(224, 24);
this.mergeAssembliesCheckBox.TabIndex = 2;
this.mergeAssembliesCheckBox.Text = "Merge tests across assemblies";
//
// singleDomainRadioButton
//
this.singleDomainRadioButton.Checked = true;
this.singleDomainRadioButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.singleDomainRadioButton.Location = new System.Drawing.Point(24, 48);
this.singleDomainRadioButton.Name = "singleDomainRadioButton";
this.helpProvider1.SetShowHelp(this.singleDomainRadioButton, false);
this.singleDomainRadioButton.Size = new System.Drawing.Size(240, 24);
this.singleDomainRadioButton.TabIndex = 1;
this.singleDomainRadioButton.TabStop = true;
this.singleDomainRadioButton.Text = "Load in a single AppDomain";
this.singleDomainRadioButton.CheckedChanged += new System.EventHandler(this.singleDomainRadioButton_CheckedChanged);
//
// multiDomainRadioButton
//
this.multiDomainRadioButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.multiDomainRadioButton.Location = new System.Drawing.Point(24, 24);
this.multiDomainRadioButton.Name = "multiDomainRadioButton";
this.helpProvider1.SetShowHelp(this.multiDomainRadioButton, false);
this.multiDomainRadioButton.Size = new System.Drawing.Size(240, 24);
this.multiDomainRadioButton.TabIndex = 0;
this.multiDomainRadioButton.Text = "Load in separate AppDomains";
//
// tabPage3
//
this.tabPage3.Controls.Add(this.panel2);
this.tabPage3.Controls.Add(this.groupBox3);
this.tabPage3.Controls.Add(this.groupBox8);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.helpProvider1.SetShowHelp(this.tabPage3, false);
this.tabPage3.Size = new System.Drawing.Size(302, 394);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "Test Output";
//
// panel2
//
this.panel2.Controls.Add(this.separateTrace);
this.panel2.Controls.Add(this.traceOutputCheckBox);
this.panel2.Controls.Add(this.mergeTrace);
this.panel2.Location = new System.Drawing.Point(8, 296);
this.panel2.Name = "panel2";
this.helpProvider1.SetShowHelp(this.panel2, false);
this.panel2.Size = new System.Drawing.Size(248, 80);
this.panel2.TabIndex = 14;
//
// separateTrace
//
this.separateTrace.Checked = true;
this.separateTrace.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.separateTrace.Location = new System.Drawing.Point(32, 32);
this.separateTrace.Name = "separateTrace";
this.helpProvider1.SetShowHelp(this.separateTrace, false);
this.separateTrace.Size = new System.Drawing.Size(224, 16);
this.separateTrace.TabIndex = 18;
this.separateTrace.TabStop = true;
this.separateTrace.Text = "In Separate Tab";
//
// traceOutputCheckBox
//
this.traceOutputCheckBox.Checked = true;
this.traceOutputCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.traceOutputCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.traceOutputCheckBox.Location = new System.Drawing.Point(8, 8);
this.traceOutputCheckBox.Name = "traceOutputCheckBox";
this.helpProvider1.SetShowHelp(this.traceOutputCheckBox, false);
this.traceOutputCheckBox.Size = new System.Drawing.Size(208, 16);
this.traceOutputCheckBox.TabIndex = 14;
this.traceOutputCheckBox.Text = "Display Trace Output";
this.traceOutputCheckBox.CheckedChanged += new System.EventHandler(this.traceOutputCheckBox_CheckedChanged);
//
// mergeTrace
//
this.mergeTrace.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.mergeTrace.Location = new System.Drawing.Point(32, 56);
this.mergeTrace.Name = "mergeTrace";
this.helpProvider1.SetShowHelp(this.mergeTrace, false);
this.mergeTrace.Size = new System.Drawing.Size(192, 16);
this.mergeTrace.TabIndex = 19;
this.mergeTrace.Text = "Merge with Console Output";
//
// groupBox3
//
this.groupBox3.Controls.Add(this.errorsTabCheckBox);
this.groupBox3.Controls.Add(this.failureToolTips);
this.groupBox3.Controls.Add(this.enableWordWrap);
this.groupBox3.Controls.Add(this.notRunTabCheckBox);
this.groupBox3.Location = new System.Drawing.Point(0, 8);
this.groupBox3.Name = "groupBox3";
this.helpProvider1.SetShowHelp(this.groupBox3, false);
this.groupBox3.Size = new System.Drawing.Size(296, 128);
this.groupBox3.TabIndex = 13;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Test Results";
//
// errorsTabCheckBox
//
this.errorsTabCheckBox.Checked = true;
this.errorsTabCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.errorsTabCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.errorsTabCheckBox.Location = new System.Drawing.Point(16, 16);
this.errorsTabCheckBox.Name = "errorsTabCheckBox";
this.helpProvider1.SetShowHelp(this.errorsTabCheckBox, false);
this.errorsTabCheckBox.Size = new System.Drawing.Size(248, 24);
this.errorsTabCheckBox.TabIndex = 15;
this.errorsTabCheckBox.Text = "Display Errors and Failures";
this.errorsTabCheckBox.CheckedChanged += new System.EventHandler(this.errorsTabCheckBox_CheckedChanged);
//
// failureToolTips
//
this.failureToolTips.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.failureToolTips.Location = new System.Drawing.Point(32, 40);
this.failureToolTips.Name = "failureToolTips";
this.helpProvider1.SetShowHelp(this.failureToolTips, false);
this.failureToolTips.Size = new System.Drawing.Size(202, 19);
this.failureToolTips.TabIndex = 13;
this.failureToolTips.Text = "Display Failure ToolTips";
//
// enableWordWrap
//
this.enableWordWrap.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.enableWordWrap.Location = new System.Drawing.Point(32, 64);
this.enableWordWrap.Name = "enableWordWrap";
this.helpProvider1.SetShowHelp(this.enableWordWrap, false);
this.enableWordWrap.Size = new System.Drawing.Size(248, 19);
this.enableWordWrap.TabIndex = 14;
this.enableWordWrap.Text = "Enable Word Wrap";
//
// notRunTabCheckBox
//
this.notRunTabCheckBox.Checked = true;
this.notRunTabCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.notRunTabCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.notRunTabCheckBox.Location = new System.Drawing.Point(16, 96);
this.notRunTabCheckBox.Name = "notRunTabCheckBox";
this.helpProvider1.SetShowHelp(this.notRunTabCheckBox, false);
this.notRunTabCheckBox.Size = new System.Drawing.Size(264, 16);
this.notRunTabCheckBox.TabIndex = 0;
this.notRunTabCheckBox.Text = "Display Tests Not Run";
//
// groupBox8
//
this.groupBox8.Controls.Add(this.consoleOutputCheckBox);
this.groupBox8.Controls.Add(this.labelTestOutputCheckBox);
this.groupBox8.Controls.Add(this.panel1);
this.groupBox8.Location = new System.Drawing.Point(0, 152);
this.groupBox8.Name = "groupBox8";
this.helpProvider1.SetShowHelp(this.groupBox8, false);
this.groupBox8.Size = new System.Drawing.Size(298, 232);
this.groupBox8.TabIndex = 12;
this.groupBox8.TabStop = false;
this.groupBox8.Text = "Text Output";
//
// consoleOutputCheckBox
//
this.consoleOutputCheckBox.Checked = true;
this.consoleOutputCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.consoleOutputCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.consoleOutputCheckBox.Location = new System.Drawing.Point(16, 18);
this.consoleOutputCheckBox.Name = "consoleOutputCheckBox";
this.helpProvider1.SetShowHelp(this.consoleOutputCheckBox, false);
this.consoleOutputCheckBox.Size = new System.Drawing.Size(240, 16);
this.consoleOutputCheckBox.TabIndex = 13;
this.consoleOutputCheckBox.Text = "Display Console Standard Output";
this.consoleOutputCheckBox.CheckedChanged += new System.EventHandler(this.consoleOutputCheckBox_CheckedChanged);
//
// labelTestOutputCheckBox
//
this.labelTestOutputCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.labelTestOutputCheckBox.Location = new System.Drawing.Point(32, 40);
this.labelTestOutputCheckBox.Name = "labelTestOutputCheckBox";
this.helpProvider1.SetShowHelp(this.labelTestOutputCheckBox, false);
this.labelTestOutputCheckBox.Size = new System.Drawing.Size(237, 19);
this.labelTestOutputCheckBox.TabIndex = 12;
this.labelTestOutputCheckBox.Text = "Label Test Cases";
//
// panel1
//
this.panel1.Controls.Add(this.consoleErrrorCheckBox);
this.panel1.Controls.Add(this.mergeErrors);
this.panel1.Controls.Add(this.separateErrors);
this.panel1.Location = new System.Drawing.Point(8, 64);
this.panel1.Name = "panel1";
this.helpProvider1.SetShowHelp(this.panel1, false);
this.panel1.Size = new System.Drawing.Size(248, 80);
this.panel1.TabIndex = 14;
//
// consoleErrrorCheckBox
//
this.consoleErrrorCheckBox.Checked = true;
this.consoleErrrorCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.consoleErrrorCheckBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.consoleErrrorCheckBox.Location = new System.Drawing.Point(8, 8);
this.consoleErrrorCheckBox.Name = "consoleErrrorCheckBox";
this.helpProvider1.SetShowHelp(this.consoleErrrorCheckBox, false);
this.consoleErrrorCheckBox.Size = new System.Drawing.Size(232, 24);
this.consoleErrrorCheckBox.TabIndex = 15;
this.consoleErrrorCheckBox.Text = "Display Console Error Output";
this.consoleErrrorCheckBox.CheckedChanged += new System.EventHandler(this.consoleErrrorCheckBox_CheckedChanged);
//
// mergeErrors
//
this.mergeErrors.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.mergeErrors.Location = new System.Drawing.Point(32, 56);
this.mergeErrors.Name = "mergeErrors";
this.helpProvider1.SetShowHelp(this.mergeErrors, false);
this.mergeErrors.Size = new System.Drawing.Size(192, 16);
this.mergeErrors.TabIndex = 17;
this.mergeErrors.Text = "Merge with Console Output";
//
// separateErrors
//
this.separateErrors.Checked = true;
this.separateErrors.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.separateErrors.Location = new System.Drawing.Point(32, 32);
this.separateErrors.Name = "separateErrors";
this.helpProvider1.SetShowHelp(this.separateErrors, false);
this.separateErrors.Size = new System.Drawing.Size(224, 16);
this.separateErrors.TabIndex = 16;
this.separateErrors.TabStop = true;
this.separateErrors.Text = "In Separate Tab";
//
// OptionsDialog
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
this.ClientSize = new System.Drawing.Size(322, 458);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.okButton);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.HelpButton = true;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "OptionsDialog";
this.helpProvider1.SetShowHelp(this, false);
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "NUnit Options";
this.Closing += new System.ComponentModel.CancelEventHandler(this.OptionsDialog_Closing);
this.Load += new System.EventHandler(this.OptionsDialog_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.groupBox9.ResumeLayout(false);
this.groupBox4.ResumeLayout(false);
this.groupBox5.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.groupBox7.ResumeLayout(false);
this.groupBox6.ResumeLayout(false);
this.tabPage3.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
this.groupBox8.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void OptionsDialog_Load(object sender, System.EventArgs e)
{
this.settings = Services.UserSettings;
recentFilesCountTextBox.Text = Services.RecentFiles.MaxFiles.ToString();
loadLastProjectCheckBox.Checked = settings.GetSetting( "Options.LoadLastProject", true );
initialDisplayComboBox.SelectedIndex = (int)(TestSuiteTreeView.DisplayStyle)settings.GetSetting( "Gui.TestTree.InitialTreeDisplay", TestSuiteTreeView.DisplayStyle.Auto );
visualStudioSupportCheckBox.Checked = settings.GetSetting( "Options.TestLoader.VisualStudioSupport", false );
shadowCopyCheckBox.Checked = settings.GetSetting( "Options.TestLoader.ShadowCopyFiles", true );
reloadOnChangeCheckBox.Enabled = Environment.OSVersion.Platform == System.PlatformID.Win32NT;
reloadOnChangeCheckBox.Checked = settings.GetSetting( "Options.TestLoader.ReloadOnChange", true );
rerunOnChangeCheckBox.Checked = settings.GetSetting( "Options.TestLoader.RerunOnChange", false );
reloadOnRunCheckBox.Checked = settings.GetSetting( "Options.TestLoader.ReloadOnRun", true );
clearResultsCheckBox.Checked = settings.GetSetting( "Options.TestLoader.ClearResultsOnReload", true );
bool multiDomain = settings.GetSetting( "Options.TestLoader.MultiDomain", false );
multiDomainRadioButton.Checked = multiDomain;
singleDomainRadioButton.Checked = !multiDomain;
mergeAssembliesCheckBox.Enabled = !multiDomain;
mergeAssembliesCheckBox.Checked = settings.GetSetting( "Options.TestLoader.MergeAssemblies", false );
autoNamespaceSuites.Checked = settings.GetSetting( "Options.TestLoader.AutoNamespaceSuites", true );
flatTestList.Checked = !autoNamespaceSuites.Checked;
errorsTabCheckBox.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayErrorsTab", true );
notRunTabCheckBox.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayNotRunTab", true );
consoleOutputCheckBox.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayConsoleOutputTab", true );
consoleErrrorCheckBox.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayConsoleErrorTab", true )
|| settings.GetSetting( "Gui.ResultTabs.MergeErrorOutput", false );
traceOutputCheckBox.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayTraceTab", true )
|| settings.GetSetting( "Gui.ResultTabs.MergeTraceOutput", false );
labelTestOutputCheckBox.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayTestLabels", false );
failureToolTips.Checked = settings.GetSetting( "Gui.ResultTabs.ErrorsTab.ToolTipsEnabled", true );
enableWordWrap.Checked = settings.GetSetting( "Gui.ResultTabs.ErrorsTab.WordWrapEnabled", true );
mergeErrors.Checked = settings.GetSetting( "Gui.ResultTabs.MergeErrorOutput", false );
mergeTrace.Checked = settings.GetSetting( "Gui.ResultTabs.MergeTraceOutput", false );
}
private void okButton_Click(object sender, System.EventArgs e)
{
if ( settings.GetSetting( "Options.TestLoader.ReloadOnChange", true ) != reloadOnChangeCheckBox.Checked )
{
string msg = String.Format(
"Watching for file changes will be {0} the next time you load an assembly.",
reloadOnChangeCheckBox.Checked ? "enabled" : "disabled" );
UserMessage.DisplayInfo( msg, "NUnit Options" );
}
settings.SaveSetting( "Options.LoadLastProject", loadLastProjectCheckBox.Checked );
TestLoader loader = Services.TestLoader;
settings.SaveSetting( "Options.TestLoader.ReloadOnChange", loader.ReloadOnChange = reloadOnChangeCheckBox.Checked );
settings.SaveSetting( "Options.TestLoader.RerunOnChange", loader.RerunOnChange = rerunOnChangeCheckBox.Checked );
settings.SaveSetting( "Options.TestLoader.ReloadOnRun", loader.ReloadOnRun = reloadOnRunCheckBox.Checked );
settings.SaveSetting( "Options.TestLoader.ClearResultsOnReload", clearResultsCheckBox.Checked );
settings.SaveSetting( "Options.TestLoader.MultiDomain", loader.MultiDomain = multiDomainRadioButton.Checked );
settings.SaveSetting( "Options.TestLoader.MergeAssemblies", loader.MergeAssemblies = mergeAssembliesCheckBox.Checked );
settings.SaveSetting( "Options.TestLoader.AutoNamespaceSuites", loader.AutoNamespaceSuites = autoNamespaceSuites.Checked );
settings.SaveSetting( "Gui.ResultTabs.DisplayTestLabels", labelTestOutputCheckBox.Checked );
settings.SaveSetting( "Gui.ResultTabs.ErrorsTab.ToolTipsEnabled", failureToolTips.Checked );
settings.SaveSetting( "Gui.ResultTabs.ErrorsTab.WordWrapEnabled", enableWordWrap.Checked );
settings.SaveSetting( "Options.TestLoader.VisualStudioSupport", visualStudioSupportCheckBox.Checked );
settings.SaveSetting( "Options.TestLoader.ShadowCopyFiles", loader.ShadowCopyFiles = shadowCopyCheckBox.Checked );
settings.SaveSetting( "Gui.TestTree.InitialTreeDisplay", (TestSuiteTreeView.DisplayStyle)initialDisplayComboBox.SelectedIndex );
settings.SaveSetting( "Gui.ResultTabs.DisplayErrorsTab", errorsTabCheckBox.Checked );
settings.SaveSetting( "Gui.ResultTabs.DisplayNotRunTab", notRunTabCheckBox.Checked );
settings.SaveSetting( "Gui.ResultTabs.DisplayConsoleOutputTab", consoleOutputCheckBox.Checked );
settings.SaveSetting( "Gui.ResultTabs.DisplayConsoleErrorTab", consoleErrrorCheckBox.Checked && separateErrors.Checked );
settings.SaveSetting( "Gui.ResultTabs.DisplayTraceTab", traceOutputCheckBox.Checked && separateTrace.Checked );
settings.SaveSetting( "Gui.ResultTabs.MergeErrorOutput", mergeErrors.Checked );
settings.SaveSetting( "Gui.ResultTabs.MergeTraceOutput", mergeTrace.Checked );
DialogResult = DialogResult.OK;
Close();
}
private void recentFilesCountTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
if ( recentFilesCountTextBox.Text.Length == 0 )
{
recentFilesCountTextBox.Text = Services.RecentFiles.MaxFiles.ToString();
recentFilesCountTextBox.SelectAll();
e.Cancel = true;
}
else
{
string errmsg = null;
try
{
int count = int.Parse( recentFilesCountTextBox.Text );
if ( count < RecentFilesService.MinSize ||
count > RecentFilesService.MaxSize )
{
errmsg = string.Format( "Number of files must be from {0} to {1}",
RecentFilesService.MinSize, RecentFilesService.MaxSize );
}
}
catch
{
errmsg = "Number of files must be numeric";
}
if ( errmsg != null )
{
recentFilesCountTextBox.SelectAll();
UserMessage.DisplayFailure( errmsg );
e.Cancel = true;
}
}
}
private void recentFilesCountTextBox_Validated(object sender, System.EventArgs e)
{
int count = int.Parse( recentFilesCountTextBox.Text );
Services.RecentFiles.MaxFiles = count;
}
private void OptionsDialog_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = false;
}
private void singleDomainRadioButton_CheckedChanged(object sender, System.EventArgs e)
{
mergeAssembliesCheckBox.Enabled = singleDomainRadioButton.Checked;
}
private void reloadOnChangeCheckBox_CheckedChanged(object sender, System.EventArgs e)
{
rerunOnChangeCheckBox.Enabled = reloadOnChangeCheckBox.Checked;
rerunOnChangeCheckBox.Checked = false;
}
private void errorsTabCheckBox_CheckedChanged(object sender, System.EventArgs e)
{
this.failureToolTips.Enabled = this.enableWordWrap.Enabled = this.errorsTabCheckBox.Checked;
}
private void consoleOutputCheckBox_CheckedChanged(object sender, System.EventArgs e)
{
this.labelTestOutputCheckBox.Enabled = this.consoleOutputCheckBox.Checked;
}
private void consoleErrrorCheckBox_CheckedChanged(object sender, System.EventArgs e)
{
this.separateErrors.Enabled = this.mergeErrors.Enabled = this.consoleErrrorCheckBox.Checked;
}
private void traceOutputCheckBox_CheckedChanged(object sender, System.EventArgs e)
{
this.separateTrace.Enabled = this.mergeTrace.Enabled = this.traceOutputCheckBox.Checked;
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using IxMilia.Dxf.Entities;
namespace IxMilia.Dxf
{
internal class DxbWriter
{
private BinaryWriter _writer;
public DxbWriter(Stream stream)
{
_writer = new BinaryWriter(stream);
}
public void Save(DxfFile file)
{
// write sentinel "AutoCAD DXB 1.0 CR LF ^Z NUL"
foreach (var c in DxbReader.BinarySentinel)
{
_writer.Write((byte)c);
}
_writer.Write((byte)'\r'); // CR
_writer.Write((byte)'\n'); // LF
_writer.Write((byte)0x1A); // ^Z
_writer.Write((byte)0x00);
var writingBlock = file.Entities.Count == 0 && file.Blocks.Count == 1;
if (writingBlock)
{
// write block header
WriteItemType(DxbItemType.BlockBase);
var block = file.Blocks.Single();
WriteN((float)block.BasePoint.X);
WriteN((float)block.BasePoint.Y);
}
// force all numbers to be floats
WriteItemType(DxbItemType.NumberMode);
WriteW(1);
if (writingBlock)
{
WriteEntities(file.Blocks.Single().Entities);
}
else
{
var layerGroups = file.Entities.GroupBy(e => e.Layer).OrderBy(g => g.Key);
foreach (var group in layerGroups)
{
var layerName = group.Key;
WriteItemType(DxbItemType.NewLayer);
foreach (var c in layerName)
{
_writer.Write((byte)c);
}
_writer.Write((byte)0.00); // null terminator for string
WriteEntities(group);
}
}
// write null terminator
_writer.Write((byte)0x00);
_writer.Flush();
}
private void WriteEntities(IEnumerable<DxfEntity> entities)
{
foreach (var entity in entities)
{
switch (entity.EntityType)
{
case DxfEntityType.Line:
WriteLine((DxfLine)entity);
break;
case DxfEntityType.Point:
WriteModelPoint((DxfModelPoint)entity);
break;
case DxfEntityType.Circle:
WriteCircle((DxfCircle)entity);
break;
case DxfEntityType.Arc:
WriteArc((DxfArc)entity);
break;
case DxfEntityType.Trace:
WriteTrace((DxfTrace)entity);
break;
case DxfEntityType.Solid:
WriteSolid((DxfSolid)entity);
break;
case DxfEntityType.Seqend:
WriteSeqend();
break;
case DxfEntityType.Polyline:
WritePolyline((DxfPolyline)entity);
break;
case DxfEntityType.Vertex:
WriteVertex((DxfVertex)entity);
break;
case DxfEntityType.Face:
WriteFace((Dxf3DFace)entity);
break;
}
}
}
private void WriteA(double angle)
{
_writer.Write((float)angle);
}
private void WriteN(double d)
{
_writer.Write((float)d);
}
private void WriteW(short s)
{
_writer.Write(s);
}
private void WriteItemType(DxbItemType itemType)
{
_writer.Write((byte)itemType);
}
private void WriteLine(DxfLine line)
{
WriteItemType(DxbItemType.Line);
WriteN(line.P1.X);
WriteN(line.P1.Y);
WriteN(line.P1.Z);
WriteN(line.P2.X);
WriteN(line.P2.Y);
WriteN(line.P2.Z);
}
private void WriteModelPoint(DxfModelPoint point)
{
WriteItemType(DxbItemType.Point);
WriteN(point.Location.X);
WriteN(point.Location.Y);
}
private void WriteCircle(DxfCircle circle)
{
WriteItemType(DxbItemType.Circle);
WriteN(circle.Center.X);
WriteN(circle.Center.Y);
WriteN(circle.Radius);
}
private void WriteArc(DxfArc arc)
{
WriteItemType(DxbItemType.Arc);
WriteN(arc.Center.X);
WriteN(arc.Center.Y);
WriteN(arc.Radius);
WriteA(arc.StartAngle);
WriteA(arc.EndAngle);
}
private void WriteTrace(DxfTrace trace)
{
WriteItemType(DxbItemType.Trace);
WriteN(trace.FirstCorner.X);
WriteN(trace.FirstCorner.Y);
WriteN(trace.SecondCorner.X);
WriteN(trace.SecondCorner.Y);
WriteN(trace.ThirdCorner.X);
WriteN(trace.ThirdCorner.Y);
WriteN(trace.FourthCorner.X);
WriteN(trace.FourthCorner.Y);
}
private void WriteSolid(DxfSolid solid)
{
WriteItemType(DxbItemType.Solid);
WriteN(solid.FirstCorner.X);
WriteN(solid.FirstCorner.Y);
WriteN(solid.SecondCorner.X);
WriteN(solid.SecondCorner.Y);
WriteN(solid.ThirdCorner.X);
WriteN(solid.ThirdCorner.Y);
WriteN(solid.FourthCorner.X);
WriteN(solid.FourthCorner.Y);
}
private void WriteSeqend()
{
WriteItemType(DxbItemType.Seqend);
}
private void WritePolyline(DxfPolyline polyline)
{
WriteItemType(DxbItemType.Polyline);
WriteW((short)(polyline.IsClosed ? 1 : 0));
foreach (var vertex in polyline.Vertices)
{
WriteVertex(vertex);
}
WriteSeqend();
}
private void WriteVertex(DxfVertex vertex)
{
WriteItemType(DxbItemType.Vertex);
WriteN(vertex.Location.X);
WriteN(vertex.Location.Y);
}
private void WriteFace(Dxf3DFace face)
{
WriteItemType(DxbItemType.Face);
WriteN(face.FirstCorner.X);
WriteN(face.FirstCorner.Y);
WriteN(face.FirstCorner.Z);
WriteN(face.SecondCorner.X);
WriteN(face.SecondCorner.Y);
WriteN(face.SecondCorner.Z);
WriteN(face.ThirdCorner.X);
WriteN(face.ThirdCorner.Y);
WriteN(face.ThirdCorner.Z);
WriteN(face.FourthCorner.X);
WriteN(face.FourthCorner.Y);
WriteN(face.FourthCorner.Z);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Roslyn.Compilers.CSharp;
namespace Dedox
{
class GeneratedMethodCommentsChecker : GeneratedCommentsChecker<MethodDeclarationSyntax>
{
public GeneratedMethodCommentsChecker(MethodDeclarationSyntax it, IDedoxConfig config, IDedoxMetrics metrics)
: base(it, config, metrics)
{
}
protected override string Name
{
get
{
return It.Identifier.ValueText;
}
}
protected override void OnMismatch(string tag, string expectedComment, string actualComment)
{
if ("returns".Equals(tag))
{
const string genericReturnsPattern = @"The <see cref=""(\w+)""/>\.";
var match = Regex.Match(actualComment, genericReturnsPattern);
if (match.Success)
{
var typeName = match.Groups[1].Value;
Info();
Info("{0} {1}", GetCodeElementType(), Name);
Info("! The XML comment for the returns tag is probably obsolete.");
Info("! Should be {0} but is actually {1}.", GetTypeNameForReturnsComment(), typeName);
}
}
}
private string GetTypeNameForReturnsComment()
{
var ret = It.ReturnType;
if (ret.Kind == SyntaxKind.PredefinedType)
{
// This includes 'void'. It makes little sense to document 'void'. Should detect this case.
// At the same time, there will be a mismatch downstream.
var predefType = (PredefinedTypeSyntax)ret;
return predefType.Keyword.ValueText;
}
if (ret.Kind == SyntaxKind.IdentifierName)
{
// This includes custom types.
var identType = (IdentifierNameSyntax)ret;
return identType.Identifier.ValueText;
}
if (ret.Kind == SyntaxKind.GenericName)
{
var genericName = (GenericNameSyntax)ret;
return genericName.Identifier.ValueText;
}
Info("Unknown return type kind: " + ret.Kind);
return null;
}
protected override List<Func<string>> GetExpectedCommentForTag(XmlElementStartTagSyntax startTag)
{
string tag = startTag.Name.LocalName.ValueText;
if ("summary".Equals(tag))
{
return ExpectedCommentForSummaryTag();
}
if ("param".Equals(tag))
{
return ExpectedCommentForParamTag(startTag);
}
if ("returns".Equals(tag))
{
return ExpectedCommentForReturnsTag();
}
return new List<Func<string>>();
}
private List<Func<string>> ExpectedCommentForReturnsTag()
{
var returnTypeName = GetTypeNameForReturnsComment();
if (returnTypeName == null)
{
Info("Unknown content in return tag.");
return new List<Func<string>>();
}
return new List<Func<string>> { () => string.Format("The <see cref=\"{0}\"/>.", returnTypeName) };
}
private List<Func<string>> ExpectedCommentForParamTag(XmlElementStartTagSyntax startTag)
{
string paramNameFromAttribute = "";
foreach (var a in startTag.Attributes)
{
var attrName = a.Name.LocalName.ValueText;
var attrValue = string.Join("", a.TextTokens.Select(t => t.ValueText));
if ("name".Equals(attrName))
{
paramNameFromAttribute = attrValue;
}
else
{
// Unexpected attribute.
return new List<Func<string>>();
}
}
// Sanity check for attribute value.
var paramExists =
It.ParameterList.Parameters.Any(
ps =>
string.Equals(
ps.Identifier.ValueText,
paramNameFromAttribute,
StringComparison.InvariantCultureIgnoreCase));
if (!paramExists)
{
Info("! The method {0} does not have a parameter named {1}.", It.Identifier.ValueText, paramNameFromAttribute);
}
var decomposedParamName = StyleCopDecompose(paramNameFromAttribute);
return new List<Func<string>>
{
() => string.Format("The {0}.", decomposedParamName),
() => string.Format("The {0}.", paramNameFromAttribute)
};
}
private List<Func<string>> ExpectedCommentForSummaryTag()
{
// Pattern: The $(decomposed-name).
// Alternative: The $(name).
// Alternative: GhostDoc-style conjugation of verb: FooBar => Fooes the bar.
// Alternative with parameters: GhostDoc-style: FooBar(thing) => Fooes the bar given the specified thing.
var decomposed = StyleCopDecompose(Name);
var ghostDocSentence = ToGhostDocSentence(BasicDecompose(Name));
return new List<Func<string>>
{
() => string.Format("The {0}.", decomposed),
() => string.Format("The {0}.", Name),
() => string.Format(ghostDocSentence + ".")
};
}
private string ToGhostDocSentence(string[] basicDecompose)
{
return string.Join(" ", ToGhostDocSentenceParts(basicDecompose));
}
private IEnumerable<string> ToGhostDocSentenceParts(string[] decomposed)
{
if (decomposed.Length > 0)
{
var first = decomposed[0];
var cap = Char.ToUpperInvariant(first[0]) + first.Substring(1);
yield return Conjugate(cap);
if (decomposed.Length > 1)
{
yield return "the";
for (int i = 1; i < decomposed.Length; i++)
{
yield return decomposed[i];
}
}
else
{
yield return "this";
yield return "instance";
}
}
}
private static string Conjugate(string s)
{
return s[s.Length - 1] == 's' ? s : s + "s";
}
protected TypeDeclarationSyntax DeclaringCodeElement
{
get
{
return (TypeDeclarationSyntax)It.Parent;
}
}
protected override bool IsGeneratedCodeElement()
{
// Check locally first!
return IsGeneratedCodeElement(DeclaringCodeElement);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.ReflectionModel
{
// Describes the import type of a Reflection-based import definition
internal class ImportType
{
private static readonly Type LazyOfTType = typeof(Lazy<>);
private static readonly Type LazyOfTMType = typeof(Lazy<,>);
private static readonly Type ExportFactoryOfTType = typeof(ExportFactory<>);
private readonly Type _type;
private readonly bool _isAssignableCollectionType;
private Type _contractType;
private Func<Export, object> _castSingleValue;
private readonly bool _isOpenGeneric = false;
[ThreadStatic]
internal static Dictionary<Type, Func<Export, object>> _castSingleValueCache;
private static Dictionary<Type, Func<Export, object>> CastSingleValueCache
{
get
{
return _castSingleValueCache = _castSingleValueCache ?? new Dictionary<Type, Func<Export, object>>();
}
}
public ImportType(Type type, ImportCardinality cardinality)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
_type = type;
Type contractType = type;
if (cardinality == ImportCardinality.ZeroOrMore)
{
_isAssignableCollectionType = IsTypeAssignableCollectionType(type);
contractType = CheckForCollection(type);
}
// This sets contract type, metadata and the cast function
_isOpenGeneric = type.ContainsGenericParameters;
Initialize(contractType);
}
public bool IsAssignableCollectionType
{
get { return _isAssignableCollectionType; }
}
public Type ElementType { get; private set; }
public Type ActualType
{
get { return _type; }
}
public bool IsPartCreator { get; private set; }
public Type ContractType { get { return _contractType; } }
public Func<Export, object> CastExport
{
get
{
if (_isOpenGeneric)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
return _castSingleValue;
}
}
public Type MetadataViewType { get; private set; }
private Type CheckForCollection(Type type)
{
ElementType = CollectionServices.GetEnumerableElementType(type);
if (ElementType != null)
{
return ElementType;
}
return type;
}
private static bool IsGenericDescendentOf(Type type, Type baseGenericTypeDefinition)
{
if (type == typeof(object) || type == null)
{
return false;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == baseGenericTypeDefinition)
{
return true;
}
return IsGenericDescendentOf(type.BaseType, baseGenericTypeDefinition);
}
public static bool IsDescendentOf(Type type, Type baseType)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (baseType == null)
{
throw new ArgumentNullException(nameof(baseType));
}
if (!baseType.IsGenericTypeDefinition)
{
return baseType.IsAssignableFrom(type);
}
return IsGenericDescendentOf(type, baseType.GetGenericTypeDefinition());
}
private void Initialize(Type type)
{
if (!type.IsGenericType)
{
// no cast function, the original type is the contract type
_contractType = type;
return;
}
Type[] arguments = type.GetGenericArguments();
Type genericType = type.GetGenericTypeDefinition().UnderlyingSystemType;
// Look up the cast function
if (!CastSingleValueCache.TryGetValue(type, out _castSingleValue))
{
if (!TryGetCastFunction(genericType, _isOpenGeneric, arguments, out _castSingleValue))
{
// in this case, even though the type is generic, it's nothing we have recognized,
// thereforeit's the same as the non-generic case
_contractType = type;
return;
}
CastSingleValueCache.Add(type, _castSingleValue);
}
// we have found the cast function, which means, that we have found either Lazy of EF
// in this case the contract is always argument[0] and the metadata view is always argument[1]
IsPartCreator = !IsLazyGenericType(genericType) && (genericType != null);
_contractType = arguments[0];
if (arguments.Length == 2)
{
MetadataViewType = arguments[1];
}
}
private static bool IsLazyGenericType(Type genericType)
{
return (genericType == LazyOfTType) || (genericType == LazyOfTMType);
}
private static bool TryGetCastFunction(Type genericType, bool isOpenGeneric, Type[] arguments, out Func<Export, object> castFunction)
{
castFunction = null;
if (genericType == LazyOfTType)
{
if (!isOpenGeneric)
{
castFunction = ExportServices.CreateStronglyTypedLazyFactory(arguments[0].UnderlyingSystemType, null);
}
return true;
}
if (genericType == LazyOfTMType)
{
if (!isOpenGeneric)
{
castFunction = ExportServices.CreateStronglyTypedLazyFactory(arguments[0].UnderlyingSystemType, arguments[1].UnderlyingSystemType);
}
return true;
}
if (genericType != null && IsDescendentOf(genericType, ExportFactoryOfTType))
{
if (arguments.Length == 1)
{
if (!isOpenGeneric)
{
castFunction = new ExportFactoryCreator(genericType).CreateStronglyTypedExportFactoryFactory(arguments[0].UnderlyingSystemType, null);
}
return true;
}
else if (arguments.Length == 2)
{
if (!isOpenGeneric)
{
castFunction = new ExportFactoryCreator(genericType).CreateStronglyTypedExportFactoryFactory(arguments[0].UnderlyingSystemType, arguments[1].UnderlyingSystemType);
}
return true;
}
else
{
throw ExceptionBuilder.ExportFactory_TooManyGenericParameters(genericType.FullName);
}
}
return false;
}
private static bool IsTypeAssignableCollectionType(Type type)
{
if (type.IsArray || CollectionServices.IsEnumerableOfT(type))
{
return true;
}
return false;
}
}
}
| |
// MIT License - Copyright (C) The Mono.Xna Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.Runtime.Serialization;
using System.Diagnostics;
namespace TriangleDemo
{
/// <summary>
/// Describes a 4D-vector.
/// </summary>
[DataContract]
[DebuggerDisplay("{DebugDisplayString,nq}")]
public struct Vector4 : IEquatable<Vector4>
{
#region Private Fields
private static readonly Vector4 zero = new Vector4();
private static readonly Vector4 one = new Vector4(1f, 1f, 1f, 1f);
private static readonly Vector4 unitX = new Vector4(1f, 0f, 0f, 0f);
private static readonly Vector4 unitY = new Vector4(0f, 1f, 0f, 0f);
private static readonly Vector4 unitZ = new Vector4(0f, 0f, 1f, 0f);
private static readonly Vector4 unitW = new Vector4(0f, 0f, 0f, 1f);
#endregion
#region Public Fields
/// <summary>
/// The x coordinate of this <see cref="Vector4"/>.
/// </summary>
[DataMember]
public float X;
/// <summary>
/// The y coordinate of this <see cref="Vector4"/>.
/// </summary>
[DataMember]
public float Y;
/// <summary>
/// The z coordinate of this <see cref="Vector4"/>.
/// </summary>
[DataMember]
public float Z;
/// <summary>
/// The w coordinate of this <see cref="Vector4"/>.
/// </summary>
[DataMember]
public float W;
#endregion
#region Public Properties
/// <summary>
/// Returns a <see cref="Vector4"/> with components 0, 0, 0, 0.
/// </summary>
public static Vector4 Zero
{
get { return zero; }
}
/// <summary>
/// Returns a <see cref="Vector4"/> with components 1, 1, 1, 1.
/// </summary>
public static Vector4 One
{
get { return one; }
}
/// <summary>
/// Returns a <see cref="Vector4"/> with components 1, 0, 0, 0.
/// </summary>
public static Vector4 UnitX
{
get { return unitX; }
}
/// <summary>
/// Returns a <see cref="Vector4"/> with components 0, 1, 0, 0.
/// </summary>
public static Vector4 UnitY
{
get { return unitY; }
}
/// <summary>
/// Returns a <see cref="Vector4"/> with components 0, 0, 1, 0.
/// </summary>
public static Vector4 UnitZ
{
get { return unitZ; }
}
/// <summary>
/// Returns a <see cref="Vector4"/> with components 0, 0, 0, 1.
/// </summary>
public static Vector4 UnitW
{
get { return unitW; }
}
#endregion
#region Internal Properties
internal string DebugDisplayString
{
get
{
return string.Concat(
this.X.ToString(), " ",
this.Y.ToString(), " ",
this.Z.ToString(), " ",
this.W.ToString()
);
}
}
#endregion
#region Constructors
/// <summary>
/// Constructs a 3d vector with X, Y, Z and W from four values.
/// </summary>
/// <param name="x">The x coordinate in 4d-space.</param>
/// <param name="y">The y coordinate in 4d-space.</param>
/// <param name="z">The z coordinate in 4d-space.</param>
/// <param name="w">The w coordinate in 4d-space.</param>
public Vector4(float x, float y, float z, float w)
{
this.X = x;
this.Y = y;
this.Z = z;
this.W = w;
}
/// <summary>
/// Constructs a 3d vector with X, Y, Z from <see cref="Vector3"/> and W from a scalar.
/// </summary>
/// <param name="value">The x, y and z coordinates in 4d-space.</param>
/// <param name="w">The w coordinate in 4d-space.</param>
public Vector4(Vector3 value, float w)
{
this.X = value.X;
this.Y = value.Y;
this.Z = value.Z;
this.W = w;
}
/// <summary>
/// Constructs a 4d vector with X, Y, Z and W set to the same value.
/// </summary>
/// <param name="value">The x, y, z and w coordinates in 4d-space.</param>
public Vector4(float value)
{
this.X = value;
this.Y = value;
this.Z = value;
this.W = value;
}
#endregion
#region Public Methods
/// <summary>
/// Performs vector addition on <paramref name="value1"/> and <paramref name="value2"/>.
/// </summary>
/// <param name="value1">The first vector to add.</param>
/// <param name="value2">The second vector to add.</param>
/// <returns>The result of the vector addition.</returns>
public static Vector4 Add(Vector4 value1, Vector4 value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
value1.W += value2.W;
return value1;
}
/// <summary>
/// Performs vector addition on <paramref name="value1"/> and
/// <paramref name="value2"/>, storing the result of the
/// addition in <paramref name="result"/>.
/// </summary>
/// <param name="value1">The first vector to add.</param>
/// <param name="value2">The second vector to add.</param>
/// <param name="result">The result of the vector addition.</param>
public static void Add(ref Vector4 value1, ref Vector4 value2, out Vector4 result)
{
result.X = value1.X + value2.X;
result.Y = value1.Y + value2.Y;
result.Z = value1.Z + value2.Z;
result.W = value1.W + value2.W;
}
/// <summary>
/// Returns the distance between two vectors.
/// </summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The distance between two vectors.</returns>
public static float Distance(Vector4 value1, Vector4 value2)
{
return (float)Math.Sqrt(DistanceSquared(value1, value2));
}
/// <summary>
/// Returns the distance between two vectors.
/// </summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <param name="result">The distance between two vectors as an output parameter.</param>
public static void Distance(ref Vector4 value1, ref Vector4 value2, out float result)
{
result = (float)Math.Sqrt(DistanceSquared(value1, value2));
}
/// <summary>
/// Returns the squared distance between two vectors.
/// </summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The squared distance between two vectors.</returns>
public static float DistanceSquared(Vector4 value1, Vector4 value2)
{
return (value1.W - value2.W) * (value1.W - value2.W) +
(value1.X - value2.X) * (value1.X - value2.X) +
(value1.Y - value2.Y) * (value1.Y - value2.Y) +
(value1.Z - value2.Z) * (value1.Z - value2.Z);
}
/// <summary>
/// Returns the squared distance between two vectors.
/// </summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <param name="result">The squared distance between two vectors as an output parameter.</param>
public static void DistanceSquared(ref Vector4 value1, ref Vector4 value2, out float result)
{
result = (value1.W - value2.W) * (value1.W - value2.W) +
(value1.X - value2.X) * (value1.X - value2.X) +
(value1.Y - value2.Y) * (value1.Y - value2.Y) +
(value1.Z - value2.Z) * (value1.Z - value2.Z);
}
/// <summary>
/// Divides the components of a <see cref="Vector4"/> by the components of another <see cref="Vector4"/>.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/>.</param>
/// <param name="value2">Divisor <see cref="Vector4"/>.</param>
/// <returns>The result of dividing the vectors.</returns>
public static Vector4 Divide(Vector4 value1, Vector4 value2)
{
value1.W /= value2.W;
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
/// <summary>
/// Divides the components of a <see cref="Vector4"/> by a scalar.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/>.</param>
/// <param name="divider">Divisor scalar.</param>
/// <returns>The result of dividing a vector by a scalar.</returns>
public static Vector4 Divide(Vector4 value1, float divider)
{
float factor = 1f / divider;
value1.W *= factor;
value1.X *= factor;
value1.Y *= factor;
value1.Z *= factor;
return value1;
}
/// <summary>
/// Divides the components of a <see cref="Vector4"/> by a scalar.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/>.</param>
/// <param name="divider">Divisor scalar.</param>
/// <param name="result">The result of dividing a vector by a scalar as an output parameter.</param>
public static void Divide(ref Vector4 value1, float divider, out Vector4 result)
{
float factor = 1f / divider;
result.W = value1.W * factor;
result.X = value1.X * factor;
result.Y = value1.Y * factor;
result.Z = value1.Z * factor;
}
/// <summary>
/// Divides the components of a <see cref="Vector4"/> by the components of another <see cref="Vector4"/>.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/>.</param>
/// <param name="value2">Divisor <see cref="Vector4"/>.</param>
/// <param name="result">The result of dividing the vectors as an output parameter.</param>
public static void Divide(ref Vector4 value1, ref Vector4 value2, out Vector4 result)
{
result.W = value1.W / value2.W;
result.X = value1.X / value2.X;
result.Y = value1.Y / value2.Y;
result.Z = value1.Z / value2.Z;
}
/// <summary>
/// Returns a dot product of two vectors.
/// </summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The dot product of two vectors.</returns>
public static float Dot(Vector4 value1, Vector4 value2)
{
return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z + value1.W * value2.W;
}
/// <summary>
/// Returns a dot product of two vectors.
/// </summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <param name="result">The dot product of two vectors as an output parameter.</param>
public static void Dot(ref Vector4 value1, ref Vector4 value2, out float result)
{
result = value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z + value1.W * value2.W;
}
/// <summary>
/// Compares whether current instance is equal to specified <see cref="Object"/>.
/// </summary>
/// <param name="obj">The <see cref="Object"/> to compare.</param>
/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>
public override bool Equals(object obj)
{
return (obj is Vector4) ? this == (Vector4)obj : false;
}
/// <summary>
/// Compares whether current instance is equal to specified <see cref="Vector4"/>.
/// </summary>
/// <param name="other">The <see cref="Vector4"/> to compare.</param>
/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>
public bool Equals(Vector4 other)
{
return this.W == other.W
&& this.X == other.X
&& this.Y == other.Y
&& this.Z == other.Z;
}
/// <summary>
/// Gets the hash code of this <see cref="Vector4"/>.
/// </summary>
/// <returns>Hash code of this <see cref="Vector4"/>.</returns>
public override int GetHashCode()
{
return (int)(this.W + this.X + this.Y + this.Y);
}
/// <summary>
/// Returns the length of this <see cref="Vector4"/>.
/// </summary>
/// <returns>The length of this <see cref="Vector4"/>.</returns>
public float Length()
{
float result = DistanceSquared(this, zero);
return (float)Math.Sqrt(result);
}
/// <summary>
/// Returns the squared length of this <see cref="Vector4"/>.
/// </summary>
/// <returns>The squared length of this <see cref="Vector4"/>.</returns>
public float LengthSquared()
{
return DistanceSquared(this, zero);
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains a multiplication of two vectors.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/>.</param>
/// <param name="value2">Source <see cref="Vector4"/>.</param>
/// <returns>The result of the vector multiplication.</returns>
public static Vector4 Multiply(Vector4 value1, Vector4 value2)
{
value1.W *= value2.W;
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains a multiplication of <see cref="Vector4"/> and a scalar.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/>.</param>
/// <param name="scaleFactor">Scalar value.</param>
/// <returns>The result of the vector multiplication with a scalar.</returns>
public static Vector4 Multiply(Vector4 value1, float scaleFactor)
{
value1.W *= scaleFactor;
value1.X *= scaleFactor;
value1.Y *= scaleFactor;
value1.Z *= scaleFactor;
return value1;
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains a multiplication of <see cref="Vector4"/> and a scalar.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/>.</param>
/// <param name="scaleFactor">Scalar value.</param>
/// <param name="result">The result of the multiplication with a scalar as an output parameter.</param>
public static void Multiply(ref Vector4 value1, float scaleFactor, out Vector4 result)
{
result.W = value1.W * scaleFactor;
result.X = value1.X * scaleFactor;
result.Y = value1.Y * scaleFactor;
result.Z = value1.Z * scaleFactor;
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains a multiplication of two vectors.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/>.</param>
/// <param name="value2">Source <see cref="Vector4"/>.</param>
/// <param name="result">The result of the vector multiplication as an output parameter.</param>
public static void Multiply(ref Vector4 value1, ref Vector4 value2, out Vector4 result)
{
result.W = value1.W * value2.W;
result.X = value1.X * value2.X;
result.Y = value1.Y * value2.Y;
result.Z = value1.Z * value2.Z;
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains the specified vector inversion.
/// </summary>
/// <param name="value">Source <see cref="Vector4"/>.</param>
/// <returns>The result of the vector inversion.</returns>
public static Vector4 Negate(Vector4 value)
{
value = new Vector4(-value.X, -value.Y, -value.Z, -value.W);
return value;
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains the specified vector inversion.
/// </summary>
/// <param name="value">Source <see cref="Vector4"/>.</param>
/// <param name="result">The result of the vector inversion as an output parameter.</param>
public static void Negate(ref Vector4 value, out Vector4 result)
{
result.X = -value.X;
result.Y = -value.Y;
result.Z = -value.Z;
result.W = -value.W;
}
/// <summary>
/// Turns this <see cref="Vector4"/> to a unit vector with the same direction.
/// </summary>
public void Normalize()
{
Normalize(ref this, out this);
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains a normalized values from another vector.
/// </summary>
/// <param name="value">Source <see cref="Vector4"/>.</param>
/// <returns>Unit vector.</returns>
public static Vector4 Normalize(Vector4 value)
{
float factor = DistanceSquared(value, zero);
factor = 1f / (float)Math.Sqrt(factor);
return new Vector4(value.X*factor,value.Y*factor,value.Z*factor,value.W*factor);
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains a normalized values from another vector.
/// </summary>
/// <param name="value">Source <see cref="Vector4"/>.</param>
/// <param name="result">Unit vector as an output parameter.</param>
public static void Normalize(ref Vector4 value, out Vector4 result)
{
float factor = DistanceSquared(value, zero);
factor = 1f / (float)Math.Sqrt(factor);
result.W = value.W * factor;
result.X = value.X * factor;
result.Y = value.Y * factor;
result.Z = value.Z * factor;
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains subtraction of on <see cref="Vector4"/> from a another.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/>.</param>
/// <param name="value2">Source <see cref="Vector4"/>.</param>
/// <returns>The result of the vector subtraction.</returns>
public static Vector4 Subtract(Vector4 value1, Vector4 value2)
{
value1.W -= value2.W;
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains subtraction of on <see cref="Vector4"/> from a another.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/>.</param>
/// <param name="value2">Source <see cref="Vector4"/>.</param>
/// <param name="result">The result of the vector subtraction as an output parameter.</param>
public static void Subtract(ref Vector4 value1, ref Vector4 value2, out Vector4 result)
{
result.W = value1.W - value2.W;
result.X = value1.X - value2.X;
result.Y = value1.Y - value2.Y;
result.Z = value1.Z - value2.Z;
}
#region Transform
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains a transformation of 3d-vector by the specified <see cref="Matrix4"/>.
/// </summary>
/// <param name="value">Source <see cref="Vector3"/>.</param>
/// <param name="matrix">The transformation <see cref="Matrix4"/>.</param>
/// <returns>Transformed <see cref="Vector4"/>.</returns>
public static Vector4 Transform(Vector3 value, Matrix4 matrix)
{
Vector4 result;
Transform(ref value, ref matrix, out result);
return result;
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains a transformation of 4d-vector by the specified <see cref="Matrix4"/>.
/// </summary>
/// <param name="value">Source <see cref="Vector4"/>.</param>
/// <param name="matrix">The transformation <see cref="Matrix4"/>.</param>
/// <returns>Transformed <see cref="Vector4"/>.</returns>
public static Vector4 Transform(Vector4 value, Matrix4 matrix)
{
Transform(ref value, ref matrix, out value);
return value;
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains a transformation of 3d-vector by the specified <see cref="Matrix4"/>.
/// </summary>
/// <param name="value">Source <see cref="Vector3"/>.</param>
/// <param name="matrix">The transformation <see cref="Matrix4"/>.</param>
/// <param name="result">Transformed <see cref="Vector4"/> as an output parameter.</param>
public static void Transform(ref Vector3 value, ref Matrix4 matrix, out Vector4 result)
{
result.X = (value.X * matrix.M11) + (value.Y * matrix.M21) + (value.Z * matrix.M31) + matrix.M41;
result.Y = (value.X * matrix.M12) + (value.Y * matrix.M22) + (value.Z * matrix.M32) + matrix.M42;
result.Z = (value.X * matrix.M13) + (value.Y * matrix.M23) + (value.Z * matrix.M33) + matrix.M43;
result.W = (value.X * matrix.M14) + (value.Y * matrix.M24) + (value.Z * matrix.M34) + matrix.M44;
}
/// <summary>
/// Creates a new <see cref="Vector4"/> that contains a transformation of 4d-vector by the specified <see cref="Matrix4"/>.
/// </summary>
/// <param name="value">Source <see cref="Vector4"/>.</param>
/// <param name="matrix">The transformation <see cref="Matrix4"/>.</param>
/// <param name="result">Transformed <see cref="Vector4"/> as an output parameter.</param>
public static void Transform(ref Vector4 value, ref Matrix4 matrix, out Vector4 result)
{
var x = (value.X * matrix.M11) + (value.Y * matrix.M21) + (value.Z * matrix.M31) + (value.W * matrix.M41);
var y = (value.X * matrix.M12) + (value.Y * matrix.M22) + (value.Z * matrix.M32) + (value.W * matrix.M42);
var z = (value.X * matrix.M13) + (value.Y * matrix.M23) + (value.Z * matrix.M33) + (value.W * matrix.M43);
var w = (value.X * matrix.M14) + (value.Y * matrix.M24) + (value.Z * matrix.M34) + (value.W * matrix.M44);
result.X = x;
result.Y = y;
result.Z = z;
result.W = w;
}
/// <summary>
/// Apply transformation on vectors within array of <see cref="Vector4"/> by the specified <see cref="Matrix4"/> and places the results in an another array.
/// </summary>
/// <param name="sourceArray">Source array.</param>
/// <param name="sourceIndex">The starting index of transformation in the source array.</param>
/// <param name="matrix">The transformation <see cref="Matrix4"/>.</param>
/// <param name="destinationArray">Destination array.</param>
/// <param name="destinationIndex">The starting index in the destination array, where the first <see cref="Vector4"/> should be written.</param>
/// <param name="length">The number of vectors to be transformed.</param>
public static void Transform
(
Vector4[] sourceArray,
int sourceIndex,
ref Matrix4 matrix,
Vector4[] destinationArray,
int destinationIndex,
int length
)
{
if (sourceArray == null)
throw new ArgumentNullException("sourceArray");
if (destinationArray == null)
throw new ArgumentNullException("destinationArray");
if (sourceArray.Length < sourceIndex + length)
throw new ArgumentException("Source array length is lesser than sourceIndex + length");
if (destinationArray.Length < destinationIndex + length)
throw new ArgumentException("Destination array length is lesser than destinationIndex + length");
for (var i = 0; i < length; i++)
{
var value = sourceArray[sourceIndex + i];
destinationArray[destinationIndex + i] = Transform(value, matrix);
}
}
/// <summary>
/// Apply transformation on all vectors within array of <see cref="Vector4"/> by the specified <see cref="Matrix4"/> and places the results in an another array.
/// </summary>
/// <param name="sourceArray">Source array.</param>
/// <param name="matrix">The transformation <see cref="Matrix4"/>.</param>
/// <param name="destinationArray">Destination array.</param>
public static void Transform(Vector4[] sourceArray, ref Matrix4 matrix, Vector4[] destinationArray)
{
if (sourceArray == null)
throw new ArgumentNullException("sourceArray");
if (destinationArray == null)
throw new ArgumentNullException("destinationArray");
if (destinationArray.Length < sourceArray.Length)
throw new ArgumentException("Destination array length is lesser than source array length");
for (var i = 0; i < sourceArray.Length; i++)
{
var value = sourceArray[i];
destinationArray[i] = Transform(value, matrix);
}
}
#endregion
/// <summary>
/// Returns a <see cref="String"/> representation of this <see cref="Vector4"/> in the format:
/// {X:[<see cref="X"/>] Y:[<see cref="Y"/>] Z:[<see cref="Z"/>] W:[<see cref="W"/>]}
/// </summary>
/// <returns>A <see cref="String"/> representation of this <see cref="Vector4"/>.</returns>
public override string ToString()
{
return "{X:" + X + " Y:" + Y + " Z:" + Z + " W:" + W + "}";
}
#endregion
#region Operators
/// <summary>
/// Inverts values in the specified <see cref="Vector4"/>.
/// </summary>
/// <param name="value">Source <see cref="Vector4"/> on the right of the sub sign.</param>
/// <returns>Result of the inversion.</returns>
public static Vector4 operator -(Vector4 value)
{
return new Vector4(-value.X, -value.Y, -value.Z, -value.W);
}
/// <summary>
/// Compares whether two <see cref="Vector4"/> instances are equal.
/// </summary>
/// <param name="value1"><see cref="Vector4"/> instance on the left of the equal sign.</param>
/// <param name="value2"><see cref="Vector4"/> instance on the right of the equal sign.</param>
/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>
public static bool operator ==(Vector4 value1, Vector4 value2)
{
return value1.W == value2.W
&& value1.X == value2.X
&& value1.Y == value2.Y
&& value1.Z == value2.Z;
}
/// <summary>
/// Compares whether two <see cref="Vector4"/> instances are not equal.
/// </summary>
/// <param name="value1"><see cref="Vector4"/> instance on the left of the not equal sign.</param>
/// <param name="value2"><see cref="Vector4"/> instance on the right of the not equal sign.</param>
/// <returns><c>true</c> if the instances are not equal; <c>false</c> otherwise.</returns>
public static bool operator !=(Vector4 value1, Vector4 value2)
{
return !(value1 == value2);
}
/// <summary>
/// Adds two vectors.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/> on the left of the add sign.</param>
/// <param name="value2">Source <see cref="Vector4"/> on the right of the add sign.</param>
/// <returns>Sum of the vectors.</returns>
public static Vector4 operator +(Vector4 value1, Vector4 value2)
{
value1.W += value2.W;
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
/// <summary>
/// Subtracts a <see cref="Vector4"/> from a <see cref="Vector4"/>.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/> on the left of the sub sign.</param>
/// <param name="value2">Source <see cref="Vector4"/> on the right of the sub sign.</param>
/// <returns>Result of the vector subtraction.</returns>
public static Vector4 operator -(Vector4 value1, Vector4 value2)
{
value1.W -= value2.W;
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
/// <summary>
/// Multiplies the components of two vectors by each other.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/> on the left of the mul sign.</param>
/// <param name="value2">Source <see cref="Vector4"/> on the right of the mul sign.</param>
/// <returns>Result of the vector multiplication.</returns>
public static Vector4 operator *(Vector4 value1, Vector4 value2)
{
value1.W *= value2.W;
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
/// <summary>
/// Multiplies the components of vector by a scalar.
/// </summary>
/// <param name="value">Source <see cref="Vector4"/> on the left of the mul sign.</param>
/// <param name="scaleFactor">Scalar value on the right of the mul sign.</param>
/// <returns>Result of the vector multiplication with a scalar.</returns>
public static Vector4 operator *(Vector4 value, float scaleFactor)
{
value.W *= scaleFactor;
value.X *= scaleFactor;
value.Y *= scaleFactor;
value.Z *= scaleFactor;
return value;
}
/// <summary>
/// Multiplies the components of vector by a scalar.
/// </summary>
/// <param name="scaleFactor">Scalar value on the left of the mul sign.</param>
/// <param name="value">Source <see cref="Vector4"/> on the right of the mul sign.</param>
/// <returns>Result of the vector multiplication with a scalar.</returns>
public static Vector4 operator *(float scaleFactor, Vector4 value)
{
value.W *= scaleFactor;
value.X *= scaleFactor;
value.Y *= scaleFactor;
value.Z *= scaleFactor;
return value;
}
/// <summary>
/// Divides the components of a <see cref="Vector4"/> by the components of another <see cref="Vector4"/>.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/> on the left of the div sign.</param>
/// <param name="value2">Divisor <see cref="Vector4"/> on the right of the div sign.</param>
/// <returns>The result of dividing the vectors.</returns>
public static Vector4 operator /(Vector4 value1, Vector4 value2)
{
value1.W /= value2.W;
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
/// <summary>
/// Divides the components of a <see cref="Vector4"/> by a scalar.
/// </summary>
/// <param name="value1">Source <see cref="Vector4"/> on the left of the div sign.</param>
/// <param name="divider">Divisor scalar on the right of the div sign.</param>
/// <returns>The result of dividing a vector by a scalar.</returns>
public static Vector4 operator /(Vector4 value1, float divider)
{
float factor = 1f / divider;
value1.W *= factor;
value1.X *= factor;
value1.Y *= factor;
value1.Z *= factor;
return value1;
}
#endregion
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
namespace Gallio.Common.Reflection
{
/// <summary>
/// Describes characteristics used to match an assembly such as an assembly name and version range.
/// </summary>
[Serializable]
public class AssemblySignature
{
private static readonly Regex ParseRegex = new Regex(
@"^(?<name>[a-zA-Z0-9_.]+)(?:\s*,\s*Version\s*=\s*(?<minVersion>\d+\.\d+\.\d+\.\d+)(?:\s*-\s*(?<maxVersion>\d+\.\d+\.\d+\.\d+))?)?$",
RegexOptions.CultureInvariant | RegexOptions.Singleline);
private readonly string name;
private Version minVersion, maxVersion;
/// <summary>
/// Creates an assembly signature.
/// </summary>
/// <param name="name">The simple name of the assembly.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref cref="name" /> is null.</exception>
public AssemblySignature(string name)
{
if (name == null)
throw new ArgumentNullException("name");
this.name = name;
}
/// <summary>
/// Gets the simple name of the assembly.
/// </summary>
public string Name
{
get { return name; }
}
/// <summary>
/// Sets the assembly version to match.
/// </summary>
/// <param name="version">The version to match, or null if none.</param>
public void SetVersion(Version version)
{
minVersion = version;
maxVersion = version;
}
/// <summary>
/// Sets the assembly version range to match.
/// </summary>
/// <remarks>
/// <para>
/// <paramref name="minVersion"/> and <paramref name="maxVersion"/> must
/// either both be non-null or both be null.
/// </para>
/// </remarks>
/// <param name="minVersion">The minimum assembly version to match inclusively, or null if there is no lower bound.</param>
/// <param name="maxVersion">The maximum assembly version to match inclusively, or null if there is no upper bound.</param>
/// <exception cref="ArgumentException">Thrown if <paramref name="minVersion"/> is null but
/// not <paramref name="maxVersion"/> or vice-versa. Also thrown if <paramref name="minVersion"/>
/// is greater than <paramref name="maxVersion"/>.</exception>
public void SetVersionRange(Version minVersion, Version maxVersion)
{
if (minVersion == null && maxVersion != null
|| minVersion != null && maxVersion == null)
throw new ArgumentException("Min and max version must either both be non-null or both be null.");
if (minVersion != null && minVersion > maxVersion)
throw new ArgumentException("Min version must be less than or equal to max version.");
this.minVersion = minVersion;
this.maxVersion = maxVersion;
}
/// <summary>
/// Gets the minimum assembly version to match inclusively, or null if there is no lower bound.
/// </summary>
public Version MinVersion
{
get { return minVersion; }
}
/// <summary>
/// Gets the maximum assembly version to match inclusively, or null if there is no upper bound.
/// </summary>
public Version MaxVersion
{
get { return maxVersion; }
}
/// <summary>
/// Returns true if the signature matches the specified assembly name.
/// </summary>
/// <remarks>
/// <para>
/// When the assembly name is a partial name that omits version information, the version
/// criteria of the signature are ignored.
/// </para>
/// </remarks>
/// <param name="assemblyName">The assembly name.</param>
/// <returns>True if the signature matches the assembly name.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="assemblyName"/> is null.</exception>
public bool IsMatch(AssemblyName assemblyName)
{
if (assemblyName == null)
throw new ArgumentNullException("assemblyName");
if (assemblyName.Name != name)
return false;
if (minVersion != null)
{
Version assemblyVersion = assemblyName.Version;
if (assemblyVersion != null)
{
if (minVersion > assemblyVersion || maxVersion < assemblyVersion)
return false;
}
}
return true;
}
/// <summary>
/// Parses the assembly signature from a string.
/// </summary>
/// <remarks>
/// <para>
/// The string takes the form of following forms:
/// <list type="bullet">
/// <item>"AssemblyName"</item>
/// <item>"AssemblyName, Version=1.2.0.0"</item>
/// <item>"AssemblyName, Version=1.2.0.0-1.3.65535.65535"</item>
/// </list>
/// </para>
/// </remarks>
/// <param name="str">The string to parse.</param>
/// <returns>The parsed signature.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="str"/> is malformed.</exception>
public static AssemblySignature Parse(string str)
{
if (str == null)
throw new ArgumentNullException("str");
Match match = ParseRegex.Match(str);
if (! match.Success)
throw new ArgumentException("The specified assembly signature is not valid.", "str");
string name = match.Groups["name"].Value;
string minVersion = match.Groups["minVersion"].Value;
string maxVersion = match.Groups["maxVersion"].Value;
var signature = new AssemblySignature(name);
if (minVersion.Length != 0)
{
if (maxVersion.Length != 0)
{
signature.SetVersionRange(new Version(minVersion), new Version(maxVersion));
}
else
{
signature.SetVersion(new Version(minVersion));
}
}
return signature;
}
/// <summary>
/// Converts the signature to a string.
/// </summary>
/// <returns>The signature in a format that can be subsequently parsed by <see cref="Parse"/>.</returns>
/// <seealso cref="Parse"/>
public override string ToString()
{
if (minVersion == null && maxVersion == null)
return name;
var builder = new StringBuilder(name);
builder.Append(", Version=");
builder.Append(minVersion);
if (minVersion != maxVersion)
{
builder.Append('-');
builder.Append(maxVersion);
}
return builder.ToString();
}
}
}
| |
namespace Gu.Wpf.Adorners
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
/// <summary>
/// ~Inspired~ by: http://referencesource.microsoft.com/#WindowsBase/Shared/MS/Internal/DoubleUtil.cs,ef2a956bcf846761.
/// </summary>
internal static class DoubleUtil
{
// Const values come from sdk\inc\crt\float.h
internal const double DblEpsilon = 2.2204460492503131e-016; /* smallest such that 1.0+DBL_EPSILON != 1.0 */
internal const float FltMin = 1.175494351e-38F; /* Number close to zero, where float.MinValue is -float.MaxValue */
/// <summary>
/// AreClose - Returns whether or not two doubles are "close". That is, whether or
/// not they are within epsilon of each other. Note that this epsilon is proportional
/// to the numbers themselves to that AreClose survives scalar multiplication.
/// There are plenty of ways for this to return false even for numbers which
/// are theoretically identical, so no code calling this should fail to work if this
/// returns false. This is important enough to repeat:
/// NB: NO CODE CALLING THIS FUNCTION SHOULD DEPEND ON ACCURATE RESULTS - this should be
/// used for optimizations *only*.
/// </summary>
/// <returns>
/// bool - the result of the AreClose comparison.
/// </returns>
/// <param name="value1"> The first double to compare. </param>
/// <param name="value2"> The second double to compare. </param>
[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
internal static bool AreClose(double value1, double value2)
{
// in case they are Infinities (then epsilon check does not work)
if (value1 == value2)
{
return true;
}
// This computes (|value1-value2| / (|value1| + |value2| + 10.0)) < DBL_EPSILON
double eps = (Math.Abs(value1) + Math.Abs(value2) + 10.0) * DblEpsilon;
double delta = value1 - value2;
return (-eps < delta) && (eps > delta);
}
/// <summary>
/// LessThan - Returns whether or not the first double is less than the second double.
/// That is, whether or not the first is strictly less than *and* not within epsilon of
/// the other number. Note that this epsilon is proportional to the numbers themselves
/// to that AreClose survives scalar multiplication. Note,
/// There are plenty of ways for this to return false even for numbers which
/// are theoretically identical, so no code calling this should fail to work if this
/// returns false. This is important enough to repeat:
/// NB: NO CODE CALLING THIS FUNCTION SHOULD DEPEND ON ACCURATE RESULTS - this should be
/// used for optimizations *only*.
/// </summary>
/// <returns>
/// bool - the result of the LessThan comparison.
/// </returns>
/// <param name="value1"> The first double to compare. </param>
/// <param name="value2"> The second double to compare. </param>
internal static bool LessThan(double value1, double value2)
{
return (value1 < value2) && !AreClose(value1, value2);
}
/// <summary>
/// GreaterThan - Returns whether or not the first double is greater than the second double.
/// That is, whether or not the first is strictly greater than *and* not within epsilon of
/// the other number. Note that this epsilon is proportional to the numbers themselves
/// to that AreClose survives scalar multiplication. Note,
/// There are plenty of ways for this to return false even for numbers which
/// are theoretically identical, so no code calling this should fail to work if this
/// returns false. This is important enough to repeat:
/// NB: NO CODE CALLING THIS FUNCTION SHOULD DEPEND ON ACCURATE RESULTS - this should be
/// used for optimizations *only*.
/// </summary>
/// <returns>
/// bool - the result of the GreaterThan comparison.
/// </returns>
/// <param name="value1"> The first double to compare. </param>
/// <param name="value2"> The second double to compare. </param>
internal static bool GreaterThan(double value1, double value2)
{
return (value1 > value2) && !AreClose(value1, value2);
}
/// <summary>
/// LessThanOrClose - Returns whether or not the first double is less than or close to
/// the second double. That is, whether or not the first is strictly less than or within
/// epsilon of the other number. Note that this epsilon is proportional to the numbers
/// themselves to that AreClose survives scalar multiplication. Note,
/// There are plenty of ways for this to return false even for numbers which
/// are theoretically identical, so no code calling this should fail to work if this
/// returns false. This is important enough to repeat:
/// NB: NO CODE CALLING THIS FUNCTION SHOULD DEPEND ON ACCURATE RESULTS - this should be
/// used for optimizations *only*.
/// </summary>
/// <returns>
/// bool - the result of the LessThanOrClose comparison.
/// </returns>
/// <param name="value1"> The first double to compare. </param>
/// <param name="value2"> The second double to compare. </param>
internal static bool LessThanOrClose(double value1, double value2)
{
return (value1 < value2) || AreClose(value1, value2);
}
/// <summary>
/// GreaterThanOrClose - Returns whether or not the first double is greater than or close to
/// the second double. That is, whether or not the first is strictly greater than or within
/// epsilon of the other number. Note that this epsilon is proportional to the numbers
/// themselves to that AreClose survives scalar multiplication. Note,
/// There are plenty of ways for this to return false even for numbers which
/// are theoretically identical, so no code calling this should fail to work if this
/// returns false. This is important enough to repeat:
/// NB: NO CODE CALLING THIS FUNCTION SHOULD DEPEND ON ACCURATE RESULTS - this should be
/// used for optimizations *only*.
/// </summary>
/// <returns>
/// bool - the result of the GreaterThanOrClose comparison.
/// </returns>
/// <param name="value1"> The first double to compare. </param>
/// <param name="value2"> The second double to compare. </param>
internal static bool GreaterThanOrClose(double value1, double value2)
{
return (value1 > value2) || AreClose(value1, value2);
}
/// <summary>
/// IsOne - Returns whether or not the double is "close" to 1. Same as AreClose(double, 1),
/// but this is faster.
/// </summary>
/// <returns>
/// bool - the result of the AreClose comparison.
/// </returns>
/// <param name="value"> The double to compare to 1. </param>
internal static bool IsOne(double value)
{
return Math.Abs(value - 1.0) < 10.0 * DblEpsilon;
}
/// <summary>
/// IsZero - Returns whether or not the double is "close" to 0. Same as AreClose(double, 0),
/// but this is faster.
/// </summary>
/// <returns>
/// bool - the result of the AreClose comparison.
/// </returns>
/// <param name="value"> The double to compare to 0. </param>
internal static bool IsZero(double value)
{
return Math.Abs(value) < 10.0 * DblEpsilon;
}
// The Point, Size, Rect and Matrix class have moved to WinCorLib. However, we provide
// internal AreClose methods for our own use here.
/// <summary>
/// Compares two points for fuzzy equality. This function
/// helps compensate for the fact that double values can
/// acquire error when operated upon.
/// </summary>
/// <param name='point1'>The first point to compare.</param>
/// <param name='point2'>The second point to compare.</param>
/// <returns>Whether or not the two points are equal.</returns>
internal static bool AreClose(Point point1, Point point2)
{
return AreClose(point1.X, point2.X) &&
AreClose(point1.Y, point2.Y);
}
/// <summary>
/// Compares two Size instances for fuzzy equality. This function
/// helps compensate for the fact that double values can
/// acquire error when operated upon.
/// </summary>
/// <param name='size1'>The first size to compare.</param>
/// <param name='size2'>The second size to compare.</param>
/// <returns>Whether or not the two Size instances are equal.</returns>
internal static bool AreClose(Size size1, Size size2)
{
return AreClose(size1.Width, size2.Width) &&
AreClose(size1.Height, size2.Height);
}
/// <summary>
/// Compares two Vector instances for fuzzy equality. This function
/// helps compensate for the fact that double values can
/// acquire error when operated upon.
/// </summary>
/// <param name='vector1'>The first Vector to compare.</param>
/// <param name='vector2'>The second Vector to compare.</param>
/// <returns>Whether or not the two Vector instances are equal.</returns>
internal static bool AreClose(Vector vector1, Vector vector2)
{
return AreClose(vector1.X, vector2.X) &&
AreClose(vector1.Y, vector2.Y);
}
/// <summary>
/// Compares two rectangles for fuzzy equality. This function
/// helps compensate for the fact that double values can
/// acquire error when operated upon.
/// </summary>
/// <param name='rect1'>The first rectangle to compare.</param>
/// <param name='rect2'>The second rectangle to compare.</param>
/// <returns>Whether or not the two rectangles are equal.</returns>
internal static bool AreClose(Rect rect1, Rect rect2)
{
// If they're both empty, don't bother with the double logic.
if (rect1.IsEmpty)
{
return rect2.IsEmpty;
}
// At this point, rect1 isn't empty, so the first thing we can test is
// rect2.IsEmpty, followed by property-wise compares.
return !rect2.IsEmpty &&
AreClose(rect1.X, rect2.X) &&
AreClose(rect1.Y, rect2.Y) &&
AreClose(rect1.Height, rect2.Height) &&
AreClose(rect1.Width, rect2.Width);
}
internal static bool IsBetweenZeroAndOne(double val)
{
return GreaterThanOrClose(val, 0) && LessThanOrClose(val, 1);
}
internal static int DoubleToInt(double val)
{
return val > 0 ? (int)(val + 0.5) : (int)(val - 0.5);
}
/// <summary>
/// rectHasNaN - this returns true if this rect has X, Y , Height or Width as NaN.
/// </summary>
/// <param name='r'>The rectangle to test.</param>
/// <returns>returns whether the Rect has NaN.</returns>
internal static bool RectHasNaN(Rect r)
{
return double.IsNaN(r.X) ||
double.IsNaN(r.Y) ||
double.IsNaN(r.Height) ||
double.IsNaN(r.Width);
}
}
}
| |
// OutputWindow.cs
//
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace PdfSharp.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// Contains the output from the Inflation process.
/// We need to have a window so that we can refer backwards into the output stream
/// to repeat stuff.<br/>
/// Author of the original java version: John Leuner
/// </summary>
internal class OutputWindow
{
private static int WINDOW_SIZE = 1 << 15;
private static int WINDOW_MASK = WINDOW_SIZE - 1;
private byte[] window = new byte[WINDOW_SIZE]; //The window is 2^15 bytes
private int windowEnd = 0;
private int windowFilled = 0;
/// <summary>
/// Write a byte to this output window
/// </summary>
/// <param name="abyte">value to write</param>
/// <exception cref="InvalidOperationException">
/// if window is full
/// </exception>
public void Write(int abyte)
{
if (windowFilled++ == WINDOW_SIZE)
{
throw new InvalidOperationException("Window full");
}
window[windowEnd++] = (byte)abyte;
windowEnd &= WINDOW_MASK;
}
private void SlowRepeat(int repStart, int len, int dist)
{
while (len-- > 0)
{
window[windowEnd++] = window[repStart++];
windowEnd &= WINDOW_MASK;
repStart &= WINDOW_MASK;
}
}
/// <summary>
/// Append a byte pattern already in the window itself
/// </summary>
/// <param name="len">length of pattern to copy</param>
/// <param name="dist">distance from end of window pattern occurs</param>
/// <exception cref="InvalidOperationException">
/// If the repeated data overflows the window
/// </exception>
public void Repeat(int len, int dist)
{
if ((windowFilled += len) > WINDOW_SIZE)
{
throw new InvalidOperationException("Window full");
}
int rep_start = (windowEnd - dist) & WINDOW_MASK;
int border = WINDOW_SIZE - len;
if (rep_start <= border && windowEnd < border)
{
if (len <= dist)
{
System.Array.Copy(window, rep_start, window, windowEnd, len);
windowEnd += len;
}
else
{
/* We have to copy manually, since the repeat pattern overlaps. */
while (len-- > 0)
{
window[windowEnd++] = window[rep_start++];
}
}
}
else
{
SlowRepeat(rep_start, len, dist);
}
}
/// <summary>
/// Copy from input manipulator to internal window
/// </summary>
/// <param name="input">source of data</param>
/// <param name="len">length of data to copy</param>
/// <returns>the number of bytes copied</returns>
public int CopyStored(StreamManipulator input, int len)
{
len = Math.Min(Math.Min(len, WINDOW_SIZE - windowFilled), input.AvailableBytes);
int copied;
int tailLen = WINDOW_SIZE - windowEnd;
if (len > tailLen)
{
copied = input.CopyBytes(window, windowEnd, tailLen);
if (copied == tailLen)
{
copied += input.CopyBytes(window, 0, len - tailLen);
}
}
else
{
copied = input.CopyBytes(window, windowEnd, len);
}
windowEnd = (windowEnd + copied) & WINDOW_MASK;
windowFilled += copied;
return copied;
}
/// <summary>
/// Copy dictionary to window
/// </summary>
/// <param name="dict">source dictionary</param>
/// <param name="offset">offset of start in source dictionary</param>
/// <param name="len">length of dictionary</param>
/// <exception cref="InvalidOperationException">
/// If window isnt empty
/// </exception>
public void CopyDict(byte[] dict, int offset, int len)
{
if (windowFilled > 0)
{
throw new InvalidOperationException();
}
if (len > WINDOW_SIZE)
{
offset += len - WINDOW_SIZE;
len = WINDOW_SIZE;
}
System.Array.Copy(dict, offset, window, 0, len);
windowEnd = len & WINDOW_MASK;
}
/// <summary>
/// Get remaining unfilled space in window
/// </summary>
/// <returns>Number of bytes left in window</returns>
public int GetFreeSpace()
{
return WINDOW_SIZE - windowFilled;
}
/// <summary>
/// Get bytes available for output in window
/// </summary>
/// <returns>Number of bytes filled</returns>
public int GetAvailable()
{
return windowFilled;
}
/// <summary>
/// Copy contents of window to output
/// </summary>
/// <param name="output">buffer to copy to</param>
/// <param name="offset">offset to start at</param>
/// <param name="len">number of bytes to count</param>
/// <returns>The number of bytes copied</returns>
/// <exception cref="InvalidOperationException">
/// If a window underflow occurs
/// </exception>
public int CopyOutput(byte[] output, int offset, int len)
{
int copy_end = windowEnd;
if (len > windowFilled)
{
len = windowFilled;
}
else
{
copy_end = (windowEnd - windowFilled + len) & WINDOW_MASK;
}
int copied = len;
int tailLen = len - copy_end;
if (tailLen > 0)
{
System.Array.Copy(window, WINDOW_SIZE - tailLen, output, offset, tailLen);
offset += tailLen;
len = copy_end;
}
System.Array.Copy(window, copy_end - len, output, offset, len);
windowFilled -= copied;
if (windowFilled < 0)
{
throw new InvalidOperationException();
}
return copied;
}
/// <summary>
/// Reset by clearing window so <see cref="GetAvailable">GetAvailable</see> returns 0
/// </summary>
public void Reset()
{
windowFilled = windowEnd = 0;
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
#pragma warning disable 1591 // disable warning on missing comments
using System;
using Org.SbeTool.Sbe.Dll;
namespace Baseline
{
public sealed partial class Car
{
public const ushort BlockLength = (ushort)49;
public const ushort TemplateId = (ushort)1;
public const ushort SchemaId = (ushort)1;
public const ushort SchemaVersion = (ushort)0;
public const string SemanticType = "";
private readonly Car _parentMessage;
private DirectBuffer _buffer;
private int _offset;
private int _limit;
private int _actingBlockLength;
private int _actingVersion;
public int Offset { get { return _offset; } }
public Car()
{
_parentMessage = this;
}
public void WrapForEncode(DirectBuffer buffer, int offset)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = BlockLength;
_actingVersion = SchemaVersion;
Limit = offset + _actingBlockLength;
}
public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = actingBlockLength;
_actingVersion = actingVersion;
Limit = offset + _actingBlockLength;
}
public int Size
{
get
{
return _limit - _offset;
}
}
public int Limit
{
get
{
return _limit;
}
set
{
_buffer.CheckLimit(value);
_limit = value;
}
}
public const int SerialNumberId = 1;
public const int SerialNumberSinceVersion = 0;
public const int SerialNumberDeprecated = 0;
public bool SerialNumberInActingVersion()
{
return _actingVersion >= SerialNumberSinceVersion;
}
public static string SerialNumberMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ulong SerialNumberNullValue = 0xffffffffffffffffUL;
public const ulong SerialNumberMinValue = 0x0UL;
public const ulong SerialNumberMaxValue = 0xfffffffffffffffeUL;
public ulong SerialNumber
{
get
{
return _buffer.Uint64GetLittleEndian(_offset + 0);
}
set
{
_buffer.Uint64PutLittleEndian(_offset + 0, value);
}
}
public const int ModelYearId = 2;
public const int ModelYearSinceVersion = 0;
public const int ModelYearDeprecated = 0;
public bool ModelYearInActingVersion()
{
return _actingVersion >= ModelYearSinceVersion;
}
public static string ModelYearMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ushort ModelYearNullValue = (ushort)65535;
public const ushort ModelYearMinValue = (ushort)0;
public const ushort ModelYearMaxValue = (ushort)65534;
public ushort ModelYear
{
get
{
return _buffer.Uint16GetLittleEndian(_offset + 8);
}
set
{
_buffer.Uint16PutLittleEndian(_offset + 8, value);
}
}
public const int AvailableId = 3;
public const int AvailableSinceVersion = 0;
public const int AvailableDeprecated = 0;
public bool AvailableInActingVersion()
{
return _actingVersion >= AvailableSinceVersion;
}
public static string AvailableMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public BooleanType Available
{
get
{
return (BooleanType)_buffer.Uint8Get(_offset + 10);
}
set
{
_buffer.Uint8Put(_offset + 10, (byte)value);
}
}
public const int CodeId = 4;
public const int CodeSinceVersion = 0;
public const int CodeDeprecated = 0;
public bool CodeInActingVersion()
{
return _actingVersion >= CodeSinceVersion;
}
public static string CodeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public Model Code
{
get
{
return (Model)_buffer.CharGet(_offset + 11);
}
set
{
_buffer.CharPut(_offset + 11, (byte)value);
}
}
public const int SomeNumbersId = 5;
public const int SomeNumbersSinceVersion = 0;
public const int SomeNumbersDeprecated = 0;
public bool SomeNumbersInActingVersion()
{
return _actingVersion >= SomeNumbersSinceVersion;
}
public static string SomeNumbersMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const uint SomeNumbersNullValue = 4294967295U;
public const uint SomeNumbersMinValue = 0U;
public const uint SomeNumbersMaxValue = 4294967294U;
public const int SomeNumbersLength = 5;
public uint GetSomeNumbers(int index)
{
if (index < 0 || index >= 5)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.Uint32GetLittleEndian(_offset + 12 + (index * 4));
}
public void SetSomeNumbers(int index, uint value)
{
if (index < 0 || index >= 5)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.Uint32PutLittleEndian(_offset + 12 + (index * 4), value);
}
public const int VehicleCodeId = 6;
public const int VehicleCodeSinceVersion = 0;
public const int VehicleCodeDeprecated = 0;
public bool VehicleCodeInActingVersion()
{
return _actingVersion >= VehicleCodeSinceVersion;
}
public static string VehicleCodeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const byte VehicleCodeNullValue = (byte)0;
public const byte VehicleCodeMinValue = (byte)32;
public const byte VehicleCodeMaxValue = (byte)126;
public const int VehicleCodeLength = 6;
public byte GetVehicleCode(int index)
{
if (index < 0 || index >= 6)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 32 + (index * 1));
}
public void SetVehicleCode(int index, byte value)
{
if (index < 0 || index >= 6)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 32 + (index * 1), value);
}
public const string VehicleCodeCharacterEncoding = "ASCII";
public int GetVehicleCode(byte[] dst, int dstOffset)
{
const int length = 6;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 32, dst, dstOffset, length);
return length;
}
public void SetVehicleCode(byte[] src, int srcOffset)
{
const int length = 6;
if (srcOffset < 0 || srcOffset > src.Length)
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
if (src.Length > length)
{
throw new ArgumentOutOfRangeException($"src.Length={src.Length} is too large.");
}
_buffer.SetBytes(_offset + 32, src, srcOffset, src.Length - srcOffset);
}
public const int ExtrasId = 7;
public const int ExtrasSinceVersion = 0;
public const int ExtrasDeprecated = 0;
public bool ExtrasInActingVersion()
{
return _actingVersion >= ExtrasSinceVersion;
}
public static string ExtrasMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public OptionalExtras Extras
{
get
{
return (OptionalExtras)_buffer.Uint8Get(_offset + 38);
}
set
{
_buffer.Uint8Put(_offset + 38, (byte)value);
}
}
public const int DiscountedModelId = 8;
public const int DiscountedModelSinceVersion = 0;
public const int DiscountedModelDeprecated = 0;
public bool DiscountedModelInActingVersion()
{
return _actingVersion >= DiscountedModelSinceVersion;
}
public static string DiscountedModelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public Model DiscountedModel
{
get
{
return (Model)_buffer.CharGet(_offset + 39);
}
set
{
_buffer.CharPut(_offset + 39, (byte)value);
}
}
public const int EngineId = 9;
public const int EngineSinceVersion = 0;
public const int EngineDeprecated = 0;
public bool EngineInActingVersion()
{
return _actingVersion >= EngineSinceVersion;
}
public static string EngineMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
private readonly Engine _engine = new Engine();
public Engine Engine
{
get
{
_engine.Wrap(_buffer, _offset + 39, _actingVersion);
return _engine;
}
}
private readonly FuelFiguresGroup _fuelFigures = new FuelFiguresGroup();
public const long FuelFiguresId = 10;
public const int FuelFiguresSinceVersion = 0;
public const int FuelFiguresDeprecated = 0;
public bool FuelFiguresInActingVersion()
{
return _actingVersion >= FuelFiguresSinceVersion;
}
public FuelFiguresGroup FuelFigures
{
get
{
_fuelFigures.WrapForDecode(_parentMessage, _buffer, _actingVersion);
return _fuelFigures;
}
}
public FuelFiguresGroup FuelFiguresCount(int count)
{
_fuelFigures.WrapForEncode(_parentMessage, _buffer, count);
return _fuelFigures;
}
public sealed partial class FuelFiguresGroup
{
private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding();
private Car _parentMessage;
private DirectBuffer _buffer;
private int _blockLength;
private int _actingVersion;
private int _count;
private int _index;
private int _offset;
public void WrapForDecode(Car parentMessage, DirectBuffer buffer, int actingVersion)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, actingVersion);
_blockLength = _dimensions.BlockLength;
_count = _dimensions.NumInGroup;
_actingVersion = actingVersion;
_index = -1;
_parentMessage.Limit = parentMessage.Limit + SbeHeaderSize;
}
public void WrapForEncode(Car parentMessage, DirectBuffer buffer, int count)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion);
_dimensions.BlockLength = (ushort)6;
_dimensions.NumInGroup = (ushort)count;
_index = -1;
_count = count;
_blockLength = 6;
parentMessage.Limit = parentMessage.Limit + SbeHeaderSize;
}
public const int SbeBlockLength = 6;
public const int SbeHeaderSize = 4;
public int ActingBlockLength { get { return _blockLength; } }
public int Count { get { return _count; } }
public bool HasNext { get { return (_index + 1) < _count; } }
public FuelFiguresGroup Next()
{
if (_index + 1 >= _count)
{
throw new InvalidOperationException();
}
_offset = _parentMessage.Limit;
_parentMessage.Limit = _offset + _blockLength;
++_index;
return this;
}
public System.Collections.IEnumerator GetEnumerator()
{
while (this.HasNext)
{
yield return this.Next();
}
}
public const int SpeedId = 11;
public const int SpeedSinceVersion = 0;
public const int SpeedDeprecated = 0;
public bool SpeedInActingVersion()
{
return _actingVersion >= SpeedSinceVersion;
}
public static string SpeedMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ushort SpeedNullValue = (ushort)65535;
public const ushort SpeedMinValue = (ushort)0;
public const ushort SpeedMaxValue = (ushort)65534;
public ushort Speed
{
get
{
return _buffer.Uint16GetLittleEndian(_offset + 0);
}
set
{
_buffer.Uint16PutLittleEndian(_offset + 0, value);
}
}
public const int MpgId = 12;
public const int MpgSinceVersion = 0;
public const int MpgDeprecated = 0;
public bool MpgInActingVersion()
{
return _actingVersion >= MpgSinceVersion;
}
public static string MpgMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const float MpgNullValue = float.NaN;
public const float MpgMinValue = 1.401298464324817E-45f;
public const float MpgMaxValue = 3.4028234663852886E38f;
public float Mpg
{
get
{
return _buffer.FloatGetLittleEndian(_offset + 2);
}
set
{
_buffer.FloatPutLittleEndian(_offset + 2, value);
}
}
public const int UsageDescriptionId = 200;
public const int UsageDescriptionSinceVersion = 0;
public const int UsageDescriptionDeprecated = 0;
public bool UsageDescriptionInActingVersion()
{
return _actingVersion >= UsageDescriptionSinceVersion;
}
public const string UsageDescriptionCharacterEncoding = "UTF-8";
public static string UsageDescriptionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const int UsageDescriptionHeaderSize = 4;
public int GetUsageDescription(byte[] dst, int dstOffset, int length)
{
const int sizeOfLengthField = 4;
int limit = _parentMessage.Limit;
_buffer.CheckLimit(limit + sizeOfLengthField);
int dataLength = (int)_buffer.Uint32GetLittleEndian(limit);
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit = limit + sizeOfLengthField + dataLength;
_buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int SetUsageDescription(byte[] src, int srcOffset, int length)
{
const int sizeOfLengthField = 4;
int limit = _parentMessage.Limit;
_parentMessage.Limit = limit + sizeOfLengthField + length;
_buffer.Uint32PutLittleEndian(limit, (uint)length);
_buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length);
return length;
}
}
private readonly PerformanceFiguresGroup _performanceFigures = new PerformanceFiguresGroup();
public const long PerformanceFiguresId = 13;
public const int PerformanceFiguresSinceVersion = 0;
public const int PerformanceFiguresDeprecated = 0;
public bool PerformanceFiguresInActingVersion()
{
return _actingVersion >= PerformanceFiguresSinceVersion;
}
public PerformanceFiguresGroup PerformanceFigures
{
get
{
_performanceFigures.WrapForDecode(_parentMessage, _buffer, _actingVersion);
return _performanceFigures;
}
}
public PerformanceFiguresGroup PerformanceFiguresCount(int count)
{
_performanceFigures.WrapForEncode(_parentMessage, _buffer, count);
return _performanceFigures;
}
public sealed partial class PerformanceFiguresGroup
{
private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding();
private Car _parentMessage;
private DirectBuffer _buffer;
private int _blockLength;
private int _actingVersion;
private int _count;
private int _index;
private int _offset;
public void WrapForDecode(Car parentMessage, DirectBuffer buffer, int actingVersion)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, actingVersion);
_blockLength = _dimensions.BlockLength;
_count = _dimensions.NumInGroup;
_actingVersion = actingVersion;
_index = -1;
_parentMessage.Limit = parentMessage.Limit + SbeHeaderSize;
}
public void WrapForEncode(Car parentMessage, DirectBuffer buffer, int count)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion);
_dimensions.BlockLength = (ushort)1;
_dimensions.NumInGroup = (ushort)count;
_index = -1;
_count = count;
_blockLength = 1;
parentMessage.Limit = parentMessage.Limit + SbeHeaderSize;
}
public const int SbeBlockLength = 1;
public const int SbeHeaderSize = 4;
public int ActingBlockLength { get { return _blockLength; } }
public int Count { get { return _count; } }
public bool HasNext { get { return (_index + 1) < _count; } }
public PerformanceFiguresGroup Next()
{
if (_index + 1 >= _count)
{
throw new InvalidOperationException();
}
_offset = _parentMessage.Limit;
_parentMessage.Limit = _offset + _blockLength;
++_index;
return this;
}
public System.Collections.IEnumerator GetEnumerator()
{
while (this.HasNext)
{
yield return this.Next();
}
}
public const int OctaneRatingId = 14;
public const int OctaneRatingSinceVersion = 0;
public const int OctaneRatingDeprecated = 0;
public bool OctaneRatingInActingVersion()
{
return _actingVersion >= OctaneRatingSinceVersion;
}
public static string OctaneRatingMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const byte OctaneRatingNullValue = (byte)255;
public const byte OctaneRatingMinValue = (byte)90;
public const byte OctaneRatingMaxValue = (byte)110;
public byte OctaneRating
{
get
{
return _buffer.Uint8Get(_offset + 0);
}
set
{
_buffer.Uint8Put(_offset + 0, value);
}
}
private readonly AccelerationGroup _acceleration = new AccelerationGroup();
public const long AccelerationId = 15;
public const int AccelerationSinceVersion = 0;
public const int AccelerationDeprecated = 0;
public bool AccelerationInActingVersion()
{
return _actingVersion >= AccelerationSinceVersion;
}
public AccelerationGroup Acceleration
{
get
{
_acceleration.WrapForDecode(_parentMessage, _buffer, _actingVersion);
return _acceleration;
}
}
public AccelerationGroup AccelerationCount(int count)
{
_acceleration.WrapForEncode(_parentMessage, _buffer, count);
return _acceleration;
}
public sealed partial class AccelerationGroup
{
private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding();
private Car _parentMessage;
private DirectBuffer _buffer;
private int _blockLength;
private int _actingVersion;
private int _count;
private int _index;
private int _offset;
public void WrapForDecode(Car parentMessage, DirectBuffer buffer, int actingVersion)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, actingVersion);
_blockLength = _dimensions.BlockLength;
_count = _dimensions.NumInGroup;
_actingVersion = actingVersion;
_index = -1;
_parentMessage.Limit = parentMessage.Limit + SbeHeaderSize;
}
public void WrapForEncode(Car parentMessage, DirectBuffer buffer, int count)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion);
_dimensions.BlockLength = (ushort)6;
_dimensions.NumInGroup = (ushort)count;
_index = -1;
_count = count;
_blockLength = 6;
parentMessage.Limit = parentMessage.Limit + SbeHeaderSize;
}
public const int SbeBlockLength = 6;
public const int SbeHeaderSize = 4;
public int ActingBlockLength { get { return _blockLength; } }
public int Count { get { return _count; } }
public bool HasNext { get { return (_index + 1) < _count; } }
public AccelerationGroup Next()
{
if (_index + 1 >= _count)
{
throw new InvalidOperationException();
}
_offset = _parentMessage.Limit;
_parentMessage.Limit = _offset + _blockLength;
++_index;
return this;
}
public System.Collections.IEnumerator GetEnumerator()
{
while (this.HasNext)
{
yield return this.Next();
}
}
public const int MphId = 16;
public const int MphSinceVersion = 0;
public const int MphDeprecated = 0;
public bool MphInActingVersion()
{
return _actingVersion >= MphSinceVersion;
}
public static string MphMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ushort MphNullValue = (ushort)65535;
public const ushort MphMinValue = (ushort)0;
public const ushort MphMaxValue = (ushort)65534;
public ushort Mph
{
get
{
return _buffer.Uint16GetLittleEndian(_offset + 0);
}
set
{
_buffer.Uint16PutLittleEndian(_offset + 0, value);
}
}
public const int SecondsId = 17;
public const int SecondsSinceVersion = 0;
public const int SecondsDeprecated = 0;
public bool SecondsInActingVersion()
{
return _actingVersion >= SecondsSinceVersion;
}
public static string SecondsMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const float SecondsNullValue = float.NaN;
public const float SecondsMinValue = 1.401298464324817E-45f;
public const float SecondsMaxValue = 3.4028234663852886E38f;
public float Seconds
{
get
{
return _buffer.FloatGetLittleEndian(_offset + 2);
}
set
{
_buffer.FloatPutLittleEndian(_offset + 2, value);
}
}
}
}
public const int ManufacturerId = 18;
public const int ManufacturerSinceVersion = 0;
public const int ManufacturerDeprecated = 0;
public bool ManufacturerInActingVersion()
{
return _actingVersion >= ManufacturerSinceVersion;
}
public const string ManufacturerCharacterEncoding = "UTF-8";
public static string ManufacturerMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const int ManufacturerHeaderSize = 4;
public int GetManufacturer(byte[] dst, int dstOffset, int length)
{
const int sizeOfLengthField = 4;
int limit = _parentMessage.Limit;
_buffer.CheckLimit(limit + sizeOfLengthField);
int dataLength = (int)_buffer.Uint32GetLittleEndian(limit);
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit = limit + sizeOfLengthField + dataLength;
_buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int SetManufacturer(byte[] src, int srcOffset, int length)
{
const int sizeOfLengthField = 4;
int limit = _parentMessage.Limit;
_parentMessage.Limit = limit + sizeOfLengthField + length;
_buffer.Uint32PutLittleEndian(limit, (uint)length);
_buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length);
return length;
}
public const int ModelId = 19;
public const int ModelSinceVersion = 0;
public const int ModelDeprecated = 0;
public bool ModelInActingVersion()
{
return _actingVersion >= ModelSinceVersion;
}
public const string ModelCharacterEncoding = "UTF-8";
public static string ModelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const int ModelHeaderSize = 4;
public int GetModel(byte[] dst, int dstOffset, int length)
{
const int sizeOfLengthField = 4;
int limit = _parentMessage.Limit;
_buffer.CheckLimit(limit + sizeOfLengthField);
int dataLength = (int)_buffer.Uint32GetLittleEndian(limit);
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit = limit + sizeOfLengthField + dataLength;
_buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int SetModel(byte[] src, int srcOffset, int length)
{
const int sizeOfLengthField = 4;
int limit = _parentMessage.Limit;
_parentMessage.Limit = limit + sizeOfLengthField + length;
_buffer.Uint32PutLittleEndian(limit, (uint)length);
_buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length);
return length;
}
public const int ActivationCodeId = 20;
public const int ActivationCodeSinceVersion = 0;
public const int ActivationCodeDeprecated = 0;
public bool ActivationCodeInActingVersion()
{
return _actingVersion >= ActivationCodeSinceVersion;
}
public const string ActivationCodeCharacterEncoding = "UTF-8";
public static string ActivationCodeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const int ActivationCodeHeaderSize = 4;
public int GetActivationCode(byte[] dst, int dstOffset, int length)
{
const int sizeOfLengthField = 4;
int limit = _parentMessage.Limit;
_buffer.CheckLimit(limit + sizeOfLengthField);
int dataLength = (int)_buffer.Uint32GetLittleEndian(limit);
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit = limit + sizeOfLengthField + dataLength;
_buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int SetActivationCode(byte[] src, int srcOffset, int length)
{
const int sizeOfLengthField = 4;
int limit = _parentMessage.Limit;
_parentMessage.Limit = limit + sizeOfLengthField + length;
_buffer.Uint32PutLittleEndian(limit, (uint)length);
_buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length);
return length;
}
}
}
| |
// 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.Threading;
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
public sealed partial class ArrayType : ParameterizedType
{
private int _rank; // -1 for regular single dimensional arrays, > 0 for multidimensional arrays
internal ArrayType(TypeDesc elementType, int rank)
: base(elementType)
{
_rank = rank;
}
public override int GetHashCode()
{
return Internal.NativeFormat.TypeHashingAlgorithms.ComputeArrayTypeHashCode(this.ElementType.GetHashCode(), _rank == -1 ? 1 : _rank);
}
public override DefType BaseType
{
get
{
return this.Context.GetWellKnownType(WellKnownType.Array);
}
}
public TypeDesc ElementType
{
get
{
return this.ParameterType;
}
}
internal MethodDesc[] _methods;
public new bool IsSzArray
{
get
{
return _rank < 0;
}
}
public int Rank
{
get
{
return (_rank < 0) ? 1 : _rank;
}
}
private void InitializeMethods()
{
int numCtors;
if (IsSzArray)
{
numCtors = 1;
var t = this.ElementType;
while (t.IsSzArray)
{
t = ((ArrayType)t).ElementType;
numCtors++;
}
}
else
{
// ELEMENT_TYPE_ARRAY has two ctor functions, one with and one without lower bounds
numCtors = 2;
}
MethodDesc[] methods = new MethodDesc[(int)ArrayMethodKind.Ctor + numCtors];
for (int i = 0; i < methods.Length; i++)
methods[i] = new ArrayMethod(this, (ArrayMethodKind)i);
Interlocked.CompareExchange(ref _methods, methods, null);
}
public override IEnumerable<MethodDesc> GetMethods()
{
if (_methods == null)
InitializeMethods();
return _methods;
}
public MethodDesc GetArrayMethod(ArrayMethodKind kind)
{
if (_methods == null)
InitializeMethods();
return _methods[(int)kind];
}
public override TypeDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
TypeDesc instantiatedElementType = this.ElementType.InstantiateSignature(typeInstantiation, methodInstantiation);
return instantiatedElementType.Context.GetArrayType(instantiatedElementType, _rank);
}
public override TypeDesc GetTypeDefinition()
{
TypeDesc result = this;
TypeDesc elementDef = this.ElementType.GetTypeDefinition();
if (elementDef != this.ElementType)
result = elementDef.Context.GetArrayType(elementDef);
return result;
}
protected override TypeFlags ComputeTypeFlags(TypeFlags mask)
{
TypeFlags flags = _rank == -1 ? TypeFlags.SzArray : TypeFlags.Array;
if ((mask & TypeFlags.ContainsGenericVariablesComputed) != 0)
{
flags |= TypeFlags.ContainsGenericVariablesComputed;
if (this.ParameterType.ContainsGenericVariables)
flags |= TypeFlags.ContainsGenericVariables;
}
flags |= TypeFlags.HasGenericVarianceComputed;
return flags;
}
public override string ToString()
{
return this.ElementType.ToString() + "[" + new String(',', Rank - 1) + "]";
}
}
public enum ArrayMethodKind
{
Get,
Set,
Address,
Ctor
}
public partial class ArrayMethod : MethodDesc
{
private ArrayType _owningType;
private ArrayMethodKind _kind;
internal ArrayMethod(ArrayType owningType, ArrayMethodKind kind)
{
_owningType = owningType;
_kind = kind;
}
public override TypeSystemContext Context
{
get
{
return _owningType.Context;
}
}
public override TypeDesc OwningType
{
get
{
return _owningType;
}
}
public ArrayMethodKind Kind
{
get
{
return _kind;
}
}
private MethodSignature _signature;
public override MethodSignature Signature
{
get
{
if (_signature == null)
{
switch (_kind)
{
case ArrayMethodKind.Get:
{
var parameters = new TypeDesc[_owningType.Rank];
for (int i = 0; i < _owningType.Rank; i++)
parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, _owningType.ElementType, parameters);
break;
}
case ArrayMethodKind.Set:
{
var parameters = new TypeDesc[_owningType.Rank + 1];
for (int i = 0; i < _owningType.Rank; i++)
parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
parameters[_owningType.Rank] = _owningType.ElementType;
_signature = new MethodSignature(0, 0, this.Context.GetWellKnownType(WellKnownType.Void), parameters);
break;
}
case ArrayMethodKind.Address:
{
var parameters = new TypeDesc[_owningType.Rank];
for (int i = 0; i < _owningType.Rank; i++)
parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, _owningType.ElementType.MakeByRefType(), parameters);
}
break;
default:
{
int numArgs;
if (_owningType.IsSzArray)
{
numArgs = 1 + (int)_kind - (int)ArrayMethodKind.Ctor;
}
else
{
numArgs = (_kind == ArrayMethodKind.Ctor) ? _owningType.Rank : 2 * _owningType.Rank;
}
var argTypes = new TypeDesc[numArgs];
for (int i = 0; i < argTypes.Length; i++)
argTypes[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, this.Context.GetWellKnownType(WellKnownType.Void), argTypes);
}
break;
}
}
return _signature;
}
}
public override string Name
{
get
{
switch (_kind)
{
case ArrayMethodKind.Get:
return "Get";
case ArrayMethodKind.Set:
return "Set";
case ArrayMethodKind.Address:
return "Address";
default:
return ".ctor";
}
}
}
// Strips method instantiation. E.g C<int>.m<string> -> C<int>.m<U>
public override MethodDesc GetMethodDefinition()
{
return this;
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return false;
}
// Strips both type and method instantiation. E.g C<int>.m<string> -> C<T>.m<U>
public override MethodDesc GetTypicalMethodDefinition()
{
return this;
}
public override MethodDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
TypeDesc owningType = this.OwningType;
TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation);
if (owningType != instantiatedOwningType)
return ((ArrayType)instantiatedOwningType).GetArrayMethod(_kind);
else
return this;
}
public override string ToString()
{
return _owningType.ToString() + "." + Name;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using EnvDTE;
using NuGet.VisualStudio;
namespace NuGet.PowerShell.Commands
{
/// <summary>
/// This is the base class for all NuGet cmdlets.
/// </summary>
public abstract class NuGetBaseCommand : PSCmdlet, ILogger, IErrorHandler
{
// User Agent. Do NOT localize
private const string PSCommandsUserAgentClient = "NuGet Package Manager Console";
private readonly Lazy<string> _psCommandsUserAgent = new Lazy<string>(() => HttpUtility.CreateUserAgentString(PSCommandsUserAgentClient));
private IVsPackageManager _packageManager;
private readonly ISolutionManager _solutionManager;
private readonly IVsPackageManagerFactory _vsPackageManagerFactory;
private ProgressRecordCollection _progressRecordCache;
private readonly IHttpClientEvents _httpClientEvents;
protected NuGetBaseCommand(ISolutionManager solutionManager, IVsPackageManagerFactory vsPackageManagerFactory, IHttpClientEvents httpClientEvents)
{
_solutionManager = solutionManager;
_vsPackageManagerFactory = vsPackageManagerFactory;
_httpClientEvents = httpClientEvents;
}
private ProgressRecordCollection ProgressRecordCache
{
get
{
if (_progressRecordCache == null)
{
_progressRecordCache = new ProgressRecordCollection();
}
return _progressRecordCache;
}
}
protected IErrorHandler ErrorHandler
{
get
{
return this;
}
}
protected ISolutionManager SolutionManager
{
get
{
return _solutionManager;
}
}
protected IVsPackageManagerFactory PackageManagerFactory
{
get
{
return _vsPackageManagerFactory;
}
}
internal bool IsSyncMode
{
get
{
if (Host == null || Host.PrivateData == null)
{
return false;
}
PSObject privateData = Host.PrivateData;
var syncModeProp = privateData.Properties["IsSyncMode"];
return syncModeProp != null && (bool)syncModeProp.Value;
}
}
/// <summary>
/// Gets an instance of VSPackageManager to be used throughout the execution of this command.
/// </summary>
/// <value>The package manager.</value>
protected internal IVsPackageManager PackageManager
{
get
{
if (_packageManager == null)
{
_packageManager = CreatePackageManager();
}
return _packageManager;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to display friendly message to the console.")]
protected sealed override void ProcessRecord()
{
try
{
ProcessRecordCore();
}
catch (Exception ex)
{
// unhandled exceptions should be terminating
ErrorHandler.HandleException(ex, terminating: true);
}
}
/// <summary>
/// Derived classess must implement this method instead of ProcessRecord(), which is sealed by NuGetBaseCmdlet.
/// </summary>
protected abstract void ProcessRecordCore();
public void Log(MessageLevel level, string message, params object[] args)
{
string formattedMessage = String.Format(CultureInfo.CurrentCulture, message, args);
LogCore(level, formattedMessage);
}
internal void Execute()
{
BeginProcessing();
ProcessRecord();
EndProcessing();
}
protected override void BeginProcessing()
{
if (_httpClientEvents != null)
{
_httpClientEvents.SendingRequest += OnSendingRequest;
}
}
protected override void EndProcessing()
{
if (_httpClientEvents != null)
{
_httpClientEvents.SendingRequest -= OnSendingRequest;
}
}
protected void SubscribeToProgressEvents()
{
if (!IsSyncMode && _httpClientEvents != null)
{
_httpClientEvents.ProgressAvailable += OnProgressAvailable;
}
}
protected void UnsubscribeFromProgressEvents()
{
if (_httpClientEvents != null)
{
_httpClientEvents.ProgressAvailable -= OnProgressAvailable;
}
}
protected virtual void LogCore(MessageLevel level, string formattedMessage)
{
switch (level)
{
case MessageLevel.Debug:
WriteVerbose(formattedMessage);
break;
case MessageLevel.Warning:
WriteWarning(formattedMessage);
break;
case MessageLevel.Info:
WriteLine(formattedMessage);
break;
case MessageLevel.Error:
WriteError(formattedMessage);
break;
}
}
protected virtual IVsPackageManager CreatePackageManager()
{
if (!SolutionManager.IsSolutionOpen)
{
return null;
}
return PackageManagerFactory.CreatePackageManager();
}
/// <summary>
/// Return all projects in the solution matching the provided names. Wildcards are supported.
/// This method will automatically generate error records for non-wildcarded project names that
/// are not found.
/// </summary>
/// <param name="projectNames">An array of project names that may or may not include wildcards.</param>
/// <returns>Projects matching the project name(s) provided.</returns>
protected IEnumerable<Project> GetProjectsByName(string[] projectNames)
{
var allValidProjectNames = GetAllValidProjectNames().ToList();
foreach (string projectName in projectNames)
{
// if ctrl+c hit, leave immediately
if (Stopping)
{
break;
}
// Treat every name as a wildcard; results in simpler code
var pattern = new WildcardPattern(projectName, WildcardOptions.IgnoreCase);
var matches = from s in allValidProjectNames
where pattern.IsMatch(s)
select _solutionManager.GetProject(s);
int count = 0;
foreach (var project in matches)
{
count++;
yield return project;
}
// We only emit non-terminating error record if a non-wildcarded name was not found.
// This is consistent with built-in cmdlets that support wildcarded search.
// A search with a wildcard that returns nothing should not be considered an error.
if ((count == 0) && !WildcardPattern.ContainsWildcardCharacters(projectName))
{
ErrorHandler.WriteProjectNotFoundError(projectName, terminating: false);
}
}
}
/// <summary>
/// Return all possibly valid project names in the current solution. This includes all
/// unique names and safe names.
/// </summary>
/// <returns></returns>
private IEnumerable<string> GetAllValidProjectNames()
{
var safeNames = _solutionManager.GetProjects().Select(p => _solutionManager.GetProjectSafeName(p));
var uniqueNames = _solutionManager.GetProjects().Select(p => p.GetCustomUniqueName());
return uniqueNames.Concat(safeNames).Distinct();
}
/// <summary>
/// Translate a PSPath into a System.IO.* friendly Win32 path.
/// Does not resolve/glob wildcards.
/// </summary>
/// <param name="psPath">The PowerShell PSPath to translate which may reference PSDrives or have provider-qualified paths which are syntactically invalid for .NET APIs.</param>
/// <param name="path">The translated PSPath in a format understandable to .NET APIs.</param>
/// <param name="exists">Returns null if not tested, or a bool representing path existence.</param>
/// <param name="errorMessage">If translation failed, contains the reason.</param>
/// <returns>True if successfully translated, false if not.</returns>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Following TryParse pattern in BCL", Target = "path")]
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Following TryParse pattern in BCL", Target = "exists")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "ps", Justification = "ps is a common powershell prefix")]
protected bool TryTranslatePSPath(string psPath, out string path, out bool? exists, out string errorMessage)
{
return PSPathUtility.TryTranslatePSPath(SessionState, psPath, out path, out exists, out errorMessage);
}
/// <summary>
/// Create a package repository from the source by trying to resolve relative paths.
/// </summary>
protected IPackageRepository CreateRepositoryFromSource(IPackageRepositoryFactory repositoryFactory, IPackageSourceProvider sourceProvider, string source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
UriFormatException uriException = null;
string resolvedSource = sourceProvider.ResolveSource(source);
try
{
IPackageRepository repository = repositoryFactory.CreateRepository(resolvedSource);
if (repository != null)
{
return repository;
}
}
catch (UriFormatException ex)
{
// if the source is relative path, it can result in invalid uri exception
uriException = ex;
}
Uri uri;
// if it's not an absolute path, treat it as relative path
if (Uri.TryCreate(source, UriKind.Relative, out uri))
{
string outputPath;
bool? exists;
string errorMessage;
// translate relative path to absolute path
if (TryTranslatePSPath(source, out outputPath, out exists, out errorMessage) && exists == true)
{
return repositoryFactory.CreateRepository(outputPath);
}
else
{
return repositoryFactory.CreateRepository(source);
}
}
else
{
// if this is not a valid relative path either,
// we rethrow the UriFormatException that we caught earlier.
if (uriException != null)
{
throw uriException;
}
}
return null;
}
[SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes", Justification = "This exception is passed to PowerShell. We really don't care about the type of exception here.")]
protected void WriteError(string message)
{
if (!String.IsNullOrEmpty(message))
{
WriteError(new Exception(message));
}
}
protected void WriteError(Exception exception)
{
ErrorHandler.HandleException(exception, terminating: false);
}
void IErrorHandler.WriteProjectNotFoundError(string projectName, bool terminating)
{
var notFoundException =
new ItemNotFoundException(
String.Format(
CultureInfo.CurrentCulture,
Resources.Cmdlet_ProjectNotFound, projectName));
ErrorHandler.HandleError(
new ErrorRecord(
notFoundException,
NuGetErrorId.ProjectNotFound, // This is your locale-agnostic error id.
ErrorCategory.ObjectNotFound,
projectName),
terminating: terminating);
}
void IErrorHandler.ThrowSolutionNotOpenTerminatingError()
{
ErrorHandler.HandleException(
new InvalidOperationException(Resources.Cmdlet_NoSolution),
terminating: true,
errorId: NuGetErrorId.NoActiveSolution,
category: ErrorCategory.InvalidOperation);
}
void IErrorHandler.ThrowNoCompatibleProjectsTerminatingError()
{
ErrorHandler.HandleException(
new InvalidOperationException(Resources.Cmdlet_NoCompatibleProjects),
terminating: true,
errorId: NuGetErrorId.NoCompatibleProjects,
category: ErrorCategory.InvalidOperation);
}
void IErrorHandler.HandleError(ErrorRecord errorRecord, bool terminating)
{
if (terminating)
{
ThrowTerminatingError(errorRecord);
}
else
{
WriteError(errorRecord);
}
}
void IErrorHandler.HandleException(Exception exception, bool terminating,
string errorId, ErrorCategory category, object target)
{
exception = ExceptionUtility.Unwrap(exception);
var error = new ErrorRecord(exception, errorId, category, target);
ErrorHandler.HandleError(error, terminating: terminating);
}
protected void WriteLine(string message = null)
{
if (Host == null)
{
// Host is null when running unit tests. Simply return in this case
return;
}
if (message == null)
{
Host.UI.WriteLine();
}
else
{
Host.UI.WriteLine(message);
}
}
protected void WriteProgress(int activityId, string operation, int percentComplete)
{
if (IsSyncMode)
{
// don't bother to show progress if we are in synchronous mode
return;
}
ProgressRecord progressRecord;
// retrieve the ProgressRecord object for this particular activity id from the cache.
if (ProgressRecordCache.Contains(activityId))
{
progressRecord = ProgressRecordCache[activityId];
}
else
{
progressRecord = new ProgressRecord(activityId, operation, operation);
ProgressRecordCache.Add(progressRecord);
}
progressRecord.CurrentOperation = operation;
progressRecord.PercentComplete = percentComplete;
WriteProgress(progressRecord);
}
private void OnProgressAvailable(object sender, ProgressEventArgs e)
{
WriteProgress(ProgressActivityIds.DownloadPackageId, e.Operation, e.PercentComplete);
}
private class ProgressRecordCollection : KeyedCollection<int, ProgressRecord>
{
protected override int GetKeyForItem(ProgressRecord item)
{
return item.ActivityId;
}
}
private void OnSendingRequest(object sender, WebRequestEventArgs e)
{
HttpUtility.SetUserAgent(e.Request, _psCommandsUserAgent.Value);
}
}
}
| |
namespace System.Workflow.Activities
{
using System;
using System.Text;
using System.Reflection;
using System.Collections;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Runtime.Serialization;
using System.Workflow.ComponentModel.Compiler;
using System.ComponentModel.Design.Serialization;
using System.Collections.Specialized;
using System.Xml;
using System.Web.Services.Protocols;
using System.Windows.Forms.Design;
using System.Security.Permissions;
using System.Workflow.Activities.Common;
#region Class InvokeWebServiceToolboxItem
[Serializable]
internal sealed class InvokeWebServiceToolboxItem : ActivityToolboxItem
{
public InvokeWebServiceToolboxItem(Type type)
: base(type)
{
}
private InvokeWebServiceToolboxItem(SerializationInfo info, StreamingContext context)
{
base.Deserialize(info, context);
}
public override IComponent[] CreateComponentsWithUI(IDesignerHost host)
{
Uri url = null;
Type proxyClass = null;
IExtendedUIService extUIService = host.GetService(typeof(IExtendedUIService)) as IExtendedUIService;
if (extUIService != null)
extUIService.AddWebReference(out url, out proxyClass);
IComponent[] components = base.CreateComponentsWithUI(host);
if (components.GetLength(0) > 0)
{
InvokeWebServiceActivity webService = components[0] as InvokeWebServiceActivity;
if (webService != null)
webService.ProxyClass = proxyClass;
}
return components;
}
}
#endregion
#region Class InvokeWebServiceDesigner
[ActivityDesignerTheme(typeof(InvokeWebServiceDesignerTheme))]
internal sealed class InvokeWebServiceDesigner : ActivityDesigner
{
#region Members, Constructor and Destructor
private string url = null;
#endregion
#region Properties and Methods
protected override void PreFilterProperties(IDictionary properties)
{
base.PreFilterProperties(properties);
if (properties["URL"] == null)
properties["URL"] = new WebServiceUrlPropertyDescriptor(Activity.Site, TypeDescriptor.CreateProperty(this.GetType(), "URL", typeof(string), DesignOnlyAttribute.Yes, MergablePropertyAttribute.No));
//
ITypeProvider typeProvider = (ITypeProvider)GetService(typeof(ITypeProvider));
if (typeProvider == null)
throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
InvokeWebServiceActivity invokeWebService = Activity as InvokeWebServiceActivity;
invokeWebService.GetParameterPropertyDescriptors(properties);
}
[SRCategory(SR.Activity)]
[SRDescription(SR.URLDescr)]
[Editor(typeof(WebServicePickerEditor), typeof(UITypeEditor))]
[RefreshProperties(RefreshProperties.All)]
public string URL
{
get
{
if (this.url == null)
{
InvokeWebServiceActivity invokeWebServiceDecl = Activity as InvokeWebServiceActivity;
IExtendedUIService extUIService = (IExtendedUIService)Activity.Site.GetService(typeof(IExtendedUIService));
if (extUIService != null && invokeWebServiceDecl.ProxyClass != null)
{
Uri uri = extUIService.GetUrlForProxyClass(invokeWebServiceDecl.ProxyClass);
this.url = (uri != null) ? uri.ToString() : string.Empty;
}
}
return this.url;
}
set
{
if (this.url != value)
{
this.url = value;
IExtendedUIService extUIService = (IExtendedUIService)Activity.Site.GetService(typeof(IExtendedUIService));
if (extUIService == null)
throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(IExtendedUIService).FullName));
//Create the designer transaction
DesignerTransaction trans = null;
IDesignerHost host = Activity.Site.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (host != null)
trans = host.CreateTransaction(SR.GetString(SR.ChangingVariable));
try
{
PropertyDescriptorUtils.SetPropertyValue(Activity.Site, TypeDescriptor.GetProperties(Activity)["ProxyClass"], Activity, string.IsNullOrEmpty(this.url) ? null : extUIService.GetProxyClassForUrl(new Uri(this.url)));
if (trans != null)
trans.Commit();
}
finally
{
if (trans != null)
((IDisposable)trans).Dispose();
}
}
}
}
protected override void OnActivityChanged(ActivityChangedEventArgs e)
{
base.OnActivityChanged(e);
if (e.Member != null)
{
if (e.Member.Name == "ProxyClass")
{
if (Activity.Site != null)
{
InvokeWebServiceActivity invokeWebServiceDecl = e.Activity as InvokeWebServiceActivity;
PropertyDescriptorUtils.SetPropertyValue(Activity.Site, TypeDescriptor.GetProperties(Activity)["MethodName"], Activity, String.Empty);
IExtendedUIService extUIService = (IExtendedUIService)Activity.Site.GetService(typeof(IExtendedUIService));
if (extUIService == null)
throw new Exception(SR.GetString(SR.General_MissingService, typeof(IExtendedUIService).FullName));
if (invokeWebServiceDecl.ProxyClass == null)
{
this.url = null;
}
else
{
Uri uri = extUIService.GetUrlForProxyClass(invokeWebServiceDecl.ProxyClass);
this.url = (uri != null) ? uri.ToString() : string.Empty;
}
}
}
if ((e.Member.Name == "MethodName" || e.Member.Name == "TargetWorkflow")
&& e.Activity is InvokeWebServiceActivity)
(e.Activity as InvokeWebServiceActivity).ParameterBindings.Clear();
if (e.Member.Name == "ProxyClass" || e.Member.Name == "MethodName")
TypeDescriptor.Refresh(e.Activity);
}
}
#endregion
}
#endregion
#region InvokeWebServiceDesignerTheme
internal sealed class InvokeWebServiceDesignerTheme : ActivityDesignerTheme
{
public InvokeWebServiceDesignerTheme(WorkflowTheme theme)
: base(theme)
{
this.ForeColor = Color.FromArgb(0xFF, 0x00, 0x00, 0x00);
this.BorderColor = Color.FromArgb(0xFF, 0x94, 0xB6, 0xF7);
this.BorderStyle = DashStyle.Solid;
this.BackColorStart = Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF);
this.BackColorEnd = Color.FromArgb(0xFF, 0xA5, 0xC3, 0xF7);
this.BackgroundStyle = LinearGradientMode.Horizontal;
}
}
#endregion
#region Class WebServiceUrlPropertyDescriptor
internal sealed class WebServiceUrlPropertyDescriptor : DynamicPropertyDescriptor
{
internal WebServiceUrlPropertyDescriptor(IServiceProvider serviceProvider, PropertyDescriptor pd)
: base(serviceProvider, pd)
{
}
public override bool IsReadOnly
{
get
{
return true;
}
}
}
#endregion
internal sealed class WebServicePickerEditor : UITypeEditor
{
private IWindowsFormsEditorService editorService;
public WebServicePickerEditor()
{
}
public override object EditValue(ITypeDescriptorContext typeDescriptorContext, IServiceProvider serviceProvider, object o)
{
object returnVal = o;
this.editorService = (IWindowsFormsEditorService)serviceProvider.GetService(typeof(IWindowsFormsEditorService));
IExtendedUIService extUIService = (IExtendedUIService)serviceProvider.GetService(typeof(IExtendedUIService));
if (editorService != null && extUIService != null)
{
Uri url = null;
Type proxyClass = null;
if (DialogResult.OK == extUIService.AddWebReference(out url, out proxyClass))
{
returnVal = (url != null) ? url.ToString() : string.Empty;
typeDescriptorContext.PropertyDescriptor.SetValue(typeDescriptorContext.Instance, returnVal as string);
}
}
return returnVal;
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext typeDescriptorContext)
{
return UITypeEditorEditStyle.Modal;
}
}
}
| |
// 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 Xunit;
namespace System.Threading.Tasks.Dataflow.Tests
{
public class BatchedJoinBlockTests
{
[Fact]
public void TestCtor()
{
var blocks2 = new[]
{
new BatchedJoinBlock<int, string>(1),
new BatchedJoinBlock<int, string>(2, new GroupingDataflowBlockOptions {
MaxNumberOfGroups = 1 }),
new BatchedJoinBlock<int, string>(3, new GroupingDataflowBlockOptions {
MaxMessagesPerTask = 1 }),
new BatchedJoinBlock<int, string>(4, new GroupingDataflowBlockOptions {
MaxMessagesPerTask = 1, CancellationToken = new CancellationToken(true), MaxNumberOfGroups = 1 })
};
for (int i = 0; i < blocks2.Length; i++)
{
Assert.Equal(expected: i + 1, actual: blocks2[i].BatchSize);
Assert.Equal(expected: 0, actual: blocks2[i].OutputCount);
Assert.NotNull(blocks2[i].Completion);
}
var blocks3 = new[]
{
new BatchedJoinBlock<int, string, double>(1),
new BatchedJoinBlock<int, string, double>(2, new GroupingDataflowBlockOptions {
MaxNumberOfGroups = 1 }),
new BatchedJoinBlock<int, string, double>(3, new GroupingDataflowBlockOptions {
MaxMessagesPerTask = 1 }),
new BatchedJoinBlock<int, string, double>(4, new GroupingDataflowBlockOptions {
MaxMessagesPerTask = 1, CancellationToken = new CancellationToken(true), MaxNumberOfGroups = 1 })
};
for (int i = 0; i < blocks3.Length; i++)
{
Assert.Equal(expected: i + 1, actual: blocks2[i].BatchSize);
Assert.Equal(expected: 0, actual: blocks2[i].OutputCount);
Assert.NotNull(blocks2[i].Completion);
}
}
[Fact]
public void TestArgumentExceptions()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new BatchedJoinBlock<int, string>(-1));
Assert.Throws<ArgumentNullException>(() => new BatchedJoinBlock<int, string>(2, null));
Assert.Throws<ArgumentException>(() => new BatchedJoinBlock<int, string>(2, new GroupingDataflowBlockOptions { Greedy = false }));
Assert.Throws<ArgumentException>(() => new BatchedJoinBlock<int, string>(2, new GroupingDataflowBlockOptions { BoundedCapacity = 2 }));
Assert.Throws<ArgumentNullException>(() => ((IDataflowBlock)new BatchedJoinBlock<int, string>(2)).Fault(null));
Assert.Throws<ArgumentNullException>(() => new BatchedJoinBlock<int, string>(2).Target1.Fault(null));
Assert.Throws<ArgumentOutOfRangeException>(() => new BatchedJoinBlock<int, string, double>(-1));
Assert.Throws<ArgumentNullException>(() => new BatchedJoinBlock<int, string, double>(2, null));
Assert.Throws<ArgumentException>(() => new BatchedJoinBlock<int, string, double>(2, new GroupingDataflowBlockOptions { Greedy = false }));
Assert.Throws<ArgumentException>(() => new BatchedJoinBlock<int, string, double>(2, new GroupingDataflowBlockOptions { BoundedCapacity = 2 }));
Assert.Throws<ArgumentNullException>(() => ((IDataflowBlock)new BatchedJoinBlock<int, string, double>(2)).Fault(null));
DataflowTestHelpers.TestArgumentsExceptions(new BatchedJoinBlock<int, string>(1));
DataflowTestHelpers.TestArgumentsExceptions(new BatchedJoinBlock<int, string, double>(1));
}
[Fact]
public void TestToString()
{
DataflowTestHelpers.TestToString(nameFormat =>
nameFormat != null ?
new BatchedJoinBlock<int, string>(2, new GroupingDataflowBlockOptions() { NameFormat = nameFormat }) :
new BatchedJoinBlock<int, string>(2));
DataflowTestHelpers.TestToString(nameFormat =>
nameFormat != null ?
new BatchedJoinBlock<int, string, double>(3, new GroupingDataflowBlockOptions() { NameFormat = nameFormat }) :
new BatchedJoinBlock<int, string, double>(3));
}
[Fact]
public async Task TestCompletionTask()
{
await DataflowTestHelpers.TestCompletionTask(() => new BatchedJoinBlock<int, string>(2));
await DataflowTestHelpers.TestCompletionTask(() => new BatchedJoinBlock<int, string, double>(2));
await Assert.ThrowsAsync<NotSupportedException>(() => new BatchedJoinBlock<int, string>(2).Target1.Completion);
await Assert.ThrowsAsync<NotSupportedException>(() => new BatchedJoinBlock<int, string, double>(2).Target1.Completion);
}
[Fact]
public void TestPostThenReceive2()
{
const int Iters = 10;
var block = new BatchedJoinBlock<int, string>(2);
for (int i = 0; i < Iters; i++)
{
int prevCount = block.OutputCount;
block.Target1.Post(i);
Assert.Equal(expected: prevCount, actual: block.OutputCount);
block.Target2.Post(i.ToString());
if (i % block.BatchSize == 0)
{
Assert.Equal(expected: prevCount + 1, actual: block.OutputCount);
Tuple<IList<int>, IList<string>> msg;
Assert.False(block.TryReceive(f => false, out msg));
Assert.True(block.TryReceive(out msg));
Assert.Equal(expected: 1, actual: msg.Item1.Count);
Assert.Equal(expected: 1, actual: msg.Item2.Count);
for (int j = 0; j < msg.Item1.Count; j++)
{
Assert.Equal(msg.Item1[j].ToString(), msg.Item2[j]);
}
}
}
}
[Fact]
public void TestPostThenReceive3()
{
const int Iters = 10;
var block = new BatchedJoinBlock<int, string, int>(3);
for (int i = 0; i < Iters; i++)
{
Tuple<IList<int>, IList<string>, IList<int>> item;
Assert.Equal(expected: 0, actual: block.OutputCount);
block.Target1.Post(i);
Assert.Equal(expected: 0, actual: block.OutputCount);
Assert.False(block.TryReceive(out item));
block.Target2.Post(i.ToString());
Assert.Equal(expected: 0, actual: block.OutputCount);
Assert.False(block.TryReceive(out item));
block.Target3.Post(i);
Assert.Equal(expected: 1, actual: block.OutputCount);
Tuple<IList<int>, IList<string>, IList<int>> msg;
Assert.True(block.TryReceive(out msg));
Assert.Equal(expected: 1, actual: msg.Item1.Count);
Assert.Equal(expected: 1, actual: msg.Item2.Count);
Assert.Equal(expected: 1, actual: msg.Item3.Count);
for (int j = 0; j < msg.Item1.Count; j++)
{
Assert.Equal(msg.Item1[j].ToString(), msg.Item2[j]);
}
}
}
[Fact]
public void TestPostAllThenReceive()
{
const int Iters = 10;
var block = new BatchedJoinBlock<int, int>(2);
for (int i = 0; i < Iters; i++)
{
block.Target1.Post(i);
block.Target2.Post(i);
}
Assert.Equal(expected: Iters, actual: block.OutputCount);
for (int i = 0; i < block.OutputCount; i++)
{
Tuple<IList<int>, IList<int>> msg;
Assert.True(block.TryReceive(out msg));
Assert.Equal(expected: 1, actual: msg.Item1.Count);
Assert.Equal(expected: 1, actual: msg.Item2.Count);
for (int j = 0; j < msg.Item1.Count; j++)
{
Assert.Equal(msg.Item1[j], msg.Item2[j]);
}
}
}
[Fact]
public void TestUnbalanced2()
{
const int Iters = 10, NumBatches = 2;
int batchSize = Iters / NumBatches;
var block = new BatchedJoinBlock<string, int>(batchSize);
for (int i = 0; i < Iters; i++)
{
block.Target2.Post(i);
Assert.Equal(expected: (i + 1) / batchSize, actual: block.OutputCount);
}
IList<Tuple<IList<string>, IList<int>>> items;
Assert.True(block.TryReceiveAll(out items));
Assert.Equal(expected: NumBatches, actual: items.Count);
for (int i = 0; i < items.Count; i++)
{
var item = items[i];
Assert.NotNull(item.Item1);
Assert.NotNull(item.Item2);
Assert.Equal(expected: batchSize, actual: item.Item2.Count);
for (int j = 0; j < batchSize; j++)
{
Assert.Equal(expected: (i * batchSize) + j, actual: item.Item2[j]);
}
}
Assert.False(block.TryReceiveAll(out items));
}
[Fact]
public void TestUnbalanced3()
{
const int Iters = 10, NumBatches = 2;
int batchSize = Iters / NumBatches;
Tuple<IList<int>, IList<string>, IList<double>> item;
var block = new BatchedJoinBlock<int, string, double>(batchSize);
for (int i = 0; i < Iters; i++)
{
block.Target1.Post(i);
Assert.Equal(expected: (i + 1) / batchSize, actual: block.OutputCount);
}
for (int i = 0; i < NumBatches; i++)
{
Assert.True(block.TryReceive(out item));
Assert.NotNull(item.Item1);
Assert.NotNull(item.Item2);
Assert.NotNull(item.Item3);
Assert.Equal(expected: batchSize, actual: item.Item1.Count);
for (int j = 0; j < batchSize; j++)
{
Assert.Equal(expected: (i * batchSize) + j, actual: item.Item1[j]);
}
}
Assert.False(block.TryReceive(out item));
}
[Fact]
public void TestCompletion()
{
const int Iters = 10;
var block = new BatchedJoinBlock<int, int>(2);
for (int i = 0; i < Iters; i++)
{
block.Target1.Post(i);
block.Target2.Post(i);
}
Assert.Equal(expected: Iters, actual: block.OutputCount);
block.Target1.Post(10);
block.Target1.Complete();
block.Target2.Complete();
Assert.Equal(expected: Iters + 1, actual: block.OutputCount);
Tuple<IList<int>, IList<int>> item;
for (int i = 0; i < Iters; i++)
{
Assert.True(block.TryReceive(out item));
Assert.Equal(expected: 1, actual: item.Item1.Count);
Assert.Equal(expected: 1, actual: item.Item2.Count);
}
Assert.True(block.TryReceive(out item));
Assert.Equal(expected: 1, actual: item.Item1.Count);
Assert.Equal(expected: 0, actual: item.Item2.Count);
}
[Fact]
public async Task TestPrecanceled2()
{
var b = new BatchedJoinBlock<int, int>(42,
new GroupingDataflowBlockOptions { CancellationToken = new CancellationToken(canceled: true), MaxNumberOfGroups = 1 });
Tuple<IList<int>, IList<int>> ignoredValue;
IList<Tuple<IList<int>, IList<int>>> ignoredValues;
Assert.NotNull(b.LinkTo(new ActionBlock<Tuple<IList<int>, IList<int>>>(delegate { })));
Assert.False(b.Target1.Post(42));
Assert.False(b.Target2.Post(42));
foreach (var target in new[] { b.Target1, b.Target2 })
{
var t = target.SendAsync(42);
Assert.True(t.IsCompleted);
Assert.False(t.Result);
}
Assert.False(b.TryReceiveAll(out ignoredValues));
Assert.False(b.TryReceive(out ignoredValue));
Assert.Equal(expected: 0, actual: b.OutputCount);
Assert.NotNull(b.Completion);
b.Target1.Complete();
b.Target2.Complete();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => b.Completion);
}
[Fact]
public async Task TestPrecanceled3()
{
var b = new BatchedJoinBlock<int, int, int>(42,
new GroupingDataflowBlockOptions { CancellationToken = new CancellationToken(canceled: true), MaxNumberOfGroups = 1 });
Tuple<IList<int>, IList<int>, IList<int>> ignoredValue;
IList<Tuple<IList<int>, IList<int>, IList<int>>> ignoredValues;
Assert.NotNull(b.LinkTo(new ActionBlock<Tuple<IList<int>, IList<int>, IList<int>>>(delegate { })));
Assert.False(b.Target1.Post(42));
Assert.False(b.Target2.Post(42));
foreach (var target in new[] { b.Target1, b.Target2 })
{
var t = target.SendAsync(42);
Assert.True(t.IsCompleted);
Assert.False(t.Result);
}
Assert.False(b.TryReceiveAll(out ignoredValues));
Assert.False(b.TryReceive(out ignoredValue));
Assert.Equal(expected: 0, actual: b.OutputCount);
Assert.NotNull(b.Completion);
b.Target1.Complete();
b.Target2.Complete();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => b.Completion);
}
[Fact]
public async Task TestCompletesThroughTargets()
{
var b2 = new BatchedJoinBlock<int, int>(99);
b2.Target1.Post(1);
b2.Target1.Complete();
b2.Target2.Complete();
Tuple<IList<int>, IList<int>> item2 = await b2.ReceiveAsync();
Assert.Equal(expected: 1, actual: item2.Item1.Count);
Assert.Equal(expected: 0, actual: item2.Item2.Count);
await b2.Completion;
var b3 = new BatchedJoinBlock<int, int, int>(99);
b3.Target2.Post(1);
b3.Target3.Complete();
b3.Target2.Complete();
b3.Target1.Complete();
Tuple<IList<int>, IList<int>, IList<int>> item3 = await b3.ReceiveAsync();
Assert.Equal(expected: 0, actual: item3.Item1.Count);
Assert.Equal(expected: 1, actual: item3.Item2.Count);
Assert.Equal(expected: 0, actual: item3.Item3.Count);
await b3.Completion;
}
[Fact]
public async Task TestFaultsThroughTargets()
{
var b2 = new BatchedJoinBlock<int, int>(99);
b2.Target1.Post(1);
((IDataflowBlock)b2.Target1).Fault(new FormatException());
await Assert.ThrowsAsync<FormatException>(() => b2.Completion);
var b3 = new BatchedJoinBlock<int, int, int>(99);
b3.Target3.Post(1);
((IDataflowBlock)b3.Target2).Fault(new FormatException());
await Assert.ThrowsAsync<FormatException>(() => b3.Completion);
}
[Fact]
public async Task TestCompletesThroughBlock()
{
var b2 = new BatchedJoinBlock<int, int>(99);
b2.Target1.Post(1);
b2.Complete();
Tuple<IList<int>, IList<int>> item2 = await b2.ReceiveAsync();
Assert.Equal(expected: 1, actual: item2.Item1.Count);
Assert.Equal(expected: 0, actual: item2.Item2.Count);
await b2.Completion;
var b3 = new BatchedJoinBlock<int, int, int>(99);
b3.Target3.Post(1);
b3.Complete();
Tuple<IList<int>, IList<int>, IList<int>> item3 = await b3.ReceiveAsync();
Assert.Equal(expected: 0, actual: item3.Item1.Count);
Assert.Equal(expected: 0, actual: item3.Item2.Count);
Assert.Equal(expected: 1, actual: item3.Item3.Count);
await b3.Completion;
}
[Fact]
public async Task TestReserveReleaseConsume()
{
var b2 = new BatchedJoinBlock<int, int>(2);
b2.Target1.Post(1);
b2.Target2.Post(2);
await DataflowTestHelpers.TestReserveAndRelease(b2);
b2 = new BatchedJoinBlock<int, int>(2);
b2.Target1.Post(1);
b2.Target2.Post(2);
await DataflowTestHelpers.TestReserveAndConsume(b2);
var b3 = new BatchedJoinBlock<int, int, int>(1);
b3.Target2.Post(3);
await DataflowTestHelpers.TestReserveAndRelease(b3);
b3 = new BatchedJoinBlock<int, int, int>(4);
b3.Target3.Post(1);
b3.Target3.Post(2);
b3.Target3.Post(3);
b3.Target2.Post(3);
await DataflowTestHelpers.TestReserveAndConsume(b3);
}
[Fact]
public async Task TestConsumeToAccept()
{
var wob = new WriteOnceBlock<int>(i => i * 2);
wob.Post(1);
await wob.Completion;
var b2 = new BatchedJoinBlock<int, int>(1);
wob.LinkTo(b2.Target2, new DataflowLinkOptions { PropagateCompletion = true });
Tuple<IList<int>, IList<int>> item2 = await b2.ReceiveAsync();
Assert.Equal(expected: 0, actual: item2.Item1.Count);
Assert.Equal(expected: 1, actual: item2.Item2.Count);
b2.Target1.Complete();
var b3 = new BatchedJoinBlock<int, int, int>(1);
wob.LinkTo(b3.Target3, new DataflowLinkOptions { PropagateCompletion = true });
Tuple<IList<int>, IList<int>, IList<int>> item3 = await b3.ReceiveAsync();
Assert.Equal(expected: 0, actual: item3.Item1.Count);
Assert.Equal(expected: 0, actual: item3.Item2.Count);
Assert.Equal(expected: 1, actual: item3.Item3.Count);
b3.Target1.Complete();
b3.Target2.Complete();
await Task.WhenAll(b2.Completion, b3.Completion);
}
[Fact]
public async Task TestOfferMessage2()
{
Func<ITargetBlock<int>> generator = () => {
var b = new BatchedJoinBlock<int, int>(1);
return b.Target1;
};
DataflowTestHelpers.TestOfferMessage_ArgumentValidation(generator());
DataflowTestHelpers.TestOfferMessage_AcceptsDataDirectly(generator());
await DataflowTestHelpers.TestOfferMessage_AcceptsViaLinking(generator());
}
[Fact]
public async Task TestOfferMessage3()
{
Func<ITargetBlock<int>> generator = () => {
var b = new BatchedJoinBlock<int, int, int>(1);
return b.Target1;
};
DataflowTestHelpers.TestOfferMessage_ArgumentValidation(generator());
DataflowTestHelpers.TestOfferMessage_AcceptsDataDirectly(generator());
await DataflowTestHelpers.TestOfferMessage_AcceptsViaLinking(generator());
}
[Fact]
public async Task TestMaxNumberOfGroups()
{
const int MaxGroups = 2;
var b2 = new BatchedJoinBlock<int, int>(1, new GroupingDataflowBlockOptions { MaxNumberOfGroups = MaxGroups });
b2.Target1.PostRange(0, MaxGroups);
Assert.False(b2.Target1.Post(42));
Assert.False(b2.Target2.Post(42));
IList<Tuple<IList<int>, IList<int>>> items2;
Assert.True(b2.TryReceiveAll(out items2));
Assert.Equal(expected: MaxGroups, actual: items2.Count);
await b2.Completion;
var b3 = new BatchedJoinBlock<int, int, int>(1, new GroupingDataflowBlockOptions { MaxNumberOfGroups = MaxGroups });
b3.Target1.PostRange(0, MaxGroups);
Assert.False(b3.Target1.Post(42));
Assert.False(b3.Target2.Post(42));
Assert.False(b3.Target3.Post(42));
IList<Tuple<IList<int>, IList<int>, IList<int>>> items3;
Assert.True(b3.TryReceiveAll(out items3));
Assert.Equal(expected: MaxGroups, actual: items3.Count);
await b3.Completion;
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Site.MasterPages
{
using System;
using System.Web.UI.WebControls;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Portal;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Adxstudio.Xrm;
using Adxstudio.Xrm.Account;
using Adxstudio.Xrm.AspNet.Cms;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Web;
using Adxstudio.Xrm.Web.Mvc;
public class PortalMasterPage : PortalViewMasterPage
{
private readonly Lazy<OrganizationServiceContext> _xrmContext;
private readonly Lazy<string> _languageCode;
public PortalMasterPage()
{
_xrmContext = new Lazy<OrganizationServiceContext>(() => CreateXrmServiceContext());
_languageCode = new Lazy<string>(GetPortalLanguageCode);
}
/// <summary>
/// Portal language code of the current request.
/// </summary>
public string PortalLanguageCode
{
get { return _languageCode.Value; }
}
/// <summary>
/// CRM language code of the current request. ex: if the PortalLanguageCode is "en-CA", then the CrmLanguageCode would be "en-US".
/// </summary>
public string CrmLanguageCode
{
get
{
if (string.IsNullOrEmpty(_languageCode.Value))
{
return string.Empty;
}
string crmLanguageCode;
if (ContextLanguageInfo.ResolveCultureCode(_languageCode.Value, out crmLanguageCode))
{
return crmLanguageCode;
}
return _languageCode.Value;
}
}
/// <summary>
/// A general use <see cref="OrganizationServiceContext"/> for managing entities on the page.
/// </summary>
public OrganizationServiceContext XrmContext
{
get { return _xrmContext.Value; }
}
/// <summary>
/// The current <see cref="IPortalContext"/> instance.
/// </summary>
public IPortalContext Portal
{
get { return PortalCrmConfigurationManager.CreatePortalContext(PortalName); }
}
/// <summary>
/// The <see cref="OrganizationServiceContext"/> that is associated with the current <see cref="IPortalContext"/> and used to manage its entities.
/// </summary>
/// <remarks>
/// This <see cref="OrganizationServiceContext"/> instance should be used when querying against the Website, User, or Entity properties.
/// </remarks>
public OrganizationServiceContext ServiceContext
{
get { return Portal.ServiceContext; }
}
/// <summary>
/// The current adx_website <see cref="Entity"/>.
/// </summary>
public Entity Website
{
get { return Portal.Website; }
}
/// <summary>
/// The current contact <see cref="Entity"/>.
/// </summary>
public Entity Contact
{
get { return Portal.User; }
}
/// <summary>
/// The <see cref="Entity"/> representing the current page.
/// </summary>
public Entity Entity
{
get { return Portal.Entity; }
}
/// <summary>
/// A general use <see cref="IOrganizationService"/> .
/// </summary>
public IOrganizationService PortalOrganizationService
{
get { return Context.GetOrganizationService(); }
}
public void InjectClientsideApmAgent()
{
//right now the only Apm system is AppDynamics
//in the future this might be AppInsights or another engine
#region AppDynamicsAgent
#if !SelfHosted
try
{
//this code is here to inject the app dynamics js agent code
//it only does anything if:
// 1. the server side agent is turned on AND
// 2. the injection feature is turned on (which is a setting on the app dynamics side)
// in production this might not even be used, just a hook to allow us to use it if we want
var appdynamicsJsHeader = "AppDynamics_JS_HEADER";
var contextItems = Context.Items;
if (contextItems.Contains(appdynamicsJsHeader))
{
Response.Write(contextItems[appdynamicsJsHeader]);
}
}
catch (Exception e)
{
//unlikely that the above code would ever throw an error under any normal situation
//whether it works or not, this should never break the app, so just want to catch all the exceptions
ADXTrace.Instance.TraceError(TraceCategory.Monitoring, $"Unable to inject the AppDynamics Clientside Agent. Exception: {e}");
}
#endif
#endregion
}
public bool ForceRegistration
{
get
{
var siteSetting = this.Context.GetSiteSetting("Profile/ForceSignUp") ?? "false";
bool value;
return bool.TryParse(siteSetting, out value) && value;
}
}
protected override void OnInit(EventArgs args)
{
base.OnInit(args);
if (!ForceRegistration)
{
return;
}
if (!Request.IsAuthenticated || Contact == null)
{
return;
}
var profilePage = ServiceContext.GetPageBySiteMarkerName(Website, "Profile");
if (profilePage == null || Entity.ToEntityReference().Equals(profilePage.ToEntityReference()))
{
return;
}
var profilePath = ServiceContext.GetUrl(profilePage);
var returnUrl = System.Web.Security.AntiXss.AntiXssEncoder.UrlEncode(Request.Url.PathAndQuery);
var profileUrl = "{0}{1}{2}={3}".FormatWith(profilePath, profilePath.Contains("?") ? "&" : "?", "ReturnURL", returnUrl);
if (!ServiceContext.ValidateProfileSuccessfullySaved(Contact))
{
Context.RedirectAndEndResponse(profileUrl);
}
}
protected OrganizationServiceContext CreateXrmServiceContext(MergeOption? mergeOption = null)
{
var context = PortalCrmConfigurationManager.CreateServiceContext(PortalName);
if (context != null && mergeOption != null) context.MergeOption = mergeOption.Value;
return context;
}
protected virtual void LinqDataSourceSelecting(object sender, LinqDataSourceSelectEventArgs e)
{
e.Arguments.RetrieveTotalRowCount = false;
}
private string GetPortalLanguageCode()
{
var contextLanguage = this.Context.GetContextLanguageInfo();
return contextLanguage.ContextLanguage != null ? contextLanguage.ContextLanguage.Code : String.Empty;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
/*
================================================================================
The DOFFx API
================================================================================
Note that DOFFx requires ServerConnection to exist. It operates on
ServerConnection.getCameraObject().
DOFFx::setFocalDist( %dist )
@summary
This method is for manually controlling the focus distance. It will have no
effect if auto focus is currently enabled. Makes use of the parameters set by
setFocusParams.
@param dist
float distance in meters
--------------------------------------------------------------------------------
DOFFx::setAutoFocus( %enabled )
@summary
This method sets auto focus enabled or disabled. Makes use of the parameters set
by setFocusParams. When auto focus is enabled it determines the focal depth
by performing a raycast at the screen-center.
@param enabled
bool
--------------------------------------------------------------------------------
DOFFx::setFocusParams( %nearBlurMax, %farBlurMax, %minRange, %maxRange, %nearSlope, %farSlope )
Set the parameters that control how the near and far equations are calculated
from the focal distance. If you are not using auto focus you will need to call
setFocusParams PRIOR to calling setFocalDist.
@param nearBlurMax
float between 0.0 and 1.0
The max allowed value of near blur.
@param farBlurMax
float between 0.0 and 1.0
The max allowed value of far blur.
@param minRange/maxRange
float in meters
The distance range around the focal distance that remains in focus is a lerp
between the min/maxRange using the normalized focal distance as the parameter.
The point is to allow the focal range to expand as you focus farther away since this is
visually appealing.
Note: since min/maxRange are lerped by the "normalized" focal distance it is
dependant on the visible distance set in your level.
@param nearSlope
float less than zero
The slope of the near equation. A small number causes bluriness to increase gradually
at distances closer than the focal distance. A large number causes bluriness to
increase quickly.
@param farSlope
float greater than zero
The slope of the far equation. A small number causes bluriness to increase gradually
at distances farther than the focal distance. A large number causes bluriness to
increase quickly.
Note: To rephrase, the min/maxRange parameters control how much area around the
focal distance is completely in focus where the near/farSlope parameters control
how quickly or slowly bluriness increases at distances outside of that range.
================================================================================
Examples
================================================================================
Example1: Turn on DOF while zoomed in with a weapon.
NOTE: These are not real callbacks! Hook these up to your code where appropriate!
function onSniperZoom()
{
// Parameterize how you want DOF to look.
DOFFx.setFocusParams( 0.3, 0.3, 50, 500, -5, 5 );
// Turn on auto focus
DOFFx.setAutoFocus( true );
// Turn on the PostEffect
DOFFx.enable();
}
function onSniperUnzoom()
{
// Turn off the PostEffect
DOFFx.disable();
}
Example2: Manually control DOF with the mouse wheel.
// Somewhere on startup...
// Parameterize how you want DOF to look.
DOFFx.setFocusParams( 0.3, 0.3, 50, 500, -5, 5 );
// Turn off auto focus
DOFFx.setAutoFocus( false );
// Turn on the PostEffect
DOFFx.enable();
NOTE: These are not real callbacks! Hook these up to your code where appropriate!
function onMouseWheelUp()
{
// Since setFocalDist is really just a wrapper to assign to the focalDist
// dynamic field we can shortcut and increment it directly.
DOFFx.focalDist += 8;
}
function onMouseWheelDown()
{
DOFFx.focalDist -= 8;
}
*/
/// This method is for manually controlling the focal distance. It will have no
/// effect if auto focus is currently enabled. Makes use of the parameters set by
/// setFocusParams.
function DOFFx::setFocalDist( %this, %dist )
{
%this.focalDist = %dist;
}
/// This method sets auto focus enabled or disabled. Makes use of the parameters set
/// by setFocusParams. When auto focus is enabled it determine the focal depth
/// by performing a raycast at the screen-center.
function DOFFx::setAutoFocus( %this, %enabled )
{
%this.autoFocusEnabled = %enabled;
}
/// Set the parameters that control how the near and far equations are calculated
/// from the focal distance. If you are not using auto focus you will need to call
/// setFocusParams PRIOR to calling setFocalDist.
function DOFFx::setFocusParams( %this, %nearBlurMax, %farBlurMax, %minRange, %maxRange, %nearSlope, %farSlope )
{
%this.nearBlurMax = %nearBlurMax;
%this.farBlurMax = %farBlurMax;
%this.minRange = %minRange;
%this.maxRange = %maxRange;
%this.nearSlope = %nearSlope;
%this.farSlope = %farSlope;
}
/*
More information...
This DOF technique is based on this paper:
http://http.developer.nvidia.com/GPUGems3/gpugems3_ch28.html
================================================================================
1. Overview of how we represent "Depth of Field"
================================================================================
DOF is expressed as an amount of bluriness per pixel according to its depth.
We represented this by a piecewise linear curve depicted below.
Note: we also refer to "bluriness" as CoC ( circle of confusion ) which is the term
used in the basis paper and in photography.
X-axis (depth)
x = 0.0----------------------------------------------x = 1.0
Y-axis (bluriness)
y = 1.0
|
| ____(x1,y1) (x4,y4)____
| (ns,nb)\ <--Line1 line2---> /(fe,fb)
| \ /
| \(x2,y2) (x3,y3)/
| (ne,0)------(fs,0)
y = 0.0
I have labeled the "corners" of this graph with (Xn,Yn) to illustrate that
this is in fact a collection of line segments where the x/y of each point
corresponds to the key below.
key:
ns - (n)ear blur (s)tart distance
nb - (n)ear (b)lur amount (max value)
ne - (n)ear blur (e)nd distance
fs - (f)ar blur (s)tart distance
fe - (f)ar blur (e)nd distance
fb - (f)ar (b)lur amount (max value)
Of greatest importance in this graph is Line1 and Line2. Where...
L1 { (x1,y1), (x2,y2) }
L2 { (x3,y3), (x4,y4) }
Line one represents the amount of "near" blur given a pixels depth and line two
represents the amount of "far" blur at that depth.
Both these equations are evaluated for each pixel and then the larger of the two
is kept. Also the output blur (for each equation) is clamped between 0 and its
maximum allowable value.
Therefore, to specify a DOF "qualify" you need to specify the near-blur-line,
far-blur-line, and maximum near and far blur value.
================================================================================
2. Abstracting a "focal depth"
================================================================================
Although the shader(s) work in terms of a near and far equation it is more
useful to express DOF as an adjustable focal depth and derive the other parameters
"under the hood".
Given a maximum near/far blur amount and a near/far slope we can calculate the
near/far equations for any focal depth. We extend this to also support a range
of depth around the focal depth that is also in focus and for that range to
shrink or grow as the focal depth moves closer or farther.
Keep in mind this is only one implementation and depending on the effect you
desire you may which to express the relationship between focal depth and
the shader paramaters different.
*/
//-----------------------------------------------------------------------------
// GFXStateBlockData / ShaderData
//-----------------------------------------------------------------------------
singleton GFXStateBlockData( PFX_DefaultDOFStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerClampPoint;
};
singleton GFXStateBlockData( PFX_DOFCalcCoCStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
};
singleton GFXStateBlockData( PFX_DOFDownSampleStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampPoint;
};
singleton GFXStateBlockData( PFX_DOFBlurStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
};
singleton GFXStateBlockData( PFX_DOFFinalStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
samplerStates[2] = SamplerClampLinear;
samplerStates[3] = SamplerClampPoint;
blendDefined = true;
blendEnable = true;
blendDest = GFXBlendInvSrcAlpha;
blendSrc = GFXBlendOne;
};
singleton ShaderData( PFX_DOFDownSampleShader )
{
DXVertexShaderFile = "shaders/common/postFx/dof/DOF_DownSample_V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/dof/DOF_DownSample_P.hlsl";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFBlurYShader )
{
DXVertexShaderFile = "shaders/common/postFx/dof/DOF_Gausian_V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/dof/DOF_Gausian_P.hlsl";
pixVersion = 2.0;
defines = "BLUR_DIR=float2(0.0,1.0)";
};
singleton ShaderData( PFX_DOFBlurXShader : PFX_DOFBlurYShader )
{
defines = "BLUR_DIR=float2(1.0,0.0)";
};
singleton ShaderData( PFX_DOFCalcCoCShader )
{
DXVertexShaderFile = "shaders/common/postFx/dof/DOF_CalcCoC_V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/dof/DOF_CalcCoC_P.hlsl";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFSmallBlurShader )
{
DXVertexShaderFile = "shaders/common/postFx/dof/DOF_SmallBlur_V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/dof/DOF_SmallBlur_P.hlsl";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFFinalShader )
{
DXVertexShaderFile = "shaders/common/postFx/dof/DOF_Final_V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/dof/DOF_Final_P.hlsl";
pixVersion = 3.0;
};
//-----------------------------------------------------------------------------
// PostEffects
//-----------------------------------------------------------------------------
function DOFFx::onAdd( %this )
{
// The weighted distribution of CoC value to the three blur textures
// in the order small, medium, large. Most likely you will not need to
// change this value.
%this.setLerpDist( 0.2, 0.3, 0.5 );
// Fill out some default values but DOF really should not be turned on
// without actually specifying your own parameters!
%this.autoFocusEnabled = false;
%this.focalDist = 0.0;
%this.nearBlurMax = 0.5;
%this.farBlurMax = 0.5;
%this.minRange = 50;
%this.maxRange = 500;
%this.nearSlope = -5.0;
%this.farSlope = 5.0;
}
function DOFFx::setLerpDist( %this, %d0, %d1, %d2 )
{
%this.lerpScale = -1.0 / %d0 SPC -1.0 / %d1 SPC -1.0 / %d2 SPC 1.0 / %d2;
%this.lerpBias = 1.0 SPC ( 1.0 - %d2 ) / %d1 SPC 1.0 / %d2 SPC ( %d2 - 1.0 ) / %d2;
}
singleton PostEffect( DOFFx )
{
renderTime = "PFXAfterBin";
renderBin = "GlowBin";
renderPriority = 0.1;
shader = PFX_DOFDownSampleShader;
stateBlock = PFX_DOFDownSampleStateBlock;
texture[0] = "$backBuffer";
texture[1] = "#prepass";
target = "#shrunk";
targetScale = "0.25 0.25";
isEnabled = false;
singleton PostEffect()
{
shader = PFX_DOFBlurYShader;
stateBlock = PFX_DOFBlurStateBlock;
texture[0] = "#shrunk";
target = "$outTex";
};
singleton PostEffect()
{
shader = PFX_DOFBlurXShader;
stateBlock = PFX_DOFBlurStateBlock;
texture[0] = "$inTex";
target = "#largeBlur";
};
singleton PostEffect()
{
shader = PFX_DOFCalcCoCShader;
stateBlock = PFX_DOFCalcCoCStateBlock;
texture[0] = "#shrunk";
texture[1] = "#largeBlur";
target = "$outTex";
};
singleton PostEffect()
{
shader = PFX_DOFSmallBlurShader;
stateBlock = PFX_DefaultDOFStateBlock;
texture[0] = "$inTex";
target = "$outTex";
};
singleton PostEffect()
{
shader = PFX_DOFFinalShader;
stateBlock = PFX_DOFFinalStateBlock;
texture[0] = "$backBuffer";
texture[1] = "$inTex";
texture[2] = "#largeBlur";
texture[3] = "#prepass";
target = "$backBuffer";
};
};
//-----------------------------------------------------------------------------
// Scripts
//-----------------------------------------------------------------------------
function DOFFx::setShaderConsts( %this )
{
if ( %this.autoFocusEnabled )
%this.autoFocus();
%fd = %this.focalDist / $Param::FarDist;
%range = mLerp( %this.minRange, %this.maxRange, %fd ) / $Param::FarDist * 0.5;
// We work in "depth" space rather than real-world units for the
// rest of this method...
// Given the focal distance and the range around it we want in focus
// we can determine the near-end-distance and far-start-distance
%ned = getMax( %fd - %range, 0.0 );
%fsd = getMin( %fd + %range, 1.0 );
// near slope
%nsl = %this.nearSlope;
// Given slope of near blur equation and the near end dist and amount (x2,y2)
// solve for the y-intercept
// y = mx + b
// so...
// y - mx = b
%b = 0.0 - %nsl * %ned;
%eqNear = %nsl SPC %b SPC 0.0;
// Do the same for the far blur equation...
%fsl = %this.farSlope;
%b = 0.0 - %fsl * %fsd;
%eqFar = %fsl SPC %b SPC 1.0;
%this.setShaderConst( "$dofEqWorld", %eqNear );
DOFFinalPFX.setShaderConst( "$dofEqFar", %eqFar );
%this.setShaderConst( "$maxWorldCoC", %this.nearBlurMax );
DOFFinalPFX.setShaderConst( "$maxFarCoC", %this.farBlurMax );
DOFFinalPFX.setShaderConst( "$dofLerpScale", %this.lerpScale );
DOFFinalPFX.setShaderConst( "$dofLerpBias", %this.lerpBias );
}
function DOFFx::autoFocus( %this )
{
if ( !isObject( ServerConnection ) ||
!isObject( ServerConnection.getCameraObject() ) )
{
return;
}
%mask = $TypeMasks::StaticObjectType | $TypeMasks::TerrainObjectType;
%control = ServerConnection.getCameraObject();
%fvec = %control.getEyeVector();
%start = %control.getEyePoint();
%end = VectorAdd( %start, VectorScale( %fvec, $Param::FarDist ) );
// Use the client container for this ray cast.
%result = containerRayCast( %start, %end, %mask, %control, true );
%hitPos = getWords( %result, 1, 3 );
if ( %hitPos $= "" )
%focDist = $Param::FarDist;
else
%focDist = VectorDist( %hitPos, %start );
// For debuging
//$DOF::debug_dist = %focDist;
//$DOF::debug_depth = %focDist / $Param::FarDist;
//echo( "F: " @ %focDist SPC "D: " @ %delta );
%this.focalDist = %focDist;
}
// For debugging
/*
function reloadDOF()
{
exec( "./dof.cs" );
DOFFx.reload();
DOFFx.disable();
DOFFx.enable();
}
function dofMetricsCallback()
{
return " | DOF |" @
" Dist: " @ $DOF::debug_dist @
" Depth: " @ $DOF::debug_depth;
}
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.