context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenMetaverse.Messages.Linden;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Assets;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Communications.Capabilities;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Region.Physics.Manager;
using Caps = OpenSim.Framework.Communications.Capabilities.Caps;
using OSDMap = OpenMetaverse.StructuredData.OSDMap;
using OSDArray = OpenMetaverse.StructuredData.OSDArray;
using Amib.Threading;
namespace OpenSim.Region.CoreModules.Capabilities
{
public delegate void UpLoadedAsset(
string assetName, string description, UUID assetID, UUID inventoryItem, UUID parentFolder,
byte[] data, string inventoryType, string assetType, PermissionMask nextOwnerPerm, PermissionMask groupPerm, PermissionMask everyonePerm);
public delegate UpdateItemResponse UpdateItem(UUID itemID, byte[] data);
public delegate UpdateItemResponse UpdateTaskScript(UUID itemID, UUID primID, bool isScriptRunning, byte[] data);
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
public class InventoryCapsModule : INonSharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_Scene;
#region INonSharedRegionModule
public string Name
{
get { return "InventoryCapsModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialize(IConfigSource source)
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
m_Scene = scene;
}
public void RemoveRegion(Scene scene)
{
m_Scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
m_Scene.EventManager.OnDeregisterCaps -= OnDeregisterCaps;
}
public void RegionLoaded(Scene scene)
{
m_Scene.EventManager.OnRegisterCaps += OnRegisterCaps;
m_Scene.EventManager.OnDeregisterCaps += OnDeregisterCaps;
}
public void PostInitialize()
{
}
#endregion
private Dictionary<UUID, InventoryCapsHandler> m_userInventoryHandlers = new Dictionary<UUID, InventoryCapsHandler>();
private void OnRegisterCaps(UUID agentID, Caps caps)
{
InventoryCapsHandler handler = new InventoryCapsHandler(m_Scene, agentID, caps);
handler.RegisterHandlers();
lock (m_userInventoryHandlers)
{
m_userInventoryHandlers[agentID] = handler;
}
}
private void OnDeregisterCaps(UUID agentID, Caps caps)
{
InventoryCapsHandler handler;
lock (m_userInventoryHandlers)
{
if (m_userInventoryHandlers.TryGetValue(agentID, out handler))
{
m_userInventoryHandlers.Remove(agentID);
}
}
if (handler != null)
{
handler.Close();
}
}
protected class InventoryCapsHandler
{
private static readonly string m_newInventory = "0002/";
private static readonly string m_notecardUpdatePath = "0004/";
private static readonly string m_notecardTaskUpdatePath = "0005/";
private static readonly string m_fetchInventoryPath = "0006/";
private UUID m_agentID;
private Caps m_Caps;
private Scene m_Scene;
private IHttpServer m_httpServer;
private string m_regionName;
private IAssetCache m_assetCache;
private InventoryFolderImpl m_libraryFolder = null;
private IInventoryProviderSelector m_inventoryProviderSelector;
private ICheckedInventoryStorage m_checkedStorageProvider;
private SmartThreadPool m_inventoryPool = new SmartThreadPool(60 * 1000, 2, 0);
public InventoryCapsHandler(Scene scene, UUID agentID, Caps caps)
{
m_agentID = agentID;
m_Caps = caps;
m_Scene = scene;
m_httpServer = m_Caps.HttpListener;
m_regionName = m_Scene.RegionInfo.RegionName;
m_assetCache = m_Scene.CommsManager.AssetCache;
m_inventoryProviderSelector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
m_checkedStorageProvider = m_inventoryProviderSelector.GetCheckedProvider(m_Caps.AgentID);
m_libraryFolder = m_Scene.CommsManager.LibraryRoot;
m_inventoryPool.Name = "Inventory Caps " + agentID;
}
/// <summary>
/// Register a bunch of CAPS http service handlers
/// </summary>
public void RegisterHandlers()
{
try
{
IRequestHandler requestHandler;
requestHandler = new RestStreamHandler("POST", m_Caps.CapsBase + m_notecardTaskUpdatePath, ScriptTaskInventory);
m_Caps.RegisterHandler("UpdateScriptTaskInventory", requestHandler);
m_Caps.RegisterHandler("UpdateScriptTask", requestHandler);
requestHandler = new RestStreamHandler("POST", m_Caps.CapsBase + m_notecardUpdatePath, NoteCardAgentInventory);
m_Caps.RegisterHandler("UpdateNotecardAgentInventory", requestHandler);
m_Caps.RegisterHandler("UpdateScriptAgentInventory", requestHandler);
m_Caps.RegisterHandler("UpdateScriptAgent", requestHandler);
requestHandler = new RestStreamHandler("POST", m_Caps.CapsBase + "/NewFileAgentInventory/", NewAgentInventoryRequest);
m_Caps.RegisterHandler("NewFileAgentInventory", requestHandler);
//requestHandler = new RestStreamHandler("POST", m_Caps.CapsBase + "/NewFileAgentInventoryVariablePrice/", NewAgentInventoryRequestVariablePrice);
//m_Caps.RegisterHandler("NewFileAgentInventoryVariablePrice", requestHandler);
requestHandler = new AsyncRequestHandler("POST", m_Caps.CapsBase + m_fetchInventoryPath, AsyncFetchInventoryDescendents);
m_Caps.RegisterHandler("FetchInventoryDescendents", requestHandler);
m_Caps.RegisterHandler("WebFetchInventoryDescendents", requestHandler);
m_Caps.RegisterHandler("FetchInventoryDescendents2", requestHandler);
m_Caps.RegisterHandler("FetchLibDescendents", requestHandler);
m_Caps.RegisterHandler("FetchLibDescendents2", requestHandler);
requestHandler = new RestStreamHandler("POST", "/CAPS/" + UUID.Random(), FetchInventoryRequest);
m_Caps.RegisterHandler("FetchInventory", requestHandler);
m_Caps.RegisterHandler("FetchInventory2", requestHandler);
requestHandler = new RestStreamHandler("POST", "/CAPS/" + UUID.Random(), FetchLibraryRequest);
m_Caps.RegisterHandler("FetchLib", requestHandler);
m_Caps.RegisterHandler("FetchLib2", requestHandler);
requestHandler = new RestStreamHandler("POST", "/CAPS/" + UUID.Random(), CopyInventoryFromNotecard);
m_Caps.RegisterHandler("CopyInventoryFromNotecard", requestHandler);
//requestHandler = new RestStreamHandler("POST", m_Caps.CapsBase + UUID.Random(), CreateInventoryCategory);
//m_Caps.RegisterHandler("CreateInventoryCategory", requestHandler);
}
catch (Exception e)
{
m_log.Error("[CAPS]: " + e.ToString());
}
}
/// <summary>
/// Called when new asset data for an agent inventory item update has been uploaded.
/// </summary>
/// <param name="itemID">Item to update</param>
/// <param name="data">New asset data</param>
/// <returns></returns>
public UpdateItemResponse ItemUpdated(UUID itemID, byte[] data)
{
return (m_Scene.CapsUpdateInventoryItemAsset(m_Caps.AgentID, itemID, data));
}
/// <summary>
/// Handle a request from the client for a Uri to upload a baked texture.
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="httpRequest"></param>
/// <param name="httpResponse"></param>
/// <returns>The upload response if the request is successful, null otherwise.</returns>
public string ScriptTaskInventory(
string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
m_log.Debug("[CAPS]: ScriptTaskInventory Request in region: " + m_regionName);
//m_log.DebugFormat("[CAPS]: request: {0}, path: {1}, param: {2}", request, path, param);
try
{
string capsBase = m_Caps.CapsBase;
string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
LLSDTaskScriptUpdate llsdUpdateRequest = new LLSDTaskScriptUpdate();
LLSDHelpers.DeserializeOSDMap(hash, llsdUpdateRequest);
TaskInventoryScriptUpdater uploader =
new TaskInventoryScriptUpdater(
llsdUpdateRequest.item_id,
llsdUpdateRequest.task_id,
llsdUpdateRequest.is_script_running,
capsBase + uploaderPath,
m_httpServer);
uploader.OnUpLoad += TaskScriptUpdated;
m_httpServer.AddStreamHandler(new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
string uploaderURL = m_httpServer.ServerURI + capsBase + uploaderPath;
LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
uploadResponse.uploader = uploaderURL;
uploadResponse.state = "upload";
// m_log.InfoFormat("[CAPS]: " +"ScriptTaskInventory response: {0}", LLSDHelpers.SerializeLLSDReply(uploadResponse)));
return LLSDHelpers.SerializeLLSDReply(uploadResponse);
}
catch (Exception e)
{
m_log.ErrorFormat("[UPLOAD SCRIPT TASK HANDLER]: {0}{1}", e.Message, e.StackTrace);
}
return null;
}
/// <summary>
/// Called when new asset data for an agent inventory item update has been uploaded.
/// </summary>
/// <param name="itemID">Item to update</param>
/// <param name="primID">Prim containing item to update</param>
/// <param name="isScriptRunning">Signals whether the script to update is currently running</param>
/// <param name="data">New asset data</param>
public UpdateItemResponse TaskScriptUpdated(UUID itemID, UUID primID, bool isScriptRunning, byte[] data)
{
return (m_Scene.CapsUpdateTaskInventoryScriptAsset(m_agentID, itemID, primID, isScriptRunning, data));
}
/// <summary>
/// Called by the notecard update handler. Provides a URL to which the client can upload a new asset.
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
public string NoteCardAgentInventory(string request, string path, string param,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
//m_log.Debug("[CAPS]: NoteCardAgentInventory Request in region: " + m_regionName + "\n" + request);
//m_log.Debug("[CAPS]: NoteCardAgentInventory Request is: " + request);
//OpenMetaverse.StructuredData.OSDMap hash = (OpenMetaverse.StructuredData.OSDMap)OpenMetaverse.StructuredData.LLSDParser.DeserializeBinary(Utils.StringToBytes(request));
Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
LLSDItemUpdate llsdRequest = new LLSDItemUpdate();
LLSDHelpers.DeserializeOSDMap(hash, llsdRequest);
string capsBase = m_Caps.CapsBase;
string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
ItemUpdater uploader =
new ItemUpdater(llsdRequest.item_id, capsBase + uploaderPath, m_httpServer);
uploader.OnUpLoad += ItemUpdated;
m_httpServer.AddStreamHandler(new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
string uploaderURL = m_httpServer.ServerURI + capsBase + uploaderPath;
LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
uploadResponse.uploader = uploaderURL;
uploadResponse.state = "upload";
// m_log.InfoFormat("[CAPS]: " +
// "NoteCardAgentInventory response: {0}",
// LLSDHelpers.SerializeLLSDReply(uploadResponse)));
return LLSDHelpers.SerializeLLSDReply(uploadResponse);
}
/// <summary>
/// Calculate (possibly variable priced) charges.
/// </summary>
/// <param name="asset_type"></param>
/// <param name="map"></param>
/// <param name="charge"></param>
/// <param name="resourceCost"></param>
/// <returns>upload charge to user</returns>
private void CalculateCosts(IMoneyModule mm, string asset_type, OSDMap map, out int uploadCost, out int resourceCost)
{
uploadCost = 0;
resourceCost = 0;
if (mm != null)
{
int upload_price = mm.GetEconomyData().PriceUpload;
if (asset_type == "texture" ||
asset_type == "animation" ||
asset_type == "snapshot" ||
asset_type == "sound")
{
uploadCost = upload_price;
resourceCost = 0;
}
else if (asset_type == "mesh" ||
asset_type == "object")
{
OSDMap meshMap = (OSDMap)map["asset_resources"];
int meshCount = meshMap.ContainsKey("mesh_list") ?
((OSDArray)meshMap["mesh_list"]).Count : 0;
int textureCount = meshMap.ContainsKey("texture_list") ?
((OSDArray)meshMap["texture_list"]).Count : 0;
uploadCost = mm.MeshUploadCharge(meshCount, textureCount);
// simplified resource cost, for now
// see http://wiki.secondlife.com/wiki/Mesh/Mesh_physics for LL implementation
resourceCost = meshCount * upload_price;
}
}
}
private void ApplyMeshCharges(UUID agentID, int meshCount, int textureCount)
{
IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
if (mm != null)
mm.ApplyMeshUploadCharge(agentID, meshCount, textureCount);
}
/// <summary>
/// Handle the NewAgentInventory Upload request.
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="httpRequest"></param>
/// <param name="httpResponse"></param>
/// <returns></returns>
public string NewAgentInventoryRequest(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
OSDMap map = (OSDMap)OSDParser.DeserializeLLSDXml(Utils.StringToBytes(request));
string asset_type = map["asset_type"].AsString();
int uploadCost = 0;
int resourceCost = 0;
// Check to see if mesh uploads are enabled.
if (asset_type == "mesh")
{
ISimulatorFeaturesModule m_SimulatorFeatures = m_Scene.RequestModuleInterface<ISimulatorFeaturesModule>();
if ((m_SimulatorFeatures == null) || (m_SimulatorFeatures.MeshEnabled == false))
{
OSDMap errorResponse = new OSDMap();
errorResponse["uploader"] = String.Empty;
errorResponse["state"] = "error";
return (errorResponse);
}
}
string assetName = map["name"].AsString();
string assetDes = map["description"].AsString();
UUID parentFolder = map["folder_id"].AsUUID();
string inventory_type = map["inventory_type"].AsString();
PermissionMask nextOwnerPerm = PermissionMask.All;
if (map.ContainsKey("next_owner_mask")) nextOwnerPerm = (PermissionMask)map["next_owner_mask"].AsUInteger();
PermissionMask groupPerm = PermissionMask.None;
if (map.ContainsKey("group_mask")) groupPerm = (PermissionMask)map["group_mask"].AsUInteger();
PermissionMask everyonePerm = PermissionMask.None;
if (map.ContainsKey("everyone_mask")) everyonePerm = (PermissionMask)map["everyone_mask"].AsUInteger();
UUID newAsset = UUID.Random();
UUID newInvItem = UUID.Random();
IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
CalculateCosts(mm, asset_type, map, out uploadCost, out resourceCost);
IClientAPI client = m_Scene.SceneContents.GetControllingClient(m_agentID);
if (!mm.AmountCovered(client.AgentId, uploadCost))
{
if (client != null)
client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false);
OSDMap errorResponse = new OSDMap();
errorResponse["uploader"] = String.Empty;
errorResponse["state"] = "error";
return OSDParser.SerializeLLSDXmlString(errorResponse);
}
// Build the response
OSDMap uploadResponse = new OSDMap();
try
{
// Handle mesh asset "data" block
if (asset_type == "mesh")
{
OSDMap meshMap = (OSDMap)map["asset_resources"];
OSDArray mesh_list = (OSDArray)meshMap["mesh_list"];
OSDArray instance_list = (OSDArray)meshMap["instance_list"];
float streaming_cost = 0.0f;
float server_weight = 0.0f;
for (int i = 0; i < mesh_list.Count; i++)
{
OSDMap inner_instance_list = (OSDMap)instance_list[i];
byte[] mesh_data = mesh_list[i].AsBinary();
Vector3 scale = inner_instance_list["scale"].AsVector3();
int vertex_count = 0;
int hibytes = 0;
int midbytes = 0;
int lowbytes = 0;
int lowestbytes = 0;
SceneObjectPartMeshCost.GetMeshVertexCount(mesh_data, out vertex_count);
SceneObjectPartMeshCost.GetMeshLODByteCounts(mesh_data, out hibytes, out midbytes, out lowbytes, out lowestbytes);
server_weight += PrimitiveBaseShape.GetServerWeight(vertex_count);
streaming_cost += PrimitiveBaseShape.GetStreamingCost(scale, hibytes, midbytes, lowbytes, lowestbytes);
}
OSDMap data = new OSDMap();
data["resource_cost"] = Math.Min(server_weight, streaming_cost);
data["model_streaming_cost"] = streaming_cost;
data["simulation_cost"] = server_weight;
data["physics_cost"] = 0.0f;
uploadResponse["data"] = data;
}
}
catch (Exception)
{
OSDMap errorResponse = new OSDMap();
errorResponse["uploader"] = String.Empty;
errorResponse["state"] = "error";
return OSDParser.SerializeLLSDXmlString(errorResponse);
}
string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
string uploaderURL = m_Caps.HttpListener.ServerURI + m_Caps.CapsBase + uploaderPath;
AssetUploader uploader =
new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, inventory_type,
asset_type, nextOwnerPerm, groupPerm, everyonePerm,
m_Caps.CapsBase + uploaderPath, m_Caps.HttpListener);
uploader.OnUpLoad += UploadCompleteHandler;
m_Caps.HttpListener.AddStreamHandler(
new BinaryStreamHandler("POST", m_Caps.CapsBase + uploaderPath, uploader.uploaderCaps));
uploadResponse["uploader"] = uploaderURL;
uploadResponse["state"] = "upload";
uploadResponse["resource_cost"] = resourceCost;
uploadResponse["upload_price"] = uploadCost;
return OSDParser.SerializeLLSDXmlString(uploadResponse);
}
/// <summary>
/// Upload Complete CAP handler. Instantiated from the upload request above.
/// </summary>
/// <param name="assetName"></param>
/// <param name="assetDescription"></param>
/// <param name="assetID"></param>
/// <param name="inventoryItem"></param>
/// <param name="parentFolder"></param>
/// <param name="data"></param>
/// <param name="inventoryType"></param>
/// <param name="assetType"></param>
public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
string assetType, PermissionMask nextOwnerPerm, PermissionMask groupPerm, PermissionMask everyonePerm)
{
sbyte assType = (sbyte)AssetType.Texture;
sbyte inType = (sbyte)InventoryType.Texture;
if (inventoryType == "sound")
{
inType = (sbyte)InventoryType.Sound;
assType = (sbyte)AssetType.Sound;
}
else if (inventoryType == "animation")
{
inType = (sbyte)InventoryType.Animation;
assType = (sbyte)AssetType.Animation;
}
else if (inventoryType == "snapshot")
{
inType = (sbyte)InventoryType.Snapshot;
assType = (sbyte)AssetType.Texture;
}
else if (inventoryType == "wearable")
{
inType = (sbyte)InventoryType.Wearable;
switch (assetType)
{
case "bodypart":
assType = (sbyte)AssetType.Bodypart;
break;
case "clothing":
assType = (sbyte)AssetType.Clothing;
break;
}
}
else if (inventoryType == "object")
{
inType = (sbyte)InventoryType.Object;
assType = (sbyte)AssetType.Object;
data = ObjectUploadComplete(assetName, data);
}
// Bill for upload (mesh is separately billed).
IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
if (mm != null)
{
if (mm.UploadChargeApplies((AssetType)assType))
mm.ApplyUploadCharge(m_Caps.AgentID);
}
AssetBase asset;
asset = new AssetBase();
asset.FullID = assetID;
asset.Type = assType;
asset.Name = assetName;
asset.Data = data;
try
{
if (m_assetCache != null)
{
m_assetCache.AddAsset(asset, AssetRequestInfo.InternalRequest());
}
}
catch (AssetServerException e)
{
m_log.ErrorFormat("[CAPS UPLOAD] Asset write failed: {0}", e);
return;
}
InventoryItemBase item = new InventoryItemBase();
item.Owner = m_Caps.AgentID;
item.CreatorId = m_Caps.AgentID.ToString();
item.ID = inventoryItem;
item.AssetID = asset.FullID;
item.Description = assetDescription;
item.Name = assetName;
item.AssetType = assType;
item.InvType = inType;
item.Folder = parentFolder;
item.CreationDate = Util.UnixTimeSinceEpoch();
item.BasePermissions = (uint)(PermissionMask.All | PermissionMask.Export);
item.CurrentPermissions = (uint)(PermissionMask.All | PermissionMask.Export);
item.GroupPermissions = (uint)groupPerm;
item.EveryOnePermissions = (uint)everyonePerm;
item.NextPermissions = (uint)nextOwnerPerm;
m_Scene.AddInventoryItem(m_Caps.AgentID, item);
IClientAPI client = null;
m_Scene.TryGetClient(m_Caps.AgentID, out client);
if (client != null)
client.SendInventoryItemCreateUpdate(item,0);
}
private byte[] ObjectUploadComplete(string assetName, byte[] data)
{
List<Vector3> positions = new List<Vector3>();
List<Quaternion> rotations = new List<Quaternion>();
OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data);
OSDArray instance_list = (OSDArray)request["instance_list"];
OSDArray mesh_list = (OSDArray)request["mesh_list"];
OSDArray texture_list = (OSDArray)request["texture_list"];
SceneObjectGroup grp = null;
InventoryFolderBase textureFolder =
m_checkedStorageProvider.FindFolderForType(m_Caps.AgentID, AssetType.Texture);
ScenePresence avatar;
IClientAPI remoteClient = null;
if (m_Scene.TryGetAvatar(m_Caps.AgentID, out avatar))
remoteClient = avatar.ControllingClient;
List<UUID> textures = new List<UUID>();
for (int i = 0; i < texture_list.Count; i++)
{
AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, String.Empty);
textureAsset.Data = texture_list[i].AsBinary();
try
{
m_assetCache.AddAsset(textureAsset, AssetRequestInfo.GenericNetRequest());
}
catch (AssetServerException)
{
if (remoteClient != null) remoteClient.SendAgentAlertMessage("Unable to upload asset. Please try again later.", false);
throw;
}
textures.Add(textureAsset.FullID);
if (textureFolder == null)
continue;
InventoryItemBase item =
new InventoryItemBase(UUID.Random(), m_Caps.AgentID)
{
AssetType = (int)AssetType.Texture,
AssetID = textureAsset.FullID,
CreatorId = m_Caps.AgentID.ToString(),
CreationDate = Util.UnixTimeSinceEpoch(),
Folder = textureFolder.ID,
InvType = (int)InventoryType.Texture,
Name = assetName + " - " + i.ToString(),
BasePermissions = (uint)(PermissionMask.All | PermissionMask.Export),
CurrentPermissions = (uint)(PermissionMask.All | PermissionMask.Export),
GroupPermissions = (uint)PermissionMask.None,
EveryOnePermissions = (uint)PermissionMask.None,
NextPermissions = (uint)PermissionMask.All
};
m_Scene.AddInventoryItem(m_Caps.AgentID, item);
if (remoteClient != null)
remoteClient.SendBulkUpdateInventory(item);
}
for (int i = 0; i < mesh_list.Count; i++)
{
PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();
Primitive.TextureEntry textureEntry
= new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
OSDMap inner_instance_list = (OSDMap)instance_list[i];
byte[] mesh_data = mesh_list[i].AsBinary();
OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
for (uint face = 0; face < face_list.Count; face++)
{
OSDMap faceMap = (OSDMap)face_list[(int)face];
Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
if (faceMap.ContainsKey("fullbright"))
f.Fullbright = faceMap["fullbright"].AsBoolean();
if (faceMap.ContainsKey("diffuse_color"))
f.RGBA = faceMap["diffuse_color"].AsColor4();
int textureNum = faceMap["image"].AsInteger();
float imagerot = faceMap["imagerot"].AsInteger();
float offsets = (float)faceMap["offsets"].AsReal();
float offsett = (float)faceMap["offsett"].AsReal();
float scales = (float)faceMap["scales"].AsReal();
float scalet = (float)faceMap["scalet"].AsReal();
if (imagerot != 0)
f.Rotation = imagerot;
if (offsets != 0)
f.OffsetU = offsets;
if (offsett != 0)
f.OffsetV = offsett;
if (scales != 0)
f.RepeatU = scales;
if (scalet != 0)
f.RepeatV = scalet;
if (textures.Count > textureNum)
f.TextureID = textures[textureNum];
else
f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;
textureEntry.FaceTextures[face] = f;
}
pbs.Textures = textureEntry;
AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, String.Empty);
meshAsset.Data = mesh_data;
try
{
m_assetCache.AddAsset(meshAsset, AssetRequestInfo.GenericNetRequest());
}
catch (AssetServerException)
{
if (remoteClient != null) remoteClient.SendAgentAlertMessage("Unable to upload asset. Please try again later.", false);
throw;
}
pbs.SculptEntry = true;
pbs.SculptType = (byte)SculptType.Mesh;
pbs.SculptTexture = meshAsset.FullID;
pbs.SculptData = mesh_data;
pbs.Scale = inner_instance_list["scale"].AsVector3();
int vertex_count = 0;
int hibytes = 0;
int midbytes = 0;
int lowbytes = 0;
int lowestbytes = 0;
SceneObjectPartMeshCost.GetMeshVertexCount(mesh_data, out vertex_count);
SceneObjectPartMeshCost.GetMeshLODByteCounts(mesh_data, out hibytes, out midbytes, out lowbytes, out lowestbytes);
pbs.VertexCount = vertex_count;
pbs.HighLODBytes = hibytes;
pbs.MidLODBytes = midbytes;
pbs.LowLODBytes = lowbytes;
pbs.LowestLODBytes = lowestbytes;
Vector3 position = inner_instance_list["position"].AsVector3();
Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();
UUID owner_id = m_Caps.AgentID;
//m_log.DebugFormat("[MESH] Meshing high_lod returned vertex count of {0} at index {1}", vertex_count, i);
SceneObjectPart prim = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero, false);
prim.Name = assetName;
prim.Description = String.Empty;
rotations.Add(rotation);
positions.Add(position);
prim.UUID = UUID.Random();
prim.CreatorID = owner_id;
prim.OwnerID = owner_id;
prim.GroupID = UUID.Zero;
prim.LastOwnerID = prim.OwnerID;
prim.CreationDate = Util.UnixTimeSinceEpoch();
prim.ServerWeight = pbs.GetServerWeight();
prim.StreamingCost = pbs.GetStreamingCost();
if (grp == null)
grp = new SceneObjectGroup(prim);
else
grp.AddPart(prim);
}
Vector3 rootPos = positions[0];
// Fix first link number
if (mesh_list.Count > 1)
{
Quaternion rootRotConj = Quaternion.Conjugate(rotations[0]);
Quaternion tmprot;
Vector3 offset;
// Fix child rotations and positions
foreach (SceneObjectPart part in grp.GetParts())
{
// The part values are likely to come out of order from the collection,
// but the positions and rotations arrays are ordered by link number.
int i = part.LinkNum;
if (i > 0) i--; // need to convert to 0-based except for single-prim
if (i == 0)
continue; // the root prim does not need an adjustment
tmprot = rotations[i];
tmprot = rootRotConj * tmprot;
part.RotationOffset = tmprot;
offset = positions[i] - rootPos;
offset *= rootRotConj;
part.OffsetPosition = offset;
}
grp.AbsolutePosition = rootPos;
grp.UpdateGroupRotation(rotations[0], false);
}
else
{
grp.AbsolutePosition = rootPos;
grp.UpdateGroupRotation(rotations[0], false);
}
// This also notifies the user.
ApplyMeshCharges(m_Caps.AgentID, mesh_list.Count, texture_list.Count);
ISerializationEngine engine;
if (ProviderRegistry.Instance.TryGet<ISerializationEngine>(out engine))
{
return engine.InventoryObjectSerializer.SerializeGroupToInventoryBytes(grp, SerializationFlags.None);
}
else
{
return Utils.StringToBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp, StopScriptReason.None));
}
}
const ulong INVENTORY_FETCH_TIMEOUT = 60 * 1000;
public void Close()
{
m_inventoryPool.Shutdown(false, 0);
}
private void AsyncFetchInventoryDescendents(IHttpServer server, string path, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
AsyncHttpRequest request = new AsyncHttpRequest(server, httpRequest, httpResponse, m_agentID, null, 0);
m_inventoryPool.QueueWorkItem((AsyncHttpRequest req) =>
{
try
{
ulong age = Util.GetLongTickCount() - req.RequestTime;
if (age >= INVENTORY_FETCH_TIMEOUT)
{
SendFetchTimeout(req, age);
return;
}
byte[] ret = this.FetchInventoryDescendentsRequest((string)req.RequestData["body"],
(string)req.RequestData["uri"], String.Empty, req.HttpRequest, req.HttpResponse);
var respData = new Hashtable();
respData["response_binary"] = ret;
respData["int_response_code"] = 200;
respData["content_type"] = "application/llsd+xml";
req.SendResponse(respData);
}
catch (Exception e)
{
m_log.ErrorFormat("[CAPS/INVENTORY]: HandleAsyncFetchInventoryDescendents threw an exception: {0}", e);
var respData = new Hashtable();
respData["response_binary"] = new byte[0];
respData["int_response_code"] = 500;
req.SendResponse(respData);
}
},
request
);
}
private void SendFetchTimeout(AsyncHttpRequest pRequest, ulong age)
{
var timeout = new Hashtable();
timeout["response_binary"] = new byte[0];
timeout["int_response_code"] = 504; //gateway timeout
m_log.WarnFormat("[CAPS/INVENTORY]: HandleAsyncFetchInventoryDescendents: Request was too old to be processed {0}ms for {1}", age, m_agentID);
pRequest.SendResponse(timeout);
}
/// <summary>
/// Stores a list of folders we've blacklisted with a fail count and timestamp
/// </summary>
private Dictionary<UUID, TimestampedItem<int>> m_blackListedFolders = new Dictionary<UUID, TimestampedItem<int>>();
private const int MAX_FOLDER_FAIL_COUNT = 5;
private const int FOLDER_FAIL_TRACKING_TIME = 15 * 60; //15 minutes
public byte[] FetchInventoryDescendentsRequest(
string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
OpenMetaverse.StructuredData.OSDMap map = (OpenMetaverse.StructuredData.OSDMap)OSDParser.DeserializeLLSDXml(request);
OpenMetaverse.StructuredData.OSDArray osdFoldersRequested = (OpenMetaverse.StructuredData.OSDArray)map["folders"];
// m_log.ErrorFormat("[CAPS/INVENTORY] Handling a FetchInventoryDescendents Request for {0}: {1}", m_Caps.AgentID, map.ToString());
LLSDSerializationDictionary contents = new LLSDSerializationDictionary();
contents.WriteStartMap("llsd"); //Start llsd
contents.WriteKey("folders"); //Start array items
contents.WriteStartArray("folders"); //Start array folders
foreach (OSD folderInfo in osdFoldersRequested)
{
OpenMetaverse.StructuredData.OSDMap fiMap = folderInfo as OpenMetaverse.StructuredData.OSDMap;
if (fiMap == null)
continue;
UUID folderId = fiMap["folder_id"].AsUUID();
bool fetchItems = fiMap["fetch_items"].AsBoolean();
bool fetchFolders = fiMap["fetch_folders"].AsBoolean();
int count = 0;
InventoryFolderBase folder = null;
try
{
if (folderId == UUID.Zero)
{
//indicates the client wants the root for this user
folder = m_checkedStorageProvider.FindFolderForType(m_Caps.AgentID, (AssetType)FolderType.Root);
folderId = folder.ID;
}
else
{
lock (m_blackListedFolders)
{
TimestampedItem<int> entry;
if (m_blackListedFolders.TryGetValue(folderId, out entry))
{
if (entry.ElapsedSeconds > FOLDER_FAIL_TRACKING_TIME)
{
m_blackListedFolders.Remove(folderId);
}
else
{
if (entry.Item >= MAX_FOLDER_FAIL_COUNT)
{
//we're at the fail threshold. return a fake folder
folder = new InventoryFolderBase { ID = folderId, Name = "[unable to load folder]", Owner = m_agentID };
m_log.ErrorFormat("[CAPS/INVENTORY]: Fail threshold reached for {0}, sending empty folder", folderId);
}
}
}
}
if (folder == null)
{
// See if its a library folder
if (m_libraryFolder != null)
folder = m_libraryFolder.FindFolder(folderId);
if (folder == null)
{
// Nope, Look for it in regular folders
folder = m_checkedStorageProvider.GetFolder(m_Caps.AgentID, folderId);
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[CAPS/INVENTORY] Could not retrieve requested folder {0} for {1}: {2}",
folderId, m_Caps.AgentID, e);
if (folderId != UUID.Zero)
{
lock (m_blackListedFolders)
{
TimestampedItem<int> entry;
if (m_blackListedFolders.TryGetValue(folderId, out entry))
{
entry.ResetTimestamp();
entry.Item = entry.Item + 1;
}
else
{
m_blackListedFolders.Add(folderId, new TimestampedItem<int>(1));
}
}
}
continue;
}
contents.WriteStartMap("internalContents"); //Start internalContents kvp
//Set the normal stuff
contents["agent_id"] = folder.Owner;
contents["owner_id"] = folder.Owner;
contents["folder_id"] = folder.ID;
contents.WriteKey("items"); //Start array items
contents.WriteStartArray("items");
List<UUID> linkedFolders = new List<UUID>();
if (fetchItems)
{
foreach (InventoryItemBase item in folder.Items)
{
item.SerializeToLLSD(contents);
count++;
if (item.AssetType == (int)AssetType.LinkFolder)
{
// Add this when we do categories below
linkedFolders.Add(item.AssetID);
}
else if (item.AssetType == (int)AssetType.Link)
{
try
{
InventoryItemBase linkedItem = m_checkedStorageProvider.GetItem(m_agentID, item.AssetID, UUID.Zero);
if (linkedItem != null)
{
linkedItem.SerializeToLLSD(contents);
}
else
{
m_log.ErrorFormat(
"[CAPS/INVENTORY] Failed to resolve link to item {0} for {1}",
item.AssetID, m_Caps.AgentID);
}
// Don't add it to the count. It was accounted for with the link.
//count++;
}
catch (Exception e)
{
m_log.ErrorFormat(
"[CAPS/INVENTORY] Failed to resolve link to item {0} for {1}: {2}",
item.AssetID, m_Caps.AgentID, e.Message);
}
}
}
}
contents.WriteEndArray(/*"items"*/); //end array items
contents.WriteKey("categories"); //Start array cats
contents.WriteStartArray("categories"); //We don't send any folders
// If there were linked folders include the folders referenced here
if (linkedFolders.Count > 0)
{
foreach (UUID linkedFolderID in linkedFolders)
{
try
{
InventoryFolderBase linkedFolder = m_checkedStorageProvider.GetFolderAttributes(m_agentID, linkedFolderID);
if (linkedFolder != null)
{
linkedFolder.SerializeToLLSD(contents);
// Don't add it to the count.. it was accounted for with the link.
//count++;
}
}
catch (InventoryObjectMissingException)
{
m_log.ErrorFormat("[CAPS/INVENTORY] Failed to resolve link to folder {0} for {1}",
linkedFolderID, m_agentID);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[CAPS/INVENTORY] Failed to resolve link to folder {0} for {1}: {2}",
linkedFolderID, m_agentID, e);
}
}
}
if (fetchFolders)
{
foreach (InventorySubFolderBase subFolder in folder.SubFolders)
{
subFolder.SerializeToLLSD(contents, folder.ID);
count++;
}
}
contents.WriteEndArray(/*"categories"*/);
contents["descendents"] = count;
contents["version"] = folder.Version;
//Now add it to the folder array
contents.WriteEndMap(); //end array internalContents
}
contents.WriteEndArray(); //end array folders
contents.WriteEndMap(/*"llsd"*/); //end llsd
return (contents.GetSerializer());
}
/// <summary>
/// Stores a list of items we've blacklisted with a fail count and timestamp
/// </summary>
private Dictionary<UUID, TimestampedItem<int>> m_BlacklistedItems = new Dictionary<UUID, TimestampedItem<int>>();
private const int MAX_ITEM_FAIL_COUNT = 5;
private const int ITEM_FAIL_TRACKING_TIME = 5 * 60; //5 minutes
/// <summary>
/// Tracks that there was an error fetching an item
/// </summary>
/// <param name="itemId"></param>
private void AccountItemFetchFailure(UUID itemId)
{
lock (m_BlacklistedItems)
{
TimestampedItem<int> entry;
if (m_BlacklistedItems.TryGetValue(itemId, out entry))
{
entry.ResetTimestamp();
entry.Item = entry.Item + 1;
}
else
{
//add this brand new one
m_BlacklistedItems.Add(itemId, new TimestampedItem<int>(1));
//also clean out old ones
System.Lazy<List<UUID>> deadKeys = new System.Lazy<List<UUID>>();
foreach (var kvp in m_BlacklistedItems)
{
if (kvp.Value.ElapsedSeconds > ITEM_FAIL_TRACKING_TIME)
{
deadKeys.Value.Add(kvp.Key);
}
}
if (deadKeys.IsValueCreated)
{
foreach (UUID id in deadKeys.Value)
{
m_BlacklistedItems.Remove(id);
}
}
}
}
}
public string FetchInventoryRequest(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// m_log.DebugFormat("[FETCH INVENTORY HANDLER]: Received FetchInventory capabilty request");
OSDMap requestmap = (OSDMap)OSDParser.DeserializeLLSDXml(Utils.StringToBytes(request));
OSDArray itemsRequested = (OSDArray)requestmap["items"];
string reply;
LLSDFetchInventory llsdReply = new LLSDFetchInventory();
llsdReply.agent_id = m_agentID;
foreach (OSDMap osdItemId in itemsRequested)
{
UUID itemId = osdItemId["item_id"].AsUUID();
if (itemId == UUID.Zero)
continue; // don't bother
try
{
//see if we already know that this is a fail
lock (m_BlacklistedItems)
{
TimestampedItem<int> val;
if (m_BlacklistedItems.TryGetValue(itemId, out val))
{
//expired?
if (val.ElapsedSeconds > ITEM_FAIL_TRACKING_TIME)
{
m_BlacklistedItems.Remove(itemId);
}
else
{
if (val.Item >= MAX_ITEM_FAIL_COUNT)
{
//at the max fail count, don't even try to look this one up
continue;
}
}
}
}
InventoryItemBase item = m_checkedStorageProvider.GetItem(m_agentID, itemId, UUID.Zero);
if (item != null)
{
llsdReply.items.Array.Add(ConvertInventoryItem(item));
}
else
{
AccountItemFetchFailure(itemId);
}
}
catch (Exception e)
{
m_log.ErrorFormat("[CAPS/FETCH INVENTORY HANDLER] Could not retrieve requested inventory item {0} for {1}: {2}",
itemId, m_Caps.AgentID, e);
AccountItemFetchFailure(itemId);
}
}
reply = LLSDHelpers.SerializeLLSDReply(llsdReply);
return reply;
}
public string FetchLibraryRequest(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// m_log.DebugFormat("[FETCH LIBRARY HANDLER]: Received FetchInventory capabilty request");
OSDMap requestmap = (OSDMap)OSDParser.DeserializeLLSDXml(Utils.StringToBytes(request));
OSDArray itemsRequested = (OSDArray)requestmap["items"];
string reply;
LLSDFetchInventory llsdReply = new LLSDFetchInventory();
foreach (OSDMap osdItemId in itemsRequested)
{
UUID itemId = osdItemId["item_id"].AsUUID();
try
{
InventoryItemBase item = m_libraryFolder.FindItem(itemId);
if (item != null)
{
llsdReply.agent_id = item.Owner;
llsdReply.items.Array.Add(ConvertInventoryItem(item));
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[CAPS/FETCH LIBRARY HANDLER] Could not retrieve requested library item {0} for {1}: {2}",
itemId, m_Caps.AgentID, e);
}
}
reply = LLSDHelpers.SerializeLLSDReply(llsdReply);
return reply;
}
/// <summary>
/// Called by the CopyInventoryFromNotecard caps handler.
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
public string CopyInventoryFromNotecard(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
Hashtable response = new Hashtable();
response["int_response_code"] = 404;
response["content_type"] = "text/plain";
response["str_response_string"] = String.Empty;
IClientAPI client = null;
m_Scene.TryGetClient(m_Caps.AgentID, out client);
if (client == null)
return LLSDHelpers.SerializeLLSDReply(response);
try
{
OSDMap content = (OSDMap)OSDParser.DeserializeLLSDXml(request);
UUID objectID = content["object-id"].AsUUID();
UUID notecardID = content["notecard-id"].AsUUID();
UUID folderID = content["folder-id"].AsUUID();
UUID itemID = content["item-id"].AsUUID();
// m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, FolderID:{0}, ItemID:{1}, NotecardID:{2}, ObjectID:{3}", folderID, itemID, notecardID, objectID);
InventoryItemBase notecardItem = null;
IInventoryStorage inventoryService = m_inventoryProviderSelector.GetProvider(m_Caps.AgentID);
// Is this an objects task inventory?
if (objectID != UUID.Zero)
{
SceneObjectPart part = m_Scene.GetSceneObjectPart(objectID);
if (part != null)
{
TaskInventoryItem item = part.Inventory.GetInventoryItem(notecardID);
if (m_Scene.Permissions.CanCopyObjectInventory(notecardID, objectID, m_Caps.AgentID))
{
notecardItem = new InventoryItemBase(notecardID, m_agentID) { AssetID = item.AssetID };
}
}
}
// else its in inventory directly
else
{
notecardItem = inventoryService.GetItem(notecardID, UUID.Zero);
}
if ((notecardItem != null) && (notecardItem.Owner == m_agentID))
{
// Lookup up the notecard asset
IAssetCache assetCache = m_Scene.CommsManager.AssetCache;
AssetBase asset = assetCache.GetAsset(notecardItem.AssetID, AssetRequestInfo.InternalRequest());
if (asset != null)
{
AssetNotecard notecardAsset = new AssetNotecard(UUID.Zero, asset.Data);
notecardAsset.Decode();
InventoryItemBase item = null;
foreach (InventoryItem notecardObjectItem in notecardAsset.EmbeddedItems)
{
if (notecardObjectItem.UUID == itemID)
{
item = new InventoryItemBase(UUID.Random(), m_Caps.AgentID);
item.CreatorId = notecardObjectItem.CreatorID.ToString();
item.CreationDate = Util.UnixTimeSinceEpoch();
item.GroupID = notecardObjectItem.GroupID;
item.AssetID = notecardObjectItem.AssetUUID;
item.Name = notecardObjectItem.Name;
item.Description = notecardObjectItem.Description;
item.AssetType = (int)notecardObjectItem.AssetType;
item.InvType = (int)notecardObjectItem.InventoryType;
item.Folder = folderID;
//item.BasePermissions = (uint)notecardObjectItem.Permissions.BaseMask;
item.BasePermissions = (uint)(PermissionMask.All | PermissionMask.Export);
item.CurrentPermissions = (uint)(PermissionMask.All | PermissionMask.Export);
item.GroupPermissions = (uint)PermissionMask.None;
item.EveryOnePermissions = (uint)PermissionMask.None;
item.NextPermissions = (uint)PermissionMask.All;
break;
}
}
if (item != null)
{
m_Scene.AddInventoryItem(m_Caps.AgentID, item);
// m_log.InfoFormat("[CAPS]: SendInventoryItemCreateUpdate ItemID:{0}, AssetID:{1}", item.ID, item.AssetID);
client.SendInventoryItemCreateUpdate(item,0);
response["int_response_code"] = 200;
return LLSDHelpers.SerializeLLSDReply(response);
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[CAPS]: CopyInventoryFromNotecard : {0}", e.ToString());
}
// Failure case
client.SendAlertMessage("Failed to retrieve item");
return LLSDHelpers.SerializeLLSDReply(response);
}
public string CreateInventoryCategory(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
Hashtable response = new Hashtable();
response["int_response_code"] = 404;
response["content_type"] = "text/plain";
response["str_response_string"] = String.Empty;
OSDMap map = (OSDMap)OSDParser.DeserializeLLSDXml(request);
UUID folder_id = map["folder_id"].AsUUID();
UUID parent_id = map["parent_id"].AsUUID();
int type = map["type"].AsInteger();
string name = map["name"].AsString();
try
{
UUID newFolderId = UUID.Random();
InventoryFolderBase newFolder =
new InventoryFolderBase(newFolderId, name, m_Caps.AgentID, (short)type, parent_id, 1);
m_checkedStorageProvider.CreateFolder(m_Caps.AgentID, newFolder);
OSDMap resp = new OSDMap();
resp["folder_id"] = folder_id;
resp["parent_id"] = parent_id;
resp["type"] = type;
resp["name"] = name;
response["int_response_code"] = 200;
response["str_response_string"] = OSDParser.SerializeLLSDXmlString(resp);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[CAPS/INVENTORY] Could not create requested folder {0} in parent {1}: {2}", folder_id, m_Caps.AgentID, e);
}
return LLSDHelpers.SerializeLLSDReply(response);
}
/// <summary>
/// Convert an internal inventory item object into an LLSD object.
/// </summary>
/// <param name="invItem"></param>
/// <returns></returns>
private LLSDInventoryItem ConvertInventoryItem(InventoryItemBase invItem)
{
LLSDInventoryItem llsdItem = new LLSDInventoryItem();
llsdItem.asset_id = invItem.AssetID;
llsdItem.created_at = invItem.CreationDate;
llsdItem.desc = invItem.Description;
llsdItem.flags = (int)invItem.Flags;
llsdItem.item_id = invItem.ID;
llsdItem.name = invItem.Name;
llsdItem.parent_id = invItem.Folder;
llsdItem.type = invItem.AssetType;
llsdItem.inv_type = invItem.InvType;
llsdItem.permissions = new LLSDPermissions();
llsdItem.permissions.creator_id = invItem.CreatorIdAsUuid;
llsdItem.permissions.base_mask = (int)invItem.CurrentPermissions;
llsdItem.permissions.everyone_mask = (int)invItem.EveryOnePermissions;
llsdItem.permissions.group_id = invItem.GroupID;
llsdItem.permissions.group_mask = (int)invItem.GroupPermissions;
llsdItem.permissions.is_owner_group = invItem.GroupOwned;
llsdItem.permissions.next_owner_mask = (int)invItem.NextPermissions;
llsdItem.permissions.owner_id = invItem.Owner;
llsdItem.permissions.owner_mask = (int)invItem.CurrentPermissions;
llsdItem.sale_info = new LLSDSaleInfo();
llsdItem.sale_info.sale_price = invItem.SalePrice;
llsdItem.sale_info.sale_type = invItem.SaleType;
return llsdItem;
}
public class AssetUploader
{
public event UpLoadedAsset OnUpLoad;
private UpLoadedAsset handlerUpLoad = null;
private string uploaderPath = String.Empty;
private UUID newAssetID;
private UUID inventoryItemID;
private UUID parentFolder;
private IHttpServer httpListener;
private string m_assetName = String.Empty;
private string m_assetDes = String.Empty;
private string m_invType = String.Empty;
private string m_assetType = String.Empty;
private PermissionMask m_nextOwnerMask = PermissionMask.All;
private PermissionMask m_groupMask = PermissionMask.None;
private PermissionMask m_everyoneMask = PermissionMask.None;
public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem,
UUID parentFolderID, string invType, string assetType,
PermissionMask nextOwnerPerm, PermissionMask groupPerm, PermissionMask everyonePerm,
string path, IHttpServer httpServer)
{
m_assetName = assetName;
m_assetDes = description;
newAssetID = assetID;
inventoryItemID = inventoryItem;
uploaderPath = path;
httpListener = httpServer;
parentFolder = parentFolderID;
m_assetType = assetType;
m_invType = invType;
m_nextOwnerMask = nextOwnerPerm;
m_groupMask = groupPerm;
m_everyoneMask = everyonePerm;
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
public string uploaderCaps(byte[] data, string path, string param)
{
UUID inv = inventoryItemID;
string res = String.Empty;
LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
uploadComplete.new_asset = newAssetID.ToString();
uploadComplete.new_inventory_item = inv;
uploadComplete.state = "complete";
res = LLSDHelpers.SerializeLLSDReply(uploadComplete);
httpListener.RemoveStreamHandler("POST", uploaderPath);
handlerUpLoad = OnUpLoad;
if (handlerUpLoad != null)
{
handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType, m_nextOwnerMask, m_groupMask, m_everyoneMask);
}
return res;
}
}
/// <summary>
/// This class is a callback invoked when a client sends asset data to
/// an agent inventory notecard update url
/// </summary>
public class ItemUpdater
{
public event UpdateItem OnUpLoad;
private UpdateItem handlerUpdateItem = null;
private string uploaderPath = String.Empty;
private UUID inventoryItemID;
private IHttpServer httpListener;
public ItemUpdater(UUID inventoryItem, string path, IHttpServer httpServer)
{
inventoryItemID = inventoryItem;
uploaderPath = path;
httpListener = httpServer;
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
public string uploaderCaps(byte[] data, string path, string param)
{
UUID inv = inventoryItemID;
string res = String.Empty;
UpdateItemResponse response = new UpdateItemResponse();
handlerUpdateItem = OnUpLoad;
if (handlerUpdateItem != null)
{
response = handlerUpdateItem(inv, data);
}
if (response.AssetKind == AssetType.LSLText)
{
if (response.SaveErrors != null && response.SaveErrors.Count > 0)
{
LLSDScriptCompileFail compFail = new LLSDScriptCompileFail();
compFail.new_asset = response.AssetId.ToString();
compFail.new_inventory_item = inv;
compFail.state = "complete";
foreach (string str in response.SaveErrors)
{
compFail.errors.Array.Add(str);
}
res = LLSDHelpers.SerializeLLSDReply(compFail);
}
else
{
LLSDScriptCompileSuccess compSuccess = new LLSDScriptCompileSuccess();
compSuccess.new_asset = response.AssetId.ToString();
compSuccess.new_inventory_item = inv;
compSuccess.state = "complete";
res = LLSDHelpers.SerializeLLSDReply(compSuccess);
}
}
else
{
LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
uploadComplete.new_asset = response.AssetId.ToString();
uploadComplete.new_inventory_item = inv;
uploadComplete.state = "complete";
res = LLSDHelpers.SerializeLLSDReply(uploadComplete);
}
httpListener.RemoveStreamHandler("POST", uploaderPath);
return res;
}
}
}
/// <summary>
/// This class is a callback invoked when a client sends asset data to
/// a task inventory script update url
/// </summary>
protected class TaskInventoryScriptUpdater
{
public event UpdateTaskScript OnUpLoad;
private UpdateTaskScript handlerUpdateTaskScript = null;
private string uploaderPath = String.Empty;
private UUID inventoryItemID;
private UUID primID;
private bool isScriptRunning;
private IHttpServer httpListener;
public TaskInventoryScriptUpdater(UUID inventoryItemID, UUID primID, int isScriptRunning,
string path, IHttpServer httpServer)
{
this.inventoryItemID = inventoryItemID;
this.primID = primID;
// This comes in over the packet as an integer, but actually appears to be treated as a bool
this.isScriptRunning = (0 == isScriptRunning ? false : true);
uploaderPath = path;
httpListener = httpServer;
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
public string uploaderCaps(byte[] data, string path, string param)
{
try
{
// m_log.InfoFormat("[CAPS]: " +
// "TaskInventoryScriptUpdater received data: {0}, path: {1}, param: {2}",
// data, path, param));
string res = String.Empty;
UpdateItemResponse response = new UpdateItemResponse();
handlerUpdateTaskScript = OnUpLoad;
if (handlerUpdateTaskScript != null)
{
response = handlerUpdateTaskScript(inventoryItemID, primID, isScriptRunning, data);
}
if (response.AssetKind == AssetType.LSLText)
{
if (response.SaveErrors != null && response.SaveErrors.Count > 0)
{
LLSDScriptCompileFail compFail = new LLSDScriptCompileFail();
compFail.new_asset = response.AssetId.ToString();
compFail.state = "complete";
foreach (string str in response.SaveErrors)
{
compFail.errors.Array.Add(str);
}
res = LLSDHelpers.SerializeLLSDReply(compFail);
}
else
{
LLSDScriptCompileSuccess compSuccess = new LLSDScriptCompileSuccess();
compSuccess.new_asset = response.AssetId.ToString();
compSuccess.state = "complete";
res = LLSDHelpers.SerializeLLSDReply(compSuccess);
}
}
else
{
LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
uploadComplete.new_asset = response.AssetId.ToString();
uploadComplete.state = "complete";
res = LLSDHelpers.SerializeLLSDReply(uploadComplete);
}
httpListener.RemoveStreamHandler("POST", uploaderPath);
// m_log.InfoFormat("[CAPS]: TaskInventoryScriptUpdater.uploaderCaps res: {0}", res);
return res;
}
catch (Exception e)
{
m_log.Error("[CAPS]: " + e.ToString());
}
// XXX Maybe this should be some meaningful error packet
return null;
}
}
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// PDFsharp Team (mailto:[email protected])
//
// Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Collections;
using System.IO;
using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Drawing;
namespace ConcatenateDocuments
{
/// <summary>
/// This sample shows how to concatenate the pages of several PDF documents to
/// one single file.
/// </summary>
class Program
{
static void Main()
{
Variant1();
Variant2();
Variant3();
Variant4();
}
/// <summary>
/// Put your own code here to get the files to be concatenated.
/// </summary>
static string[] GetFiles()
{
DirectoryInfo dirInfo = new DirectoryInfo("../../../../../PDFs");
FileInfo[] fileInfos = dirInfo.GetFiles("*.pdf");
ArrayList list = new ArrayList();
foreach (FileInfo info in fileInfos)
{
// HACK: Just skip the protected samples file...
if (info.Name.IndexOf("protected") == -1)
list.Add(info.FullName);
}
return (string[])list.ToArray(typeof(string));
}
/// <summary>
/// Imports all pages from a list of documents.
/// </summary>
static void Variant1()
{
// Get some file names
string[] files = GetFiles();
// Open the output document
PdfDocument outputDocument = new PdfDocument();
// Iterate files
foreach (string file in files)
{
// Open the document to import pages from it.
PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);
// Iterate pages
int count = inputDocument.PageCount;
for (int idx = 0; idx < count; idx++)
{
// Get the page from the external document...
PdfPage page = inputDocument.Pages[idx];
// ...and add it to the output document.
outputDocument.AddPage(page);
}
}
// Save the document...
const string filename = "ConcatenatedDocument1_tempfile.pdf";
outputDocument.Save(filename);
// ...and start a viewer.
Process.Start(filename);
}
/// <summary>
/// This sample adds each page twice to the output document. The output document
/// becomes only a little bit larger because the content of the pages is reused
/// and not duplicated.
/// </summary>
static void Variant2()
{
// Get some file names
string[] files = GetFiles();
// Open the output document
PdfDocument outputDocument = new PdfDocument();
// Show consecutive pages facing. Requires Acrobat 5 or higher.
outputDocument.PageLayout = PdfPageLayout.TwoColumnLeft;
// Iterate files
foreach (string file in files)
{
// Open the document to import pages from it.
PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);
// Iterate pages
int count = inputDocument.PageCount;
for (int idx = 0; idx < count; idx++)
{
// Get the page from the external document...
PdfPage page = inputDocument.Pages[idx];
// ...and add them twice to the output document.
outputDocument.AddPage(page);
outputDocument.AddPage(page);
}
}
// Save the document...
const string filename = "ConcatenatedDocument2_tempfile.pdf";
outputDocument.Save(filename);
// ...and start a viewer.
Process.Start(filename);
}
/// <summary>
/// This sample adds a consecutive number in the middle of each page.
/// It shows how you can add graphics to an imported page.
/// </summary>
static void Variant3()
{
// Get some file names
string[] files = GetFiles();
// Open the output document
PdfDocument outputDocument = new PdfDocument();
// Note that the output document may look significant larger than in Variant1.
// This is because adding graphics to an imported page causes the
// uncompression of its content if it was compressed in the external document.
// To compare file sizes you should either run the sample as Release build
// or uncomment the following line.
outputDocument.Options.CompressContentStreams = true;
XFont font = new XFont("Verdana", 40, XFontStyle.Bold);
int number = 0;
// Iterate files
foreach (string file in files)
{
// Open the document to import pages from it.
PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);
// Iterate pages
int count = inputDocument.PageCount;
for (int idx = 0; idx < count; idx++)
{
// Get the page from the external document...
PdfPage page = inputDocument.Pages[idx];
// ...and add it to the output document.
// Note that the PdfPage instance returned by AddPage is a
// different object.
page = outputDocument.AddPage(page);
// Create a graphics object for this page. To draw beneath the existing
// content set 'Append' to 'Prepend'.
XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
DrawNumber(gfx, font, ++number);
}
}
// Save the document...
const string filename = "ConcatenatedDocument3_tempfile.pdf";
outputDocument.Save(filename);
// ...and start a viewer.
Process.Start(filename);
}
/// <summary>
/// This sample is the combination of Variant2 and Variant3. It shows that you
/// can add external pages more than once and still add individual graphics on
/// each page. The external content is shared among the pages, the new graphics
/// are unique to each page. You can check this by comparing the file size
/// of Variant3 and Variant4.
/// </summary>
static void Variant4()
{
// Get some file names
string[] files = GetFiles();
// Open the output document
PdfDocument outputDocument = new PdfDocument();
// For checking the file size uncomment next line.
//outputDocument.Options.CompressContentStreams = true;
XFont font = new XFont("Verdana", 40, XFontStyle.Bold);
int number = 0;
// Iterate files
foreach (string file in files)
{
// Open the document to import pages from it.
PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);
// Show consecutive pages facing. Requires Acrobat 5 or higher.
outputDocument.PageLayout = PdfPageLayout.TwoColumnLeft;
// Iterate pages
int count = inputDocument.PageCount;
for (int idx = 0; idx < count; idx++)
{
// Get the page from the external document...
PdfPage page = inputDocument.Pages[idx];
// ...and add it twice to the output document.
PdfPage page1 = outputDocument.AddPage(page);
PdfPage page2 = outputDocument.AddPage(page);
XGraphics gfx =
XGraphics.FromPdfPage(page1, XGraphicsPdfPageOptions.Append);
DrawNumber(gfx, font, ++number);
gfx = XGraphics.FromPdfPage(page2, XGraphicsPdfPageOptions.Append);
DrawNumber(gfx, font, ++number);
}
}
// Save the document...
const string filename = "ConcatenatedDocument4_tempfile.pdf";
outputDocument.Save(filename);
// ...and start a viewer.
Process.Start(filename);
}
/// <summary>
/// Draws the number in the middle of the page.
/// </summary>
static void DrawNumber(XGraphics gfx, XFont font, int number)
{
const double width = 130;
gfx.DrawEllipse(new XPen(XColors.DarkBlue, 7), XBrushes.DarkOrange,
new XRect((gfx.PageSize.Width - width) / 2, (gfx.PageSize.Height - width) / 2, width, width));
gfx.DrawString(number.ToString(), font, XBrushes.Firebrick,
new XRect(new XPoint(), gfx.PageSize), XStringFormats.Center);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataRecordInternal.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.IO;
using System.Threading;
internal sealed class DataRecordInternal : DbDataRecord, ICustomTypeDescriptor {
private SchemaInfo[] _schemaInfo;
private object[] _values;
private PropertyDescriptorCollection _propertyDescriptors;
private FieldNameLookup _fieldNameLookup; // MDAC 69015
// copy all runtime data information
internal DataRecordInternal(SchemaInfo[] schemaInfo, object[] values, PropertyDescriptorCollection descriptors, FieldNameLookup fieldNameLookup) {
Debug.Assert(null != schemaInfo, "invalid attempt to instantiate DataRecordInternal with null schema information");
Debug.Assert(null != values, "invalid attempt to instantiate DataRecordInternal with null value[]");
_schemaInfo = schemaInfo;
_values = values;
_propertyDescriptors = descriptors;
_fieldNameLookup = fieldNameLookup;
}
// copy all runtime data information
internal DataRecordInternal(object[] values, PropertyDescriptorCollection descriptors, FieldNameLookup fieldNameLookup) {
Debug.Assert(null != values, "invalid attempt to instantiate DataRecordInternal with null value[]");
_values = values;
_propertyDescriptors = descriptors;
_fieldNameLookup = fieldNameLookup;
}
internal void SetSchemaInfo(SchemaInfo[] schemaInfo) {
Debug.Assert(null == _schemaInfo, "invalid attempt to override DataRecordInternal schema information");
_schemaInfo = schemaInfo;
}
public override int FieldCount {
get {
return _schemaInfo.Length;
}
}
public override int GetValues(object[] values) {
if (null == values) {
throw ADP.ArgumentNull("values");
}
int copyLen = (values.Length < _schemaInfo.Length) ? values.Length : _schemaInfo.Length;
for (int i = 0; i < copyLen; i++) {
values[i] = _values[i];
}
return copyLen;
}
public override string GetName(int i) {
return _schemaInfo[i].name;
}
public override object GetValue(int i) {
return _values[i];
}
public override string GetDataTypeName(int i) {
return _schemaInfo[i].typeName;
}
public override Type GetFieldType(int i) {
return _schemaInfo[i].type;
}
public override int GetOrdinal(string name) { // MDAC 69015
return _fieldNameLookup.GetOrdinal(name); // MDAC 71470
}
public override object this[int i] {
get {
return GetValue(i);
}
}
public override object this[string name] {
get {
return GetValue(GetOrdinal(name));
}
}
public override bool GetBoolean(int i) {
return((bool) _values[i]);
}
public override byte GetByte(int i) {
return((byte) _values[i]);
}
public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) {
int cbytes = 0;
int ndataIndex;
byte[] data = (byte[])_values[i];
cbytes = data.Length;
// since arrays can't handle 64 bit values and this interface doesn't
// allow chunked access to data, a dataIndex outside the rang of Int32
// is invalid
if (dataIndex > Int32.MaxValue) {
throw ADP.InvalidSourceBufferIndex(cbytes, dataIndex, "dataIndex");
}
ndataIndex = (int)dataIndex;
// if no buffer is passed in, return the number of characters we have
if (null == buffer)
return cbytes;
try {
if (ndataIndex < cbytes) {
// help the user out in the case where there's less data than requested
if ((ndataIndex + length) > cbytes)
cbytes = cbytes - ndataIndex;
else
cbytes = length;
}
// until arrays are 64 bit, we have to do these casts
Array.Copy(data, ndataIndex, buffer, bufferIndex, (int)cbytes);
}
catch (Exception e) {
//
if (ADP.IsCatchableExceptionType(e)) {
cbytes = data.Length;
if (length < 0)
throw ADP.InvalidDataLength(length);
// if bad buffer index, throw
if (bufferIndex < 0 || bufferIndex >= buffer.Length)
throw ADP.InvalidDestinationBufferIndex(length, bufferIndex, "bufferIndex");
// if bad data index, throw
if (dataIndex < 0 || dataIndex >= cbytes)
throw ADP.InvalidSourceBufferIndex(length, dataIndex, "dataIndex");
// if there is not enough room in the buffer for data
if (cbytes + bufferIndex > buffer.Length)
throw ADP.InvalidBufferSizeOrIndex(cbytes, bufferIndex);
}
throw;
}
return cbytes;
}
public override char GetChar(int i) {
string s;
s = (string)_values[i];
char[] c = s.ToCharArray();
return c[0];
}
public override long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) {
int cchars = 0;
string s;
int ndataIndex;
// if the object doesn't contain a char[] then the user will get an exception
s = (string)_values[i];
char[] data = s.ToCharArray();
cchars = data.Length;
// since arrays can't handle 64 bit values and this interface doesn't
// allow chunked access to data, a dataIndex outside the rang of Int32
// is invalid
if (dataIndex > Int32.MaxValue) {
throw ADP.InvalidSourceBufferIndex(cchars, dataIndex, "dataIndex");
}
ndataIndex = (int)dataIndex;
// if no buffer is passed in, return the number of characters we have
if (null == buffer)
return cchars;
try {
if (ndataIndex < cchars) {
// help the user out in the case where there's less data than requested
if ((ndataIndex + length) > cchars)
cchars = cchars - ndataIndex;
else
cchars = length;
}
Array.Copy(data, ndataIndex, buffer, bufferIndex, cchars);
}
catch (Exception e) {
//
if (ADP.IsCatchableExceptionType(e)) {
cchars = data.Length;
if (length < 0)
throw ADP.InvalidDataLength(length);
// if bad buffer index, throw
if (bufferIndex < 0 || bufferIndex >= buffer.Length)
throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex");
// if bad data index, throw
if (ndataIndex < 0 || ndataIndex >= cchars)
throw ADP.InvalidSourceBufferIndex(cchars, dataIndex, "dataIndex");
// if there is not enough room in the buffer for data
if (cchars + bufferIndex > buffer.Length)
throw ADP.InvalidBufferSizeOrIndex(cchars, bufferIndex);
}
throw;
}
return cchars;
}
public override Guid GetGuid(int i) {
return ((Guid)_values[i]);
}
public override Int16 GetInt16(int i) {
return((Int16) _values[i]);
}
public override Int32 GetInt32(int i) {
return((Int32) _values[i]);
}
public override Int64 GetInt64(int i) {
return((Int64) _values[i]);
}
public override float GetFloat(int i) {
return((float) _values[i]);
}
public override double GetDouble(int i) {
return((double) _values[i]);
}
public override string GetString(int i) {
return((string) _values[i]);
}
public override Decimal GetDecimal(int i) {
return((Decimal) _values[i]);
}
public override DateTime GetDateTime(int i) {
return((DateTime) _values[i]);
}
public override bool IsDBNull(int i) {
object o = _values[i];
return (null == o || Convert.IsDBNull(o));
}
//
// ICustomTypeDescriptor
//
AttributeCollection ICustomTypeDescriptor.GetAttributes() {
return new AttributeCollection((Attribute[])null);
}
string ICustomTypeDescriptor.GetClassName() {
return null;
}
string ICustomTypeDescriptor.GetComponentName() {
return null;
}
TypeConverter ICustomTypeDescriptor.GetConverter() {
return null;
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() {
return null;
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() {
return null;
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType) {
return null;
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents() {
return new EventDescriptorCollection(null);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) {
return new EventDescriptorCollection(null);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() {
return((ICustomTypeDescriptor)this).GetProperties(null);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) {
if(_propertyDescriptors == null) {
_propertyDescriptors = new PropertyDescriptorCollection(null);
}
return _propertyDescriptors;
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) {
return this;
}
}
// this doesn't change per record, only alloc once
internal struct SchemaInfo {
public string name;
public string typeName;
public Type type;
}
}
| |
// 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.Buffers;
using System.Buffers.Text;
using System.Diagnostics;
namespace System.Text.Json
{
public ref partial struct Utf8JsonReader
{
/// <summary>
/// Parses the current JSON token value from the source, unescaped, and transcoded as a <see cref="string"/>.
/// </summary>
/// <remarks>
/// Returns <see langword="null" /> when <see cref="TokenType"/> is <see cref="JsonTokenType.Null"/>.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of the JSON token that is not a string
/// (i.e. other than <see cref="JsonTokenType.String"/>, <see cref="JsonTokenType.PropertyName"/> or
/// <see cref="JsonTokenType.Null"/>).
/// <seealso cref="TokenType" />
/// It will also throw when the JSON string contains invalid UTF-8 bytes, or invalid UTF-16 surrogates.
/// </exception>
public string GetString()
{
if (TokenType == JsonTokenType.Null)
{
return null;
}
if (TokenType != JsonTokenType.String && TokenType != JsonTokenType.PropertyName)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedString(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (_stringHasEscaping)
{
int idx = span.IndexOf(JsonConstants.BackSlash);
Debug.Assert(idx != -1);
return JsonReaderHelper.GetUnescapedString(span, idx);
}
Debug.Assert(span.IndexOf(JsonConstants.BackSlash) == -1);
return JsonReaderHelper.TranscodeHelper(span);
}
/// <summary>
/// Parses the current JSON token value from the source as a comment, transcoded as a <see cref="string"/>.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of the JSON token that is not a comment.
/// <seealso cref="TokenType" />
/// </exception>
public string GetComment()
{
if (TokenType != JsonTokenType.Comment)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedComment(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
return JsonReaderHelper.TranscodeHelper(span);
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="bool"/>.
/// Returns <see langword="true"/> if the TokenType is JsonTokenType.True and <see langword="false"/> if the TokenType is JsonTokenType.False.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a boolean (i.e. <see cref="JsonTokenType.True"/> or <see cref="JsonTokenType.False"/>).
/// <seealso cref="TokenType" />
/// </exception>
public bool GetBoolean()
{
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (TokenType == JsonTokenType.True)
{
Debug.Assert(span.Length == 4);
return true;
}
else if (TokenType == JsonTokenType.False)
{
Debug.Assert(span.Length == 5);
return false;
}
else
{
throw ThrowHelper.GetInvalidOperationException_ExpectedBoolean(TokenType);
}
}
/// <summary>
/// Parses the current JSON token value from the source and decodes the Base64 encoded JSON string as bytes.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.String"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown when the JSON string contains data outside of the expected Base64 range, or if it contains invalid/more than two padding characters,
/// or is incomplete (i.e. the JSON string length is not a multiple of 4).
/// </exception>
public byte[] GetBytesFromBase64()
{
if (!TryGetBytesFromBase64(out byte[] value))
{
throw ThrowHelper.GetFormatException(DataType.Base64String);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="byte"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to a <see cref="byte"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown if the JSON token value is either of incorrect numeric format (for example if it contains a decimal or
/// is written in scientific notation) or, it represents a number less than <see cref="byte.MinValue"/> or greater
/// than <see cref="byte.MaxValue"/>.
/// </exception>
public byte GetByte()
{
if (!TryGetByte(out byte value))
{
throw ThrowHelper.GetFormatException(NumericType.Byte);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as an <see cref="sbyte"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to an <see cref="sbyte"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown if the JSON token value is either of incorrect numeric format (for example if it contains a decimal or
/// is written in scientific notation) or, it represents a number less than <see cref="sbyte.MinValue"/> or greater
/// than <see cref="sbyte.MaxValue"/>.
/// </exception>
[System.CLSCompliantAttribute(false)]
public sbyte GetSByte()
{
if (!TryGetSByte(out sbyte value))
{
throw ThrowHelper.GetFormatException(NumericType.SByte);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="short"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to a <see cref="short"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown if the JSON token value is either of incorrect numeric format (for example if it contains a decimal or
/// is written in scientific notation) or, it represents a number less than <see cref="short.MinValue"/> or greater
/// than <see cref="short.MaxValue"/>.
/// </exception>
public short GetInt16()
{
if (!TryGetInt16(out short value))
{
throw ThrowHelper.GetFormatException(NumericType.Int16);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as an <see cref="int"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to an <see cref="int"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown if the JSON token value is either of incorrect numeric format (for example if it contains a decimal or
/// is written in scientific notation) or, it represents a number less than <see cref="int.MinValue"/> or greater
/// than <see cref="int.MaxValue"/>.
/// </exception>
public int GetInt32()
{
if (!TryGetInt32(out int value))
{
throw ThrowHelper.GetFormatException(NumericType.Int32);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="long"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to a <see cref="long"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown if the JSON token value is either of incorrect numeric format (for example if it contains a decimal or
/// is written in scientific notation) or, it represents a number less than <see cref="long.MinValue"/> or greater
/// than <see cref="long.MaxValue"/>.
/// </exception>
public long GetInt64()
{
if (!TryGetInt64(out long value))
{
throw ThrowHelper.GetFormatException(NumericType.Int64);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="ushort"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to a <see cref="ushort"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown if the JSON token value is either of incorrect numeric format (for example if it contains a decimal or
/// is written in scientific notation) or, it represents a number less than <see cref="ushort.MinValue"/> or greater
/// than <see cref="ushort.MaxValue"/>.
/// </exception>
[System.CLSCompliantAttribute(false)]
public ushort GetUInt16()
{
if (!TryGetUInt16(out ushort value))
{
throw ThrowHelper.GetFormatException(NumericType.UInt16);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="uint"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to a <see cref="uint"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown if the JSON token value is either of incorrect numeric format (for example if it contains a decimal or
/// is written in scientific notation) or, it represents a number less than <see cref="uint.MinValue"/> or greater
/// than <see cref="uint.MaxValue"/>.
/// </exception>
[System.CLSCompliantAttribute(false)]
public uint GetUInt32()
{
if (!TryGetUInt32(out uint value))
{
throw ThrowHelper.GetFormatException(NumericType.UInt32);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="ulong"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to a <see cref="ulong"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown if the JSON token value is either of incorrect numeric format (for example if it contains a decimal or
/// is written in scientific notation) or, it represents a number less than <see cref="ulong.MinValue"/> or greater
/// than <see cref="ulong.MaxValue"/>.
/// </exception>
[System.CLSCompliantAttribute(false)]
public ulong GetUInt64()
{
if (!TryGetUInt64(out ulong value))
{
throw ThrowHelper.GetFormatException(NumericType.UInt64);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="float"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to a <see cref="float"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// On any framework that is not .NET Core 3.0 or higher, thrown if the JSON token value represents a number less than <see cref="float.MinValue"/> or greater
/// than <see cref="float.MaxValue"/>.
/// </exception>
public float GetSingle()
{
if (!TryGetSingle(out float value))
{
throw ThrowHelper.GetFormatException(NumericType.Single);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="double"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to a <see cref="double"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// On any framework that is not .NET Core 3.0 or higher, thrown if the JSON token value represents a number less than <see cref="double.MinValue"/> or greater
/// than <see cref="double.MaxValue"/>.
/// </exception>
public double GetDouble()
{
if (!TryGetDouble(out double value))
{
throw ThrowHelper.GetFormatException(NumericType.Double);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="decimal"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to a <see cref="decimal"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown if the JSON token value represents a number less than <see cref="decimal.MinValue"/> or greater
/// than <see cref="decimal.MaxValue"/>.
/// </exception>
public decimal GetDecimal()
{
if (!TryGetDecimal(out decimal value))
{
throw ThrowHelper.GetFormatException(NumericType.Decimal);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="DateTime"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to a <see cref="DateTime"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.String"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown if the JSON token value is of an unsupported format. Only a subset of ISO 8601 formats are supported.
/// </exception>
public DateTime GetDateTime()
{
if (!TryGetDateTime(out DateTime value))
{
throw ThrowHelper.GetFormatException(DataType.DateTime);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="DateTimeOffset"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to a <see cref="DateTimeOffset"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.String"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown if the JSON token value is of an unsupported format. Only a subset of ISO 8601 formats are supported.
/// </exception>
public DateTimeOffset GetDateTimeOffset()
{
if (!TryGetDateTimeOffset(out DateTimeOffset value))
{
throw ThrowHelper.GetFormatException(DataType.DateTimeOffset);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="Guid"/>.
/// Returns the value if the entire UTF-8 encoded token value can be successfully parsed to a <see cref="Guid"/>
/// value.
/// Throws exceptions otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.String"/>.
/// <seealso cref="TokenType" />
/// </exception>
/// <exception cref="FormatException">
/// Thrown if the JSON token value is of an unsupported format for a Guid.
/// </exception>
public Guid GetGuid()
{
if (!TryGetGuid(out Guid value))
{
throw ThrowHelper.GetFormatException(DataType.Guid);
}
return value;
}
/// <summary>
/// Parses the current JSON token value from the source and decodes the Base64 encoded JSON string as bytes.
/// Returns <see langword="true"/> if the entire token value is encoded as valid Base64 text and can be successfully
/// decoded to bytes.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.String"/>.
/// <seealso cref="TokenType" />
/// </exception>
public bool TryGetBytesFromBase64(out byte[] value)
{
if (TokenType != JsonTokenType.String)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedString(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (_stringHasEscaping)
{
int idx = span.IndexOf(JsonConstants.BackSlash);
Debug.Assert(idx != -1);
return JsonReaderHelper.TryGetUnescapedBase64Bytes(span, idx, out value);
}
Debug.Assert(span.IndexOf(JsonConstants.BackSlash) == -1);
return JsonReaderHelper.TryDecodeBase64(span, out value);
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="byte"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to a <see cref="byte"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
public bool TryGetByte(out byte value)
{
if (TokenType != JsonTokenType.Number)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (Utf8Parser.TryParse(span, out byte tmp, out int bytesConsumed)
&& span.Length == bytesConsumed)
{
value = tmp;
return true;
}
value = 0;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as an <see cref="sbyte"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to an <see cref="sbyte"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
[System.CLSCompliantAttribute(false)]
public bool TryGetSByte(out sbyte value)
{
if (TokenType != JsonTokenType.Number)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (Utf8Parser.TryParse(span, out sbyte tmp, out int bytesConsumed)
&& span.Length == bytesConsumed)
{
value = tmp;
return true;
}
value = 0;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="short"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to a <see cref="short"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
public bool TryGetInt16(out short value)
{
if (TokenType != JsonTokenType.Number)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (Utf8Parser.TryParse(span, out short tmp, out int bytesConsumed)
&& span.Length == bytesConsumed)
{
value = tmp;
return true;
}
value = 0;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as an <see cref="int"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to an <see cref="int"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
public bool TryGetInt32(out int value)
{
if (TokenType != JsonTokenType.Number)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (Utf8Parser.TryParse(span, out int tmp, out int bytesConsumed)
&& span.Length == bytesConsumed)
{
value = tmp;
return true;
}
value = 0;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="long"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to a <see cref="long"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
public bool TryGetInt64(out long value)
{
if (TokenType != JsonTokenType.Number)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (Utf8Parser.TryParse(span, out long tmp, out int bytesConsumed)
&& span.Length == bytesConsumed)
{
value = tmp;
return true;
}
value = 0;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="ushort"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to a <see cref="ushort"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt16(out ushort value)
{
if (TokenType != JsonTokenType.Number)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (Utf8Parser.TryParse(span, out ushort tmp, out int bytesConsumed)
&& span.Length == bytesConsumed)
{
value = tmp;
return true;
}
value = 0;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="uint"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to a <see cref="uint"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt32(out uint value)
{
if (TokenType != JsonTokenType.Number)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (Utf8Parser.TryParse(span, out uint tmp, out int bytesConsumed)
&& span.Length == bytesConsumed)
{
value = tmp;
return true;
}
value = 0;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="ulong"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to a <see cref="ulong"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt64(out ulong value)
{
if (TokenType != JsonTokenType.Number)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (Utf8Parser.TryParse(span, out ulong tmp, out int bytesConsumed)
&& span.Length == bytesConsumed)
{
value = tmp;
return true;
}
value = 0;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="float"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to a <see cref="float"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
public bool TryGetSingle(out float value)
{
if (TokenType != JsonTokenType.Number)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (Utf8Parser.TryParse(span, out float tmp, out int bytesConsumed, _numberFormat)
&& span.Length == bytesConsumed)
{
value = tmp;
return true;
}
value = 0;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="double"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to a <see cref="double"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
public bool TryGetDouble(out double value)
{
if (TokenType != JsonTokenType.Number)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (Utf8Parser.TryParse(span, out double tmp, out int bytesConsumed, _numberFormat)
&& span.Length == bytesConsumed)
{
value = tmp;
return true;
}
value = 0;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="decimal"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to a <see cref="decimal"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.Number"/>.
/// <seealso cref="TokenType" />
/// </exception>
public bool TryGetDecimal(out decimal value)
{
if (TokenType != JsonTokenType.Number)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedNumber(TokenType);
}
ReadOnlySpan<byte> span = HasValueSequence ? ValueSequence.ToArray() : ValueSpan;
if (Utf8Parser.TryParse(span, out decimal tmp, out int bytesConsumed, _numberFormat)
&& span.Length == bytesConsumed)
{
value = tmp;
return true;
}
value = 0;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="DateTime"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to a <see cref="DateTime"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.String"/>.
/// <seealso cref="TokenType" />
/// </exception>
public bool TryGetDateTime(out DateTime value)
{
if (TokenType != JsonTokenType.String)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedString(TokenType);
}
ReadOnlySpan<byte> span = stackalloc byte[0];
if (HasValueSequence)
{
long sequenceLength = ValueSequence.Length;
if (!JsonReaderHelper.IsValidDateTimeOffsetParseLength(sequenceLength))
{
value = default;
return false;
}
Debug.Assert(sequenceLength <= JsonConstants.MaximumEscapedDateTimeOffsetParseLength);
Span<byte> stackSpan = stackalloc byte[(int)sequenceLength];
ValueSequence.CopyTo(stackSpan);
span = stackSpan;
}
else
{
if (!JsonReaderHelper.IsValidDateTimeOffsetParseLength(ValueSpan.Length))
{
value = default;
return false;
}
span = ValueSpan;
}
if (_stringHasEscaping)
{
return JsonReaderHelper.TryGetEscapedDateTime(span, out value);
}
Debug.Assert(span.IndexOf(JsonConstants.BackSlash) == -1);
if (span.Length <= JsonConstants.MaximumDateTimeOffsetParseLength
&& JsonHelpers.TryParseAsISO(span, out DateTime tmp))
{
value = tmp;
return true;
}
value = default;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="DateTimeOffset"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to a <see cref="DateTimeOffset"/> value.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.String"/>.
/// <seealso cref="TokenType" />
/// </exception>
public bool TryGetDateTimeOffset(out DateTimeOffset value)
{
if (TokenType != JsonTokenType.String)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedString(TokenType);
}
ReadOnlySpan<byte> span = stackalloc byte[0];
if (HasValueSequence)
{
long sequenceLength = ValueSequence.Length;
if (!JsonReaderHelper.IsValidDateTimeOffsetParseLength(sequenceLength))
{
value = default;
return false;
}
Debug.Assert(sequenceLength <= JsonConstants.MaximumEscapedDateTimeOffsetParseLength);
Span<byte> stackSpan = stackalloc byte[(int)sequenceLength];
ValueSequence.CopyTo(stackSpan);
span = stackSpan;
}
else
{
if (!JsonReaderHelper.IsValidDateTimeOffsetParseLength(ValueSpan.Length))
{
value = default;
return false;
}
span = ValueSpan;
}
if (_stringHasEscaping)
{
return JsonReaderHelper.TryGetEscapedDateTimeOffset(span, out value);
}
Debug.Assert(span.IndexOf(JsonConstants.BackSlash) == -1);
if (span.Length <= JsonConstants.MaximumDateTimeOffsetParseLength
&& JsonHelpers.TryParseAsISO(span, out DateTimeOffset tmp))
{
value = tmp;
return true;
}
value = default;
return false;
}
/// <summary>
/// Parses the current JSON token value from the source as a <see cref="Guid"/>.
/// Returns <see langword="true"/> if the entire UTF-8 encoded token value can be successfully
/// parsed to a <see cref="Guid"/> value. Only supports <see cref="Guid"/> values with hyphens
/// and without any surrounding decorations.
/// Returns <see langword="false"/> otherwise.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to get the value of a JSON token that is not a <see cref="JsonTokenType.String"/>.
/// <seealso cref="TokenType" />
/// </exception>
public bool TryGetGuid(out Guid value)
{
if (TokenType != JsonTokenType.String)
{
throw ThrowHelper.GetInvalidOperationException_ExpectedString(TokenType);
}
ReadOnlySpan<byte> span = stackalloc byte[0];
if (HasValueSequence)
{
long sequenceLength = ValueSequence.Length;
if (sequenceLength > JsonConstants.MaximumEscapedGuidLength)
{
value = default;
return false;
}
Debug.Assert(sequenceLength <= JsonConstants.MaximumEscapedGuidLength);
Span<byte> stackSpan = stackalloc byte[(int)sequenceLength];
ValueSequence.CopyTo(stackSpan);
span = stackSpan;
}
else
{
if (ValueSpan.Length > JsonConstants.MaximumEscapedGuidLength)
{
value = default;
return false;
}
span = ValueSpan;
}
if (_stringHasEscaping)
{
return JsonReaderHelper.TryGetEscapedGuid(span, out value);
}
Debug.Assert(span.IndexOf(JsonConstants.BackSlash) == -1);
if (span.Length == JsonConstants.MaximumFormatGuidLength
&& Utf8Parser.TryParse(span, out Guid tmp, out _, 'D'))
{
value = tmp;
return true;
}
value = default;
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsSubscriptionIdApiVersion
{
using System.Linq;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Some cool documentation.
/// </summary>
public partial class MicrosoftAzureTestUrl : Microsoft.Rest.ServiceClient<MicrosoftAzureTestUrl>, IMicrosoftAzureTestUrl, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Subscription Id.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// API Version with value '2014-04-01-preview'.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IGroupOperations.
/// </summary>
public virtual IGroupOperations Group { get; private set; }
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected MicrosoftAzureTestUrl(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected MicrosoftAzureTestUrl(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected MicrosoftAzureTestUrl(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected MicrosoftAzureTestUrl(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MicrosoftAzureTestUrl(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MicrosoftAzureTestUrl(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MicrosoftAzureTestUrl(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MicrosoftAzureTestUrl(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Group = new GroupOperations(this);
this.BaseUri = new System.Uri("https://management.azure.com/");
this.ApiVersion = "2014-04-01-preview";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
}
}
| |
// .NET speech synthesis library for VBScript
// requires an assembly reference to
// %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\WPF\System.Speech.dll
using System.Speech.Synthesis;
using System.Runtime.InteropServices;
using System.Linq; // for Cast<object>
using System.Collections.Generic; // for List
using System.Windows.Forms; // for MessageBox
namespace VBScripting
{
/// <summary> Provide a wrapper for the .NET speech synthesizer for VBScript, for demonstration purposes. </summary>
/// <remarks> Requires an assembly reference to <tt>%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\WPF\System.Speech.dll</tt>. </remarks>
[Guid("2650C2AB-2AF8-495F-AB4D-6C61BD463EA4")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("VBScripting.SpeechSynthesis")]
public class SpeechSynthesis : ISpeechSynthesis
{
private SpeechSynthesizer ss;
private List<string> installedVoices;
private List<string> voices; // installed & enabled
/// <summary> Constructor </summary>
public SpeechSynthesis()
{
this.ss = new SpeechSynthesizer();
this.voices = new List<string>(); // installed, enabled voices
this.installedVoices = new List<string>(); // installed voices
string name;
foreach (InstalledVoice voice in ss.GetInstalledVoices())
{
name = voice.VoiceInfo.Name;
this.installedVoices.Add(name);
if (voice.Enabled)
{
this.voices.Add(name);
}
}
}
/// <summary> Convert text to speech. </summary>
/// <remarks> This method is synchronous. </remarks>
public void Speak(string text)
{
if (!string.IsNullOrWhiteSpace(text))
{
this.ss.Speak(text);
}
}
/// <summary> Convert text to speech. </summary>
/// <remarks> This method is asynchronous. </remarks>
public void SpeakAsync(string text)
{
if (!string.IsNullOrWhiteSpace(text))
{
this.ss.SpeakAsync(text);
}
}
/// <summary> Pause speech synthesis. </summary>
public void Pause()
{
if (System.Speech.Synthesis.SynthesizerState.Speaking == this.ss.State)
{
this.ss.Pause();
}
}
/// <summary> Resume speech synthesis. </summary>
public void Resume()
{
if (System.Speech.Synthesis.SynthesizerState.Paused == this.ss.State)
{
this.ss.Resume();
}
}
/// <summary> Gets an array of the names of the installed, enabled voices. </summary>
/// <remarks> Each element of the array can be used to set <tt>Voice</tt>.</remarks>
public object Voices()
{
return this.voices.Cast<object>().ToArray(); // convert to VBScript array
}
/// <summary> Gets or sets the current voice by name. </summary>
/// <remarks> A string. One of the names from the <tt>Voices</tt> array. </remarks>
public string Voice
{
set
{
if (this.voices.Contains(value))
{
this.ss.SelectVoice(value);
}
else if (this.installedVoices.Contains(value))
{
string msg = string.Format(
"\"{0}\" is an installed voice but is not enabled.", value);
ShowInfoMessage(msg);
}
else
{
string msg = string.Format(
"\"{0}\" is not an installed voice.", value);
ShowInfoMessage(msg);
}
}
get
{
return this.ss.Voice.Name;
}
}
// Shows a message box with the specified string
private void ShowInfoMessage(string msg)
{
MessageBox.Show(msg,
"SpeechSynthesis class",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
/// <summary> Disposes the SpeechSynthesis object's resources. </summary>
public void Dispose()
{
if (this.ss != null)
{
this.ss.Dispose();
}
}
/// <summary> Gets the state of the SpeechSynthesizer. </summary>
/// <remarks> Read only. Returns an integer equal to one of the <tt>State</tt> method return values. </remarks>
public int SynthesizerState
{
get
{
if (System.Speech.Synthesis.SynthesizerState.Ready == this.ss.State)
{
return 1;
}
else if (System.Speech.Synthesis.SynthesizerState.Paused == this.ss.State)
{
return 2;
}
else if (System.Speech.Synthesis.SynthesizerState.Speaking == this.ss.State)
{
return 3;
}
else
{
return 4;
}
}
private set { }
}
/// <summary> Gets or sets the volume. </summary>
/// <remarks> An integer from 0 to 100. </remarks>
public int Volume
{
get
{
return this.ss.Volume;
}
set
{
this.ss.Volume = value;
}
}
/// <summary> Gets an object whose properties (Ready, Paused, and Speaking) provide values useful for comparing to <tt>SynthesizerState</tt>. </summary>
/// <returns> a SynthersizerStateT </returns>
public SynthesizerStateT State
{
get { return new SynthesizerStateT(); }
private set { }
}
}
/// <summary> Enumerates the synthesizer states. </summary>
/// <remarks> Not intended for use in VBScript. See <tt>SpeechSynthesis.State</tt>. </remarks>
[Guid("2650C2AB-2DF8-495F-AB4D-6C61BD463EA4")]
public class SynthesizerStateT
{
/// <summary> Constructor </summary>
public SynthesizerStateT() { }
/// <returns> 1 </returns>
public int Ready { get { return 1; } private set { } }
/// <returns> 2 </returns>
public int Paused { get { return 2; } private set { } }
/// <returns> 3 </returns>
public int Speaking { get { return 3; } private set { } }
/// <returns> 4 </returns>
public int Unexpected { get { return 4; } private set { } }
}
/// <summary> The COM interface for <tt>VBScripting.SpeechSynthesis</tt> </summary>
[Guid("2650C2AB-2BF8-495F-AB4D-6C61BD463EA4")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ISpeechSynthesis
{
/// <summary> </summary>
[DispId(1)]
void Speak(string text);
/// <summary> </summary>
[DispId(2)]
void SpeakAsync(string text);
/// <summary> </summary>
[DispId(3)]
void Pause();
/// <summary> </summary>
[DispId(4)]
void Resume();
/// <summary> </summary>
[DispId(5)]
object Voices(); // array
/// <summary> </summary>
[DispId(6)]
string Voice { get; set; }
/// <summary> </summary>
[DispId(7)]
void Dispose();
/// <summary> </summary>
[DispId(8)]
int SynthesizerState { get; }
/// <summary> </summary>
[DispId(9)]
SynthesizerStateT State { get; }
/// <summary> </summary>
[DispId(13)]
int Volume { get; set; }
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:[email protected])
// Klaus Potzesny (mailto:[email protected])
// David Stephensen (mailto:[email protected])
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Reflection;
using MigraDoc.DocumentObjectModel.IO;
using MigraDoc.DocumentObjectModel.Internals;
using MigraDoc.DocumentObjectModel.Visitors;
namespace MigraDoc.DocumentObjectModel.Tables
{
/// <summary>
/// Represents a row of a table.
/// </summary>
public class Row : DocumentObject, IVisitable
{
/// <summary>
/// Initializes a new instance of the Row class.
/// </summary>
public Row()
{
}
/// <summary>
/// Initializes a new instance of the Row class with the specified parent.
/// </summary>
internal Row(DocumentObject parent) : base(parent) { }
#region Methods
/// <summary>
/// Creates a deep copy of this object.
/// </summary>
public new Row Clone()
{
return (Row)DeepCopy();
}
/// <summary>
/// Implements the deep copy of the object.
/// </summary>
protected override object DeepCopy()
{
Row row = (Row)base.DeepCopy();
if (row.format != null)
{
row.format = row.format.Clone();
row.format.parent = row;
}
if (row.borders != null)
{
row.borders = row.borders.Clone();
row.borders.parent = row;
}
if (row.shading != null)
{
row.shading = row.shading.Clone();
row.shading.parent = row;
}
if (row.cells != null)
{
row.cells = row.cells.Clone();
row.cells.parent = row;
}
return row;
}
#endregion
#region Properties
/// <summary>
/// Gets the table the row belongs to.
/// </summary>
public Table Table
{
get
{
if (this.table == null)
{
Rows rws = this.Parent as Rows;
if (rws != null)
this.table = rws.Table;
}
return this.table;
}
}
Table table;
/// <summary>
/// Gets the index of the row. First row has index 0.
/// </summary>
public int Index
{
get
{
if (IsNull("index"))
{
Rows rws = this.parent as Rows;
SetValue("Index", rws.IndexOf(this));
}
return index;
}
}
[DV]
internal NInt index = NInt.NullValue;
/// <summary>
/// Gets a cell by its column index. The first cell has index 0.
/// </summary>
public Cell this[int index]
{
get { return Cells[index]; }
}
/// <summary>
/// Gets or sets the default style name for all cells of the row.
/// </summary>
public string Style
{
get { return this.style.Value; }
set { this.style.Value = value; }
}
[DV]
internal NString style = NString.NullValue;
/// <summary>
/// Gets the default ParagraphFormat for all cells of the row.
/// </summary>
public ParagraphFormat Format
{
get
{
if (this.format == null)
this.format = new ParagraphFormat(this);
return this.format;
}
set
{
SetParent(value);
this.format = value;
}
}
[DV]
internal ParagraphFormat format;
/// <summary>
/// Gets or sets the default vertical alignment for all cells of the row.
/// </summary>
public VerticalAlignment VerticalAlignment
{
get { return (VerticalAlignment)this.verticalAlignment.Value; }
set { this.verticalAlignment.Value = (int)value; }
}
[DV(Type = typeof(VerticalAlignment))]
internal NEnum verticalAlignment = NEnum.NullValue(typeof(VerticalAlignment));
/// <summary>
/// Gets or sets the height of the row.
/// </summary>
public Unit Height
{
get { return this.height; }
set { this.height = value; }
}
[DV]
internal Unit height = Unit.NullValue;
/// <summary>
/// Gets or sets the rule which is used to determine the height of the row.
/// </summary>
public RowHeightRule HeightRule
{
get { return (RowHeightRule)this.heightRule.Value; }
set { this.heightRule.Value = (int)value; }
}
[DV(Type = typeof(RowHeightRule))]
internal NEnum heightRule = NEnum.NullValue(typeof(RowHeightRule));
/// <summary>
/// Gets or sets the default value for all cells of the row.
/// </summary>
public Unit TopPadding
{
get { return this.topPadding; }
set { this.topPadding = value; }
}
[DV]
internal Unit topPadding = Unit.NullValue;
/// <summary>
/// Gets or sets the default value for all cells of the row.
/// </summary>
public Unit BottomPadding
{
get { return this.bottomPadding; }
set { this.bottomPadding = value; }
}
[DV]
internal Unit bottomPadding = Unit.NullValue;
/// <summary>
/// Gets or sets a value which define whether the row is a header.
/// </summary>
public bool HeadingFormat
{
get { return this.headingFormat.Value; }
set { this.headingFormat.Value = value; }
}
[DV]
internal NBool headingFormat = NBool.NullValue;
/// <summary>
/// Gets the default Borders object for all cells of the row.
/// </summary>
public Borders Borders
{
get
{
if (this.borders == null)
this.borders = new Borders(this);
return this.borders;
}
set
{
SetParent(value);
this.borders = value;
}
}
[DV]
internal Borders borders;
/// <summary>
/// Gets the default Shading object for all cells of the row.
/// </summary>
public Shading Shading
{
get
{
if (this.shading == null)
this.shading = new Shading(this);
return this.shading;
}
set
{
SetParent(value);
this.shading = value;
}
}
[DV]
internal Shading shading;
/// <summary>
/// Gets or sets the number of rows that should be
/// kept together with the current row in case of a page break.
/// </summary>
public int KeepWith
{
get { return this.keepWith.Value; }
set { this.keepWith.Value = value; }
}
[DV]
internal NInt keepWith = NInt.NullValue;
/// <summary>
/// Gets the Cells collection of the table.
/// </summary>
public Cells Cells
{
get
{
if (this.cells == null)
this.cells = new Cells(this);
return this.cells;
}
set
{
SetParent(value);
this.cells = value;
}
}
[DV]
internal Cells cells;
/// <summary>
/// Gets or sets a comment associated with this object.
/// </summary>
public string Comment
{
get { return this.comment.Value; }
set { this.comment.Value = value; }
}
[DV]
internal NString comment = NString.NullValue;
#endregion
#region Internal
/// <summary>
/// Converts Row into DDL.
/// </summary>
internal override void Serialize(Serializer serializer)
{
serializer.WriteComment(this.comment.Value);
serializer.WriteLine("\\row");
int pos = serializer.BeginAttributes();
if (this.style.Value != String.Empty)
serializer.WriteSimpleAttribute("Style", this.Style);
if (!this.IsNull("Format"))
this.format.Serialize(serializer, "Format", null);
if (!this.height.IsNull)
serializer.WriteSimpleAttribute("Height", this.Height);
if (!this.heightRule.IsNull)
serializer.WriteSimpleAttribute("HeightRule", this.HeightRule);
if (!this.topPadding.IsNull)
serializer.WriteSimpleAttribute("TopPadding", this.TopPadding);
if (!this.bottomPadding.IsNull)
serializer.WriteSimpleAttribute("BottomPadding", this.BottomPadding);
if (!this.headingFormat.IsNull)
serializer.WriteSimpleAttribute("HeadingFormat", this.HeadingFormat);
if (!this.verticalAlignment.IsNull)
serializer.WriteSimpleAttribute("VerticalAlignment", this.VerticalAlignment);
if (!this.keepWith.IsNull)
serializer.WriteSimpleAttribute("KeepWith", this.KeepWith);
//Borders & Shading
if (!this.IsNull("Borders"))
this.borders.Serialize(serializer, null);
if (!this.IsNull("Shading"))
this.shading.Serialize(serializer);
serializer.EndAttributes(pos);
serializer.BeginContent();
if (!IsNull("Cells"))
this.cells.Serialize(serializer);
serializer.EndContent();
}
/// <summary>
/// Allows the visitor object to visit the document object and it's child objects.
/// </summary>
void IVisitable.AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren)
{
visitor.VisitRow(this);
foreach (Cell cell in this.cells)
((IVisitable)cell).AcceptVisitor(visitor, visitChildren);
}
/// <summary>
/// Returns the meta object of this instance.
/// </summary>
internal override Meta Meta
{
get
{
if (meta == null)
meta = new Meta(typeof(Row));
return meta;
}
}
static Meta meta;
#endregion
}
}
| |
// Python Tools for Visual Studio
// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
namespace Microsoft.PythonTools.Debugger {
/// <summary>
/// Handles all interactions with a Python process which is being debugged.
/// </summary>
class PythonProcess : IDisposable {
private static Random _portGenerator = new Random();
private readonly Process _process;
private readonly Dictionary<long, PythonThread> _threads = new Dictionary<long, PythonThread>();
private readonly Dictionary<int, PythonBreakpoint> _breakpoints = new Dictionary<int, PythonBreakpoint>();
private readonly IdDispenser _ids = new IdDispenser();
private readonly AutoResetEvent _lineEvent = new AutoResetEvent(false); // set when result of setting current line returns
private readonly Dictionary<int, CompletionInfo> _pendingExecutes = new Dictionary<int, CompletionInfo>();
private readonly Dictionary<int, ChildrenInfo> _pendingChildEnums = new Dictionary<int, ChildrenInfo>();
private readonly Dictionary<int, TaskCompletionSource<int>> _pendingGetHitCountRequests = new Dictionary<int, TaskCompletionSource<int>>();
private readonly List<TaskCompletionSource<int>> _pendingGetThreadFramesRequests = new List<TaskCompletionSource<int>>();
private readonly object _pendingGetHitCountRequestsLock = new object();
private readonly object _pendingGetThreadFramesRequestsLock = new object();
private readonly PythonLanguageVersion _langVersion;
private readonly Guid _processGuid = Guid.NewGuid();
private readonly List<string[]> _dirMapping;
private readonly bool _delayUnregister;
private readonly object _streamLock = new object();
private readonly Dictionary<string, PythonAst> _astCache = new Dictionary<string, PythonAst>();
private readonly object _astCacheLock = new object();
private int _pid;
private bool _sentExited, _startedProcess;
private Stream _stream;
private int _breakpointCounter;
private bool _setLineResult; // contains result of attempting to set the current line of a frame
private bool _createdFirstThread;
private bool _stoppedForException;
private int _defaultBreakMode;
private ICollection<KeyValuePair<string, int>> _breakOn;
private bool _handleEntryPointHit = true;
private bool _handleEntryPointBreakpoint = true;
protected PythonProcess(int pid, PythonLanguageVersion languageVersion) {
_pid = pid;
_langVersion = languageVersion;
_dirMapping = new List<string[]>();
}
private PythonProcess(int pid, PythonDebugOptions debugOptions) {
_pid = pid;
_process = Process.GetProcessById(pid);
_process.EnableRaisingEvents = true;
_process.Exited += new EventHandler(_process_Exited);
ListenForConnection();
using (var result = DebugAttach.AttachAD7(pid, DebugConnectionListener.ListenerPort, _processGuid, debugOptions.ToString())) {
if (result.Error != ConnErrorMessages.None) {
throw new ConnectionException(result.Error);
}
_langVersion = (PythonLanguageVersion)result.LanguageVersion;
if (!result.AttachDone.WaitOne(20000)) {
throw new ConnectionException(ConnErrorMessages.TimeOut);
}
}
}
private PythonProcess(Stream stream, int pid, PythonLanguageVersion version, PythonDebugOptions debugOptions) {
_pid = pid;
_process = Process.GetProcessById(pid);
_process.EnableRaisingEvents = true;
_process.Exited += new EventHandler(_process_Exited);
_delayUnregister = true;
ListenForConnection();
stream.WriteInt32(DebugConnectionListener.ListenerPort);
stream.WriteString(_processGuid.ToString());
stream.WriteString(debugOptions.ToString());
}
public PythonProcess(PythonLanguageVersion languageVersion, string exe, string args, string dir, string env, string interpreterOptions, PythonDebugOptions options = PythonDebugOptions.None, List<string[]> dirMapping = null)
: this(0, languageVersion) {
ListenForConnection();
if (dir.EndsWith("\\")) {
dir = dir.Substring(0, dir.Length - 1);
}
_dirMapping = dirMapping;
var processInfo = new ProcessStartInfo(exe);
processInfo.CreateNoWindow = (options & PythonDebugOptions.CreateNoWindow) != 0;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardOutput = false;
processInfo.RedirectStandardInput = (options & PythonDebugOptions.RedirectInput) != 0;
processInfo.Arguments =
(String.IsNullOrWhiteSpace(interpreterOptions) ? "" : (interpreterOptions + " ")) +
"\"" + PythonToolsInstallPath.GetFile("visualstudio_py_launcher.py") + "\" " +
"\"" + dir + "\" " +
" " + DebugConnectionListener.ListenerPort + " " +
" " + _processGuid + " " +
"\"" + options + "\" " +
args;
if (env != null) {
string[] envValues = env.Split('\0');
foreach (var curValue in envValues) {
string[] nameValue = curValue.Split(new[] { '=' }, 2);
if (nameValue.Length == 2 && !String.IsNullOrWhiteSpace(nameValue[0])) {
processInfo.EnvironmentVariables[nameValue[0]] = nameValue[1];
}
}
}
Debug.WriteLine(String.Format("Launching: {0} {1}", processInfo.FileName, processInfo.Arguments));
_process = new Process();
_process.StartInfo = processInfo;
_process.EnableRaisingEvents = true;
_process.Exited += new EventHandler(_process_Exited);
}
public static PythonProcess Attach(int pid, PythonDebugOptions debugOptions = PythonDebugOptions.None) {
return new PythonProcess(pid, debugOptions);
}
public static PythonProcess AttachRepl(Stream stream, int pid, PythonLanguageVersion version, PythonDebugOptions debugOptions = PythonDebugOptions.None) {
return new PythonProcess(stream, pid, version, debugOptions);
}
#region Public Process API
public int Id {
get {
return _pid;
}
}
public Guid ProcessGuid {
get {
return _processGuid;
}
}
public void Start(bool startListening = true) {
_process.Start();
_startedProcess = true;
_pid = _process.Id;
if (startListening) {
StartListening();
}
}
private void ListenForConnection() {
DebugConnectionListener.RegisterProcess(_processGuid, this);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
internal void AddDirMapping(string[] mapping) {
if (mapping != null) {
_dirMapping.Add(mapping);
}
}
protected virtual void Dispose(bool disposing) {
DebugConnectionListener.UnregisterProcess(_processGuid);
if (disposing) {
lock (_streamLock) {
if (_stream != null) {
_stream.Dispose();
}
if (_process != null) {
_process.Dispose();
}
_lineEvent.Dispose();
}
}
}
~PythonProcess() {
Dispose(false);
}
void _process_Exited(object sender, EventArgs e) {
// TODO: Abort all pending operations
if (!_sentExited) {
_sentExited = true;
var exited = ProcessExited;
if (exited != null) {
int exitCode;
try {
exitCode = (_process != null && _process.HasExited) ? _process.ExitCode : -1;
} catch (InvalidOperationException) {
// debug attach, we didn't start the process...
exitCode = -1;
}
exited(this, new ProcessExitedEventArgs(exitCode));
}
}
}
public void WaitForExit() {
if (_process == null) {
throw new InvalidOperationException();
}
_process.WaitForExit();
}
public bool WaitForExit(int milliseconds) {
if (_process == null) {
throw new InvalidOperationException();
}
return _process.WaitForExit(milliseconds);
}
public void Terminate() {
if (_process != null && !_process.HasExited) {
_process.Kill();
}
if (_stream != null) {
_stream.Dispose();
}
}
public bool HasExited {
get {
return _process != null && _process.HasExited;
}
}
/// <summary>
/// Breaks into the process.
/// </summary>
public void Break() {
DebugWriteCommand("BreakAll");
lock(_streamLock) {
_stream.Write(BreakAllCommandBytes);
}
}
[Conditional("DEBUG")]
private void DebugWriteCommand(string commandName) {
Debug.WriteLine("PythonDebugger " + _processGuid + " Sending Command " + commandName);
}
public void Resume() {
// Resume must be from entry point or past
_handleEntryPointHit = false;
_stoppedForException = false;
DebugWriteCommand("ResumeAll");
lock (_streamLock) {
if (_stream != null) {
_stream.Write(ResumeAllCommandBytes);
}
}
}
public void AutoResumeThread(long threadId) {
if (_handleEntryPointHit) {
// Handle entrypoint breakpoint/tracepoint
var thread = _threads[threadId];
if (_handleEntryPointBreakpoint) {
_handleEntryPointBreakpoint = false;
var frames = thread.Frames;
if (frames != null && frames.Count() > 0) {
var frame = frames[0];
if (frame != null) {
foreach (var breakpoint in _breakpoints.Values) {
// UNDONE Fuzzy filename matching
if (breakpoint.LineNo == frame.StartLine && breakpoint.Filename.Equals(frame.FileName, StringComparison.OrdinalIgnoreCase)) {
// UNDONE: Conditional breakpoint/tracepoint
var breakpointHit = BreakpointHit;
if (breakpointHit != null) {
breakpointHit(this, new BreakpointHitEventArgs(breakpoint, thread));
return;
}
}
}
}
}
}
_handleEntryPointHit = false;
var entryPointHit = EntryPointHit;
if (entryPointHit != null) {
entryPointHit(this, new ThreadEventArgs(thread));
return;
}
}
SendAutoResumeThread(threadId);
}
public bool StoppedForException {
get {
return _stoppedForException;
}
}
public void Continue() {
Resume();
}
public PythonBreakpoint AddBreakPoint(
string filename,
int lineNo,
PythonBreakpointConditionKind conditionKind = PythonBreakpointConditionKind.Always,
string condition = "",
PythonBreakpointPassCountKind passCountKind = PythonBreakpointPassCountKind.Always,
int passCount = 0
) {
int id = _breakpointCounter++;
var res = new PythonBreakpoint(this, filename, lineNo, conditionKind, condition, passCountKind, passCount, id);
_breakpoints[id] = res;
return res;
}
public PythonBreakpoint AddDjangoBreakPoint(string filename, int lineNo) {
int id = _breakpointCounter++;
var res = new PythonBreakpoint(this, filename, lineNo, PythonBreakpointConditionKind.Always, "", PythonBreakpointPassCountKind.Always, 0 , id, true);
_breakpoints[id] = res;
return res;
}
public PythonLanguageVersion LanguageVersion {
get {
return _langVersion;
}
}
public void SetExceptionInfo(int defaultBreakOnMode, IEnumerable<KeyValuePair<string, int>> breakOn) {
lock (_streamLock) {
if (_stream != null) {
SendExceptionInfo(defaultBreakOnMode, breakOn);
} else {
_breakOn = breakOn.ToArray();
_defaultBreakMode = defaultBreakOnMode;
}
}
}
private void SendExceptionInfo(int defaultBreakOnMode, IEnumerable<KeyValuePair<string, int>> breakOn) {
lock (_streamLock) {
_stream.Write(SetExceptionInfoCommandBytes);
_stream.WriteInt32(defaultBreakOnMode);
_stream.WriteInt32(breakOn.Count());
foreach (var item in breakOn) {
_stream.WriteInt32(item.Value);
_stream.WriteString(item.Key);
}
}
}
#endregion
#region Debuggee Communcation
internal void Connect(Stream stream) {
Debug.WriteLine("Process Connected: " + _processGuid);
EventHandler connected;
lock (_streamLock) {
_stream = stream;
if (_breakOn != null) {
SendExceptionInfo(_defaultBreakMode, _breakOn);
}
// This must be done under the lock so that any handlers that are added after we assigned _stream
// above won't get called twice, once from Connected add handler, and the second time below.
connected = _connected;
}
if (!_delayUnregister) {
Unregister();
}
if (connected != null) {
connected(this, EventArgs.Empty);
}
}
internal void Unregister() {
DebugConnectionListener.UnregisterProcess(_processGuid);
}
/// <summary>
/// Starts listening for debugger communication. Can be called after Start
/// to give time to attach to debugger events.
/// </summary>
public void StartListening() {
var debuggerThread = new Thread(DebugEventThread);
debuggerThread.Name = "Python Debugger Thread " + _processGuid;
debuggerThread.Start();
}
private void DebugEventThread() {
Debug.WriteLine("DebugEvent Thread Started " + _processGuid);
try {
while ((_process == null || !_process.HasExited) && _stream == null) {
// wait for connection...
System.Threading.Thread.Sleep(10);
}
} catch (InvalidOperationException) {
// Process termination - let any listeners know
_process_Exited(this, EventArgs.Empty);
return;
} catch (System.ComponentModel.Win32Exception) {
// Process termination - let any listeners know
_process_Exited(this, EventArgs.Empty);
return;
}
try {
while (true) {
Stream stream = _stream;
if (stream == null) {
break;
}
string cmd = stream.ReadAsciiString(4);
Debug.WriteLine(String.Format("Received Debugger command: {0} ({1})", cmd, _processGuid));
switch (cmd) {
case "EXCP": HandleException(stream); break;
case "EXC2": HandleRichException(stream); break;
case "BRKH": HandleBreakPointHit(stream); break;
case "NEWT": HandleThreadCreate(stream); break;
case "EXTT": HandleThreadExit(stream); break;
case "MODL": HandleModuleLoad(stream); break;
case "STPD": HandleStepDone(stream); break;
case "BRKS": HandleBreakPointSet(stream); break;
case "BRKF": HandleBreakPointFailed(stream); break;
case "BKHC": HandleBreakPointHitCount(stream); break;
case "LOAD": HandleProcessLoad(stream); break;
case "THRF": HandleThreadFrameList(stream); break;
case "EXCR": HandleExecutionResult(stream); break;
case "EXCE": HandleExecutionException(stream); break;
case "ASBR": HandleAsyncBreak(stream); break;
case "SETL": HandleSetLineResult(stream); break;
case "CHLD": HandleEnumChildren(stream); break;
case "OUTP": HandleDebuggerOutput(stream); break;
case "REQH": HandleRequestHandlers(stream); break;
case "DETC": _process_Exited(this, EventArgs.Empty); break; // detach, report process exit
case "LAST": HandleLast(stream); break;
}
}
} catch (IOException) {
} catch (ObjectDisposedException ex) {
// Socket or stream have been disposed
Debug.Assert(
ex.ObjectName == typeof(NetworkStream).FullName ||
ex.ObjectName == typeof(Socket).FullName,
"Accidentally handled ObjectDisposedException(" + ex.ObjectName + ")"
);
}
// If the event thread ends, and the process is not controlled by the debugger (e.g. in remote scenarios, where there's no process),
// make sure that we report ProcessExited event. If the thread has ended gracefully, we have already done this when handling DETC,
// so it's a no-op. But if connection broke down unexpectedly, no-one knows yet, so we need to tell them.
if (!_startedProcess) {
_process_Exited(this, EventArgs.Empty);
}
}
private static string ToDottedNameString(Expression expr, PythonAst ast) {
NameExpression name;
MemberExpression member;
ParenthesisExpression paren;
if ((name = expr as NameExpression) != null) {
return name.Name;
} else if ((member = expr as MemberExpression) != null) {
while (member.Target is MemberExpression) {
member = (MemberExpression)member.Target;
}
if (member.Target is NameExpression) {
return expr.ToCodeString(ast);
}
} else if ((paren = expr as ParenthesisExpression) != null) {
return ToDottedNameString(paren.Expression, ast);
}
return null;
}
internal IList<PythonThread> GetThreads() {
List<PythonThread> threads = new List<PythonThread>();
foreach (var thread in _threads.Values) {
threads.Add(thread);
}
return threads;
}
internal PythonAst GetAst(string filename) {
PythonAst ast;
lock (_astCacheLock) {
if (_astCache.TryGetValue(filename, out ast)) {
return ast;
}
}
try {
using (var source = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
ast = Parser.CreateParser(source, LanguageVersion).ParseFile();
}
} catch (ArgumentException) {
} catch (IOException) {
} catch (UnauthorizedAccessException) {
} catch (NotSupportedException) {
} catch (System.Security.SecurityException) {
}
lock (_astCacheLock) {
_astCache[filename] = ast;
}
return ast;
}
internal IList<Tuple<int, int, IList<string>>> GetHandledExceptionRanges(string filename) {
PythonAst ast;
TryHandlerWalker walker = new TryHandlerWalker();
var statements = new List<Tuple<int, int, IList<string>>>();
try {
ast = GetAst(filename);
if (ast == null) {
return statements;
}
ast.Walk(walker);
} catch (Exception ex) {
Debug.WriteLine("Exception in GetHandledExceptionRanges:");
Debug.WriteLine(string.Format("Filename: {0}", filename));
Debug.WriteLine(ex);
return statements;
}
foreach (var statement in walker.Statements) {
int start = statement.GetStart(ast).Line;
int end = statement.Body.GetEnd(ast).Line + 1;
var expressions = new List<string>();
if (statement.Handlers == null) {
if (statement.Finally != null) {
// This is a try/finally block without an except, which
// means that no exceptions are handled.
continue;
} else {
// If Handlers and Finally are null, there was probably
// a parser error. We assume all exceptions are handled
// by default, to avoid bothering the user too much, so
// handle everything here since we can't be more
// accurate.
expressions.Add("*");
}
} else {
foreach (var handler in statement.Handlers) {
Expression expr = handler.Test;
TupleExpression tuple;
if (expr == null) {
expressions.Clear();
expressions.Add("*");
break;
} else if ((tuple = handler.Test as TupleExpression) != null) {
foreach (var e in tuple.Items) {
var text = ToDottedNameString(e, ast);
if (text != null) {
expressions.Add(text);
}
}
} else {
var text = ToDottedNameString(expr, ast);
if (text != null) {
expressions.Add(text);
}
}
}
}
if (expressions.Count > 0) {
statements.Add(new Tuple<int, int, IList<string>>(start, end, expressions));
}
}
return statements;
}
private void HandleRequestHandlers(Stream stream) {
string filename = stream.ReadString();
Debug.WriteLine("Exception handlers requested for: " + filename);
var statements = GetHandledExceptionRanges(filename);
lock (_streamLock) {
stream.Write(SetExceptionHandlerInfoCommandBytes);
stream.WriteString(filename);
stream.WriteInt32(statements.Count);
foreach (var t in statements) {
stream.WriteInt32(t.Item1);
stream.WriteInt32(t.Item2);
foreach (var expr in t.Item3) {
stream.WriteString(expr);
}
stream.WriteString("-");
}
}
}
private void HandleDebuggerOutput(Stream stream) {
long tid = stream.ReadInt64();
string output = stream.ReadString();
PythonThread thread;
if (_threads.TryGetValue(tid, out thread)) {
var outputEvent = DebuggerOutput;
if (outputEvent != null) {
outputEvent(this, new OutputEventArgs(thread, output));
}
}
}
private void HandleSetLineResult(Stream stream) {
int res = stream.ReadInt32();
long tid = stream.ReadInt64();
int newLine = stream.ReadInt32();
_setLineResult = res != 0;
if (_setLineResult) {
var frame = _threads[tid].Frames.FirstOrDefault();
if (frame != null) {
frame.LineNo = newLine;
} else {
Debug.Fail("SETL result received, but there is no frame to update");
}
}
_lineEvent.Set();
}
private void HandleAsyncBreak(Stream stream) {
long tid = stream.ReadInt64();
var thread = _threads[tid];
var asyncBreak = AsyncBreakComplete;
Debug.WriteLine("Received async break command from thread {0}", tid);
if (asyncBreak != null) {
asyncBreak(this, new ThreadEventArgs(thread));
}
}
private void HandleExecutionException(Stream stream) {
int execId = stream.ReadInt32();
CompletionInfo completion;
lock (_pendingExecutes) {
if (_pendingExecutes.TryGetValue(execId, out completion)) {
_pendingExecutes.Remove(execId);
_ids.Free(execId);
} else {
Debug.Fail("Received execution result with unknown execution ID " + execId);
}
}
string exceptionText = stream.ReadString();
if (completion != null) {
completion.Completion(new PythonEvaluationResult(this, exceptionText, completion.Text, completion.Frame));
}
}
private void HandleExecutionResult(Stream stream) {
int execId = stream.ReadInt32();
CompletionInfo completion;
lock (_pendingExecutes) {
if (_pendingExecutes.TryGetValue(execId, out completion)) {
_pendingExecutes.Remove(execId);
_ids.Free(execId);
} else {
Debug.Fail("Received execution result with unknown execution ID " + execId);
}
}
Debug.WriteLine("Received execution request {0}", execId);
if (completion != null) {
var evalResult = ReadPythonObject(stream, completion.Text, null, completion.Frame);
completion.Completion(evalResult);
} else {
// Passing null for parameters other than stream is okay as long
// as we drop the result.
ReadPythonObject(stream, null, null, null);
}
}
private void HandleEnumChildren(Stream stream) {
int execId = stream.ReadInt32();
ChildrenInfo completion;
lock (_pendingChildEnums) {
if (_pendingChildEnums.TryGetValue(execId, out completion)) {
_pendingChildEnums.Remove(execId);
_ids.Free(execId);
} else {
Debug.Fail("Received enum children result with unknown execution ID " + execId);
}
}
var children = new PythonEvaluationResult[stream.ReadInt32()];
for (int i = 0; i < children.Length; i++) {
string childName = stream.ReadString();
string childExpr = stream.ReadString();
children[i] = ReadPythonObject(stream, childExpr, childName, completion != null ? completion.Frame : null);
}
if (completion != null) {
completion.Completion(children);
}
}
private PythonEvaluationResult ReadPythonObject(Stream stream, string expr, string childName, PythonStackFrame frame) {
string objRepr = stream.ReadString();
string hexRepr = stream.ReadString();
string typeName = stream.ReadString();
long length = stream.ReadInt64();
var flags = (PythonEvaluationResultFlags)stream.ReadInt32();
if (!flags.HasFlag(PythonEvaluationResultFlags.Raw) && ((typeName == "unicode" && LanguageVersion.Is2x()) || (typeName == "str" && LanguageVersion.Is3x()))) {
objRepr = objRepr.FixupEscapedUnicodeChars();
}
if (typeName == "bool") {
hexRepr = null;
}
return new PythonEvaluationResult(this, objRepr, hexRepr, typeName, length, expr, childName, frame, flags);
}
private void HandleThreadFrameList(Stream stream) {
// list of thread frames
var frames = new List<PythonStackFrame>();
long tid = stream.ReadInt64();
PythonThread thread;
_threads.TryGetValue(tid, out thread);
var threadName = stream.ReadString();
int frameCount = stream.ReadInt32();
for (int i = 0; i < frameCount; i++) {
int startLine = stream.ReadInt32();
int endLine = stream.ReadInt32();
int lineNo = stream.ReadInt32();
string frameName = stream.ReadString();
string filename = stream.ReadString();
int argCount = stream.ReadInt32();
var frameKind = (FrameKind)stream.ReadInt32();
PythonStackFrame frame = null;
if (thread != null) {
switch (frameKind) {
case FrameKind.Django:
string sourceFile = stream.ReadString();
var sourceLine = stream.ReadInt32();
frame = new DjangoStackFrame(thread, frameName, filename, startLine, endLine, lineNo, argCount, i, sourceFile, sourceLine);
break;
default:
frame = new PythonStackFrame(thread, frameName, filename, startLine, endLine, lineNo, argCount, i, frameKind);
break;
}
}
int varCount = stream.ReadInt32();
PythonEvaluationResult[] variables = new PythonEvaluationResult[varCount];
for (int j = 0; j < variables.Length; j++) {
string name = stream.ReadString();
if (frame != null) {
variables[j] = ReadPythonObject(stream, name, name, frame);
}
}
if (frame != null) {
frame.SetVariables(variables);
frames.Add(frame);
}
}
Debug.WriteLine("Received frames for thread {0}", tid);
if (thread != null) {
thread.Frames = frames;
if (threadName != null) {
thread.Name = threadName;
}
}
lock(_pendingGetThreadFramesRequestsLock) {
foreach (TaskCompletionSource<int> tcs in _pendingGetThreadFramesRequests) {
tcs.SetResult(0);
}
_pendingGetThreadFramesRequests.Clear();
}
}
private void HandleProcessLoad(Stream stream) {
Debug.WriteLine("Process loaded " + _processGuid);
// process is loaded, no user code has run
long threadId = stream.ReadInt64();
var thread = _threads[threadId];
var loaded = ProcessLoaded;
if (loaded != null) {
loaded(this, new ThreadEventArgs(thread));
}
}
private void HandleBreakPointFailed(Stream stream) {
// break point failed to set
int id = stream.ReadInt32();
var brkEvent = BreakpointBindFailed;
PythonBreakpoint breakpoint;
if (brkEvent != null && _breakpoints.TryGetValue(id, out breakpoint)) {
brkEvent(this, new BreakpointEventArgs(breakpoint));
}
}
private void HandleBreakPointSet(Stream stream) {
// break point successfully set
int id = stream.ReadInt32();
PythonBreakpoint unbound;
if (_breakpoints.TryGetValue(id, out unbound)) {
var brkEvent = BreakpointBindSucceeded;
if (brkEvent != null) {
brkEvent(this, new BreakpointEventArgs(unbound));
}
}
}
private void HandleBreakPointHitCount(Stream stream) {
// break point hit count retrieved
int reqId = stream.ReadInt32();
int hitCount = stream.ReadInt32();
TaskCompletionSource<int> tcs;
lock (_pendingGetHitCountRequestsLock) {
if (_pendingGetHitCountRequests.TryGetValue(reqId, out tcs)) {
_pendingGetHitCountRequests.Remove(reqId);
}
}
if (tcs != null) {
tcs.SetResult(hitCount);
} else {
Debug.Fail("Breakpoint hit count response for unknown request ID.");
}
}
private void HandleStepDone(Stream stream) {
// stepping done
long threadId = stream.ReadInt64();
var stepComp = StepComplete;
if (stepComp != null) {
stepComp(this, new ThreadEventArgs(_threads[threadId]));
}
}
private void HandleModuleLoad(Stream stream) {
// module load
int moduleId = stream.ReadInt32();
string filename = stream.ReadString();
if (filename != null) {
Debug.WriteLine(String.Format("Module Loaded ({0}): {1}", moduleId, filename));
var module = new PythonModule(moduleId, filename);
var loaded = ModuleLoaded;
if (loaded != null) {
loaded(this, new ModuleLoadedEventArgs(module));
}
}
}
private void HandleThreadExit(Stream stream) {
// thread exit
long threadId = stream.ReadInt64();
PythonThread thread;
if (_threads.TryGetValue(threadId, out thread)) {
var exited = ThreadExited;
if (exited != null) {
exited(this, new ThreadEventArgs(thread));
}
_threads.Remove(threadId);
Debug.WriteLine("Thread exited, {0} active threads", _threads.Count);
}
}
private void HandleThreadCreate(Stream stream) {
// new thread
long threadId = stream.ReadInt64();
var thread = _threads[threadId] = new PythonThread(this, threadId, _createdFirstThread);
_createdFirstThread = true;
var created = ThreadCreated;
if (created != null) {
created(this, new ThreadEventArgs(thread));
}
}
private void HandleBreakPointHit(Stream stream) {
int breakId = stream.ReadInt32();
long threadId = stream.ReadInt64();
var brkEvent = BreakpointHit;
PythonBreakpoint unboundBreakpoint;
if (brkEvent != null) {
if (_breakpoints.TryGetValue(breakId, out unboundBreakpoint)) {
brkEvent(this, new BreakpointHitEventArgs(unboundBreakpoint, _threads[threadId]));
} else {
SendResumeThread(threadId);
}
}
}
private void HandleException(Stream stream) {
string typeName = stream.ReadString();
long tid = stream.ReadInt64();
int breakType = stream.ReadInt32();
string desc = stream.ReadString();
if (typeName != null && desc != null) {
Debug.WriteLine("Exception: " + desc);
ExceptionRaised?.Invoke(this, new ExceptionRaisedEventArgs(
_threads[tid],
new PythonException {
TypeName = typeName,
FormattedDescription = desc,
UserUnhandled = (breakType == 1) /* BREAK_TYPE_UNHANLDED */
}
));
}
_stoppedForException = true;
}
private void HandleRichException(Stream stream) {
var exc = new PythonException();
long tid = stream.ReadInt64();
int count = stream.ReadInt32();
while (--count >= 0) {
string key = stream.ReadString();
string value = stream.ReadString();
exc.SetValue(this, key, value);
}
if (tid != 0) {
Debug.WriteLine("Exception: " + exc.FormattedDescription ?? exc.ExceptionMessage ?? exc.TypeName);
ExceptionRaised?.Invoke(this, new ExceptionRaisedEventArgs(_threads[tid], exc));
_stoppedForException = true;
}
}
private static string CommandtoString(byte[] cmd_buffer) {
return new string(new char[] { (char)cmd_buffer[0], (char)cmd_buffer[1], (char)cmd_buffer[2], (char)cmd_buffer[3] });
}
private void HandleLast(Stream stream) {
DebugWriteCommand("LAST ack");
lock (_streamLock) {
stream.Write(LastAckCommandBytes);
}
}
internal void SendStepOut(long threadId) {
DebugWriteCommand("StepOut");
lock (_streamLock) {
_stream.Write(StepOutCommandBytes);
_stream.WriteInt64(threadId);
}
}
internal void SendStepOver(long threadId) {
DebugWriteCommand("StepOver");
lock (_streamLock) {
_stream.Write(StepOverCommandBytes);
_stream.WriteInt64(threadId);
}
}
internal void SendStepInto(long threadId) {
DebugWriteCommand("StepInto");
lock (_streamLock) {
_stream.Write(StepIntoCommandBytes);
_stream.WriteInt64(threadId);
}
}
public void SendResumeThread(long threadId) {
_stoppedForException = false;
DebugWriteCommand("ResumeThread");
lock (_streamLock) {
// race w/ removing the breakpoint, let the thread continue
_stream.Write(ResumeThreadCommandBytes);
_stream.WriteInt64(threadId);
}
}
public void SendAutoResumeThread(long threadId) {
_stoppedForException = false;
DebugWriteCommand("AutoResumeThread");
lock (_streamLock) {
_stream.Write(AutoResumeThreadCommandBytes);
_stream.WriteInt64(threadId);
}
}
public void SendClearStepping(long threadId) {
DebugWriteCommand("ClearStepping");
lock (_streamLock) {
// race w/ removing the breakpoint, let the thread continue
_stream.Write(ClearSteppingCommandBytes);
_stream.WriteInt64(threadId);
}
}
public Task GetThreadFramesAsync(long threadId) {
DebugWriteCommand("GetThreadFrames");
var tcs = new TaskCompletionSource<int>();
lock (_pendingGetThreadFramesRequestsLock) {
_pendingGetThreadFramesRequests.Add(tcs);
}
lock (_streamLock) {
_stream.Write(GetThreadFramesCommandBytes);
_stream.WriteInt64(threadId);
}
return tcs.Task;
}
public void Detach() {
DebugWriteCommand("Detach");
try {
lock (_streamLock) {
_stream.Write(DetachCommandBytes);
}
} catch (IOException) {
// socket is closed after we send detach
}
}
internal void BindBreakpoint(PythonBreakpoint breakpoint) {
DebugWriteCommand(String.Format("Bind Breakpoint IsDjango: {0}", breakpoint.IsDjangoBreakpoint));
lock (_streamLock) {
if (breakpoint.IsDjangoBreakpoint) {
_stream.Write(AddDjangoBreakPointCommandBytes);
} else {
_stream.Write(SetBreakPointCommandBytes);
}
_stream.WriteInt32(breakpoint.Id);
_stream.WriteInt32(breakpoint.LineNo);
_stream.WriteString(MapFile(breakpoint.Filename));
if (!breakpoint.IsDjangoBreakpoint) {
SendCondition(breakpoint);
SendPassCount(breakpoint);
}
}
}
/// <summary>
/// Maps a filename from the debugger machine to the debugge machine to vice versa.
///
/// The file mapping information is provided by our options when the debugger is started.
///
/// This is used so that we can use the files local on the developers machine which have
/// for setting breakpoints and viewing source code even though the files have been
/// deployed to a remote machine. For example the user may have:
///
/// C:\Users\Me\Documents\MyProject\Fob.py
///
/// which is deployed to
///
/// \\mycluster\deploydir\MyProject\Fob.py
///
/// We want the user to be working w/ the local project files during development but
/// want to set break points in the cluster deployment share.
/// </summary>
internal string MapFile(string file, bool toDebuggee = true) {
if (_dirMapping != null) {
foreach (var mappingInfo in _dirMapping) {
string mapFrom = mappingInfo[toDebuggee ? 0 : 1];
string mapTo = mappingInfo[toDebuggee ? 1 : 0];
if (file.StartsWith(mapFrom, StringComparison.OrdinalIgnoreCase)) {
int len = mapFrom.Length;
if (!mappingInfo[0].EndsWith("\\")) {
len++;
}
string newFile = Path.Combine(mapTo, file.Substring(len));
Debug.WriteLine("Filename mapped from {0} to {1}", file, newFile);
return newFile;
}
}
}
return file;
}
private void SendCondition(PythonBreakpoint breakpoint) {
DebugWriteCommand("Send BP Condition");
_stream.WriteInt32((int)breakpoint.ConditionKind);
_stream.WriteString(breakpoint.Condition ?? "");
}
internal void SetBreakPointCondition(PythonBreakpoint breakpoint) {
DebugWriteCommand("Set BP Condition");
lock (_streamLock) {
_stream.Write(SetBreakPointConditionCommandBytes);
_stream.WriteInt32(breakpoint.Id);
SendCondition(breakpoint);
}
}
private void SendPassCount(PythonBreakpoint breakpoint) {
DebugWriteCommand("Send BP pass count");
_stream.WriteInt32((int)breakpoint.PassCountKind);
_stream.WriteInt32(breakpoint.PassCount);
}
internal void SetBreakPointPassCount(PythonBreakpoint breakpoint) {
DebugWriteCommand("Set BP pass count");
lock (_streamLock) {
_stream.Write(SetBreakPointPassCountCommandBytes);
_stream.WriteInt32(breakpoint.Id);
SendPassCount(breakpoint);
}
}
internal void SetBreakPointHitCount(PythonBreakpoint breakpoint, int count) {
DebugWriteCommand("Set BP hit count");
lock (_streamLock) {
_stream.Write(SetBreakPointHitCountCommandBytes);
_stream.WriteInt32(breakpoint.Id);
_stream.WriteInt32(count);
}
}
internal Task<int> GetBreakPointHitCountAsync(PythonBreakpoint breakpoint) {
DebugWriteCommand("Get BP hit count");
int reqId = _ids.Allocate();
var tcs = new TaskCompletionSource<int>();
lock (_pendingGetHitCountRequestsLock) {
_pendingGetHitCountRequests[reqId] = tcs;
}
lock (_streamLock) {
_stream.Write(GetBreakPointHitCountCommandBytes);
_stream.WriteInt32(reqId);
_stream.WriteInt32(breakpoint.Id);
}
return tcs.Task;
}
internal void ExecuteText(string text, PythonEvaluationResultReprKind reprKind, PythonStackFrame pythonStackFrame, Action<PythonEvaluationResult> completion) {
int executeId = _ids.Allocate();
DebugWriteCommand("ExecuteText to thread " + pythonStackFrame.Thread.Id + " " + executeId);
lock (_pendingExecutes) {
_pendingExecutes[executeId] = new CompletionInfo(completion, text, pythonStackFrame);
}
lock (_streamLock) {
_stream.Write(ExecuteTextCommandBytes);
_stream.WriteString(text);
_stream.WriteInt64(pythonStackFrame.Thread.Id);
_stream.WriteInt32(pythonStackFrame.FrameId);
_stream.WriteInt32(executeId);
_stream.WriteInt32((int)pythonStackFrame.Kind);
_stream.WriteInt32((int)reprKind);
}
}
internal void EnumChildren(string text, PythonStackFrame pythonStackFrame, Action<PythonEvaluationResult[]> completion) {
DebugWriteCommand("Enum Children");
int executeId = _ids.Allocate();
lock (_pendingChildEnums) {
_pendingChildEnums[executeId] = new ChildrenInfo(completion, text, pythonStackFrame);
}
lock (_streamLock) {
_stream.Write(GetChildrenCommandBytes);
_stream.WriteString(text);
_stream.WriteInt64(pythonStackFrame.Thread.Id);
_stream.WriteInt32(pythonStackFrame.FrameId);
_stream.WriteInt32(executeId);
_stream.WriteInt32((int)pythonStackFrame.Kind);
}
}
internal void RemoveBreakPoint(PythonBreakpoint unboundBreakpoint) {
DebugWriteCommand("Remove Breakpoint");
_breakpoints.Remove(unboundBreakpoint.Id);
DisableBreakPoint(unboundBreakpoint);
}
internal void DisableBreakPoint(PythonBreakpoint unboundBreakpoint) {
if (_stream != null) {
DebugWriteCommand("Disable Breakpoint");
lock (_streamLock) {
if (unboundBreakpoint.IsDjangoBreakpoint) {
_stream.Write(RemoveDjangoBreakPointCommandBytes);
} else {
_stream.Write(RemoveBreakPointCommandBytes);
}
_stream.WriteInt32(unboundBreakpoint.LineNo);
_stream.WriteInt32(unboundBreakpoint.Id);
if (unboundBreakpoint.IsDjangoBreakpoint) {
_stream.WriteString(unboundBreakpoint.Filename);
}
}
}
}
internal void ConnectRepl(int portNum) {
DebugWriteCommand("Connect Repl");
lock (_streamLock) {
_stream.Write(ConnectReplCommandBytes);
_stream.WriteInt32(portNum);
}
}
internal void DisconnectRepl() {
DebugWriteCommand("Disconnect Repl");
lock (_streamLock) {
if (_stream == null) {
return;
}
try {
_stream.Write(DisconnectReplCommandBytes);
} catch (IOException) {
} catch (ObjectDisposedException) {
// If the process has terminated, we expect an exception
}
}
}
internal bool SetLineNumber(PythonStackFrame pythonStackFrame, int lineNo) {
if (_stoppedForException) {
return false;
}
DebugWriteCommand("Set Line Number");
lock (_streamLock) {
_setLineResult = false;
_stream.Write(SetLineNumberCommand);
_stream.WriteInt64(pythonStackFrame.Thread.Id);
_stream.WriteInt32(pythonStackFrame.FrameId);
_stream.WriteInt32(lineNo);
}
// wait up to 2 seconds for line event...
for (int i = 0; i < 20 && _stream != null; i++) {
if (NativeMethods.WaitForSingleObject(_lineEvent.SafeWaitHandle, 100) == 0) {
break;
}
}
return _setLineResult;
}
private static byte[] ExitCommandBytes = MakeCommand("exit");
private static byte[] StepIntoCommandBytes = MakeCommand("stpi");
private static byte[] StepOutCommandBytes = MakeCommand("stpo");
private static byte[] StepOverCommandBytes = MakeCommand("stpv");
private static byte[] BreakAllCommandBytes = MakeCommand("brka");
private static byte[] SetBreakPointCommandBytes = MakeCommand("brkp");
private static byte[] SetBreakPointConditionCommandBytes = MakeCommand("brkc");
private static byte[] SetBreakPointPassCountCommandBytes = MakeCommand("bkpc");
private static byte[] GetBreakPointHitCountCommandBytes = MakeCommand("bkgh");
private static byte[] SetBreakPointHitCountCommandBytes = MakeCommand("bksh");
private static byte[] RemoveBreakPointCommandBytes = MakeCommand("brkr");
private static byte[] ResumeAllCommandBytes = MakeCommand("resa");
private static byte[] GetThreadFramesCommandBytes = MakeCommand("thrf");
private static byte[] ExecuteTextCommandBytes = MakeCommand("exec");
private static byte[] ResumeThreadCommandBytes = MakeCommand("rest");
private static byte[] AutoResumeThreadCommandBytes = MakeCommand("ares");
private static byte[] ClearSteppingCommandBytes = MakeCommand("clst");
private static byte[] SetLineNumberCommand = MakeCommand("setl");
private static byte[] GetChildrenCommandBytes = MakeCommand("chld");
private static byte[] DetachCommandBytes = MakeCommand("detc");
private static byte[] SetExceptionInfoCommandBytes = MakeCommand("sexi");
private static byte[] SetExceptionHandlerInfoCommandBytes = MakeCommand("sehi");
private static byte[] RemoveDjangoBreakPointCommandBytes = MakeCommand("bkdr");
private static byte[] AddDjangoBreakPointCommandBytes = MakeCommand("bkda");
private static byte[] ConnectReplCommandBytes = MakeCommand("crep");
private static byte[] DisconnectReplCommandBytes = MakeCommand("drep");
private static byte[] LastAckCommandBytes = MakeCommand("lack");
private static byte[] MakeCommand(string command) {
return new byte[] { (byte)command[0], (byte)command[1], (byte)command[2], (byte)command[3] };
}
internal void SendStringToStdInput(string text) {
if (_process == null) {
throw new InvalidOperationException();
}
_process.StandardInput.Write(text);
}
#endregion
#region Debugging Events
private EventHandler _connected;
public event EventHandler Connected {
add {
lock (_streamLock) {
_connected += value;
// If a subscriber adds the handler after the process is connected, fire the event immediately.
// Since connection happens on a background thread, subscribers are racing against that thread
// when registering handlers, so we need to notify them even if they're too late.
if (_stream != null) {
value(this, EventArgs.Empty);
}
}
}
remove {
lock (_streamLock) {
_connected -= value;
}
}
}
/// <summary>
/// Fired when the process has started and is broken into the debugger, but before any user code is run.
/// </summary>
public event EventHandler<ThreadEventArgs> ProcessLoaded;
public event EventHandler<ThreadEventArgs> ThreadCreated;
public event EventHandler<ThreadEventArgs> ThreadExited;
public event EventHandler<ThreadEventArgs> StepComplete;
public event EventHandler<ThreadEventArgs> AsyncBreakComplete;
public event EventHandler<ProcessExitedEventArgs> ProcessExited;
public event EventHandler<ModuleLoadedEventArgs> ModuleLoaded;
public event EventHandler<ExceptionRaisedEventArgs> ExceptionRaised;
public event EventHandler<ThreadEventArgs> EntryPointHit;
public event EventHandler<BreakpointHitEventArgs> BreakpointHit;
public event EventHandler<BreakpointEventArgs> BreakpointBindSucceeded;
public event EventHandler<BreakpointEventArgs> BreakpointBindFailed;
public event EventHandler<OutputEventArgs> DebuggerOutput;
#endregion
class CompletionInfo {
public readonly Action<PythonEvaluationResult> Completion;
public readonly string Text;
public readonly PythonStackFrame Frame;
public CompletionInfo(Action<PythonEvaluationResult> completion, string text, PythonStackFrame frame) {
Completion = completion;
Text = text;
Frame = frame;
}
}
class ChildrenInfo {
public readonly Action<PythonEvaluationResult[]> Completion;
public readonly string Text;
public readonly PythonStackFrame Frame;
public ChildrenInfo(Action<PythonEvaluationResult[]> completion, string text, PythonStackFrame frame) {
Completion = completion;
Text = text;
Frame = frame;
}
}
}
}
| |
/* Copyright 2010, Object Management Group, Inc.
* Copyright 2010, PrismTech, Inc.
* Copyright 2010, Real-Time Innovations, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using org.omg.dds.core;
using org.omg.dds.core.modifiable;
using org.omg.dds.core.policy;
using org.omg.dds.type;
using org.omg.dds.type.typeobject;
namespace org.omg.dds.topic
{
[Extensibility(ExtensibilityKind.MUTABLE_EXTENSIBILITY)]
public abstract class PublicationBuiltinTopicData : ModifiableValue<PublicationBuiltinTopicData,
PublicationBuiltinTopicData>
{
// -----------------------------------------------------------------------
// Factory Methods
// -----------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// <param name="bootstrap">Identifies the Service instance to which the new
/// object will belong
/// </param>
/// <returns></returns>
public static PublicationBuiltinTopicData NewPublicationBuiltinTopicData(
Bootstrap bootstrap)
{
return bootstrap.GetSPI().NewPublicationBuiltinTopicData();
}
// -----------------------------------------------------------------------
// Instance Methods
// -----------------------------------------------------------------------
[ID(0x005A)]
[Key]
public abstract BuiltinTopicKey Key { get; }
/// <summary>
/// Return the participantKey
/// </summary>
[ID(0x0050)]
public abstract BuiltinTopicKey ParticipantKey { get; }
/// <summary>
/// Return the topicName
/// </summary>
[ID(0x0005)]
public abstract string TopicName { get; }
/// <summary>
/// Return the typeName
/// </summary>
[ID(0x0007)]
public abstract string TypeName { get; }
[ID(0x0075)]
[Optional]
public abstract List<string> EquivalentTypeName { get; }
[ID(0x0076)]
[Optional]
public abstract List<string> BaseTypeName { get; }
[ID(0x0072)]
[Optional]
public abstract TypeObject Type { get; }
/// <summary>
/// Return the durability
/// </summary>
[ID(0x001D)]
public abstract DurabilityQosPolicy Durability { get; }
/// <summary>
/// Return the durabilityService
/// </summary>
[ID(0x001E)]
public abstract DurabilityServiceQosPolicy DurabilityService { get; }
/// <summary>
/// Return the deadline
/// </summary>
[ID(0x0023)]
public abstract DeadlineQosPolicy Deadline { get; }
/// <summary>
/// Return the latencyBudget
/// </summary>
[ID(0x0027)]
public abstract LatencyBudgetQosPolicy LatencyBudget { get; }
/// <summary>
/// Return the liveliness
/// </summary>
[ID(0x001B)]
public abstract LivelinessQosPolicy Liveliness { get; }
/// <summary>
/// Return the reliability
/// </summary>
[ID(0x001A)]
public abstract ReliabilityQosPolicy Reliability { get; }
/// <summary>
/// Return the lifespan
/// </summary>
[ID(0x002B)]
public abstract LifespanQosPolicy Lifespan { get; }
/// <summary>
/// Return the userData
/// </summary>
[ID(0x002C)]
public abstract UserDataQosPolicy UserData { get; }
/// <summary>
/// Return the ownership
/// </summary>
[ID(0x001F)]
public abstract OwnershipQosPolicy Ownership { get; }
/// <summary>
/// Return the ownershipStrength
/// </summary>
[ID(0x0006)]
public abstract OwnershipStrengthQosPolicy OwnershipStrength { get; }
/// <summary>
/// Return the destinationOrder
/// </summary>
[ID(0x0025)]
public abstract DestinationOrderQosPolicy DestinationOrder { get; }
/// <summary>
/// Return the presentation
/// </summary>
[ID(0x0021)]
public abstract PresentationQosPolicy Presentation { get; }
/// <summary>
/// Return the partition
/// </summary>
[ID(0x0029)]
public abstract PartitionQosPolicy Partition { get; }
/// <summary>
/// Return the topicData
/// </summary>
[ID(0x002E)]
public abstract TopicDataQosPolicy TopicData { get; }
/// <summary>
/// Return the groupData
/// </summary>
[ID(0x002D)]
public abstract GroupDataQosPolicy GroupData { get; }
[ID(0x0073)]
public abstract DataRepresentationQosPolicy Representation { get; }
[ID(0x0074)]
public abstract TypeConsistencyEnforcementQosPolicy TypeConsistency { get; }
// --- From Object: ------------------------------------------------------
//public abstract PublicationBuiltinTopicData clone();
public abstract PublicationBuiltinTopicData CopyFrom(PublicationBuiltinTopicData other);
public abstract PublicationBuiltinTopicData FinishModification();
public abstract PublicationBuiltinTopicData Clone();
public abstract PublicationBuiltinTopicData Modify();
public abstract Bootstrap GetBootstrap();
}
}
| |
// 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.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
// A MemoryStream represents a Stream in memory (ie, it has no backing store).
// This stream may reduce the need for temporary buffers and files in
// an application.
//
// There are two ways to create a MemoryStream. You can initialize one
// from an unsigned byte array, or you can create an empty one. Empty
// memory streams are resizable, while ones created with a byte array provide
// a stream "view" of the data.
public class MemoryStream : Stream
{
private byte[] _buffer; // Either allocated internally or externally.
private readonly int _origin; // For user-provided arrays, start at this origin
private int _position; // read/write head.
private int _length; // Number of bytes within the memory stream
private int _capacity; // length of usable portion of buffer for stream
// Note that _capacity == _buffer.Length for non-user-provided byte[]'s
private bool _expandable; // User-provided buffers aren't expandable.
private bool _writable; // Can user write to this stream?
private readonly bool _exposable; // Whether the array can be returned to the user.
private bool _isOpen; // Is this stream open or closed?
private Task<int>? _lastReadTask; // The last successful task returned from ReadAsync
private const int MemStreamMaxLength = int.MaxValue;
public MemoryStream()
: this(0)
{
}
public MemoryStream(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity);
_buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>();
_capacity = capacity;
_expandable = true;
_writable = true;
_exposable = true;
_origin = 0; // Must be 0 for byte[]'s created by MemoryStream
_isOpen = true;
}
public MemoryStream(byte[] buffer)
: this(buffer, true)
{
}
public MemoryStream(byte[] buffer, bool writable)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
_buffer = buffer;
_length = _capacity = buffer.Length;
_writable = writable;
_exposable = false;
_origin = 0;
_isOpen = true;
}
public MemoryStream(byte[] buffer, int index, int count)
: this(buffer, index, count, true, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable)
: this(buffer, index, count, writable, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
_buffer = buffer;
_origin = _position = index;
_length = _capacity = index + count;
_writable = writable;
_exposable = publiclyVisible; // Can TryGetBuffer/GetBuffer return the array?
_expandable = false;
_isOpen = true;
}
public override bool CanRead => _isOpen;
public override bool CanSeek => _isOpen;
public override bool CanWrite => _writable;
private void EnsureNotClosed()
{
if (!_isOpen)
throw Error.GetStreamIsClosed();
}
private void EnsureWriteable()
{
if (!CanWrite)
throw Error.GetWriteNotSupported();
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
_isOpen = false;
_writable = false;
_expandable = false;
// Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work.
_lastReadTask = null;
}
}
finally
{
// Call base.Close() to cleanup async IO resources
base.Dispose(disposing);
}
}
// returns a bool saying whether we allocated a new array.
private bool EnsureCapacity(int value)
{
// Check for overflow
if (value < 0)
throw new IOException(SR.IO_StreamTooLong);
if (value > _capacity)
{
int newCapacity = Math.Max(value, 256);
// We are ok with this overflowing since the next statement will deal
// with the cases where _capacity*2 overflows.
if (newCapacity < _capacity * 2)
{
newCapacity = _capacity * 2;
}
// We want to expand the array up to Array.MaxByteArrayLength
// And we want to give the user the value that they asked for
if ((uint)(_capacity * 2) > Array.MaxByteArrayLength)
{
newCapacity = Math.Max(value, Array.MaxByteArrayLength);
}
Capacity = newCapacity;
return true;
}
return false;
}
public override void Flush()
{
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Flush();
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
public virtual byte[] GetBuffer()
{
if (!_exposable)
throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer);
return _buffer;
}
public virtual bool TryGetBuffer(out ArraySegment<byte> buffer)
{
if (!_exposable)
{
buffer = default;
return false;
}
buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: _length - _origin);
return true;
}
// -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) ---------------
// PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer())
internal byte[] InternalGetBuffer()
{
return _buffer;
}
// PERF: True cursor position, we don't need _origin for direct access
internal int InternalGetPosition()
{
return _position;
}
// PERF: Expose internal buffer for BinaryReader instead of going via the regular Stream interface which requires to copy the data out
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlySpan<byte> InternalReadSpan(int count)
{
EnsureNotClosed();
int origPos = _position;
int newPos = origPos + count;
if ((uint)newPos > (uint)_length)
{
_position = _length;
throw Error.GetEndOfFile();
}
var span = new ReadOnlySpan<byte>(_buffer, origPos, count);
_position = newPos;
return span;
}
// PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes
internal int InternalEmulateRead(int count)
{
EnsureNotClosed();
int n = _length - _position;
if (n > count)
n = count;
if (n < 0)
n = 0;
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
_position += n;
return n;
}
// Gets & sets the capacity (number of bytes allocated) for this stream.
// The capacity cannot be set to a value less than the current length
// of the stream.
//
public virtual int Capacity
{
get
{
EnsureNotClosed();
return _capacity - _origin;
}
set
{
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
if (value < Length)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
EnsureNotClosed();
if (!_expandable && (value != Capacity))
throw new NotSupportedException(SR.NotSupported_MemStreamNotExpandable);
// MemoryStream has this invariant: _origin > 0 => !expandable (see ctors)
if (_expandable && value != _capacity)
{
if (value > 0)
{
byte[] newBuffer = new byte[value];
if (_length > 0)
{
Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _length);
}
_buffer = newBuffer;
}
else
{
_buffer = Array.Empty<byte>();
}
_capacity = value;
}
}
}
public override long Length
{
get
{
EnsureNotClosed();
return _length - _origin;
}
}
public override long Position
{
get
{
EnsureNotClosed();
return _position - _origin;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
EnsureNotClosed();
if (value > MemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
_position = _origin + (int)value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
EnsureNotClosed();
int n = _length - _position;
if (n > count)
n = count;
if (n <= 0)
return 0;
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
if (n <= 8)
{
int byteCount = n;
while (--byteCount >= 0)
buffer[offset + byteCount] = _buffer[_position + byteCount];
}
else
Buffer.BlockCopy(_buffer, _position, buffer, offset, n);
_position += n;
return n;
}
public override int Read(Span<byte> buffer)
{
if (GetType() != typeof(MemoryStream))
{
// MemoryStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior
// to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload
// should use the behavior of Read(byte[],int,int) overload.
return base.Read(buffer);
}
EnsureNotClosed();
int n = Math.Min(_length - _position, buffer.Length);
if (n <= 0)
return 0;
// TODO https://github.com/dotnet/coreclr/issues/15076:
// Read(byte[], int, int) has an n <= 8 optimization, presumably based
// on benchmarking. Determine if/where such a cut-off is here and add
// an equivalent optimization if necessary.
new Span<byte>(_buffer, _position, n).CopyTo(buffer);
_position += n;
return n;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
// If cancellation was requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
try
{
int n = Read(buffer, offset, count);
Task<int>? t = _lastReadTask;
Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
"Expected that a stored last task completed successfully");
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
}
catch (OperationCanceledException oce)
{
return Task.FromCanceled<int>(oce);
}
catch (Exception exception)
{
return Task.FromException<int>(exception);
}
}
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
try
{
// ReadAsync(Memory<byte>,...) needs to delegate to an existing virtual to do the work, in case an existing derived type
// has changed or augmented the logic associated with reads. If the Memory wraps an array, we could delegate to
// ReadAsync(byte[], ...), but that would defeat part of the purpose, as ReadAsync(byte[], ...) often needs to allocate
// a Task<int> for the return value, so we want to delegate to one of the synchronous methods. We could always
// delegate to the Read(Span<byte>) method, and that's the most efficient solution when dealing with a concrete
// MemoryStream, but if we're dealing with a type derived from MemoryStream, Read(Span<byte>) will end up delegating
// to Read(byte[], ...), which requires it to get a byte[] from ArrayPool and copy the data. So, we special-case the
// very common case of the Memory<byte> wrapping an array: if it does, we delegate to Read(byte[], ...) with it,
// as that will be efficient in both cases, and we fall back to Read(Span<byte>) if the Memory<byte> wrapped something
// else; if this is a concrete MemoryStream, that'll be efficient, and only in the case where the Memory<byte> wrapped
// something other than an array and this is a MemoryStream-derived type that doesn't override Read(Span<byte>) will
// it then fall back to doing the ArrayPool/copy behavior.
return new ValueTask<int>(
MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> destinationArray) ?
Read(destinationArray.Array!, destinationArray.Offset, destinationArray.Count) :
Read(buffer.Span));
}
catch (OperationCanceledException oce)
{
return new ValueTask<int>(Task.FromCanceled<int>(oce));
}
catch (Exception exception)
{
return new ValueTask<int>(Task.FromException<int>(exception));
}
}
public override int ReadByte()
{
EnsureNotClosed();
if (_position >= _length)
return -1;
return _buffer[_position++];
}
public override void CopyTo(Stream destination, int bufferSize)
{
// Since we did not originally override this method, validate the arguments
// the same way Stream does for back-compat.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read) when we are not sure.
if (GetType() != typeof(MemoryStream))
{
base.CopyTo(destination, bufferSize);
return;
}
int originalPosition = _position;
// Seek to the end of the MemoryStream.
int remaining = InternalEmulateRead(_length - originalPosition);
// If we were already at or past the end, there's no copying to do so just quit.
if (remaining > 0)
{
// Call Write() on the other Stream, using our internal buffer and avoiding any
// intermediary allocations.
destination.Write(_buffer, originalPosition, remaining);
}
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// This implementation offers better performance compared to the base class version.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to ReadAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into ReadAsync) when we are not sure.
if (GetType() != typeof(MemoryStream))
return base.CopyToAsync(destination, bufferSize, cancellationToken);
// If cancelled - return fast:
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
int pos = _position;
int n = InternalEmulateRead(_length - _position);
// If we were already at or past the end, there's no copying to do so just quit.
if (n == 0)
return Task.CompletedTask;
// If destination is not a memory stream, write there asynchronously:
if (!(destination is MemoryStream memStrDest))
return destination.WriteAsync(_buffer, pos, n, cancellationToken);
try
{
// If destination is a MemoryStream, CopyTo synchronously:
memStrDest.Write(_buffer, pos, n);
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
public override long Seek(long offset, SeekOrigin loc)
{
EnsureNotClosed();
if (offset > MemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength);
switch (loc)
{
case SeekOrigin.Begin:
{
int tempPosition = unchecked(_origin + (int)offset);
if (offset < 0 || tempPosition < _origin)
throw new IOException(SR.IO_SeekBeforeBegin);
_position = tempPosition;
break;
}
case SeekOrigin.Current:
{
int tempPosition = unchecked(_position + (int)offset);
if (unchecked(_position + offset) < _origin || tempPosition < _origin)
throw new IOException(SR.IO_SeekBeforeBegin);
_position = tempPosition;
break;
}
case SeekOrigin.End:
{
int tempPosition = unchecked(_length + (int)offset);
if (unchecked(_length + offset) < _origin || tempPosition < _origin)
throw new IOException(SR.IO_SeekBeforeBegin);
_position = tempPosition;
break;
}
default:
throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
Debug.Assert(_position >= 0, "_position >= 0");
return _position;
}
// Sets the length of the stream to a given value. The new
// value must be nonnegative and less than the space remaining in
// the array, int.MaxValue - origin
// Origin is 0 in all cases other than a MemoryStream created on
// top of an existing array and a specific starting offset was passed
// into the MemoryStream constructor. The upper bounds prevents any
// situations where a stream may be created on top of an array then
// the stream is made longer than the maximum possible length of the
// array (int.MaxValue).
//
public override void SetLength(long value)
{
if (value < 0 || value > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
EnsureWriteable();
// Origin wasn't publicly exposed above.
Debug.Assert(MemStreamMaxLength == int.MaxValue); // Check parameter validation logic in this method if this fails.
if (value > (int.MaxValue - _origin))
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
int newLength = _origin + (int)value;
bool allocatedNewArray = EnsureCapacity(newLength);
if (!allocatedNewArray && newLength > _length)
Array.Clear(_buffer, _length, newLength - _length);
_length = newLength;
if (_position > newLength)
_position = newLength;
}
public virtual byte[] ToArray()
{
int count = _length - _origin;
if (count == 0)
return Array.Empty<byte>();
byte[] copy = new byte[count];
Buffer.BlockCopy(_buffer, _origin, copy, 0, count);
return copy;
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
EnsureNotClosed();
EnsureWriteable();
int i = _position + count;
// Check for overflow
if (i < 0)
throw new IOException(SR.IO_StreamTooLong);
if (i > _length)
{
bool mustZero = _position > _length;
if (i > _capacity)
{
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, i - _length);
}
_length = i;
}
if ((count <= 8) && (buffer != _buffer))
{
int byteCount = count;
while (--byteCount >= 0)
{
_buffer[_position + byteCount] = buffer[offset + byteCount];
}
}
else
{
Buffer.BlockCopy(buffer, offset, _buffer, _position, count);
}
_position = i;
}
public override void Write(ReadOnlySpan<byte> buffer)
{
if (GetType() != typeof(MemoryStream))
{
// MemoryStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior
// to this Write(Span<byte>) overload being introduced. In that case, this Write(Span<byte>) overload
// should use the behavior of Write(byte[],int,int) overload.
base.Write(buffer);
return;
}
EnsureNotClosed();
EnsureWriteable();
// Check for overflow
int i = _position + buffer.Length;
if (i < 0)
throw new IOException(SR.IO_StreamTooLong);
if (i > _length)
{
bool mustZero = _position > _length;
if (i > _capacity)
{
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, i - _length);
}
_length = i;
}
buffer.CopyTo(new Span<byte>(_buffer, _position, buffer.Length));
_position = i;
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
// If cancellation is already requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
catch (OperationCanceledException oce)
{
return Task.FromCanceled(oce);
}
catch (Exception exception)
{
return Task.FromException(exception);
}
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask(Task.FromCanceled(cancellationToken));
}
try
{
// See corresponding comment in ReadAsync for why we don't just always use Write(ReadOnlySpan<byte>).
// Unlike ReadAsync, we could delegate to WriteAsync(byte[], ...) here, but we don't for consistency.
if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> sourceArray))
{
Write(sourceArray.Array!, sourceArray.Offset, sourceArray.Count);
}
else
{
Write(buffer.Span);
}
return default;
}
catch (OperationCanceledException oce)
{
return new ValueTask(Task.FromCanceled(oce));
}
catch (Exception exception)
{
return new ValueTask(Task.FromException(exception));
}
}
public override void WriteByte(byte value)
{
EnsureNotClosed();
EnsureWriteable();
if (_position >= _length)
{
int newLength = _position + 1;
bool mustZero = _position > _length;
if (newLength >= _capacity)
{
bool allocatedNewArray = EnsureCapacity(newLength);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, _position - _length);
}
_length = newLength;
}
_buffer[_position++] = value;
}
// Writes this MemoryStream to another stream.
public virtual void WriteTo(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
EnsureNotClosed();
stream.Write(_buffer, _origin, _length - _origin);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Shared;
using osu.Shared.Serialization;
using osu_database_reader.BinaryFiles;
namespace osu_database_reader.Components.Beatmaps
{
/// <summary>
/// An entry in <see cref="OsuDb"/> with information about a beatmap.
/// </summary>
public class BeatmapEntry : ISerializable
{
public string Artist, ArtistUnicode;
public string Title, TitleUnicode;
public string Creator; //mapper
public string Version; //difficulty name
public string AudioFileName;
public string BeatmapChecksum;
public string BeatmapFileName;
public SubmissionStatus RankedStatus;
public ushort CountHitCircles, CountSliders, CountSpinners;
public DateTime LastModifiedTime;
public float ApproachRate, CircleSize, HPDrainRate, OveralDifficulty;
public double SliderVelocity;
public Dictionary<Mods, double> DiffStarRatingStandard, DiffStarRatingTaiko, DiffStarRatingCtB, DiffStarRatingMania;
public int DrainTimeSeconds; //NOTE: in s
public int TotalTime; //NOTE: in ms
public int AudioPreviewTime; //NOTE: in ms
public List<TimingPoint> TimingPoints;
public int BeatmapId, BeatmapSetId, ThreadId;
public Ranking GradeStandard, GradeTaiko, GradeCtB, GradeMania;
public short OffsetLocal;
public float StackLeniency;
public GameMode GameMode;
public string SongSource, SongTags;
public short OffsetOnline;
public string TitleFont;
public bool Unplayed;
public DateTime LastPlayed;
public bool IsOsz2;
public string FolderName;
public DateTime LastCheckAgainstOsuRepo;
public bool IgnoreBeatmapSounds, IgnoreBeatmapSkin, DisableStoryBoard, DisableVideo, VisualOverride;
public short OldUnknown1; //unused
public int LastEditTime;
public byte ManiaScrollSpeed;
private int _version;
public static BeatmapEntry ReadFromReader(SerializationReader r, int version) {
var e = new BeatmapEntry {
_version = version,
};
e.ReadFromStream(r);
return e;
}
public void ReadFromStream(SerializationReader r)
{
Artist = r.ReadString();
if (_version >= OsuVersions.FirstOsz2)
ArtistUnicode = r.ReadString();
Title = r.ReadString();
if (_version >= OsuVersions.FirstOsz2)
TitleUnicode = r.ReadString();
Creator = r.ReadString();
Version = r.ReadString();
AudioFileName = r.ReadString();
BeatmapChecksum = r.ReadString(); //always 32 in length, so the 2 preceding bytes in the file are practically wasting space
BeatmapFileName = r.ReadString();
RankedStatus = (SubmissionStatus)r.ReadByte();
CountHitCircles = r.ReadUInt16();
CountSliders = r.ReadUInt16();
CountSpinners = r.ReadUInt16();
LastModifiedTime = r.ReadDateTime();
if (_version >= OsuVersions.FloatDifficultyValues)
{
ApproachRate = r.ReadSingle();
CircleSize = r.ReadSingle();
HPDrainRate = r.ReadSingle();
OveralDifficulty = r.ReadSingle();
}
else
{
ApproachRate = r.ReadByte();
CircleSize = r.ReadByte();
HPDrainRate = r.ReadByte();
OveralDifficulty = r.ReadByte();
}
SliderVelocity = r.ReadDouble();
if (_version >= OsuVersions.FloatDifficultyValues)
{
DiffStarRatingStandard = r.ReadDictionary<Mods, double>();
DiffStarRatingTaiko = r.ReadDictionary<Mods, double>();
DiffStarRatingCtB = r.ReadDictionary<Mods, double>();
DiffStarRatingMania = r.ReadDictionary<Mods, double>();
// TODO: there may be different reading behavior for versions before 20190204, 20200916, 20200504 and 20191024 here.
}
DrainTimeSeconds = r.ReadInt32();
TotalTime = r.ReadInt32();
AudioPreviewTime = r.ReadInt32();
TimingPoints = r.ReadSerializableList<TimingPoint>();
BeatmapId = r.ReadInt32();
BeatmapSetId = r.ReadInt32();
ThreadId = r.ReadInt32();
GradeStandard = (Ranking)r.ReadByte();
GradeTaiko = (Ranking)r.ReadByte();
GradeCtB = (Ranking)r.ReadByte();
GradeMania = (Ranking)r.ReadByte();
OffsetLocal = r.ReadInt16();
StackLeniency = r.ReadSingle();
GameMode = (GameMode)r.ReadByte();
SongSource = r.ReadString();
SongTags = r.ReadString();
OffsetOnline = r.ReadInt16();
TitleFont = r.ReadString();
Unplayed = r.ReadBoolean();
LastPlayed = r.ReadDateTime();
IsOsz2 = r.ReadBoolean();
FolderName = r.ReadString();
LastCheckAgainstOsuRepo = r.ReadDateTime();
IgnoreBeatmapSounds = r.ReadBoolean();
IgnoreBeatmapSkin = r.ReadBoolean();
DisableStoryBoard = r.ReadBoolean();
DisableVideo = r.ReadBoolean();
VisualOverride = r.ReadBoolean();
if (_version < OsuVersions.FloatDifficultyValues)
OldUnknown1 = r.ReadInt16();
LastEditTime = r.ReadInt32();
ManiaScrollSpeed = r.ReadByte();
}
public void WriteToStream(SerializationWriter w)
{
w.Write(Artist);
if (_version >= OsuVersions.FirstOsz2)
w.Write(ArtistUnicode);
w.Write(Title);
if (_version >= OsuVersions.FirstOsz2)
w.Write(TitleUnicode);
w.Write(Creator);
w.Write(Version);
w.Write(AudioFileName);
w.Write(BeatmapChecksum);
w.Write(BeatmapFileName);
w.Write((byte)RankedStatus);
w.Write(CountHitCircles);
w.Write(CountSliders);
w.Write(CountSpinners);
w.Write(LastModifiedTime);
if (_version >= OsuVersions.FloatDifficultyValues)
{
w.Write(ApproachRate);
w.Write(CircleSize);
w.Write(HPDrainRate);
w.Write(OveralDifficulty);
}
else
{
w.Write(ApproachRate);
w.Write(CircleSize);
w.Write(HPDrainRate);
w.Write(OveralDifficulty);
}
w.Write(SliderVelocity);
if (_version >= OsuVersions.FloatDifficultyValues)
{
static Dictionary<int, double> ConvertToWritableDictionary(IDictionary<Mods, double> dic)
=> dic.ToDictionary(pair => (int) pair.Key, pair => pair.Value);
w.Write(ConvertToWritableDictionary(DiffStarRatingStandard));
w.Write(ConvertToWritableDictionary(DiffStarRatingTaiko));
w.Write(ConvertToWritableDictionary(DiffStarRatingCtB));
w.Write(ConvertToWritableDictionary(DiffStarRatingMania));
// TODO: there may be different reading behavior for versions before 20190204, 20200916, 20200504 and 20191024 here.
}
w.Write(DrainTimeSeconds);
w.Write(TotalTime);
w.Write(AudioPreviewTime);
w.WriteSerializableList(TimingPoints);
w.Write(BeatmapId);
w.Write(BeatmapSetId);
w.Write(ThreadId);
w.Write((byte)GradeStandard);
w.Write((byte)GradeTaiko);
w.Write((byte)GradeCtB);
w.Write((byte)GradeMania);
w.Write(OffsetLocal);
w.Write(StackLeniency);
w.Write((byte)GameMode);
w.Write(SongSource);
w.Write(SongTags);
w.Write(OffsetOnline);
w.Write(TitleFont);
w.Write(Unplayed);
w.Write(LastPlayed);
w.Write(IsOsz2);
w.Write(FolderName);
w.Write(LastCheckAgainstOsuRepo);
w.Write(IgnoreBeatmapSounds);
w.Write(IgnoreBeatmapSkin);
w.Write(DisableStoryBoard);
w.Write(DisableVideo);
w.Write(VisualOverride);
if (_version < OsuVersions.FloatDifficultyValues)
w.Write(OldUnknown1);
w.Write(LastEditTime);
w.Write(ManiaScrollSpeed);
}
}
}
| |
// DeflaterHuffman.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// 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 GitHub.ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// This is the DeflaterHuffman class.
///
/// This class is <i>not</i> thread safe. This is inherent in the API, due
/// to the split of Deflate and SetInput.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class DeflaterHuffman
{
const int BUFSIZE = 1 << (DeflaterConstants.DEFAULT_MEM_LEVEL + 6);
const int LITERAL_NUM = 286;
// Number of distance codes
const int DIST_NUM = 30;
// Number of codes used to transfer bit lengths
const int BITLEN_NUM = 19;
// repeat previous bit length 3-6 times (2 bits of repeat count)
const int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
const int REP_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
const int REP_11_138 = 18;
const int EOF_SYMBOL = 256;
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit length codes.
static readonly int[] BL_ORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
static readonly byte[] bit4Reverse = {
0,
8,
4,
12,
2,
10,
6,
14,
1,
9,
5,
13,
3,
11,
7,
15
};
static short[] staticLCodes;
static byte[] staticLLength;
static short[] staticDCodes;
static byte[] staticDLength;
class Tree
{
#region Instance Fields
public short[] freqs;
public byte[] length;
public int minNumCodes;
public int numCodes;
short[] codes;
int[] bl_counts;
int maxLength;
DeflaterHuffman dh;
#endregion
#region Constructors
public Tree(DeflaterHuffman dh, int elems, int minCodes, int maxLength)
{
this.dh = dh;
this.minNumCodes = minCodes;
this.maxLength = maxLength;
freqs = new short[elems];
bl_counts = new int[maxLength];
}
#endregion
/// <summary>
/// Resets the internal state of the tree
/// </summary>
public void Reset()
{
for (int i = 0; i < freqs.Length; i++) {
freqs[i] = 0;
}
codes = null;
length = null;
}
public void WriteSymbol(int code)
{
// if (DeflaterConstants.DEBUGGING) {
// freqs[code]--;
// // Console.Write("writeSymbol("+freqs.length+","+code+"): ");
// }
dh.pending.WriteBits(codes[code] & 0xffff, length[code]);
}
/// <summary>
/// Check that all frequencies are zero
/// </summary>
/// <exception cref="SharpZipBaseException">
/// At least one frequency is non-zero
/// </exception>
public void CheckEmpty()
{
bool empty = true;
for (int i = 0; i < freqs.Length; i++) {
if (freqs[i] != 0) {
//Console.WriteLine("freqs[" + i + "] == " + freqs[i]);
empty = false;
}
}
if (!empty) {
throw new SharpZipBaseException("!Empty");
}
}
/// <summary>
/// Set static codes and length
/// </summary>
/// <param name="staticCodes">new codes</param>
/// <param name="staticLengths">length for new codes</param>
public void SetStaticCodes(short[] staticCodes, byte[] staticLengths)
{
codes = staticCodes;
length = staticLengths;
}
/// <summary>
/// Build dynamic codes and lengths
/// </summary>
public void BuildCodes()
{
int numSymbols = freqs.Length;
int[] nextCode = new int[maxLength];
int code = 0;
codes = new short[freqs.Length];
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("buildCodes: "+freqs.Length);
// }
for (int bits = 0; bits < maxLength; bits++) {
nextCode[bits] = code;
code += bl_counts[bits] << (15 - bits);
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("bits: " + ( bits + 1) + " count: " + bl_counts[bits]
// +" nextCode: "+code);
// }
}
#if DebugDeflation
if ( DeflaterConstants.DEBUGGING && (code != 65536) )
{
throw new SharpZipBaseException("Inconsistent bl_counts!");
}
#endif
for (int i=0; i < numCodes; i++) {
int bits = length[i];
if (bits > 0) {
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("codes["+i+"] = rev(" + nextCode[bits-1]+"),
// +bits);
// }
codes[i] = BitReverse(nextCode[bits-1]);
nextCode[bits-1] += 1 << (16 - bits);
}
}
}
public void BuildTree()
{
int numSymbols = freqs.Length;
/* heap is a priority queue, sorted by frequency, least frequent
* nodes first. The heap is a binary tree, with the property, that
* the parent node is smaller than both child nodes. This assures
* that the smallest node is the first parent.
*
* The binary tree is encoded in an array: 0 is root node and
* the nodes 2*n+1, 2*n+2 are the child nodes of node n.
*/
int[] heap = new int[numSymbols];
int heapLen = 0;
int maxCode = 0;
for (int n = 0; n < numSymbols; n++) {
int freq = freqs[n];
if (freq != 0) {
// Insert n into heap
int pos = heapLen++;
int ppos;
while (pos > 0 && freqs[heap[ppos = (pos - 1) / 2]] > freq) {
heap[pos] = heap[ppos];
pos = ppos;
}
heap[pos] = n;
maxCode = n;
}
}
/* We could encode a single literal with 0 bits but then we
* don't see the literals. Therefore we force at least two
* literals to avoid this case. We don't care about order in
* this case, both literals get a 1 bit code.
*/
while (heapLen < 2) {
int node = maxCode < 2 ? ++maxCode : 0;
heap[heapLen++] = node;
}
numCodes = Math.Max(maxCode + 1, minNumCodes);
int numLeafs = heapLen;
int[] childs = new int[4 * heapLen - 2];
int[] values = new int[2 * heapLen - 1];
int numNodes = numLeafs;
for (int i = 0; i < heapLen; i++) {
int node = heap[i];
childs[2 * i] = node;
childs[2 * i + 1] = -1;
values[i] = freqs[node] << 8;
heap[i] = i;
}
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
do {
int first = heap[0];
int last = heap[--heapLen];
// Propagate the hole to the leafs of the heap
int ppos = 0;
int path = 1;
while (path < heapLen) {
if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) {
path++;
}
heap[ppos] = heap[path];
ppos = path;
path = path * 2 + 1;
}
/* Now propagate the last element down along path. Normally
* it shouldn't go too deep.
*/
int lastVal = values[last];
while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) {
heap[path] = heap[ppos];
}
heap[path] = last;
int second = heap[0];
// Create a new node father of first and second
last = numNodes++;
childs[2 * last] = first;
childs[2 * last + 1] = second;
int mindepth = Math.Min(values[first] & 0xff, values[second] & 0xff);
values[last] = lastVal = values[first] + values[second] - mindepth + 1;
// Again, propagate the hole to the leafs
ppos = 0;
path = 1;
while (path < heapLen) {
if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) {
path++;
}
heap[ppos] = heap[path];
ppos = path;
path = ppos * 2 + 1;
}
// Now propagate the new element down along path
while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) {
heap[path] = heap[ppos];
}
heap[path] = last;
} while (heapLen > 1);
if (heap[0] != childs.Length / 2 - 1) {
throw new SharpZipBaseException("Heap invariant violated");
}
BuildLength(childs);
}
/// <summary>
/// Get encoded length
/// </summary>
/// <returns>Encoded length, the sum of frequencies * lengths</returns>
public int GetEncodedLength()
{
int len = 0;
for (int i = 0; i < freqs.Length; i++) {
len += freqs[i] * length[i];
}
return len;
}
/// <summary>
/// Scan a literal or distance tree to determine the frequencies of the codes
/// in the bit length tree.
/// </summary>
public void CalcBLFreq(Tree blTree)
{
int max_count; /* max repeat count */
int min_count; /* min repeat count */
int count; /* repeat count of the current code */
int curlen = -1; /* length of current code */
int i = 0;
while (i < numCodes) {
count = 1;
int nextlen = length[i];
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else {
max_count = 6;
min_count = 3;
if (curlen != nextlen) {
blTree.freqs[nextlen]++;
count = 0;
}
}
curlen = nextlen;
i++;
while (i < numCodes && curlen == length[i]) {
i++;
if (++count >= max_count) {
break;
}
}
if (count < min_count) {
blTree.freqs[curlen] += (short)count;
} else if (curlen != 0) {
blTree.freqs[REP_3_6]++;
} else if (count <= 10) {
blTree.freqs[REP_3_10]++;
} else {
blTree.freqs[REP_11_138]++;
}
}
}
/// <summary>
/// Write tree values
/// </summary>
/// <param name="blTree">Tree to write</param>
public void WriteTree(Tree blTree)
{
int max_count; // max repeat count
int min_count; // min repeat count
int count; // repeat count of the current code
int curlen = -1; // length of current code
int i = 0;
while (i < numCodes) {
count = 1;
int nextlen = length[i];
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else {
max_count = 6;
min_count = 3;
if (curlen != nextlen) {
blTree.WriteSymbol(nextlen);
count = 0;
}
}
curlen = nextlen;
i++;
while (i < numCodes && curlen == length[i]) {
i++;
if (++count >= max_count) {
break;
}
}
if (count < min_count) {
while (count-- > 0) {
blTree.WriteSymbol(curlen);
}
} else if (curlen != 0) {
blTree.WriteSymbol(REP_3_6);
dh.pending.WriteBits(count - 3, 2);
} else if (count <= 10) {
blTree.WriteSymbol(REP_3_10);
dh.pending.WriteBits(count - 3, 3);
} else {
blTree.WriteSymbol(REP_11_138);
dh.pending.WriteBits(count - 11, 7);
}
}
}
void BuildLength(int[] childs)
{
this.length = new byte [freqs.Length];
int numNodes = childs.Length / 2;
int numLeafs = (numNodes + 1) / 2;
int overflow = 0;
for (int i = 0; i < maxLength; i++) {
bl_counts[i] = 0;
}
// First calculate optimal bit lengths
int[] lengths = new int[numNodes];
lengths[numNodes-1] = 0;
for (int i = numNodes - 1; i >= 0; i--) {
if (childs[2 * i + 1] != -1) {
int bitLength = lengths[i] + 1;
if (bitLength > maxLength) {
bitLength = maxLength;
overflow++;
}
lengths[childs[2 * i]] = lengths[childs[2 * i + 1]] = bitLength;
} else {
// A leaf node
int bitLength = lengths[i];
bl_counts[bitLength - 1]++;
this.length[childs[2*i]] = (byte) lengths[i];
}
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Tree "+freqs.Length+" lengths:");
// for (int i=0; i < numLeafs; i++) {
// //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]]
// + " len: "+length[childs[2*i]]);
// }
// }
if (overflow == 0) {
return;
}
int incrBitLen = maxLength - 1;
do {
// Find the first bit length which could increase:
while (bl_counts[--incrBitLen] == 0)
;
// Move this node one down and remove a corresponding
// number of overflow nodes.
do {
bl_counts[incrBitLen]--;
bl_counts[++incrBitLen]++;
overflow -= 1 << (maxLength - 1 - incrBitLen);
} while (overflow > 0 && incrBitLen < maxLength - 1);
} while (overflow > 0);
/* We may have overshot above. Move some nodes from maxLength to
* maxLength-1 in that case.
*/
bl_counts[maxLength-1] += overflow;
bl_counts[maxLength-2] -= overflow;
/* Now recompute all bit lengths, scanning in increasing
* frequency. It is simpler to reconstruct all lengths instead of
* fixing only the wrong ones. This idea is taken from 'ar'
* written by Haruhiko Okumura.
*
* The nodes were inserted with decreasing frequency into the childs
* array.
*/
int nodePtr = 2 * numLeafs;
for (int bits = maxLength; bits != 0; bits--) {
int n = bl_counts[bits-1];
while (n > 0) {
int childPtr = 2*childs[nodePtr++];
if (childs[childPtr + 1] == -1) {
// We found another leaf
length[childs[childPtr]] = (byte) bits;
n--;
}
}
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("*** After overflow elimination. ***");
// for (int i=0; i < numLeafs; i++) {
// //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]]
// + " len: "+length[childs[2*i]]);
// }
// }
}
}
#region Instance Fields
/// <summary>
/// Pending buffer to use
/// </summary>
public DeflaterPending pending;
Tree literalTree;
Tree distTree;
Tree blTree;
// Buffer for distances
short[] d_buf;
byte[] l_buf;
int last_lit;
int extra_bits;
#endregion
static DeflaterHuffman()
{
// See RFC 1951 3.2.6
// Literal codes
staticLCodes = new short[LITERAL_NUM];
staticLLength = new byte[LITERAL_NUM];
int i = 0;
while (i < 144) {
staticLCodes[i] = BitReverse((0x030 + i) << 8);
staticLLength[i++] = 8;
}
while (i < 256) {
staticLCodes[i] = BitReverse((0x190 - 144 + i) << 7);
staticLLength[i++] = 9;
}
while (i < 280) {
staticLCodes[i] = BitReverse((0x000 - 256 + i) << 9);
staticLLength[i++] = 7;
}
while (i < LITERAL_NUM) {
staticLCodes[i] = BitReverse((0x0c0 - 280 + i) << 8);
staticLLength[i++] = 8;
}
// Distance codes
staticDCodes = new short[DIST_NUM];
staticDLength = new byte[DIST_NUM];
for (i = 0; i < DIST_NUM; i++) {
staticDCodes[i] = BitReverse(i << 11);
staticDLength[i] = 5;
}
}
/// <summary>
/// Construct instance with pending buffer
/// </summary>
/// <param name="pending">Pending buffer to use</param>
public DeflaterHuffman(DeflaterPending pending)
{
this.pending = pending;
literalTree = new Tree(this, LITERAL_NUM, 257, 15);
distTree = new Tree(this, DIST_NUM, 1, 15);
blTree = new Tree(this, BITLEN_NUM, 4, 7);
d_buf = new short[BUFSIZE];
l_buf = new byte [BUFSIZE];
}
/// <summary>
/// Reset internal state
/// </summary>
public void Reset()
{
last_lit = 0;
extra_bits = 0;
literalTree.Reset();
distTree.Reset();
blTree.Reset();
}
/// <summary>
/// Write all trees to pending buffer
/// </summary>
/// <param name="blTreeCodes">The number/rank of treecodes to send.</param>
public void SendAllTrees(int blTreeCodes)
{
blTree.BuildCodes();
literalTree.BuildCodes();
distTree.BuildCodes();
pending.WriteBits(literalTree.numCodes - 257, 5);
pending.WriteBits(distTree.numCodes - 1, 5);
pending.WriteBits(blTreeCodes - 4, 4);
for (int rank = 0; rank < blTreeCodes; rank++) {
pending.WriteBits(blTree.length[BL_ORDER[rank]], 3);
}
literalTree.WriteTree(blTree);
distTree.WriteTree(blTree);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
blTree.CheckEmpty();
}
#endif
}
/// <summary>
/// Compress current buffer writing data to pending buffer
/// </summary>
public void CompressBlock()
{
for (int i = 0; i < last_lit; i++) {
int litlen = l_buf[i] & 0xff;
int dist = d_buf[i];
if (dist-- != 0) {
// if (DeflaterConstants.DEBUGGING) {
// Console.Write("["+(dist+1)+","+(litlen+3)+"]: ");
// }
int lc = Lcode(litlen);
literalTree.WriteSymbol(lc);
int bits = (lc - 261) / 4;
if (bits > 0 && bits <= 5) {
pending.WriteBits(litlen & ((1 << bits) - 1), bits);
}
int dc = Dcode(dist);
distTree.WriteSymbol(dc);
bits = dc / 2 - 1;
if (bits > 0) {
pending.WriteBits(dist & ((1 << bits) - 1), bits);
}
} else {
// if (DeflaterConstants.DEBUGGING) {
// if (litlen > 32 && litlen < 127) {
// Console.Write("("+(char)litlen+"): ");
// } else {
// Console.Write("{"+litlen+"}: ");
// }
// }
literalTree.WriteSymbol(litlen);
}
}
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.Write("EOF: ");
}
#endif
literalTree.WriteSymbol(EOF_SYMBOL);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
literalTree.CheckEmpty();
distTree.CheckEmpty();
}
#endif
}
/// <summary>
/// Flush block to output with no compression
/// </summary>
/// <param name="stored">Data to write</param>
/// <param name="storedOffset">Index of first byte to write</param>
/// <param name="storedLength">Count of bytes to write</param>
/// <param name="lastBlock">True if this is the last block</param>
public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock)
{
#if DebugDeflation
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Flushing stored block "+ storedLength);
// }
#endif
pending.WriteBits((DeflaterConstants.STORED_BLOCK << 1) + (lastBlock ? 1 : 0), 3);
pending.AlignToByte();
pending.WriteShort(storedLength);
pending.WriteShort(~storedLength);
pending.WriteBlock(stored, storedOffset, storedLength);
Reset();
}
/// <summary>
/// Flush block to output with compression
/// </summary>
/// <param name="stored">Data to flush</param>
/// <param name="storedOffset">Index of first byte to flush</param>
/// <param name="storedLength">Count of bytes to flush</param>
/// <param name="lastBlock">True if this is the last block</param>
public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock)
{
literalTree.freqs[EOF_SYMBOL]++;
// Build trees
literalTree.BuildTree();
distTree.BuildTree();
// Calculate bitlen frequency
literalTree.CalcBLFreq(blTree);
distTree.CalcBLFreq(blTree);
// Build bitlen tree
blTree.BuildTree();
int blTreeCodes = 4;
for (int i = 18; i > blTreeCodes; i--) {
if (blTree.length[BL_ORDER[i]] > 0) {
blTreeCodes = i+1;
}
}
int opt_len = 14 + blTreeCodes * 3 + blTree.GetEncodedLength() +
literalTree.GetEncodedLength() + distTree.GetEncodedLength() +
extra_bits;
int static_len = extra_bits;
for (int i = 0; i < LITERAL_NUM; i++) {
static_len += literalTree.freqs[i] * staticLLength[i];
}
for (int i = 0; i < DIST_NUM; i++) {
static_len += distTree.freqs[i] * staticDLength[i];
}
if (opt_len >= static_len) {
// Force static trees
opt_len = static_len;
}
if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3) {
// Store Block
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Storing, since " + storedLength + " < " + opt_len
// + " <= " + static_len);
// }
FlushStoredBlock(stored, storedOffset, storedLength, lastBlock);
} else if (opt_len == static_len) {
// Encode with static tree
pending.WriteBits((DeflaterConstants.STATIC_TREES << 1) + (lastBlock ? 1 : 0), 3);
literalTree.SetStaticCodes(staticLCodes, staticLLength);
distTree.SetStaticCodes(staticDCodes, staticDLength);
CompressBlock();
Reset();
} else {
// Encode with dynamic tree
pending.WriteBits((DeflaterConstants.DYN_TREES << 1) + (lastBlock ? 1 : 0), 3);
SendAllTrees(blTreeCodes);
CompressBlock();
Reset();
}
}
/// <summary>
/// Get value indicating if internal buffer is full
/// </summary>
/// <returns>true if buffer is full</returns>
public bool IsFull()
{
return last_lit >= BUFSIZE;
}
/// <summary>
/// Add literal to buffer
/// </summary>
/// <param name="literal">Literal value to add to buffer.</param>
/// <returns>Value indicating internal buffer is full</returns>
public bool TallyLit(int literal)
{
// if (DeflaterConstants.DEBUGGING) {
// if (lit > 32 && lit < 127) {
// //Console.WriteLine("("+(char)lit+")");
// } else {
// //Console.WriteLine("{"+lit+"}");
// }
// }
d_buf[last_lit] = 0;
l_buf[last_lit++] = (byte)literal;
literalTree.freqs[literal]++;
return IsFull();
}
/// <summary>
/// Add distance code and length to literal and distance trees
/// </summary>
/// <param name="distance">Distance code</param>
/// <param name="length">Length</param>
/// <returns>Value indicating if internal buffer is full</returns>
public bool TallyDist(int distance, int length)
{
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("[" + distance + "," + length + "]");
// }
d_buf[last_lit] = (short)distance;
l_buf[last_lit++] = (byte)(length - 3);
int lc = Lcode(length - 3);
literalTree.freqs[lc]++;
if (lc >= 265 && lc < 285) {
extra_bits += (lc - 261) / 4;
}
int dc = Dcode(distance - 1);
distTree.freqs[dc]++;
if (dc >= 4) {
extra_bits += dc / 2 - 1;
}
return IsFull();
}
/// <summary>
/// Reverse the bits of a 16 bit value.
/// </summary>
/// <param name="toReverse">Value to reverse bits</param>
/// <returns>Value with bits reversed</returns>
public static short BitReverse(int toReverse)
{
return (short) (bit4Reverse[toReverse & 0xF] << 12 |
bit4Reverse[(toReverse >> 4) & 0xF] << 8 |
bit4Reverse[(toReverse >> 8) & 0xF] << 4 |
bit4Reverse[toReverse >> 12]);
}
static int Lcode(int length)
{
if (length == 255) {
return 285;
}
int code = 257;
while (length >= 8) {
code += 4;
length >>= 1;
}
return code + length;
}
static int Dcode(int distance)
{
int code = 0;
while (distance >= 4) {
code += 2;
distance >>= 1;
}
return code + distance;
}
}
}
| |
using System;
using System.Globalization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OpenTelemetry.Trace;
using Quartz.Impl.Calendar;
using Quartz.Impl.Matchers;
using Quartz.Plugin.Interrupt;
using Serilog;
namespace Quartz.Examples.AspNetCore
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// make sure you configure logging and open telemetry before quartz services
services.AddLogging(loggingBuilder =>
{
loggingBuilder.ClearProviders();
loggingBuilder.AddSerilog(dispose: true);
});
services.AddOpenTelemetryTracing(builder =>
{
builder
.AddQuartzInstrumentation()
.AddZipkinExporter(o =>
{
o.Endpoint = new Uri("http://localhost:9411/api/v2/spans");
o.ServiceName = "Quartz.Examples.AspNetCore";
})
.AddJaegerExporter(o =>
{
o.ServiceName = "Quartz.Examples.AspNetCore";
// these are the defaults
o.AgentHost = "localhost";
o.AgentPort = 6831;
});
});
services.AddRazorPages();
// base configuration for DI, read from appSettings.json
services.Configure<QuartzOptions>(Configuration.GetSection("Quartz"));
// if you are using persistent job store, you might want to alter some options
services.Configure<QuartzOptions>(options =>
{
options.Scheduling.IgnoreDuplicates = true; // default: false
options.Scheduling.OverWriteExistingData = true; // default: true
});
services.AddQuartz(q =>
{
// handy when part of cluster or you want to otherwise identify multiple schedulers
q.SchedulerId = "Scheduler-Core";
// you can control whether job interruption happens for running jobs when scheduler is shutting down
q.InterruptJobsOnShutdown = true;
// when QuartzHostedServiceOptions.WaitForJobsToComplete = true or scheduler.Shutdown(waitForJobsToComplete: true)
q.InterruptJobsOnShutdownWithWait = true;
// we can change from the default of 1
q.MaxBatchSize = 5;
// we take this from appsettings.json, just show it's possible
// q.SchedulerName = "Quartz ASP.NET Core Sample Scheduler";
// this is default configuration if you don't alter it
q.UseMicrosoftDependencyInjectionJobFactory();
// these are the defaults
q.UseSimpleTypeLoader();
q.UseInMemoryStore();
q.UseDefaultThreadPool(maxConcurrency: 10);
// quickest way to create a job with single trigger is to use ScheduleJob
q.ScheduleJob<ExampleJob>(trigger => trigger
.WithIdentity("Combined Configuration Trigger")
.StartAt(DateBuilder.EvenSecondDate(DateTimeOffset.UtcNow.AddSeconds(7)))
.WithDailyTimeIntervalSchedule(x => x.WithInterval(10, IntervalUnit.Second))
.WithDescription("my awesome trigger configured for a job with single call")
);
// you can also configure individual jobs and triggers with code
// this allows you to associated multiple triggers with same job
// (if you want to have different job data map per trigger for example)
q.AddJob<ExampleJob>(j => j
.StoreDurably() // we need to store durably if no trigger is associated
.WithDescription("my awesome job")
);
// here's a known job for triggers
var jobKey = new JobKey("awesome job", "awesome group");
q.AddJob<ExampleJob>(jobKey, j => j
.WithDescription("my awesome job")
);
q.AddTrigger(t => t
.WithIdentity("Simple Trigger")
.ForJob(jobKey)
.StartNow()
.WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(10)).RepeatForever())
.WithDescription("my awesome simple trigger")
);
q.AddTrigger(t => t
.WithIdentity("Cron Trigger")
.ForJob(jobKey)
.StartAt(DateBuilder.EvenSecondDate(DateTimeOffset.UtcNow.AddSeconds(3)))
.WithCronSchedule("0/3 * * * * ?")
.WithDescription("my awesome cron trigger")
);
// auto-interrupt long-running job
q.UseJobAutoInterrupt(options =>
{
// this is the default
options.DefaultMaxRunTime = TimeSpan.FromMinutes(5);
});
q.ScheduleJob<SlowJob>(
triggerConfigurator => triggerConfigurator
.WithIdentity("slowJobTrigger")
.StartNow()
.WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever()),
jobConfigurator => jobConfigurator
.WithIdentity("slowJob")
.UsingJobData(JobInterruptMonitorPlugin.JobDataMapKeyAutoInterruptable, true)
// allow only five seconds for this job, overriding default configuration
.UsingJobData(JobInterruptMonitorPlugin.JobDataMapKeyMaxRunTime, TimeSpan.FromSeconds(5).TotalMilliseconds.ToString(CultureInfo.InvariantCulture)));
const string calendarName = "myHolidayCalendar";
q.AddCalendar<HolidayCalendar>(
name: calendarName,
replace: true,
updateTriggers: true,
x => x.AddExcludedDate(new DateTime(2020, 5, 15))
);
q.AddTrigger(t => t
.WithIdentity("Daily Trigger")
.ForJob(jobKey)
.StartAt(DateBuilder.EvenSecondDate(DateTimeOffset.UtcNow.AddSeconds(5)))
.WithDailyTimeIntervalSchedule(x => x.WithInterval(10, IntervalUnit.Second))
.WithDescription("my awesome daily time interval trigger")
.ModifiedByCalendar(calendarName)
);
// also add XML configuration and poll it for changes
q.UseXmlSchedulingConfiguration(x =>
{
x.Files = new[] { "~/quartz_jobs.config" };
x.ScanInterval = TimeSpan.FromMinutes(1);
x.FailOnFileNotFound = true;
x.FailOnSchedulingError = true;
});
// convert time zones using converter that can handle Windows/Linux differences
q.UseTimeZoneConverter();
// add some listeners
q.AddSchedulerListener<SampleSchedulerListener>();
q.AddJobListener<SampleJobListener>(GroupMatcher<JobKey>.GroupEquals(jobKey.Group));
q.AddTriggerListener<SampleTriggerListener>();
// example of persistent job store using JSON serializer as an example
/*
q.UsePersistentStore(s =>
{
s.UseProperties = true;
s.RetryInterval = TimeSpan.FromSeconds(15);
s.UseSqlServer(sqlServer =>
{
sqlServer.ConnectionString = "some connection string";
// this is the default
sqlServer.TablePrefix = "QRTZ_";
});
s.UseJsonSerializer();
s.UseClustering(c =>
{
c.CheckinMisfireThreshold = TimeSpan.FromSeconds(20);
c.CheckinInterval = TimeSpan.FromSeconds(10);
});
});
*/
});
// we can use options pattern to support hooking your own configuration with Quartz's
// because we don't use service registration api, we need to manally ensure the job is present in DI
services.AddTransient<ExampleJob>();
services.Configure<SampleOptions>(Configuration.GetSection("Sample"));
services.AddOptions<QuartzOptions>()
.Configure<IOptions<SampleOptions>>((options, dep) =>
{
if (!string.IsNullOrWhiteSpace(dep.Value.CronSchedule))
{
var jobKey = new JobKey("options-custom-job", "custom");
options.AddJob<ExampleJob>(j => j.WithIdentity(jobKey));
options.AddTrigger(trigger => trigger
.WithIdentity("options-custom-trigger", "custom")
.ForJob(jobKey)
.WithCronSchedule(dep.Value.CronSchedule));
}
});
// ASP.NET Core hosting
services.AddQuartzServer(options =>
{
// when shutting down we want jobs to complete gracefully
options.WaitForJobsToComplete = true;
});
services
.AddHealthChecksUI()
.AddInMemoryStorage();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapHealthChecksUI();
});
}
}
}
| |
//
// X501Name.cs: X.501 Distinguished Names stuff
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
using System.Text;
using Mono.Security;
using Mono.Security.Cryptography;
namespace Mono.Security.X509 {
// References:
// 1. Information technology - Open Systems Interconnection - The Directory: Models
// http://www.itu.int/rec/recommendation.asp?type=items&lang=e&parent=T-REC-X.501-200102-I
// 2. RFC2253: Lightweight Directory Access Protocol (v3): UTF-8 String Representation of Distinguished Names
// http://www.ietf.org/rfc/rfc2253.txt
/*
* Name ::= CHOICE { RDNSequence }
*
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
*/
internal sealed class X501 {
static byte[] countryName = { 0x55, 0x04, 0x06 };
static byte[] organizationName = { 0x55, 0x04, 0x0A };
static byte[] organizationalUnitName = { 0x55, 0x04, 0x0B };
static byte[] commonName = { 0x55, 0x04, 0x03 };
static byte[] localityName = { 0x55, 0x04, 0x07 };
static byte[] stateOrProvinceName = { 0x55, 0x04, 0x08 };
static byte[] streetAddress = { 0x55, 0x04, 0x09 };
//static byte[] serialNumber = { 0x55, 0x04, 0x05 };
static byte[] domainComponent = { 0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01, 0x19 };
static byte[] userid = { 0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01, 0x01 };
static byte[] email = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01 };
static byte[] dnQualifier = { 0x55, 0x04, 0x2E };
static byte[] title = { 0x55, 0x04, 0x0C };
static byte[] surname = { 0x55, 0x04, 0x04 };
static byte[] givenName = { 0x55, 0x04, 0x2A };
static byte[] initial = { 0x55, 0x04, 0x2B };
private X501 ()
{
}
static public string ToString (ASN1 seq)
{
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < seq.Count; i++) {
ASN1 entry = seq [i];
AppendEntry (sb, entry, true);
// separator (not on last iteration)
if (i < seq.Count - 1)
sb.Append (", ");
}
return sb.ToString ();
}
static public string ToString (ASN1 seq, bool reversed, string separator, bool quotes)
{
StringBuilder sb = new StringBuilder ();
if (reversed) {
for (int i = seq.Count - 1; i >= 0; i--) {
ASN1 entry = seq [i];
AppendEntry (sb, entry, quotes);
// separator (not on last iteration)
if (i > 0)
sb.Append (separator);
}
} else {
for (int i = 0; i < seq.Count; i++) {
ASN1 entry = seq [i];
AppendEntry (sb, entry, quotes);
// separator (not on last iteration)
if (i < seq.Count - 1)
sb.Append (separator);
}
}
return sb.ToString ();
}
static private void AppendEntry (StringBuilder sb, ASN1 entry, bool quotes)
{
// multiple entries are valid
for (int k = 0; k < entry.Count; k++) {
ASN1 pair = entry [k];
ASN1 s = pair [1];
if (s == null)
continue;
ASN1 poid = pair [0];
if (poid == null)
continue;
if (poid.CompareValue (countryName))
sb.Append ("C=");
else if (poid.CompareValue (organizationName))
sb.Append ("O=");
else if (poid.CompareValue (organizationalUnitName))
sb.Append ("OU=");
else if (poid.CompareValue (commonName))
sb.Append ("CN=");
else if (poid.CompareValue (localityName))
sb.Append ("L=");
else if (poid.CompareValue (stateOrProvinceName))
sb.Append ("S="); // NOTE: RFC2253 uses ST=
else if (poid.CompareValue (streetAddress))
sb.Append ("STREET=");
else if (poid.CompareValue (domainComponent))
sb.Append ("DC=");
else if (poid.CompareValue (userid))
sb.Append ("UID=");
else if (poid.CompareValue (email))
sb.Append ("E="); // NOTE: Not part of RFC2253
else if (poid.CompareValue (dnQualifier))
sb.Append ("dnQualifier=");
else if (poid.CompareValue (title))
sb.Append ("T=");
else if (poid.CompareValue (surname))
sb.Append ("SN=");
else if (poid.CompareValue (givenName))
sb.Append ("G=");
else if (poid.CompareValue (initial))
sb.Append ("I=");
else {
// unknown OID
sb.Append ("OID."); // NOTE: Not present as RFC2253
sb.Append (ASN1Convert.ToOid (poid));
sb.Append ("=");
}
string sValue = null;
// 16bits or 8bits string ? TODO not complete (+special chars!)
if (s.Tag == 0x1E) {
// BMPSTRING
StringBuilder sb2 = new StringBuilder ();
for (int j = 1; j < s.Value.Length; j += 2)
sb2.Append ((char)s.Value[j]);
sValue = sb2.ToString ();
} else {
if (s.Tag == 0x14)
sValue = Encoding.UTF7.GetString (s.Value);
else
sValue = Encoding.UTF8.GetString (s.Value);
// in some cases we must quote (") the value
// Note: this doesn't seems to conform to RFC2253
char[] specials = { ',', '+', '"', '\\', '<', '>', ';' };
if (quotes) {
if ((sValue.IndexOfAny (specials, 0, sValue.Length) > 0) ||
sValue.StartsWith (" ") || (sValue.EndsWith (" ")))
sValue = "\"" + sValue + "\"";
}
}
sb.Append (sValue);
// separator (not on last iteration)
if (k < entry.Count - 1)
sb.Append (", ");
}
}
static private X520.AttributeTypeAndValue GetAttributeFromOid (string attributeType)
{
string s = attributeType.ToUpper (CultureInfo.InvariantCulture).Trim ();
switch (s) {
case "C":
return new X520.CountryName ();
case "O":
return new X520.OrganizationName ();
case "OU":
return new X520.OrganizationalUnitName ();
case "CN":
return new X520.CommonName ();
case "L":
return new X520.LocalityName ();
case "S": // Microsoft
case "ST": // RFC2253
return new X520.StateOrProvinceName ();
case "E": // NOTE: Not part of RFC2253
return new X520.EmailAddress ();
case "DC": // RFC2247
return new X520.DomainComponent ();
case "UID": // RFC1274
return new X520.UserId ();
case "DNQUALIFIER":
return new X520.DnQualifier ();
case "T":
return new X520.Title ();
case "SN":
return new X520.Surname ();
case "G":
return new X520.GivenName ();
case "I":
return new X520.Initial ();
default:
if (s.StartsWith ("OID.")) {
// MUST support it but it OID may be without it
return new X520.Oid (s.Substring (4));
} else {
if (IsOid (s))
return new X520.Oid (s);
else
return null;
}
}
}
static private bool IsOid (string oid)
{
try {
ASN1 asn = ASN1Convert.FromOid (oid);
return (asn.Tag == 0x06);
}
catch {
return false;
}
}
// no quote processing
static private X520.AttributeTypeAndValue ReadAttribute (string value, ref int pos)
{
while ((value[pos] == ' ') && (pos < value.Length))
pos++;
// get '=' position in substring
int equal = value.IndexOf ('=', pos);
if (equal == -1) {
string msg = Locale.GetText ("No attribute found.");
throw new FormatException (msg);
}
string s = value.Substring (pos, equal - pos);
X520.AttributeTypeAndValue atv = GetAttributeFromOid (s);
if (atv == null) {
string msg = Locale.GetText ("Unknown attribute '{0}'.");
throw new FormatException (String.Format (msg, s));
}
pos = equal + 1; // skip the '='
return atv;
}
static private bool IsHex (char c)
{
if (Char.IsDigit (c))
return true;
char up = Char.ToUpper (c, CultureInfo.InvariantCulture);
return ((up >= 'A') && (up <= 'F'));
}
static string ReadHex (string value, ref int pos)
{
StringBuilder sb = new StringBuilder ();
// it is (at least an) 8 bits char
sb.Append (value[pos++]);
sb.Append (value[pos]);
// look ahead for a 16 bits char
if ((pos < value.Length - 4) && (value[pos+1] == '\\') && IsHex (value[pos+2])) {
pos += 2; // pass last char and skip \
sb.Append (value[pos++]);
sb.Append (value[pos]);
}
byte[] data = CryptoConvert.FromHex (sb.ToString ());
return Encoding.UTF8.GetString (data);
}
static private int ReadEscaped (StringBuilder sb, string value, int pos)
{
switch (value[pos]) {
case '\\':
case '"':
case '=':
case ';':
case '<':
case '>':
case '+':
case '#':
case ',':
sb.Append (value[pos]);
return pos;
default:
if (pos >= value.Length - 2) {
string msg = Locale.GetText ("Malformed escaped value '{0}'.");
throw new FormatException (string.Format (msg, value.Substring (pos)));
}
// it's either a 8 bits or 16 bits char
sb.Append (ReadHex (value, ref pos));
return pos;
}
}
static private int ReadQuoted (StringBuilder sb, string value, int pos)
{
int original = pos;
while (pos <= value.Length) {
switch (value[pos]) {
case '"':
return pos;
case '\\':
return ReadEscaped (sb, value, pos);
default:
sb.Append (value[pos]);
pos++;
break;
}
}
string msg = Locale.GetText ("Malformed quoted value '{0}'.");
throw new FormatException (string.Format (msg, value.Substring (original)));
}
static private string ReadValue (string value, ref int pos)
{
int original = pos;
StringBuilder sb = new StringBuilder ();
while (pos < value.Length) {
switch (value [pos]) {
case '\\':
pos = ReadEscaped (sb, value, ++pos);
break;
case '"':
pos = ReadQuoted (sb, value, ++pos);
break;
case '=':
case ';':
case '<':
case '>':
string msg = Locale.GetText ("Malformed value '{0}' contains '{1}' outside quotes.");
throw new FormatException (string.Format (msg, value.Substring (original), value[pos]));
case '+':
case '#':
throw new NotImplementedException ();
case ',':
pos++;
return sb.ToString ();
default:
sb.Append (value[pos]);
break;
}
pos++;
}
return sb.ToString ();
}
static public ASN1 FromString (string rdn)
{
if (rdn == null)
throw new ArgumentNullException ("rdn");
int pos = 0;
ASN1 asn1 = new ASN1 (0x30);
while (pos < rdn.Length) {
X520.AttributeTypeAndValue atv = ReadAttribute (rdn, ref pos);
atv.Value = ReadValue (rdn, ref pos);
ASN1 sequence = new ASN1 (0x31);
sequence.Add (atv.GetASN1 ());
asn1.Add (sequence);
}
return asn1;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using System.Collections.Generic;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
using NPOI.XSSF.Util;
namespace NPOI.XSSF.UserModel.Helpers
{
/**
* Helper class for dealing with the Column Settings on
* a CT_Worksheet (the data part of a sheet).
* Note - within POI, we use 0 based column indexes, but
* the column defInitions in the XML are 1 based!
*/
public class ColumnHelper
{
private CT_Worksheet worksheet;
private CT_Cols newCols;
public ColumnHelper(CT_Worksheet worksheet)
{
this.worksheet = worksheet;
CleanColumns();
}
public void CleanColumns()
{
this.newCols = new CT_Cols();
CT_Cols aggregateCols = new CT_Cols();
List<CT_Cols> colsList = worksheet.GetColsList();
if (colsList == null)
{
return;
}
foreach (CT_Cols cols in colsList)
{
foreach (CT_Col col in cols.GetColList())
{
CloneCol(aggregateCols, col);
}
}
SortColumns(aggregateCols);
CT_Col[] colArray = aggregateCols.GetColList().ToArray();
SweepCleanColumns(newCols, colArray, null);
int i = colsList.Count;
for (int y = i - 1; y >= 0; y--)
{
worksheet.RemoveCols(y);
}
worksheet.AddNewCols();
worksheet.SetColsArray(0, newCols);
}
//YK: GetXYZArray() array accessors are deprecated in xmlbeans with JDK 1.5 support
public static void SortColumns(CT_Cols newCols)
{
List<CT_Col> colArray = newCols.GetColList();
colArray.Sort(new CTColComparator());
newCols.SetColArray(colArray);
}
public CT_Col CloneCol(CT_Cols cols, CT_Col col)
{
CT_Col newCol = cols.AddNewCol();
newCol.min = (uint)(col.min);
newCol.max = (uint)(col.max);
SetColumnAttributes(col, newCol);
return newCol;
}
/**
* Returns the Column at the given 0 based index
*/
public CT_Col GetColumn(long index, bool splitColumns)
{
return GetColumn1Based(index + 1, splitColumns);
}
/**
* Returns the Column at the given 1 based index.
* POI default is 0 based, but the file stores
* as 1 based.
*/
public CT_Col GetColumn1Based(long index1, bool splitColumns)
{
CT_Cols colsArray = worksheet.GetColsArray(0);
// Fetching the array is quicker than working on the new style
// list, assuming we need to read many of them (which we often do),
// and assuming we're not making many changes (which we're not)
CT_Col[] cols = colsArray.GetColList().ToArray();
for (int i = 0; i < cols.Length; i++)
{
CT_Col colArray = cols[i];
long colMin = colArray.min;
long colMax = colArray.max;
if (colMin <= index1 && colMax >= index1)
{
if (splitColumns)
{
if (colMin < index1)
{
insertCol(colsArray, colMin, (index1 - 1), new CT_Col[] { colArray });
}
if (colMax > index1)
{
insertCol(colsArray, (index1 + 1), colMax, new CT_Col[] { colArray });
}
colArray.min = (uint)(index1);
colArray.max = (uint)(index1);
}
return colArray;
}
}
return null;
}
public CT_Cols AddCleanColIntoCols(CT_Cols cols, CT_Col col)
{
CT_Cols newCols = new CT_Cols();
foreach (CT_Col c in cols.GetColList())
{
CloneCol(newCols, c);
}
CloneCol(newCols, col);
SortColumns(newCols);
CT_Col[] colArray = newCols.GetColList().ToArray();
CT_Cols returnCols = new CT_Cols();
SweepCleanColumns(returnCols, colArray, col);
colArray = returnCols.GetColList().ToArray();
cols.SetColArray(colArray);
return returnCols;
}
public class TreeSet<T>
{
private SortedList<T, object> innerObj;
public TreeSet(IComparer<T> comparer)
{
innerObj = new SortedList<T, object>(comparer);
}
public T First()
{
IEnumerator<T> enumerator = this.innerObj.Keys.GetEnumerator();
if (enumerator.MoveNext())
return enumerator.Current;
return default(T);
}
public T Higher(T element)
{
IEnumerator<T> enumerator = this.innerObj.Keys.GetEnumerator();
while (enumerator.MoveNext())
{
if (this.innerObj.Comparer.Compare(enumerator.Current, element) > 0)
return enumerator.Current;
}
return default(T);
}
public void Add(T item)
{
this.innerObj.Add(item,null);
}
public bool Remove(T item)
{
return this.innerObj.Remove(item);
}
public int Count
{
get { return this.innerObj.Count; }
}
public void CopyTo(T[] target)
{
for (int i = 0; i < this.innerObj.Count; i++)
{
target[i] = (T)this.innerObj.Keys[i];
}
}
public IEnumerator<T> GetEnumerator()
{
return this.innerObj.Keys.GetEnumerator();
}
}
/**
* @see <a href="http://en.wikipedia.org/wiki/Sweep_line_algorithm">Sweep line algorithm</a>
*/
private void SweepCleanColumns(CT_Cols cols, CT_Col[] flattenedColsArray, CT_Col overrideColumn)
{
List<CT_Col> flattenedCols = new List<CT_Col>(flattenedColsArray);
TreeSet<CT_Col> currentElements = new TreeSet<CT_Col>(CTColComparator.BY_MAX);
IEnumerator<CT_Col> flIter = flattenedCols.GetEnumerator();
CT_Col haveOverrideColumn = null;
long lastMaxIndex = 0;
long currentMax = 0;
IList<CT_Col> toRemove = new List<CT_Col>();
int pos = -1;
//while (flIter.hasNext())
while ((pos + 1) < flattenedCols.Count)
{
//CTCol col = flIter.next();
pos++;
CT_Col col = flattenedCols[pos];
long currentIndex = col.min;
long colMax = col.max;
long nextIndex = (colMax > currentMax) ? colMax : currentMax;
//if (flIter.hasNext()) {
if((pos+1)<flattenedCols.Count)
{
//nextIndex = flIter.next().getMin();
nextIndex = flattenedCols[pos + 1].min;
//flIter.previous();
}
IEnumerator<CT_Col> iter = currentElements.GetEnumerator();
toRemove.Clear();
while (iter.MoveNext())
{
CT_Col elem = iter.Current;
if (currentIndex <= elem.max) break; // all passed elements have been purged
//iter.remove();
toRemove.Add(elem);
}
foreach (CT_Col rc in toRemove)
{
currentElements.Remove(rc);
}
if (!(currentElements.Count == 0) && lastMaxIndex < currentIndex)
{
// we need to process previous elements first
CT_Col[] copyCols = new CT_Col[currentElements.Count];
currentElements.CopyTo(copyCols);
insertCol(cols, lastMaxIndex, currentIndex - 1, copyCols, true, haveOverrideColumn);
}
currentElements.Add(col);
if (colMax > currentMax) currentMax = colMax;
if (col.Equals(overrideColumn)) haveOverrideColumn = overrideColumn;
while (currentIndex <= nextIndex && !(currentElements.Count == 0))
{
NPOI.Util.Collections.HashSet<CT_Col> currentIndexElements = new NPOI.Util.Collections.HashSet<CT_Col>();
long currentElemIndex;
{
// narrow scope of currentElem
CT_Col currentElem = currentElements.First();
currentElemIndex = currentElem.max;
currentIndexElements.Add(currentElem);
while (true)
{
CT_Col higherElem = currentElements.Higher(currentElem);
if (higherElem == null || higherElem.max != currentElemIndex)
break;
currentElem = higherElem;
currentIndexElements.Add(currentElem);
if (colMax > currentMax) currentMax = colMax;
if (col.Equals(overrideColumn)) haveOverrideColumn = overrideColumn;
}
}
//if (currentElemIndex < nextIndex || !flIter.hasNext()) {
if (currentElemIndex < nextIndex || !((pos + 1) < flattenedCols.Count))
{
CT_Col[] copyCols = new CT_Col[currentElements.Count];
currentElements.CopyTo(copyCols);
insertCol(cols, currentIndex, currentElemIndex, copyCols, true, haveOverrideColumn);
//if (flIter.hasNext()) {
if ((pos + 1) < flattenedCols.Count)
{
if (nextIndex > currentElemIndex)
{
//currentElements.removeAll(currentIndexElements);
foreach (CT_Col rc in currentIndexElements)
currentElements.Remove(rc);
if (currentIndexElements.Contains(overrideColumn)) haveOverrideColumn = null;
}
}
else
{
//currentElements.removeAll(currentIndexElements);
foreach (CT_Col rc in currentIndexElements)
currentElements.Remove(rc);
if (currentIndexElements.Contains(overrideColumn)) haveOverrideColumn = null;
}
lastMaxIndex = currentIndex = currentElemIndex + 1;
}
else
{
lastMaxIndex = currentIndex;
currentIndex = nextIndex + 1;
}
}
}
SortColumns(cols);
}
//public CT_Cols AddCleanColIntoCols(CT_Cols cols, CT_Col col)
//{
// bool colOverlaps = false;
// // a Map to remember overlapping columns
// Dictionary<long, bool> overlappingCols = new Dictionary<long, bool>();
// int sizeOfColArray = cols.sizeOfColArray();
// for (int i = 0; i < sizeOfColArray; i++)
// {
// CT_Col ithCol = cols.GetColArray(i);
// long[] range1 = { ithCol.min, ithCol.max };
// long[] range2 = { col.min, col.max };
// long[] overlappingRange = NumericRanges.GetOverlappingRange(range1,
// range2);
// int overlappingType = NumericRanges.GetOverlappingType(range1,
// range2);
// // different behavior required for each of the 4 different
// // overlapping types
// if (overlappingType == NumericRanges.OVERLAPS_1_MINOR)
// {
// // move the max border of the ithCol
// // and insert a new column within the overlappingRange with merged column attributes
// ithCol.max = (uint)(overlappingRange[0] - 1);
// insertCol(cols, overlappingRange[0],
// overlappingRange[1], new CT_Col[] { ithCol, col });
// i++;
// //CT_Col newCol = insertCol(cols, (overlappingRange[1] + 1), col
// // .max, new CT_Col[] { col });
// //i++;
// }
// else if (overlappingType == NumericRanges.OVERLAPS_2_MINOR)
// {
// // move the min border of the ithCol
// // and insert a new column within the overlappingRange with merged column attributes
// ithCol.min = (uint)(overlappingRange[1] + 1);
// insertCol(cols, overlappingRange[0],
// overlappingRange[1], new CT_Col[] { ithCol, col });
// i++;
// //CT_Col newCol = insertCol(cols, col.min,
// // (overlappingRange[0] - 1), new CT_Col[] { col });
// //i++;
// }
// else if (overlappingType == NumericRanges.OVERLAPS_2_WRAPS)
// {
// // merge column attributes, no new column is needed
// SetColumnAttributes(col, ithCol);
// }
// else if (overlappingType == NumericRanges.OVERLAPS_1_WRAPS)
// {
// // split the ithCol in three columns: before the overlappingRange, overlappingRange, and after the overlappingRange
// // before overlappingRange
// if (col.min != ithCol.min)
// {
// insertCol(cols, ithCol.min, (col
// .min - 1), new CT_Col[] { ithCol });
// i++;
// }
// // after the overlappingRange
// if (col.max != ithCol.max)
// {
// insertCol(cols, (col.max + 1),
// ithCol.max, new CT_Col[] { ithCol });
// i++;
// }
// // within the overlappingRange
// ithCol.min = (uint)(overlappingRange[0]);
// ithCol.max = (uint)(overlappingRange[1]);
// SetColumnAttributes(col, ithCol);
// }
// if (overlappingType != NumericRanges.NO_OVERLAPS)
// {
// colOverlaps = true;
// // remember overlapped columns
// for (long j = overlappingRange[0]; j <= overlappingRange[1]; j++)
// {
// overlappingCols.Add(j, true);
// }
// }
// }
// if (!colOverlaps)
// {
// CloneCol(cols, col);
// }
// else
// {
// // insert new columns for ranges without overlaps
// long colMin = -1;
// for (long j = col.min; j <= col.max; j++)
// {
// if (overlappingCols.ContainsKey(j) && !overlappingCols[j])
// {
// if (colMin < 0)
// {
// colMin = j;
// }
// if ((j + 1) > col.max || overlappingCols[(j + 1)])
// {
// insertCol(cols, colMin, j, new CT_Col[] { col });
// colMin = -1;
// }
// }
// }
// }
// SortColumns(cols);
// return cols;
//}
/*
* Insert a new CT_Col at position 0 into cols, Setting min=min, max=max and
* copying all the colsWithAttributes array cols attributes into newCol
*/
private CT_Col insertCol(CT_Cols cols, long min, long max,
CT_Col[] colsWithAttributes)
{
return insertCol(cols, min, max, colsWithAttributes, false, null);
}
private CT_Col insertCol(CT_Cols cols, long min, long max,
CT_Col[] colsWithAttributes, bool ignoreExistsCheck, CT_Col overrideColumn)
{
if (ignoreExistsCheck || !columnExists(cols, min, max))
{
CT_Col newCol = cols.InsertNewCol(0);
newCol.min = (uint)(min);
newCol.max = (uint)(max);
foreach (CT_Col col in colsWithAttributes)
{
SetColumnAttributes(col, newCol);
}
if (overrideColumn != null) SetColumnAttributes(overrideColumn, newCol);
return newCol;
}
return null;
}
/**
* Does the column at the given 0 based index exist
* in the supplied list of column defInitions?
*/
public bool columnExists(CT_Cols cols, long index)
{
return columnExists1Based(cols, index + 1);
}
private bool columnExists1Based(CT_Cols cols, long index1)
{
for (int i = 0; i < cols.sizeOfColArray(); i++)
{
if (cols.GetColArray(i).min == index1)
{
return true;
}
}
return false;
}
public void SetColumnAttributes(CT_Col fromCol, CT_Col toCol)
{
if (fromCol.IsSetBestFit())
{
toCol.bestFit = (fromCol.bestFit);
}
if (fromCol.IsSetCustomWidth())
{
toCol.customWidth = (fromCol.customWidth);
}
if (fromCol.IsSetHidden())
{
toCol.hidden = (fromCol.hidden);
}
if (fromCol.IsSetStyle())
{
toCol.style = (fromCol.style);
toCol.styleSpecified = fromCol.styleSpecified;
}
if (fromCol.IsSetWidth())
{
toCol.width = (fromCol.width);
toCol.widthSpecified = fromCol.widthSpecified;
}
if (fromCol.IsSetCollapsed())
{
toCol.collapsed = (fromCol.collapsed);
toCol.collapsedSpecified = fromCol.collapsedSpecified;
}
if (fromCol.IsSetPhonetic())
{
toCol.phonetic = (fromCol.phonetic);
}
if (fromCol.IsSetOutlineLevel())
{
toCol.outlineLevel = (fromCol.outlineLevel);
}
if (fromCol.IsSetCollapsed())
{
toCol.collapsed = fromCol.collapsed;
}
}
public void SetColBestFit(long index, bool bestFit)
{
CT_Col col = GetOrCreateColumn1Based(index + 1, false);
col.bestFit = (bestFit);
}
public void SetCustomWidth(long index, bool width)
{
CT_Col col = GetOrCreateColumn1Based(index + 1, true);
col.customWidth = (width);
}
public void SetColWidth(long index, double width)
{
CT_Col col = GetOrCreateColumn1Based(index + 1, true);
col.width = (width);
}
public void SetColHidden(long index, bool hidden)
{
CT_Col col = GetOrCreateColumn1Based(index + 1, true);
col.hidden = (hidden);
}
/**
* Return the CT_Col at the given (0 based) column index,
* creating it if required.
*/
internal CT_Col GetOrCreateColumn1Based(long index1, bool splitColumns)
{
CT_Col col = GetColumn1Based(index1, splitColumns);
if (col == null)
{
col = worksheet.GetColsArray(0).AddNewCol();
col.min = (uint)(index1);
col.max = (uint)(index1);
}
return col;
}
public void SetColDefaultStyle(long index, ICellStyle style)
{
SetColDefaultStyle(index, style.Index);
}
public void SetColDefaultStyle(long index, int styleId)
{
CT_Col col = GetOrCreateColumn1Based(index + 1, true);
col.style = (uint)styleId;
col.styleSpecified = true;
}
// Returns -1 if no column is found for the given index
public int GetColDefaultStyle(long index)
{
if (GetColumn(index, false) != null)
{
return (int)GetColumn(index, false).style;
}
return -1;
}
private bool columnExists(CT_Cols cols, long min, long max)
{
for (int i = 0; i < cols.sizeOfColArray(); i++)
{
if (cols.GetColArray(i).min == min && cols.GetColArray(i).max == max)
{
return true;
}
}
return false;
}
public int GetIndexOfColumn(CT_Cols cols, CT_Col col)
{
for (int i = 0; i < cols.sizeOfColArray(); i++)
{
if (cols.GetColArray(i).min == col.min && cols.GetColArray(i).max == col.max)
{
return i;
}
}
return -1;
}
}
}
| |
using System;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using ServiceStack.Common;
using ServiceStack.Common.Utils;
using ServiceStack.Common.Web;
using ServiceStack.FluentValidation;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.ServiceModel;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints;
using ServiceStack.WebHost.Endpoints.Extensions;
using ServiceStack.Text;
namespace ServiceStack.ServiceInterface.Auth
{
/// <summary>
/// Inject logic into existing services by introspecting the request and injecting your own
/// validation logic. Exceptions thrown will have the same behaviour as if the service threw it.
///
/// If a non-null object is returned the request will short-circuit and return that response.
/// </summary>
/// <param name="service">The instance of the service</param>
/// <param name="httpMethod">GET,POST,PUT,DELETE</param>
/// <param name="requestDto"></param>
/// <returns>Response DTO; non-null will short-circuit execution and return that response</returns>
public delegate object ValidateFn(IServiceBase service, string httpMethod, object requestDto);
public class Auth
{
public string provider { get; set; }
public string State { get; set; }
public string oauth_token { get; set; }
public string oauth_verifier { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class AuthResponse
{
public AuthResponse()
{
this.ResponseStatus = new ResponseStatus();
}
public string SessionId { get; set; }
public string UserName { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class AuthService : RestServiceBase<Auth>
{
public const string BasicProvider = "basic";
public const string CredentialsProvider = "credentials";
public const string LogoutAction = "logout";
public static string DefaultOAuthProvider { get; private set; }
public static string DefaultOAuthRealm { get; private set; }
public static AuthConfig[] AuthConfigs { get; private set; }
public static Func<IAuthSession> SessionFactory { get; private set; }
public static ValidateFn ValidateFn { get; set; }
public static string GetSessionKey(string sessionId)
{
return IdUtils.CreateUrn<IAuthSession>(sessionId);
}
public static void Init(IAppHost appHost, Func<IAuthSession> sessionFactory, params AuthConfig[] authConfigs)
{
if (authConfigs.Length == 0)
throw new ArgumentNullException("authConfigs");
DefaultOAuthProvider = authConfigs[0].Provider;
DefaultOAuthRealm = authConfigs[0].AuthRealm;
AuthConfigs = authConfigs;
SessionFactory = sessionFactory;
appHost.RegisterService<AuthService>();
SessionFeature.Init(appHost);
}
private void AssertAuthProviders()
{
if (AuthConfigs == null || AuthConfigs.Length == 0)
throw new ConfigurationException("No OAuth providers have been registered in your AppHost.");
}
public override object OnGet(Auth request)
{
if (ValidateFn != null)
{
var response = ValidateFn(this, HttpMethods.Get, request);
if (response != null) return response;
}
AssertAuthProviders();
if (request.provider == LogoutAction)
{
this.RemoveSession();
return new AuthResponse();
}
var provider = request.provider ?? AuthConfigs[0].Provider;
if (provider == BasicProvider || provider == CredentialsProvider)
{
return CredentialsAuth(request);
}
var oAuthConfig = AuthConfigs.FirstOrDefault(x => x.Provider == provider);
if (oAuthConfig == null)
throw HttpError.NotFound("No configuration was added for OAuth provider '{0}'".Fmt(provider));
var session = this.GetSession();
if (oAuthConfig.CallbackUrl.IsNullOrEmpty())
oAuthConfig.CallbackUrl = base.RequestContext.AbsoluteUri;
if (session.ReferrerUrl.IsNullOrEmpty())
session.ReferrerUrl = base.RequestContext.GetHeader("Referer") ?? oAuthConfig.CallbackUrl;
var oAuth = new OAuthAuthorizer(oAuthConfig);
if (!session.IsAuthorized(provider))
{
var tokens = session.ProviderOAuthAccess.FirstOrDefault(x => x.Provider == provider);
if (tokens == null)
session.ProviderOAuthAccess.Add(tokens = new OAuthTokens { Provider = provider });
return oAuthConfig.Authenticate(this, request, session, tokens, oAuth);
}
//Already Authenticated
return this.Redirect(session.ReferrerUrl.AddHashParam("s", "0"));
}
public override object OnPost(Auth request)
{
if (ValidateFn != null)
{
var response = ValidateFn(this, HttpMethods.Post, request);
if (response != null) return response;
}
return CredentialsAuth(request);
}
public override object OnDelete(Auth request)
{
if (ValidateFn != null)
{
var response = ValidateFn(this, HttpMethods.Delete, request);
if (response != null) return response;
}
this.RemoveSession();
return new AuthResponse();
}
class CredentialsAuthValidator : AbstractValidator<Auth>
{
public CredentialsAuthValidator()
{
RuleFor(x => x.provider)
.Must(x => x == BasicProvider || x == CredentialsProvider)
.WithErrorCode("InvalidProvider")
.WithMessage("Provider must be either 'basic' or 'credentials'");
RuleFor(x => x.UserName).NotEmpty();
RuleFor(x => x.Password).NotEmpty();
}
}
private object CredentialsAuth(Auth request)
{
AssertAuthProviders();
new CredentialsAuthValidator().ValidateAndThrow(request);
var userName = request.UserName;
var password = request.Password;
var session = this.GetSession();
if (request.provider == BasicProvider)
{
var httpReq = base.RequestContext.Get<IHttpRequest>();
var basicAuth = httpReq.GetBasicAuthUserAndPassword();
if (basicAuth == null)
throw HttpError.Unauthorized("Invalid BasicAuth credentials");
userName = basicAuth.Value.Key;
password = basicAuth.Value.Value;
}
if (session.TryAuthenticate(this, userName, password))
{
if (session.UserName == null)
session.UserName = userName;
this.SaveSession(session);
return new AuthResponse {
UserName = userName,
SessionId = session.Id,
};
}
throw HttpError.Unauthorized("Invalid UserName or Password");
}
}
}
| |
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Newtonsoft.Json.Linq;
using Orchard.ContentManagement;
using Orchard.Data;
using Orchard.DisplayManagement;
using Orchard.Forms.Services;
using Orchard.Localization;
using Orchard.Mvc;
using Orchard.Mvc.Extensions;
using Orchard.Security;
using Orchard.Themes;
using System;
using Orchard.Settings;
using Orchard.UI.Navigation;
using Orchard.UI.Notify;
using Orchard.Workflows.Models;
using Orchard.Workflows.Services;
using Orchard.Workflows.ViewModels;
namespace Orchard.Workflows.Controllers {
[ValidateInput(false)]
public class AdminController : Controller, IUpdateModel {
private readonly ISiteService _siteService;
private readonly IRepository<WorkflowDefinitionRecord> _workflowDefinitionRecords;
private readonly IRepository<WorkflowRecord> _workflowRecords;
private readonly IActivitiesManager _activitiesManager;
private readonly IFormManager _formManager;
public AdminController(
IOrchardServices services,
IShapeFactory shapeFactory,
ISiteService siteService,
IRepository<WorkflowDefinitionRecord> workflowDefinitionRecords,
IRepository<WorkflowRecord> workflowRecords,
IActivitiesManager activitiesManager,
IFormManager formManager
) {
_siteService = siteService;
_workflowDefinitionRecords = workflowDefinitionRecords;
_workflowRecords = workflowRecords;
_activitiesManager = activitiesManager;
_formManager = formManager;
Services = services;
T = NullLocalizer.Instance;
New = shapeFactory;
}
dynamic New { get; set; }
public IOrchardServices Services { get; set; }
public Localizer T { get; set; }
public ActionResult Index(AdminIndexOptions options, PagerParameters pagerParameters) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list workflows")))
return new HttpUnauthorizedResult();
var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);
// default options
if (options == null)
options = new AdminIndexOptions();
var queries = _workflowDefinitionRecords.Table;
switch (options.Filter) {
case WorkflowDefinitionFilter.All:
break;
default:
throw new ArgumentOutOfRangeException();
}
if (!String.IsNullOrWhiteSpace(options.Search)) {
queries = queries.Where(w => w.Name.Contains(options.Search));
}
var pagerShape = New.Pager(pager).TotalItemCount(queries.Count());
switch (options.Order) {
case WorkflowDefinitionOrder.Name:
queries = queries.OrderBy(u => u.Name);
break;
}
if (pager.GetStartIndex() > 0) {
queries = queries.Skip(pager.GetStartIndex());
}
if (pager.PageSize > 0) {
queries = queries.Take(pager.PageSize);
}
var results = queries.ToList();
var model = new AdminIndexViewModel {
WorkflowDefinitions = results.Select(x => new WorkflowDefinitionEntry {
WorkflowDefinitionRecord = x,
WokflowDefinitionId = x.Id,
Name = x.Name
}).ToList(),
Options = options,
Pager = pagerShape
};
// maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Filter", options.Filter);
routeData.Values.Add("Options.Search", options.Search);
routeData.Values.Add("Options.Order", options.Order);
pagerShape.RouteData(routeData);
return View(model);
}
public ActionResult List(int id) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list workflows")))
return new HttpUnauthorizedResult();
var contentItem = Services.ContentManager.Get(id, VersionOptions.Latest);
if (contentItem == null) {
return HttpNotFound();
}
var workflows = _workflowRecords.Table.Where(x => x.ContentItemRecord == contentItem.Record).ToList();
var viewModel = New.ViewModel(
ContentItem: contentItem,
Workflows: workflows
);
return View(viewModel);
}
public ActionResult Create() {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to create workflows")))
return new HttpUnauthorizedResult();
return View();
}
[HttpPost, ActionName("Create")]
public ActionResult CreatePost(string name) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to create workflows")))
return new HttpUnauthorizedResult();
var workflowDefinitionRecord = new WorkflowDefinitionRecord {
Name = name
};
_workflowDefinitionRecords.Create(workflowDefinitionRecord);
return RedirectToAction("Edit", new { workflowDefinitionRecord.Id });
}
public ActionResult Edit(int id, string localId, int? workflowId) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
// convert the workflow definition into its view model
var workflowDefinitionRecord = _workflowDefinitionRecords.Get(id);
var workflowDefinitionViewModel = CreateWorkflowDefinitionViewModel(workflowDefinitionRecord);
var workflow = workflowId.HasValue ? _workflowRecords.Get(workflowId.Value) : null;
var viewModel = new AdminEditViewModel {
LocalId = String.IsNullOrEmpty(localId) ? Guid.NewGuid().ToString() : localId,
IsLocal = !String.IsNullOrEmpty(localId),
WorkflowDefinition = workflowDefinitionViewModel,
AllActivities = _activitiesManager.GetActivities(),
Workflow = workflow
};
return View(viewModel);
}
[HttpPost]
public ActionResult Delete(int id) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage workflows")))
return new HttpUnauthorizedResult();
var workflowDefinition = _workflowDefinitionRecords.Get(id);
if (workflowDefinition != null) {
_workflowDefinitionRecords.Delete(workflowDefinition);
Services.Notifier.Information(T("Workflow {0} deleted", workflowDefinition.Name));
}
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult DeleteWorkflow(int id, string returnUrl) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage workflows")))
return new HttpUnauthorizedResult();
var workflow = _workflowRecords.Get(id);
if (workflow != null) {
_workflowRecords.Delete(workflow);
Services.Notifier.Information(T("Workflow deleted"));
}
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index"));
}
private WorkflowDefinitionViewModel CreateWorkflowDefinitionViewModel(WorkflowDefinitionRecord workflowDefinitionRecord) {
if (workflowDefinitionRecord == null) {
throw new ArgumentNullException("workflowDefinitionRecord");
}
var workflowDefinitionModel = new WorkflowDefinitionViewModel {
Id = workflowDefinitionRecord.Id,
Name = workflowDefinitionRecord.Name
};
dynamic workflow = new JObject();
workflow.Activities = new JArray(workflowDefinitionRecord.ActivityRecords.Select(x => {
dynamic activity = new JObject();
activity.Name = x.Name;
activity.Id = x.Id;
activity.ClientId = x.Name + "_" + x.Id;
activity.Left = x.X;
activity.Top = x.Y;
activity.Start = x.Start;
activity.State = FormParametersHelper.FromJsonString(x.State);
return activity;
}));
workflow.Connections = new JArray(workflowDefinitionRecord.TransitionRecords.Select(x => {
dynamic connection = new JObject();
connection.Id = x.Id;
connection.SourceId = x.SourceActivityRecord.Name + "_" + x.SourceActivityRecord.Id;
connection.TargetId = x.DestinationActivityRecord.Name + "_" + x.DestinationActivityRecord.Id;
connection.SourceEndpoint = x.SourceEndpoint;
return connection;
}));
workflowDefinitionModel.JsonData = FormParametersHelper.ToJsonString(workflow);
return workflowDefinitionModel;
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Save")]
public ActionResult EditPost(int id, string localId, string data) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
var workflowDefinitionRecord = _workflowDefinitionRecords.Get(id);
if (workflowDefinitionRecord == null) {
return HttpNotFound();
}
workflowDefinitionRecord.Enabled = true;
var state = FormParametersHelper.FromJsonString(data);
var activitiesIndex = new Dictionary<string, ActivityRecord>();
workflowDefinitionRecord.ActivityRecords.Clear();
foreach (var activity in state.Activities) {
ActivityRecord activityRecord;
workflowDefinitionRecord.ActivityRecords.Add(activityRecord = new ActivityRecord {
Name = activity.Name,
X = activity.Left,
Y = activity.Top,
Start = activity.Start,
State = FormParametersHelper.ToJsonString(activity.State),
WorkflowDefinitionRecord = workflowDefinitionRecord
});
activitiesIndex.Add((string)activity.ClientId, activityRecord);
}
workflowDefinitionRecord.TransitionRecords.Clear();
foreach (var connection in state.Connections) {
workflowDefinitionRecord.TransitionRecords.Add(new TransitionRecord {
SourceActivityRecord = activitiesIndex[(string)connection.SourceId],
DestinationActivityRecord = activitiesIndex[(string)connection.TargetId],
SourceEndpoint = connection.SourceEndpoint,
WorkflowDefinitionRecord = workflowDefinitionRecord
});
}
Services.Notifier.Information(T("Workflow saved successfully"));
return RedirectToAction("Edit", new { id, localId });
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Cancel")]
public ActionResult EditPostCancel() {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
return View();
}
[Themed(false)]
[HttpPost]
public ActionResult RenderActivity(ActivityViewModel model) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
var activity = _activitiesManager.GetActivityByName(model.Name);
if (activity == null) {
return HttpNotFound();
}
dynamic shape = New.Activity(activity);
if (model.State != null) {
var state = FormParametersHelper.ToDynamic(FormParametersHelper.ToString(model.State));
shape.State(state);
}
else {
shape.State(FormParametersHelper.FromJsonString("{}"));
}
shape.Metadata.Alternates.Add("Activity__" + activity.Name);
return new ShapeResult(this, shape);
}
public ActionResult EditActivity(string localId, string clientId, ActivityViewModel model) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
var activity = _activitiesManager.GetActivityByName(model.Name);
if (activity == null) {
return HttpNotFound();
}
// build the form, and let external components alter it
var form = activity.Form == null ? null : _formManager.Build(activity.Form);
// form is bound on client side
var viewModel = New.ViewModel(LocalId: localId, ClientId: clientId, Form: form);
return View(viewModel);
}
[HttpPost, ActionName("EditActivity")]
[FormValueRequired("_submit.Save")]
public ActionResult EditActivityPost(int id, string localId, string name, string clientId, FormCollection formValues) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
var activity = _activitiesManager.GetActivityByName(name);
if (activity == null) {
return HttpNotFound();
}
// validating form values
_formManager.Validate(new ValidatingContext { FormName = activity.Form, ModelState = ModelState, ValueProvider = ValueProvider });
// stay on the page if there are validation errors
if (!ModelState.IsValid) {
// build the form, and let external components alter it
var form = activity.Form == null ? null : _formManager.Build(activity.Form);
// bind form with existing values.
_formManager.Bind(form, ValueProvider);
var viewModel = New.ViewModel(Id: id, LocalId: localId, Form: form);
return View(viewModel);
}
var model = new UpdatedActivityModel {
ClientId = clientId,
Data = HttpUtility.JavaScriptStringEncode(FormParametersHelper.ToJsonString(formValues))
};
TempData["UpdatedViewModel"] = model;
return RedirectToAction("Edit", new {
id,
localId
});
}
[HttpPost, ActionName("EditActivity")]
[FormValueRequired("_submit.Cancel")]
public ActionResult EditActivityPostCancel(int id, string localId, string name, string clientId, FormCollection formValues) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
return new HttpUnauthorizedResult();
return RedirectToAction("Edit", new {id, localId });
}
bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) {
return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
}
public void AddModelError(string key, LocalizedString errorMessage) {
ModelState.AddModelError(key, errorMessage.ToString());
}
}
}
| |
namespace ThreePaneApplication
{
partial class Form1
{
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printPreviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.customizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.indexToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.searchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.newToolStripButton = new System.Windows.Forms.ToolStripButton();
this.openToolStripButton = new System.Windows.Forms.ToolStripButton();
this.saveToolStripButton = new System.Windows.Forms.ToolStripButton();
this.printToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripButton = new System.Windows.Forms.ToolStripButton();
this.copyToolStripButton = new System.Windows.Forms.ToolStripButton();
this.pasteToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.helpToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.kryptonPanelMain = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.kryptonSplitContainerMain = new ComponentFactory.Krypton.Toolkit.KryptonSplitContainer();
this.kryptonHeaderGroupNavigation = new ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup();
this.kryptonSplitContainerDetails = new ComponentFactory.Krypton.Toolkit.KryptonSplitContainer();
this.kryptonHeaderGroupDetails = new ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup();
this.kryptonButtonGroup = new ComponentFactory.Krypton.Toolkit.KryptonGroup();
this.kryptonGroup1 = new ComponentFactory.Krypton.Toolkit.KryptonGroup();
this.kryptonSparkleOrange = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton();
this.kryptonSparklePurple = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton();
this.kryptonSparkleBlue = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton();
this.kryptonCustom = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton();
this.kryptonSystem = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton();
this.kryptonOffice2003 = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton();
this.kryptonOffice2007Black = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton();
this.kryptonOffice2007Silver = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton();
this.kryptonOffice2007Blue = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton();
this.kryptonManager = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components);
this.kryptonPaletteCustom = new ComponentFactory.Krypton.Toolkit.KryptonPalette(this.components);
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.kryptonOffice2010Black = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton();
this.kryptonOffice2010Silver = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton();
this.kryptonOffice2010Blue = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton();
this.menuStrip1.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanelMain)).BeginInit();
this.kryptonPanelMain.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerMain)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerMain.Panel1)).BeginInit();
this.kryptonSplitContainerMain.Panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerMain.Panel2)).BeginInit();
this.kryptonSplitContainerMain.Panel2.SuspendLayout();
this.kryptonSplitContainerMain.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupNavigation)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupNavigation.Panel)).BeginInit();
this.kryptonHeaderGroupNavigation.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerDetails)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerDetails.Panel1)).BeginInit();
this.kryptonSplitContainerDetails.Panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerDetails.Panel2)).BeginInit();
this.kryptonSplitContainerDetails.Panel2.SuspendLayout();
this.kryptonSplitContainerDetails.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupDetails)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupDetails.Panel)).BeginInit();
this.kryptonHeaderGroupDetails.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonButtonGroup)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonButtonGroup.Panel)).BeginInit();
this.kryptonButtonGroup.Panel.SuspendLayout();
this.kryptonButtonGroup.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonGroup1.Panel)).BeginInit();
this.kryptonGroup1.Panel.SuspendLayout();
this.kryptonGroup1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Font = new System.Drawing.Font("Segoe UI", 9F);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.toolsToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(443, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripMenuItem,
this.openToolStripMenuItem,
this.toolStripSeparator,
this.saveToolStripMenuItem,
this.saveAsToolStripMenuItem,
this.toolStripSeparator1,
this.printToolStripMenuItem,
this.printPreviewToolStripMenuItem,
this.toolStripSeparator2,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// newToolStripMenuItem
//
this.newToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripMenuItem.Image")));
this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.newToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.newToolStripMenuItem.Text = "&New";
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image")));
this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.openToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.openToolStripMenuItem.Text = "&Open";
//
// toolStripSeparator
//
this.toolStripSeparator.Name = "toolStripSeparator";
this.toolStripSeparator.Size = new System.Drawing.Size(143, 6);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image")));
this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.saveToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.saveToolStripMenuItem.Text = "&Save";
//
// saveAsToolStripMenuItem
//
this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.saveAsToolStripMenuItem.Text = "Save &As";
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(143, 6);
//
// printToolStripMenuItem
//
this.printToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripMenuItem.Image")));
this.printToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printToolStripMenuItem.Name = "printToolStripMenuItem";
this.printToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P)));
this.printToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.printToolStripMenuItem.Text = "&Print";
//
// printPreviewToolStripMenuItem
//
this.printPreviewToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printPreviewToolStripMenuItem.Image")));
this.printPreviewToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printPreviewToolStripMenuItem.Name = "printPreviewToolStripMenuItem";
this.printPreviewToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.printPreviewToolStripMenuItem.Text = "Print Pre&view";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(143, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.exitToolStripMenuItem.Text = "E&xit";
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem,
this.toolStripSeparator3,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.toolStripSeparator4,
this.selectAllToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "&Edit";
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
this.undoToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.undoToolStripMenuItem.Text = "&Undo";
//
// redoToolStripMenuItem
//
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y)));
this.redoToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.redoToolStripMenuItem.Text = "&Redo";
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(141, 6);
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripMenuItem.Image")));
this.cutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X)));
this.cutToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.cutToolStripMenuItem.Text = "Cu&t";
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripMenuItem.Image")));
this.copyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.copyToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.copyToolStripMenuItem.Text = "&Copy";
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripMenuItem.Image")));
this.pasteToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.pasteToolStripMenuItem.Text = "&Paste";
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(141, 6);
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.selectAllToolStripMenuItem.Text = "Select &All";
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.customizeToolStripMenuItem,
this.optionsToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.toolsToolStripMenuItem.Text = "&Tools";
//
// customizeToolStripMenuItem
//
this.customizeToolStripMenuItem.Name = "customizeToolStripMenuItem";
this.customizeToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.customizeToolStripMenuItem.Text = "&Customize";
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.optionsToolStripMenuItem.Text = "&Options";
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.contentsToolStripMenuItem,
this.indexToolStripMenuItem,
this.searchToolStripMenuItem,
this.toolStripSeparator5,
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// contentsToolStripMenuItem
//
this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem";
this.contentsToolStripMenuItem.Size = new System.Drawing.Size(122, 22);
this.contentsToolStripMenuItem.Text = "&Contents";
//
// indexToolStripMenuItem
//
this.indexToolStripMenuItem.Name = "indexToolStripMenuItem";
this.indexToolStripMenuItem.Size = new System.Drawing.Size(122, 22);
this.indexToolStripMenuItem.Text = "&Index";
//
// searchToolStripMenuItem
//
this.searchToolStripMenuItem.Name = "searchToolStripMenuItem";
this.searchToolStripMenuItem.Size = new System.Drawing.Size(122, 22);
this.searchToolStripMenuItem.Text = "&Search";
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(119, 6);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(122, 22);
this.aboutToolStripMenuItem.Text = "&About...";
//
// toolStrip1
//
this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None;
this.toolStrip1.Font = new System.Drawing.Font("Segoe UI", 9F);
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripButton,
this.openToolStripButton,
this.saveToolStripButton,
this.printToolStripButton,
this.toolStripSeparator6,
this.cutToolStripButton,
this.copyToolStripButton,
this.pasteToolStripButton,
this.toolStripSeparator7,
this.helpToolStripButton});
this.toolStrip1.Location = new System.Drawing.Point(3, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(208, 25);
this.toolStrip1.TabIndex = 1;
this.toolStrip1.Text = "toolStrip1";
//
// newToolStripButton
//
this.newToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.newToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripButton.Image")));
this.newToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.newToolStripButton.Name = "newToolStripButton";
this.newToolStripButton.Size = new System.Drawing.Size(23, 22);
this.newToolStripButton.Text = "&New";
//
// openToolStripButton
//
this.openToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.openToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripButton.Image")));
this.openToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripButton.Name = "openToolStripButton";
this.openToolStripButton.Size = new System.Drawing.Size(23, 22);
this.openToolStripButton.Text = "&Open";
//
// saveToolStripButton
//
this.saveToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.saveToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripButton.Image")));
this.saveToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripButton.Name = "saveToolStripButton";
this.saveToolStripButton.Size = new System.Drawing.Size(23, 22);
this.saveToolStripButton.Text = "&Save";
//
// printToolStripButton
//
this.printToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.printToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripButton.Image")));
this.printToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printToolStripButton.Name = "printToolStripButton";
this.printToolStripButton.Size = new System.Drawing.Size(23, 22);
this.printToolStripButton.Text = "&Print";
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25);
//
// cutToolStripButton
//
this.cutToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.cutToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripButton.Image")));
this.cutToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutToolStripButton.Name = "cutToolStripButton";
this.cutToolStripButton.Size = new System.Drawing.Size(23, 22);
this.cutToolStripButton.Text = "C&ut";
//
// copyToolStripButton
//
this.copyToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.copyToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripButton.Image")));
this.copyToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyToolStripButton.Name = "copyToolStripButton";
this.copyToolStripButton.Size = new System.Drawing.Size(23, 22);
this.copyToolStripButton.Text = "&Copy";
//
// pasteToolStripButton
//
this.pasteToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.pasteToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripButton.Image")));
this.pasteToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteToolStripButton.Name = "pasteToolStripButton";
this.pasteToolStripButton.Size = new System.Drawing.Size(23, 22);
this.pasteToolStripButton.Text = "&Paste";
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(6, 25);
//
// helpToolStripButton
//
this.helpToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.helpToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("helpToolStripButton.Image")));
this.helpToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.helpToolStripButton.Name = "helpToolStripButton";
this.helpToolStripButton.Size = new System.Drawing.Size(23, 22);
this.helpToolStripButton.Text = "He&lp";
//
// toolStripContainer1
//
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.Controls.Add(this.kryptonPanelMain);
this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(443, 400);
this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer1.Location = new System.Drawing.Point(0, 24);
this.toolStripContainer1.Name = "toolStripContainer1";
this.toolStripContainer1.Size = new System.Drawing.Size(443, 425);
this.toolStripContainer1.TabIndex = 1;
this.toolStripContainer1.Text = "toolStripContainer1";
//
// toolStripContainer1.TopToolStripPanel
//
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip1);
//
// kryptonPanelMain
//
this.kryptonPanelMain.Controls.Add(this.kryptonSplitContainerMain);
this.kryptonPanelMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonPanelMain.Location = new System.Drawing.Point(0, 0);
this.kryptonPanelMain.Name = "kryptonPanelMain";
this.kryptonPanelMain.Padding = new System.Windows.Forms.Padding(4);
this.kryptonPanelMain.Size = new System.Drawing.Size(443, 400);
this.kryptonPanelMain.TabIndex = 0;
//
// kryptonSplitContainerMain
//
this.kryptonSplitContainerMain.Cursor = System.Windows.Forms.Cursors.Default;
this.kryptonSplitContainerMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonSplitContainerMain.Location = new System.Drawing.Point(4, 4);
this.kryptonSplitContainerMain.Name = "kryptonSplitContainerMain";
//
// kryptonSplitContainerMain.Panel1
//
this.kryptonSplitContainerMain.Panel1.Controls.Add(this.kryptonHeaderGroupNavigation);
//
// kryptonSplitContainerMain.Panel2
//
this.kryptonSplitContainerMain.Panel2.Controls.Add(this.kryptonSplitContainerDetails);
this.kryptonSplitContainerMain.Size = new System.Drawing.Size(435, 392);
this.kryptonSplitContainerMain.SplitterDistance = 127;
this.kryptonSplitContainerMain.TabIndex = 0;
//
// kryptonHeaderGroupNavigation
//
this.kryptonHeaderGroupNavigation.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonHeaderGroupNavigation.Location = new System.Drawing.Point(0, 0);
this.kryptonHeaderGroupNavigation.Name = "kryptonHeaderGroupNavigation";
this.kryptonHeaderGroupNavigation.Size = new System.Drawing.Size(127, 392);
this.kryptonHeaderGroupNavigation.TabIndex = 0;
this.kryptonHeaderGroupNavigation.ValuesPrimary.Image = null;
//
// kryptonSplitContainerDetails
//
this.kryptonSplitContainerDetails.Cursor = System.Windows.Forms.Cursors.Default;
this.kryptonSplitContainerDetails.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonSplitContainerDetails.Location = new System.Drawing.Point(0, 0);
this.kryptonSplitContainerDetails.Name = "kryptonSplitContainerDetails";
this.kryptonSplitContainerDetails.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// kryptonSplitContainerDetails.Panel1
//
this.kryptonSplitContainerDetails.Panel1.Controls.Add(this.kryptonHeaderGroupDetails);
//
// kryptonSplitContainerDetails.Panel2
//
this.kryptonSplitContainerDetails.Panel2.Controls.Add(this.kryptonButtonGroup);
this.kryptonSplitContainerDetails.Size = new System.Drawing.Size(303, 392);
this.kryptonSplitContainerDetails.SplitterDistance = 171;
this.kryptonSplitContainerDetails.TabIndex = 0;
//
// kryptonHeaderGroupDetails
//
this.kryptonHeaderGroupDetails.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonHeaderGroupDetails.HeaderVisibleSecondary = false;
this.kryptonHeaderGroupDetails.Location = new System.Drawing.Point(0, 0);
this.kryptonHeaderGroupDetails.Name = "kryptonHeaderGroupDetails";
this.kryptonHeaderGroupDetails.Size = new System.Drawing.Size(303, 171);
this.kryptonHeaderGroupDetails.StateNormal.HeaderPrimary.Content.Image.ImageH = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Far;
this.kryptonHeaderGroupDetails.TabIndex = 0;
this.kryptonHeaderGroupDetails.ValuesPrimary.Image = ((System.Drawing.Image)(resources.GetObject("kryptonHeaderGroupDetails.ValuesPrimary.Image")));
//
// kryptonButtonGroup
//
this.kryptonButtonGroup.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonButtonGroup.GroupBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.ControlAlternate;
this.kryptonButtonGroup.GroupBorderStyle = ComponentFactory.Krypton.Toolkit.PaletteBorderStyle.ControlAlternate;
this.kryptonButtonGroup.Location = new System.Drawing.Point(0, 0);
this.kryptonButtonGroup.Name = "kryptonButtonGroup";
//
// kryptonButtonGroup.Panel
//
this.kryptonButtonGroup.Panel.Controls.Add(this.kryptonGroup1);
this.kryptonButtonGroup.Panel.Padding = new System.Windows.Forms.Padding(5);
this.kryptonButtonGroup.Size = new System.Drawing.Size(303, 216);
this.kryptonButtonGroup.StateCommon.Back.Color1 = System.Drawing.SystemColors.AppWorkspace;
this.kryptonButtonGroup.StateCommon.Back.ColorAngle = 45F;
this.kryptonButtonGroup.StateCommon.Back.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Solid;
this.kryptonButtonGroup.TabIndex = 0;
//
// kryptonGroup1
//
this.kryptonGroup1.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonGroup1.Location = new System.Drawing.Point(5, 5);
this.kryptonGroup1.Name = "kryptonGroup1";
//
// kryptonGroup1.Panel
//
this.kryptonGroup1.Panel.Controls.Add(this.kryptonOffice2010Black);
this.kryptonGroup1.Panel.Controls.Add(this.kryptonSparkleOrange);
this.kryptonGroup1.Panel.Controls.Add(this.kryptonOffice2010Blue);
this.kryptonGroup1.Panel.Controls.Add(this.kryptonOffice2010Silver);
this.kryptonGroup1.Panel.Controls.Add(this.kryptonSparklePurple);
this.kryptonGroup1.Panel.Controls.Add(this.kryptonSparkleBlue);
this.kryptonGroup1.Panel.Controls.Add(this.kryptonCustom);
this.kryptonGroup1.Panel.Controls.Add(this.kryptonSystem);
this.kryptonGroup1.Panel.Controls.Add(this.kryptonOffice2003);
this.kryptonGroup1.Panel.Controls.Add(this.kryptonOffice2007Black);
this.kryptonGroup1.Panel.Controls.Add(this.kryptonOffice2007Silver);
this.kryptonGroup1.Panel.Controls.Add(this.kryptonOffice2007Blue);
this.kryptonGroup1.Size = new System.Drawing.Size(291, 204);
this.kryptonGroup1.TabIndex = 0;
//
// kryptonSparkleOrange
//
this.kryptonSparkleOrange.Location = new System.Drawing.Point(13, 126);
this.kryptonSparkleOrange.Name = "kryptonSparkleOrange";
this.kryptonSparkleOrange.Size = new System.Drawing.Size(110, 19);
this.kryptonSparkleOrange.TabIndex = 7;
this.kryptonSparkleOrange.Values.Text = "Sparkle - Orange";
this.kryptonSparkleOrange.CheckedChanged += new System.EventHandler(this.kryptonSparkleOrange_CheckedChanged);
//
// kryptonSparklePurple
//
this.kryptonSparklePurple.Location = new System.Drawing.Point(13, 151);
this.kryptonSparklePurple.Name = "kryptonSparklePurple";
this.kryptonSparklePurple.Size = new System.Drawing.Size(104, 19);
this.kryptonSparklePurple.TabIndex = 8;
this.kryptonSparklePurple.Values.Text = "Sparkle - Purple";
this.kryptonSparklePurple.CheckedChanged += new System.EventHandler(this.kryptonSparklePurple_CheckedChanged);
//
// kryptonSparkleBlue
//
this.kryptonSparkleBlue.Location = new System.Drawing.Point(13, 101);
this.kryptonSparkleBlue.Name = "kryptonSparkleBlue";
this.kryptonSparkleBlue.Size = new System.Drawing.Size(93, 19);
this.kryptonSparkleBlue.TabIndex = 6;
this.kryptonSparkleBlue.Values.Text = "Sparkle - Blue";
this.kryptonSparkleBlue.CheckedChanged += new System.EventHandler(this.kryptonSparkleBlue_CheckedChanged);
//
// kryptonCustom
//
this.kryptonCustom.Location = new System.Drawing.Point(147, 151);
this.kryptonCustom.Name = "kryptonCustom";
this.kryptonCustom.Size = new System.Drawing.Size(62, 19);
this.kryptonCustom.TabIndex = 11;
this.kryptonCustom.Values.Text = "Custom";
this.kryptonCustom.CheckedChanged += new System.EventHandler(this.kryptonCustom_CheckedChanged);
//
// kryptonSystem
//
this.kryptonSystem.Location = new System.Drawing.Point(147, 126);
this.kryptonSystem.Name = "kryptonSystem";
this.kryptonSystem.Size = new System.Drawing.Size(59, 19);
this.kryptonSystem.TabIndex = 10;
this.kryptonSystem.Values.Text = "System";
this.kryptonSystem.CheckedChanged += new System.EventHandler(this.kryptonSystem_CheckedChanged);
//
// kryptonOffice2003
//
this.kryptonOffice2003.Location = new System.Drawing.Point(147, 101);
this.kryptonOffice2003.Name = "kryptonOffice2003";
this.kryptonOffice2003.Size = new System.Drawing.Size(81, 19);
this.kryptonOffice2003.TabIndex = 9;
this.kryptonOffice2003.Values.Text = "Office 2003";
this.kryptonOffice2003.CheckedChanged += new System.EventHandler(this.kryptonOffice2003_CheckedChanged);
//
// kryptonOffice2007Black
//
this.kryptonOffice2007Black.Location = new System.Drawing.Point(147, 66);
this.kryptonOffice2007Black.Name = "kryptonOffice2007Black";
this.kryptonOffice2007Black.Size = new System.Drawing.Size(119, 19);
this.kryptonOffice2007Black.TabIndex = 5;
this.kryptonOffice2007Black.Values.Text = "Office 2007 - Black";
this.kryptonOffice2007Black.CheckedChanged += new System.EventHandler(this.kryptonOffice2007Black_CheckedChanged);
//
// kryptonOffice2007Silver
//
this.kryptonOffice2007Silver.Location = new System.Drawing.Point(147, 41);
this.kryptonOffice2007Silver.Name = "kryptonOffice2007Silver";
this.kryptonOffice2007Silver.Size = new System.Drawing.Size(120, 19);
this.kryptonOffice2007Silver.TabIndex = 4;
this.kryptonOffice2007Silver.Values.Text = "Office 2007 - Silver";
this.kryptonOffice2007Silver.CheckedChanged += new System.EventHandler(this.kryptonOffice2007Silver_CheckedChanged);
//
// kryptonOffice2007Blue
//
this.kryptonOffice2007Blue.Location = new System.Drawing.Point(147, 16);
this.kryptonOffice2007Blue.Name = "kryptonOffice2007Blue";
this.kryptonOffice2007Blue.Size = new System.Drawing.Size(114, 19);
this.kryptonOffice2007Blue.TabIndex = 3;
this.kryptonOffice2007Blue.Values.Text = "Office 2007 - Blue";
this.kryptonOffice2007Blue.CheckedChanged += new System.EventHandler(this.kryptonOffice2007Blue_CheckedChanged);
//
// kryptonPaletteCustom
//
this.kryptonPaletteCustom.AllowFormChrome = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.kryptonPaletteCustom.BasePaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.ProfessionalSystem;
this.kryptonPaletteCustom.ButtonStyles.ButtonButtonSpec.StateDisabled.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.kryptonPaletteCustom.ButtonStyles.ButtonButtonSpec.StateDisabled.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonButtonSpec.StateNormal.Back.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.kryptonPaletteCustom.ButtonStyles.ButtonButtonSpec.StateNormal.Border.Color1 = System.Drawing.Color.Transparent;
this.kryptonPaletteCustom.ButtonStyles.ButtonButtonSpec.StateNormal.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.True;
this.kryptonPaletteCustom.ButtonStyles.ButtonButtonSpec.StateNormal.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonButtonSpec.StateNormal.Content.LongText.Color1 = System.Drawing.Color.Black;
this.kryptonPaletteCustom.ButtonStyles.ButtonButtonSpec.StateNormal.Content.Padding = new System.Windows.Forms.Padding(3);
this.kryptonPaletteCustom.ButtonStyles.ButtonButtonSpec.StateNormal.Content.ShortText.Color1 = System.Drawing.Color.Black;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCheckedNormal.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCheckedPressed.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(102)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCheckedPressed.Content.Padding = new System.Windows.Forms.Padding(5, 5, 1, 1);
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCheckedTracking.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(102)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCommon.Back.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Solid;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCommon.Border.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCommon.Border.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Solid;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCommon.Border.GraphicsHint = ComponentFactory.Krypton.Toolkit.PaletteGraphicsHint.AntiAlias;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCommon.Border.Rounding = 3;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCommon.Border.Width = 2;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCommon.Content.LongText.Color1 = System.Drawing.Color.White;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCommon.Content.LongText.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Solid;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCommon.Content.Padding = new System.Windows.Forms.Padding(3);
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCommon.Content.ShortText.Color1 = System.Drawing.Color.White;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateCommon.Content.ShortText.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Solid;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateDisabled.Border.Color1 = System.Drawing.Color.Silver;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateDisabled.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateDisabled.Content.LongText.Color1 = System.Drawing.Color.Silver;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateDisabled.Content.ShortText.Color1 = System.Drawing.Color.Silver;
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateNormal.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(102)))), ((int)(((byte)(204)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StatePressed.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StatePressed.Content.Padding = new System.Windows.Forms.Padding(5, 5, 1, 1);
this.kryptonPaletteCustom.ButtonStyles.ButtonCommon.StateTracking.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonLowProfile.StateDisabled.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.kryptonPaletteCustom.ButtonStyles.ButtonLowProfile.StateDisabled.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonLowProfile.StateNormal.Back.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.kryptonPaletteCustom.ButtonStyles.ButtonLowProfile.StateNormal.Border.Color1 = System.Drawing.Color.Transparent;
this.kryptonPaletteCustom.ButtonStyles.ButtonLowProfile.StateNormal.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.True;
this.kryptonPaletteCustom.ButtonStyles.ButtonLowProfile.StateNormal.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonLowProfile.StateNormal.Content.LongText.Color1 = System.Drawing.Color.Black;
this.kryptonPaletteCustom.ButtonStyles.ButtonLowProfile.StateNormal.Content.Padding = new System.Windows.Forms.Padding(3);
this.kryptonPaletteCustom.ButtonStyles.ButtonLowProfile.StateNormal.Content.ShortText.Color1 = System.Drawing.Color.Black;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.OverrideDefault.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(102)))), ((int)(((byte)(204)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateDisabled.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(237)))), ((int)(((byte)(227)))));
this.kryptonPaletteCustom.ControlStyles.ControlCommon.StateCommon.Border.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Solid;
this.kryptonPaletteCustom.ControlStyles.ControlCommon.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ControlStyles.ControlCommon.StateCommon.Border.GraphicsHint = ComponentFactory.Krypton.Toolkit.PaletteGraphicsHint.AntiAlias;
this.kryptonPaletteCustom.ControlStyles.ControlCommon.StateCommon.Border.Rounding = 9;
this.kryptonPaletteCustom.ControlStyles.ControlCommon.StateCommon.Border.Width = 3;
this.kryptonPaletteCustom.ControlStyles.ControlCommon.StateDisabled.Border.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.kryptonPaletteCustom.ControlStyles.ControlCommon.StateDisabled.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ControlStyles.ControlCommon.StateNormal.Border.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(212)))), ((int)(((byte)(192)))));
this.kryptonPaletteCustom.ControlStyles.ControlCommon.StateNormal.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.HeaderGroup.StateCommon.OverlayHeaders = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.kryptonPaletteCustom.HeaderGroup.StateCommon.PrimaryHeaderPadding = new System.Windows.Forms.Padding(3);
this.kryptonPaletteCustom.HeaderGroup.StateCommon.SecondaryHeaderPadding = new System.Windows.Forms.Padding(3);
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Back.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Linear;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Back.GraphicsHint = ComponentFactory.Krypton.Toolkit.PaletteGraphicsHint.AntiAlias;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Border.Rounding = 7;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Border.Width = 3;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Content.AdjacentGap = 2;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Content.LongText.Color1 = System.Drawing.Color.Black;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Content.LongText.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Solid;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Content.LongText.TextH = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Far;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Content.Padding = new System.Windows.Forms.Padding(10, 2, 10, 2);
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Content.ShortText.Color1 = System.Drawing.Color.Black;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Content.ShortText.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Solid;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateCommon.Content.ShortText.TextH = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Near;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateDisabled.Content.LongText.Color1 = System.Drawing.Color.Silver;
this.kryptonPaletteCustom.HeaderStyles.HeaderCommon.StateDisabled.Content.ShortText.Color1 = System.Drawing.Color.Silver;
this.kryptonPaletteCustom.HeaderStyles.HeaderPrimary.StateDisabled.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.kryptonPaletteCustom.HeaderStyles.HeaderPrimary.StateDisabled.Back.Color2 = System.Drawing.Color.White;
this.kryptonPaletteCustom.HeaderStyles.HeaderPrimary.StateNormal.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(213)))), ((int)(((byte)(194)))));
this.kryptonPaletteCustom.HeaderStyles.HeaderPrimary.StateNormal.Back.Color2 = System.Drawing.Color.White;
this.kryptonPaletteCustom.HeaderStyles.HeaderSecondary.StateDisabled.Back.Color1 = System.Drawing.Color.White;
this.kryptonPaletteCustom.HeaderStyles.HeaderSecondary.StateDisabled.Back.Color2 = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.kryptonPaletteCustom.HeaderStyles.HeaderSecondary.StateNormal.Back.Color1 = System.Drawing.Color.White;
this.kryptonPaletteCustom.HeaderStyles.HeaderSecondary.StateNormal.Back.Color2 = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(213)))), ((int)(((byte)(194)))));
this.kryptonPaletteCustom.PanelStyles.PanelAlternate.StateCommon.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(212)))), ((int)(((byte)(192)))));
this.kryptonPaletteCustom.PanelStyles.PanelClient.StateCommon.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(237)))), ((int)(((byte)(227)))));
this.kryptonPaletteCustom.PanelStyles.PanelCommon.StateCommon.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Solid;
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonCheckedGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(102)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonCheckedGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(102)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonCheckedGradientMiddle = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(102)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonCheckedHighlight = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonCheckedHighlightBorder = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonPressedBorder = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonPressedGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonPressedGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonPressedGradientMiddle = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonPressedHighlight = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonPressedHighlightBorder = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonSelectedBorder = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonSelectedGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonSelectedGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonSelectedGradientMiddle = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonSelectedHighlight = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.ButtonSelectedHighlightBorder = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.CheckBackground = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(102)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.CheckPressedBackground = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.CheckSelectedBackground = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.OverflowButtonGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.OverflowButtonGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(77)))), ((int)(((byte)(144)))));
this.kryptonPaletteCustom.ToolMenuStatus.Button.OverflowButtonGradientMiddle = System.Drawing.Color.FromArgb(((int)(((byte)(76)))), ((int)(((byte)(126)))), ((int)(((byte)(226)))));
this.kryptonPaletteCustom.ToolMenuStatus.Grip.GripDark = System.Drawing.Color.FromArgb(((int)(((byte)(72)))), ((int)(((byte)(133)))), ((int)(((byte)(215)))));
this.kryptonPaletteCustom.ToolMenuStatus.Grip.GripLight = System.Drawing.Color.Transparent;
this.kryptonPaletteCustom.ToolMenuStatus.Menu.ImageMarginGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.ImageMarginGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(102)))), ((int)(((byte)(204)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.ImageMarginGradientMiddle = System.Drawing.Color.FromArgb(((int)(((byte)(76)))), ((int)(((byte)(126)))), ((int)(((byte)(226)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.ImageMarginRevealedGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.ImageMarginRevealedGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(102)))), ((int)(((byte)(204)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.ImageMarginRevealedGradientMiddle = System.Drawing.Color.FromArgb(((int)(((byte)(76)))), ((int)(((byte)(126)))), ((int)(((byte)(226)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.MenuBorder = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.MenuItemBorder = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.MenuItemPressedGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.MenuItemPressedGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(102)))), ((int)(((byte)(204)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.MenuItemPressedGradientMiddle = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(102)))), ((int)(((byte)(204)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.MenuItemSelected = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(102)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.MenuItemSelectedGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.MenuItemSelectedGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ToolMenuStatus.Menu.MenuItemText = System.Drawing.Color.White;
this.kryptonPaletteCustom.ToolMenuStatus.MenuStrip.MenuStripGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.MenuStrip.MenuStripGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.MenuStrip.MenuStripText = System.Drawing.Color.WhiteSmoke;
this.kryptonPaletteCustom.ToolMenuStatus.Rafting.RaftingContainerGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.Rafting.RaftingContainerGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.Separator.SeparatorDark = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.Separator.SeparatorLight = System.Drawing.Color.Transparent;
this.kryptonPaletteCustom.ToolMenuStatus.StatusStrip.StatusStripGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.StatusStrip.StatusStripGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.StatusStrip.StatusStripText = System.Drawing.Color.WhiteSmoke;
this.kryptonPaletteCustom.ToolMenuStatus.ToolStrip.ToolStripBorder = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(77)))), ((int)(((byte)(144)))));
this.kryptonPaletteCustom.ToolMenuStatus.ToolStrip.ToolStripContentPanelGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(237)))), ((int)(((byte)(227)))));
this.kryptonPaletteCustom.ToolMenuStatus.ToolStrip.ToolStripContentPanelGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(237)))), ((int)(((byte)(227)))));
this.kryptonPaletteCustom.ToolMenuStatus.ToolStrip.ToolStripDropDownBackground = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(153)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ToolMenuStatus.ToolStrip.ToolStripGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(77)))), ((int)(((byte)(144)))));
this.kryptonPaletteCustom.ToolMenuStatus.ToolStrip.ToolStripGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(77)))), ((int)(((byte)(144)))));
this.kryptonPaletteCustom.ToolMenuStatus.ToolStrip.ToolStripGradientMiddle = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(77)))), ((int)(((byte)(144)))));
this.kryptonPaletteCustom.ToolMenuStatus.ToolStrip.ToolStripPanelGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.ToolStrip.ToolStripPanelGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102)))));
this.kryptonPaletteCustom.ToolMenuStatus.ToolStrip.ToolStripText = System.Drawing.Color.WhiteSmoke;
this.kryptonPaletteCustom.ToolMenuStatus.UseRoundedEdges = ComponentFactory.Krypton.Toolkit.InheritBool.False;
//
// statusStrip1
//
this.statusStrip1.Font = new System.Drawing.Font("Segoe UI", 9F);
this.statusStrip1.Location = new System.Drawing.Point(0, 449);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode;
this.statusStrip1.Size = new System.Drawing.Size(443, 22);
this.statusStrip1.TabIndex = 2;
this.statusStrip1.Text = "statusStrip1";
//
// kryptonOffice2010Black
//
this.kryptonOffice2010Black.Location = new System.Drawing.Point(13, 66);
this.kryptonOffice2010Black.Name = "kryptonOffice2010Black";
this.kryptonOffice2010Black.Size = new System.Drawing.Size(119, 19);
this.kryptonOffice2010Black.TabIndex = 2;
this.kryptonOffice2010Black.Values.Text = "Office 2010 - Black";
this.kryptonOffice2010Black.CheckedChanged += new System.EventHandler(this.kryptonOffice2010Black_CheckedChanged);
//
// kryptonOffice2010Silver
//
this.kryptonOffice2010Silver.Location = new System.Drawing.Point(13, 41);
this.kryptonOffice2010Silver.Name = "kryptonOffice2010Silver";
this.kryptonOffice2010Silver.Size = new System.Drawing.Size(120, 19);
this.kryptonOffice2010Silver.TabIndex = 1;
this.kryptonOffice2010Silver.Values.Text = "Office 2010 - Silver";
this.kryptonOffice2010Silver.CheckedChanged += new System.EventHandler(this.kryptonOffice2010Silver_CheckedChanged);
//
// kryptonOffice2010Blue
//
this.kryptonOffice2010Blue.Checked = true;
this.kryptonOffice2010Blue.Location = new System.Drawing.Point(13, 16);
this.kryptonOffice2010Blue.Name = "kryptonOffice2010Blue";
this.kryptonOffice2010Blue.Size = new System.Drawing.Size(114, 19);
this.kryptonOffice2010Blue.TabIndex = 0;
this.kryptonOffice2010Blue.Values.Text = "Office 2010 - Blue";
this.kryptonOffice2010Blue.CheckedChanged += new System.EventHandler(this.kryptonOffice2010Blue_CheckedChanged);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(443, 471);
this.Controls.Add(this.toolStripContainer1);
this.Controls.Add(this.menuStrip1);
this.Controls.Add(this.statusStrip1);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.MinimumSize = new System.Drawing.Size(459, 509);
this.Name = "Form1";
this.Text = "Three Pane Application (Basic)";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.PerformLayout();
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanelMain)).EndInit();
this.kryptonPanelMain.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerMain.Panel1)).EndInit();
this.kryptonSplitContainerMain.Panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerMain.Panel2)).EndInit();
this.kryptonSplitContainerMain.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerMain)).EndInit();
this.kryptonSplitContainerMain.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupNavigation.Panel)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupNavigation)).EndInit();
this.kryptonHeaderGroupNavigation.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerDetails.Panel1)).EndInit();
this.kryptonSplitContainerDetails.Panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerDetails.Panel2)).EndInit();
this.kryptonSplitContainerDetails.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainerDetails)).EndInit();
this.kryptonSplitContainerDetails.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupDetails.Panel)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroupDetails)).EndInit();
this.kryptonHeaderGroupDetails.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonButtonGroup.Panel)).EndInit();
this.kryptonButtonGroup.Panel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonButtonGroup)).EndInit();
this.kryptonButtonGroup.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonGroup1.Panel)).EndInit();
this.kryptonGroup1.Panel.ResumeLayout(false);
this.kryptonGroup1.Panel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonGroup1)).EndInit();
this.kryptonGroup1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem printPreviewToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem customizeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem contentsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem indexToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem searchToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton newToolStripButton;
private System.Windows.Forms.ToolStripButton openToolStripButton;
private System.Windows.Forms.ToolStripButton saveToolStripButton;
private System.Windows.Forms.ToolStripButton printToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripButton cutToolStripButton;
private System.Windows.Forms.ToolStripButton copyToolStripButton;
private System.Windows.Forms.ToolStripButton pasteToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripButton helpToolStripButton;
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanelMain;
private ComponentFactory.Krypton.Toolkit.KryptonSplitContainer kryptonSplitContainerMain;
private ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup kryptonHeaderGroupNavigation;
private ComponentFactory.Krypton.Toolkit.KryptonSplitContainer kryptonSplitContainerDetails;
private ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup kryptonHeaderGroupDetails;
private ComponentFactory.Krypton.Toolkit.KryptonGroup kryptonButtonGroup;
private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager;
private ComponentFactory.Krypton.Toolkit.KryptonPalette kryptonPaletteCustom;
private ComponentFactory.Krypton.Toolkit.KryptonGroup kryptonGroup1;
private System.Windows.Forms.StatusStrip statusStrip1;
private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonOffice2007Black;
private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonOffice2007Silver;
private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonOffice2007Blue;
private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonOffice2003;
private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonCustom;
private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonSystem;
private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonSparkleBlue;
private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonSparkleOrange;
private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonSparklePurple;
private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonOffice2010Black;
private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonOffice2010Blue;
private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonOffice2010Silver;
}
}
| |
// 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.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security;
using System.Windows.Input;
namespace System.Runtime.InteropServices.WindowsRuntime
{
// Local definition of Windows.UI.Xaml.Interop.INotifyCollectionChangedEventArgs
[ComImport]
[Guid("4cf68d33-e3f2-4964-b85e-945b4f7e2f21")]
[WindowsRuntimeImport]
internal interface INotifyCollectionChangedEventArgs
{
NotifyCollectionChangedAction Action { get; }
IList NewItems { get; }
IList OldItems { get; }
int NewStartingIndex { get; }
int OldStartingIndex { get; }
}
// Local definition of Windows.UI.Xaml.Data.IPropertyChangedEventArgs
[ComImport]
[Guid("4f33a9a0-5cf4-47a4-b16f-d7faaf17457e")]
[WindowsRuntimeImport]
internal interface IPropertyChangedEventArgs
{
string PropertyName { get; }
}
// Local definition of Windows.UI.Xaml.Interop.INotifyCollectionChanged
[ComImport]
[Guid("28b167d5-1a31-465b-9b25-d5c3ae686c40")]
[WindowsRuntimeImport]
internal interface INotifyCollectionChanged_WinRT
{
EventRegistrationToken add_CollectionChanged(NotifyCollectionChangedEventHandler value);
void remove_CollectionChanged(EventRegistrationToken token);
}
// Local definition of Windows.UI.Xaml.Data.INotifyPropertyChanged
[ComImport]
[Guid("cf75d69c-f2f4-486b-b302-bb4c09baebfa")]
[WindowsRuntimeImport]
internal interface INotifyPropertyChanged_WinRT
{
EventRegistrationToken add_PropertyChanged(PropertyChangedEventHandler value);
void remove_PropertyChanged(EventRegistrationToken token);
}
// Local definition of Windows.UI.Xaml.Input.ICommand
[ComImport]
[Guid("e5af3542-ca67-4081-995b-709dd13792df")]
[WindowsRuntimeImport]
internal interface ICommand_WinRT
{
EventRegistrationToken add_CanExecuteChanged(EventHandler<object> value);
void remove_CanExecuteChanged(EventRegistrationToken token);
bool CanExecute(object parameter);
void Execute(object parameter);
}
// Local definition of Windows.UI.Xaml.Interop.NotifyCollectionChangedEventHandler
[Guid("ca10b37c-f382-4591-8557-5e24965279b0")]
[WindowsRuntimeImport]
internal delegate void NotifyCollectionChangedEventHandler_WinRT(object sender, NotifyCollectionChangedEventArgs e);
// Local definition of Windows.UI.Xaml.Data.PropertyChangedEventHandler
[Guid("50f19c16-0a22-4d8e-a089-1ea9951657d2")]
[WindowsRuntimeImport]
internal delegate void PropertyChangedEventHandler_WinRT(object sender, PropertyChangedEventArgs e);
internal static class NotifyCollectionChangedEventArgsMarshaler
{
// Extracts properties from a managed NotifyCollectionChangedEventArgs and passes them to
// a VM-implemented helper that creates a WinRT NotifyCollectionChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
internal static IntPtr ConvertToNative(NotifyCollectionChangedEventArgs managedArgs)
{
if (managedArgs == null)
return IntPtr.Zero;
return System.StubHelpers.EventArgsMarshaler.CreateNativeNCCEventArgsInstance(
(int)managedArgs.Action,
managedArgs.NewItems,
managedArgs.OldItems,
managedArgs.NewStartingIndex,
managedArgs.OldStartingIndex);
}
// Extracts properties from a WinRT NotifyCollectionChangedEventArgs and creates a new
// managed NotifyCollectionChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
internal static NotifyCollectionChangedEventArgs ConvertToManaged(IntPtr nativeArgsIP)
{
if (nativeArgsIP == IntPtr.Zero)
return null;
object obj = System.StubHelpers.InterfaceMarshaler.ConvertToManagedWithoutUnboxing(nativeArgsIP);
INotifyCollectionChangedEventArgs nativeArgs = (INotifyCollectionChangedEventArgs)obj;
return CreateNotifyCollectionChangedEventArgs(
nativeArgs.Action,
nativeArgs.NewItems,
nativeArgs.OldItems,
nativeArgs.NewStartingIndex,
nativeArgs.OldStartingIndex);
}
internal static NotifyCollectionChangedEventArgs CreateNotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action, IList newItems, IList oldItems, int newStartingIndex, int oldStartingIndex)
{
switch (action)
{
case NotifyCollectionChangedAction.Add:
return new NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex);
case NotifyCollectionChangedAction.Remove:
return new NotifyCollectionChangedEventArgs(action, oldItems, oldStartingIndex);
case NotifyCollectionChangedAction.Replace:
return new NotifyCollectionChangedEventArgs(action, newItems, oldItems, newStartingIndex);
case NotifyCollectionChangedAction.Move:
return new NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex, oldStartingIndex);
case NotifyCollectionChangedAction.Reset:
return new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
default: throw new ArgumentException("Invalid action value: " + action);
}
}
}
internal static class PropertyChangedEventArgsMarshaler
{
// Extracts PropertyName from a managed PropertyChangedEventArgs and passes them to
// a VM-implemented helper that creates a WinRT PropertyChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
internal static IntPtr ConvertToNative(PropertyChangedEventArgs managedArgs)
{
if (managedArgs == null)
return IntPtr.Zero;
return System.StubHelpers.EventArgsMarshaler.CreateNativePCEventArgsInstance(managedArgs.PropertyName);
}
// Extracts properties from a WinRT PropertyChangedEventArgs and creates a new
// managed PropertyChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
internal static PropertyChangedEventArgs ConvertToManaged(IntPtr nativeArgsIP)
{
if (nativeArgsIP == IntPtr.Zero)
return null;
object obj = System.StubHelpers.InterfaceMarshaler.ConvertToManagedWithoutUnboxing(nativeArgsIP);
IPropertyChangedEventArgs nativeArgs = (IPropertyChangedEventArgs)obj;
return new PropertyChangedEventArgs(nativeArgs.PropertyName);
}
}
// This is a set of stub methods implementing the support for the managed INotifyCollectionChanged
// interface on WinRT objects that support the WinRT INotifyCollectionChanged. Used by the interop
// mashaling infrastructure.
internal sealed class NotifyCollectionChangedToManagedAdapter
{
private NotifyCollectionChangedToManagedAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
internal event NotifyCollectionChangedEventHandler CollectionChanged
{
// void CollectionChanged.add(NotifyCollectionChangedEventHandler)
add
{
INotifyCollectionChanged_WinRT _this = JitHelpers.UnsafeCast<INotifyCollectionChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to subscribe the event
Func<NotifyCollectionChangedEventHandler, EventRegistrationToken> addMethod =
new Func<NotifyCollectionChangedEventHandler, EventRegistrationToken>(_this.add_CollectionChanged);
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_CollectionChanged);
WindowsRuntimeMarshal.AddEventHandler<NotifyCollectionChangedEventHandler>(addMethod, removeMethod, value);
}
// void CollectionChanged.remove(NotifyCollectionChangedEventHandler)
remove
{
INotifyCollectionChanged_WinRT _this = JitHelpers.UnsafeCast<INotifyCollectionChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to unsubscribe the event
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_CollectionChanged);
WindowsRuntimeMarshal.RemoveEventHandler<NotifyCollectionChangedEventHandler>(removeMethod, value);
}
}
}
// This is a set of stub methods implementing the support for the WinRT INotifyCollectionChanged
// interface on managed objects that support the managed INotifyCollectionChanged. Used by the interop
// mashaling infrastructure.
internal sealed class NotifyCollectionChangedToWinRTAdapter
{
private NotifyCollectionChangedToWinRTAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
// An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj.
// Since here the class can be an arbitrary implementation of INotifyCollectionChanged, we have to keep the EventRegistrationTokenTable's
// separately, associated with the implementations using ConditionalWeakTable.
private static ConditionalWeakTable<INotifyCollectionChanged, EventRegistrationTokenTable<NotifyCollectionChangedEventHandler>> s_weakTable =
new ConditionalWeakTable<INotifyCollectionChanged, EventRegistrationTokenTable<NotifyCollectionChangedEventHandler>>();
// EventRegistrationToken CollectionChanged.add(NotifyCollectionChangedEventHandler value)
internal EventRegistrationToken add_CollectionChanged(NotifyCollectionChangedEventHandler value)
{
INotifyCollectionChanged _this = JitHelpers.UnsafeCast<INotifyCollectionChanged>(this);
EventRegistrationTokenTable<NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventRegistrationToken token = table.AddEventHandler(value);
_this.CollectionChanged += value;
return token;
}
// void CollectionChanged.remove(EventRegistrationToken token)
internal void remove_CollectionChanged(EventRegistrationToken token)
{
INotifyCollectionChanged _this = JitHelpers.UnsafeCast<INotifyCollectionChanged>(this);
EventRegistrationTokenTable<NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
NotifyCollectionChangedEventHandler handler = table.ExtractHandler(token);
if (handler != null)
{
_this.CollectionChanged -= handler;
}
}
}
// This is a set of stub methods implementing the support for the managed INotifyPropertyChanged
// interface on WinRT objects that support the WinRT INotifyPropertyChanged. Used by the interop
// mashaling infrastructure.
internal sealed class NotifyPropertyChangedToManagedAdapter
{
private NotifyPropertyChangedToManagedAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
internal event PropertyChangedEventHandler PropertyChanged
{
// void PropertyChanged.add(PropertyChangedEventHandler)
add
{
INotifyPropertyChanged_WinRT _this = JitHelpers.UnsafeCast<INotifyPropertyChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to subscribe the event
Func<PropertyChangedEventHandler, EventRegistrationToken> addMethod =
new Func<PropertyChangedEventHandler, EventRegistrationToken>(_this.add_PropertyChanged);
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_PropertyChanged);
WindowsRuntimeMarshal.AddEventHandler<PropertyChangedEventHandler>(addMethod, removeMethod, value);
}
// void PropertyChanged.remove(PropertyChangedEventHandler)
remove
{
INotifyPropertyChanged_WinRT _this = JitHelpers.UnsafeCast<INotifyPropertyChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to unsubscribe the event
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_PropertyChanged);
WindowsRuntimeMarshal.RemoveEventHandler<PropertyChangedEventHandler>(removeMethod, value);
}
}
}
// This is a set of stub methods implementing the support for the WinRT INotifyPropertyChanged
// interface on managed objects that support the managed INotifyPropertyChanged. Used by the interop
// mashaling infrastructure.
internal sealed class NotifyPropertyChangedToWinRTAdapter
{
private NotifyPropertyChangedToWinRTAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
// An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj.
// Since here the class can be an arbitrary implementation of INotifyCollectionChanged, we have to keep the EventRegistrationTokenTable's
// separately, associated with the implementations using ConditionalWeakTable.
private static ConditionalWeakTable<INotifyPropertyChanged, EventRegistrationTokenTable<PropertyChangedEventHandler>> s_weakTable =
new ConditionalWeakTable<INotifyPropertyChanged, EventRegistrationTokenTable<PropertyChangedEventHandler>>();
// EventRegistrationToken PropertyChanged.add(PropertyChangedEventHandler value)
internal EventRegistrationToken add_PropertyChanged(PropertyChangedEventHandler value)
{
INotifyPropertyChanged _this = JitHelpers.UnsafeCast<INotifyPropertyChanged>(this);
EventRegistrationTokenTable<PropertyChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventRegistrationToken token = table.AddEventHandler(value);
_this.PropertyChanged += value;
return token;
}
// void PropertyChanged.remove(EventRegistrationToken token)
internal void remove_PropertyChanged(EventRegistrationToken token)
{
INotifyPropertyChanged _this = JitHelpers.UnsafeCast<INotifyPropertyChanged>(this);
EventRegistrationTokenTable<PropertyChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
PropertyChangedEventHandler handler = table.ExtractHandler(token);
if (handler != null)
{
_this.PropertyChanged -= handler;
}
}
}
// This is a set of stub methods implementing the support for the managed ICommand
// interface on WinRT objects that support the WinRT ICommand_WinRT.
// Used by the interop mashaling infrastructure.
// Instances of this are really RCWs of ICommand_WinRT (not ICommandToManagedAdapter or any ICommand).
internal sealed class ICommandToManagedAdapter /*: System.Windows.Input.ICommand*/
{
private static ConditionalWeakTable<EventHandler, EventHandler<object>> s_weakTable =
new ConditionalWeakTable<EventHandler, EventHandler<object>>();
private ICommandToManagedAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
private event EventHandler CanExecuteChanged
{
// void CanExecuteChanged.add(EventHandler)
add
{
ICommand_WinRT _this = JitHelpers.UnsafeCast<ICommand_WinRT>(this);
// call the WinRT eventing support in mscorlib to subscribe the event
Func<EventHandler<object>, EventRegistrationToken> addMethod =
new Func<EventHandler<object>, EventRegistrationToken>(_this.add_CanExecuteChanged);
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_CanExecuteChanged);
// value is of type System.EventHandler, but ICommand_WinRT (and thus WindowsRuntimeMarshal.AddEventHandler)
// expects an instance of EventHandler<object>. So we get/create a wrapper of value here.
EventHandler<object> handler_WinRT = s_weakTable.GetValue(value, ICommandAdapterHelpers.CreateWrapperHandler);
WindowsRuntimeMarshal.AddEventHandler<EventHandler<object>>(addMethod, removeMethod, handler_WinRT);
}
// void CanExecuteChanged.remove(EventHandler)
remove
{
ICommand_WinRT _this = JitHelpers.UnsafeCast<ICommand_WinRT>(this);
// call the WinRT eventing support in mscorlib to unsubscribe the event
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_CanExecuteChanged);
// value is of type System.EventHandler, but ICommand_WinRT (and thus WindowsRuntimeMarshal.RemoveEventHandler)
// expects an instance of EventHandler<object>. So we get/create a wrapper of value here.
// Also we do a value check rather than an instance check to ensure that different instances of the same delegates are treated equal.
EventHandler<object> handler_WinRT = ICommandAdapterHelpers.GetValueFromEquivalentKey(s_weakTable, value, ICommandAdapterHelpers.CreateWrapperHandler);
WindowsRuntimeMarshal.RemoveEventHandler<EventHandler<object>>(removeMethod, handler_WinRT);
}
}
private bool CanExecute(object parameter)
{
ICommand_WinRT _this = JitHelpers.UnsafeCast<ICommand_WinRT>(this);
return _this.CanExecute(parameter);
}
private void Execute(object parameter)
{
ICommand_WinRT _this = JitHelpers.UnsafeCast<ICommand_WinRT>(this);
_this.Execute(parameter);
}
}
// This is a set of stub methods implementing the support for the WinRT ICommand_WinRT
// interface on managed objects that support the managed ICommand interface.
// Used by the interop mashaling infrastructure.
// Instances of this are really CCWs of ICommand (not ICommandToWinRTAdapter or any ICommand_WinRT).
internal sealed class ICommandToWinRTAdapter /*: ICommand_WinRT*/
{
private ICommandToWinRTAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
// An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj.
// Since here the class can be an arbitrary implementation of ICommand, we have to keep the EventRegistrationTokenTable's
// separately, associated with the implementations using ConditionalWeakTable.
private static ConditionalWeakTable<ICommand, EventRegistrationTokenTable<EventHandler>> s_weakTable =
new ConditionalWeakTable<ICommand, EventRegistrationTokenTable<EventHandler>>();
// EventRegistrationToken PropertyChanged.add(EventHandler<object> value)
private EventRegistrationToken add_CanExecuteChanged(EventHandler<object> value)
{
ICommand _this = JitHelpers.UnsafeCast<ICommand>(this);
EventRegistrationTokenTable<EventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventHandler handler = ICommandAdapterHelpers.CreateWrapperHandler(value);
EventRegistrationToken token = table.AddEventHandler(handler);
_this.CanExecuteChanged += handler;
return token;
}
// void PropertyChanged.remove(EventRegistrationToken token)
private void remove_CanExecuteChanged(EventRegistrationToken token)
{
ICommand _this = JitHelpers.UnsafeCast<ICommand>(this);
EventRegistrationTokenTable<EventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventHandler handler = table.ExtractHandler(token);
if (handler != null)
{
_this.CanExecuteChanged -= handler;
}
}
private bool CanExecute(object parameter)
{
ICommand _this = JitHelpers.UnsafeCast<ICommand>(this);
return _this.CanExecute(parameter);
}
private void Execute(object parameter)
{
ICommand _this = JitHelpers.UnsafeCast<ICommand>(this);
_this.Execute(parameter);
}
}
// A couple of ICommand adapter helpers need to be transparent, and so are in their own type
internal static class ICommandAdapterHelpers
{
internal static EventHandler<object> CreateWrapperHandler(EventHandler handler)
{
// Check whether it is a round-tripping case i.e. the sender is of the type eventArgs,
// If so we use it else we pass EventArgs.Empty
return (object sender, object e) =>
{
EventArgs eventArgs = e as EventArgs;
handler(sender, (eventArgs == null ? System.EventArgs.Empty : eventArgs));
};
}
internal static EventHandler CreateWrapperHandler(EventHandler<object> handler)
{
return (object sender, EventArgs e) => handler(sender, e);
}
internal static EventHandler<object> GetValueFromEquivalentKey(
ConditionalWeakTable<EventHandler, EventHandler<object>> table,
EventHandler key,
ConditionalWeakTable<EventHandler, EventHandler<object>>.CreateValueCallback callback)
{
foreach (KeyValuePair<EventHandler, EventHandler<object>> item in table)
{
if (Object.Equals(item.Key, key))
return item.Value;
}
EventHandler<object> value = callback(key);
table.Add(key, value);
return value;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Fadd;
using Fadd.Logging;
using Xunit;
namespace HttpServer.Rendering
{
/// <summary>
/// Class to handle loading of resource files
/// </summary>
public class ResourceManager
{
/// <summary><![CDATA[
/// Maps uri's to resources, Dictionary<uri, resource>
/// ]]></summary>
private readonly Dictionary<string, List<ResourceInfo>> _loadedResources = new Dictionary<string, List<ResourceInfo>>();
private readonly ILogWriter _logWriter;
/// <summary>
/// Initializes the <see cref="ResourceManager"/>
/// </summary>
/// <param name="logWriter">The log writer to use for outputting loaded resource</param>
public ResourceManager(ILogWriter logWriter)
{
_logWriter = logWriter;
}
/// <summary>
/// Parses a filename and sets it to the extensionless name in lowercase. The extension is cut out without the dot.
/// </summary>
/// <param name="filename"></param>
/// <param name="extension"></param>
/// <usage>
/// string ext;
/// string filename = "/uSeR/teSt.haMl";
/// ParseName(ref filename, out ext);
/// Console.WriteLine("File: " + filename);
/// Console.WriteLine("Ext: " + ext);
/// -> user/test
/// -> haml
/// </usage>
private static void ParseName(ref string filename, out string extension)
{
Check.NotEmpty(filename, "filename");
filename = filename.ToLower();
int indexOfExtension = filename.LastIndexOf('.');
if (indexOfExtension == -1)
{
extension = string.Empty;
filename = filename.TrimStart('/');
}
else
{
extension = filename.Substring(indexOfExtension + 1);
filename = filename.Substring(0, indexOfExtension).TrimStart('/');
}
}
#region Test for ParseName
[Fact]
private static void TestParseName()
{
string extension;
string filename = "/uSEr/test/hej.*";
ParseName(ref filename, out extension);
Assert.Equal("*", extension);
Assert.Equal("user/test/hej", filename);
filename = "test/teSt.xMl";
ParseName(ref filename, out extension);
Assert.Equal("xml", extension);
Assert.Equal("test/test", filename);
filename = "test/TeSt";
ParseName(ref filename, out extension);
Assert.Equal(string.Empty, extension);
Assert.Equal("test/test", filename);
}
#endregion
/// <summary>
/// Add a resource to a specified uri without extension, ie user/test
/// </summary>
/// <param name="uri">The uri to add the resource to</param>
/// <param name="info">The <see cref="ResourceInfo"/> instance describing the resource</param>
private void AddResource(string uri, ResourceInfo info)
{
List<ResourceInfo> resources;
if (!_loadedResources.TryGetValue(uri, out resources))
{
resources = new List<ResourceInfo>();
_loadedResources.Add(uri, resources);
}
if (resources.Find(delegate(ResourceInfo resource) { return resource.Extension == info.Extension; }) != null)
throw new InvalidOperationException(string.Format("A resource with the name '{0}.{1}' has already been added.", uri, info.Extension));
resources.Add(info);
}
/// <summary>
/// Loads resources from a namespace in the given assembly to an uri
/// </summary>
/// <param name="toUri">The uri to map the resources to</param>
/// <param name="fromAssembly">The assembly in which the resources reside</param>
/// <param name="fromNamespace">The namespace from which to load the resources</param>
/// <usage>
/// resourceLoader.LoadResources("/user/", typeof(User).Assembly, "MyLib.Models.User.Views");
///
/// will make ie the resource MyLib.Models.User.Views.list.Haml accessible via /user/list.haml or /user/list/
/// </usage>
public void LoadResources(string toUri, Assembly fromAssembly, string fromNamespace)
{
toUri = toUri.ToLower().TrimEnd('/');
fromNamespace = fromNamespace.ToLower();
if (!fromNamespace.EndsWith("."))
fromNamespace += ".";
foreach (string resourceName in fromAssembly.GetManifestResourceNames())
{
if (resourceName.ToLower().StartsWith(fromNamespace))
{
ResourceInfo info = new ResourceInfo(resourceName, fromAssembly);
string uri = toUri + "/" + resourceName.Substring(fromNamespace.Length).ToLower().Replace('.', '/');
uri = uri.TrimStart('/');
if (!string.IsNullOrEmpty(info.Extension))
uri = uri.Substring(0, uri.Length - info.Extension.Length - 1);
AddResource(uri, info);
_logWriter.Write(this, LogPrio.Info, "Resource '" + info.Name + "' loaded to uri: " + uri);
}
}
}
#region Test for LoadResources
[Fact]
private static void TestLoadTemplates()
{
LogManager.SetProvider(new NullLogProvider());
ResourceManager resourceManager = new ResourceManager(new NullLogWriter());
resourceManager.LoadResources("/test/", resourceManager.GetType().Assembly, resourceManager.GetType().Namespace);
Assert.NotNull(resourceManager._loadedResources["test/resourcetest"]);
Assert.Equal("haml", resourceManager._loadedResources["test/resourcetest"][0].Extension);
Assert.Equal(resourceManager.GetType().Namespace + ".resourcetest.haml", resourceManager._loadedResources["test/resourcetest"][0].Name);
resourceManager._loadedResources.Clear();
resourceManager.LoadResources("/user", resourceManager.GetType().Assembly, resourceManager.GetType().Namespace);
Assert.Equal(resourceManager.GetType().Namespace + ".resourcetest.haml", resourceManager._loadedResources["user/resourcetest"][0].Name);
resourceManager._loadedResources.Clear();
resourceManager.LoadResources("/user/test/", resourceManager.GetType().Assembly, resourceManager.GetType().Namespace);
Assert.Equal(resourceManager.GetType().Namespace + ".resourcetest.haml", resourceManager._loadedResources["user/test/resourcetest"][0].Name);
resourceManager._loadedResources.Clear();
resourceManager.LoadResources("/", resourceManager.GetType().Assembly, resourceManager.GetType().Namespace);
Assert.Equal(resourceManager.GetType().Namespace + ".resourcetest.haml", resourceManager._loadedResources["resourcetest"][0].Name);
}
#endregion
/// <summary>
/// Retrieves a stream for the specified resource path if loaded otherwise null
/// </summary>
/// <param name="path">Path to the resource to retrieve a stream for</param>
/// <returns>A stream or null if the resource couldn't be found</returns>
public Stream GetResourceStream(string path)
{
path = path.Replace('\\', '/');
if(!ContainsResource(path))
return null;
string ext;
ParseName(ref path, out ext);
List<ResourceInfo> resources = _loadedResources[path];
ResourceInfo info = resources.Find(delegate(ResourceInfo resInfo) { return resInfo.Extension == ext; });
return info != null ? info.GetStream() : null;
}
#region Test for GetResourceStream
[Fact]
private static void TestGetResourceStream()
{
ResourceManager resources = new ResourceManager(new NullLogWriter());
resources.LoadResources("/", resources.GetType().Assembly, "HttpServer.Rendering");
Assert.NotNull(resources.GetResourceStream("resourcetest.haml"));
Assert.NotNull(resources.GetResourceStream("\\resourcetest.haml"));
}
#endregion
/// <summary>
/// Fetch all files from the resource that matches the specified arguments.
/// </summary>
/// <param name="path">The path to the resource to extract</param>
/// <returns>
/// a list of files if found; or an empty array if no files are found.
/// </returns>
public string[] GetFiles(string path)
{
Check.NotEmpty(path, "path");
path = path.Replace('\\', '/');
List<string> files = new List<string>();
string ext;
ParseName(ref path, out ext);
List<ResourceInfo> resources;
if (!_loadedResources.TryGetValue(path, out resources))
return new string[] { };
foreach (ResourceInfo resource in resources)
if (resource.Extension == ext || ext == "*")
files.Add(path + "." + resource.Extension);
return files.ToArray();
}
/// <summary>
/// Fetch all files from the resource that matches the specified arguments.
/// </summary>
/// <param name="path">Where the file should reside.</param>
/// <param name="filename">Files to check</param>
/// <returns>
/// a list of files if found; or an empty array if no files are found.
/// </returns>
public string[] GetFiles(string path, string filename)
{
Check.NotEmpty(path, "path");
Check.NotEmpty(filename, "filename");
path = path.EndsWith("/") ? path : path + "/";
return GetFiles(path + filename);
}
#region Test GetFiles
[Fact]
private static void TestGetFiles()
{
ResourceManager resourceManager = new ResourceManager(new NullLogWriter());
resourceManager.LoadResources("/test/", resourceManager.GetType().Assembly, resourceManager.GetType().Namespace);
string[] files = resourceManager.GetFiles("/test/", "resourcetest.xml");
Assert.Equal(1, files.Length);
Assert.Equal("test/resourcetest.xml", files[0]);
files = resourceManager.GetFiles("/test/", "resourcetest.*");
Assert.Equal(2, files.Length);
files = resourceManager.GetFiles("/test/haml/", "resourcetest2.haml");
Assert.Equal(1, files.Length);
files = resourceManager.GetFiles("/test/haml/resourcetest2.haml");
Assert.Equal(1, files.Length);
files = resourceManager.GetFiles("/test/resourcetest.*");
Assert.Equal(2, files.Length);
}
#endregion
/// <summary>
/// Returns whether or not the loader has an instance of the file requested
/// </summary>
/// <param name="filename">The name of the template/file</param>
/// <returns>True if the loader can provide the file</returns>
public bool ContainsResource(string filename)
{
filename = filename.Replace('\\', '/');
string ext;
ParseName(ref filename, out ext);
List<ResourceInfo> resources;
if (!_loadedResources.TryGetValue(filename, out resources))
return false;
foreach (ResourceInfo resource in resources)
if (resource.Extension == ext || ext == "*")
return true;
return false;
}
#region Test ContainsResource
[Fact]
private static void TestContainsResource()
{
ResourceManager resourceManager = new ResourceManager(new NullLogWriter());
resourceManager.LoadResources("/test/", resourceManager.GetType().Assembly, resourceManager.GetType().Namespace);
Assert.True(resourceManager.ContainsResource("/test/resourcetest.xml"));
Assert.True(resourceManager.ContainsResource("/test/resourcetest.haml"));
Assert.True(resourceManager.ContainsResource("/test/resourcetest.*"));
Assert.True(resourceManager.ContainsResource("/test/haml/resourcetest2.*"));
Assert.True(resourceManager.ContainsResource("/test/haml/resourcetest2.haml"));
Assert.False(resourceManager.ContainsResource("/test/resourcetest"));
Assert.False(resourceManager.ContainsResource("/test/rwerourcetest.xml"));
Assert.False(resourceManager.ContainsResource("/test/resourcetest.qaml"));
Assert.False(resourceManager.ContainsResource("/wrong/rwerourcetest.xml"));
Assert.False(resourceManager.ContainsResource("/test/haml/resourcetest2.xml"));
resourceManager._loadedResources.Clear();
resourceManager.LoadResources("/", resourceManager.GetType().Assembly, resourceManager.GetType().Namespace);
Assert.True(resourceManager.ContainsResource("/resourcetest.*"));
Assert.True(resourceManager.ContainsResource("resourcetest.haml"));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SharpCompress.Archive;
using SharpCompress.Common;
using SharpCompress.IO;
namespace SharpCompress
{
internal static class Utility
{
public static ReadOnlyCollection<T> ToReadOnly<T>(this IEnumerable<T> items)
{
return new ReadOnlyCollection<T>(items.ToList());
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static int URShift(int number, int bits)
{
if (number >= 0)
return number >> bits;
else
return (number >> bits) + (2 << ~bits);
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static int URShift(int number, long bits)
{
return URShift(number, (int)bits);
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static long URShift(long number, int bits)
{
if (number >= 0)
return number >> bits;
else
return (number >> bits) + (2L << ~bits);
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static long URShift(long number, long bits)
{
return URShift(number, (int)bits);
}
/// <summary>
/// Fills the array with an specific value from an specific index to an specific index.
/// </summary>
/// <param name="array">The array to be filled.</param>
/// <param name="fromindex">The first index to be filled.</param>
/// <param name="toindex">The last index to be filled.</param>
/// <param name="val">The value to fill the array with.</param>
public static void Fill<T>(T[] array, int fromindex, int toindex, T val) where T : struct
{
if (array.Length == 0)
{
throw new NullReferenceException();
}
if (fromindex > toindex)
{
throw new ArgumentException();
}
if ((fromindex < 0) || ((System.Array)array).Length < toindex)
{
throw new IndexOutOfRangeException();
}
for (int index = (fromindex > 0) ? fromindex-- : fromindex; index < toindex; index++)
{
array[index] = val;
}
}
/// <summary>
/// Fills the array with an specific value.
/// </summary>
/// <param name="array">The array to be filled.</param>
/// <param name="val">The value to fill the array with.</param>
public static void Fill<T>(T[] array, T val) where T : struct
{
Fill(array, 0, array.Length, val);
}
public static void SetSize(this List<byte> list, int count)
{
if (count > list.Count)
{
for (int i = list.Count; i < count; i++)
{
list.Add(0x0);
}
}
else
{
byte[] temp = new byte[count];
list.CopyTo(temp, 0);
list.Clear();
list.AddRange(temp);
}
}
/// <summary> Read a int value from the byte array at the given position (Big Endian)
///
/// </summary>
/// <param name="array">the array to read from
/// </param>
/// <param name="pos">the offset
/// </param>
/// <returns> the value
/// </returns>
public static int readIntBigEndian(byte[] array, int pos)
{
int temp = 0;
temp |= array[pos] & 0xff;
temp <<= 8;
temp |= array[pos + 1] & 0xff;
temp <<= 8;
temp |= array[pos + 2] & 0xff;
temp <<= 8;
temp |= array[pos + 3] & 0xff;
return temp;
}
/// <summary> Read a short value from the byte array at the given position (little
/// Endian)
///
/// </summary>
/// <param name="array">the array to read from
/// </param>
/// <param name="pos">the offset
/// </param>
/// <returns> the value
/// </returns>
public static short readShortLittleEndian(byte[] array, int pos)
{
return BitConverter.ToInt16(array, pos);
}
/// <summary> Read an int value from the byte array at the given position (little
/// Endian)
///
/// </summary>
/// <param name="array">the array to read from
/// </param>
/// <param name="pos">the offset
/// </param>
/// <returns> the value
/// </returns>
public static int readIntLittleEndian(byte[] array, int pos)
{
return BitConverter.ToInt32(array, pos);
}
/// <summary> Write an int value into the byte array at the given position (Big endian)
///
/// </summary>
/// <param name="array">the array
/// </param>
/// <param name="pos">the offset
/// </param>
/// <param name="value">the value to write
/// </param>
public static void writeIntBigEndian(byte[] array, int pos, int value)
{
array[pos] = (byte)((Utility.URShift(value, 24)) & 0xff);
array[pos + 1] = (byte)((Utility.URShift(value, 16)) & 0xff);
array[pos + 2] = (byte)((Utility.URShift(value, 8)) & 0xff);
array[pos + 3] = (byte)((value) & 0xff);
}
/// <summary> Write a short value into the byte array at the given position (little
/// endian)
///
/// </summary>
/// <param name="array">the array
/// </param>
/// <param name="pos">the offset
/// </param>
/// <param name="value">the value to write
/// </param>
#if PORTABLE || NETFX_CORE
public static void WriteLittleEndian(byte[] array, int pos, short value)
{
byte[] newBytes = BitConverter.GetBytes(value);
Array.Copy(newBytes, 0, array, pos, newBytes.Length);
}
#else
public static unsafe void WriteLittleEndian(byte[] array, int pos, short value)
{
fixed (byte* numRef = &(array[pos]))
{
*((short*)numRef) = value;
}
}
#endif
/// <summary> Increment a short value at the specified position by the specified amount
/// (little endian).
/// </summary>
public static void incShortLittleEndian(byte[] array, int pos, short incrementValue)
{
short existingValue = BitConverter.ToInt16(array, pos);
existingValue += incrementValue;
WriteLittleEndian(array, pos, existingValue);
//int c = Utility.URShift(((array[pos] & 0xff) + (dv & 0xff)), 8);
//array[pos] = (byte)(array[pos] + (dv & 0xff));
//if ((c > 0) || ((dv & 0xff00) != 0))
//{
// array[pos + 1] = (byte)(array[pos + 1] + ((Utility.URShift(dv, 8)) & 0xff) + c);
//}
}
/// <summary> Write an int value into the byte array at the given position (little
/// endian)
///
/// </summary>
/// <param name="array">the array
/// </param>
/// <param name="pos">the offset
/// </param>
/// <param name="value">the value to write
/// </param>
#if PORTABLE || NETFX_CORE
public static void WriteLittleEndian(byte[] array, int pos, int value)
{
byte[] newBytes = BitConverter.GetBytes(value);
Array.Copy(newBytes, 0, array, pos, newBytes.Length);
}
#else
public static unsafe void WriteLittleEndian(byte[] array, int pos, int value)
{
fixed (byte* numRef = &(array[pos]))
{
*((int*)numRef) = value;
}
}
#endif
public static void Initialize<T>(this T[] array, Func<T> func)
{
for (int i = 0; i < array.Length; i++)
{
array[i] = func();
}
}
public static void AddRange<T>(this ICollection<T> destination, IEnumerable<T> source)
{
foreach (T item in source)
{
destination.Add(item);
}
}
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (T item in items)
{
action(item);
}
}
public static IEnumerable<T> AsEnumerable<T>(this T item)
{
yield return item;
}
public static void CheckNotNull(this object obj, string name)
{
if (obj == null)
{
throw new ArgumentNullException(name);
}
}
public static void CheckNotNullOrEmpty(this string obj, string name)
{
obj.CheckNotNull(name);
if (obj.Length == 0)
{
throw new ArgumentException("String is empty.");
}
}
public static void Skip(this Stream source, long advanceAmount)
{
byte[] buffer = new byte[32 * 1024];
int read = 0;
int readCount = 0;
do
{
readCount = buffer.Length;
if (readCount > advanceAmount)
{
readCount = (int)advanceAmount;
}
read = source.Read(buffer, 0, readCount);
if (read < 0)
{
break;
}
advanceAmount -= read;
if (advanceAmount == 0)
{
break;
}
} while (true);
}
public static void SkipAll(this Stream source)
{
byte[] buffer = new byte[32 * 1024];
do
{
} while (source.Read(buffer, 0, buffer.Length) == buffer.Length);
}
public static byte[] UInt32ToBigEndianBytes(uint x)
{
return new byte[]
{
(byte) ((x >> 24) & 0xff),
(byte) ((x >> 16) & 0xff),
(byte) ((x >> 8) & 0xff),
(byte) (x & 0xff)
};
}
public static DateTime DosDateToDateTime(UInt16 iDate, UInt16 iTime)
{
int year = iDate / 512 + 1980;
int month = iDate % 512 / 32;
int day = iDate % 512 % 32;
int hour = iTime / 2048;
int minute = iTime % 2048 / 32;
int second = iTime % 2048 % 32 * 2;
if (iDate == UInt16.MaxValue || month == 0 || day == 0)
{
year = 1980;
month = 1;
day = 1;
}
if (iTime == UInt16.MaxValue)
{
hour = minute = second = 0;
}
DateTime dt;
try
{
dt = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Local);
}
catch
{
dt = new DateTime();
}
return dt;
}
public static uint DateTimeToDosTime(this DateTime? dateTime)
{
if (dateTime == null)
{
return 0;
}
var localDateTime = dateTime.Value.ToLocalTime();
return (uint)(
(localDateTime.Second / 2) | (localDateTime.Minute << 5) | (localDateTime.Hour << 11) |
(localDateTime.Day << 16) | (localDateTime.Month << 21) |
((localDateTime.Year - 1980) << 25));
}
public static DateTime DosDateToDateTime(UInt32 iTime)
{
return DosDateToDateTime((UInt16)(iTime / 65536),
(UInt16)(iTime % 65536));
}
public static DateTime DosDateToDateTime(Int32 iTime)
{
return DosDateToDateTime((UInt32)iTime);
}
public static long TransferTo(this Stream source, Stream destination)
{
byte[] array = new byte[81920];
int count;
long total = 0;
while ((count = source.Read(array, 0, array.Length)) != 0)
{
total += count;
destination.Write(array, 0, count);
}
return total;
}
public static bool ReadFully(this Stream stream, byte[] buffer)
{
int total = 0;
int read;
while ((read = stream.Read(buffer, total, buffer.Length - total)) > 0)
{
total += read;
if (total >= buffer.Length)
{
return true;
}
}
return (total >= buffer.Length);
}
public static string TrimNulls(this string source)
{
return source.Replace('\0', ' ').Trim();
}
public static bool BinaryEquals(this byte[] source, byte[] target)
{
if (source.Length != target.Length)
{
return false;
}
for (int i = 0; i < source.Length; ++i)
{
if (source[i] != target[i])
{
return false;
}
}
return true;
}
#if PORTABLE || NETFX_CORE
public static void CopyTo(this byte[] array, byte[] destination, int index)
{
Array.Copy(array, 0, destination, index, array.Length);
}
public static long HostToNetworkOrder(long host)
{
return (int)((long)HostToNetworkOrder((int)host)
& unchecked((long)(unchecked((ulong)-1))) << 32
| ((long)HostToNetworkOrder((int)((int)host >> 32)) & unchecked((long)(unchecked((ulong)-1)))));
}
public static int HostToNetworkOrder(int host)
{
return (int)((int)(HostToNetworkOrder((short)host) & -1) << 16 | (HostToNetworkOrder((short)(host >> 16)) & -1));
}
public static short HostToNetworkOrder(short host)
{
return (short)((int)(host & 255) << 8 | ((int)host >> 8 & 255));
}
public static long NetworkToHostOrder(long network)
{
return HostToNetworkOrder(network);
}
public static int NetworkToHostOrder(int network)
{
return HostToNetworkOrder(network);
}
public static short NetworkToHostOrder(short network)
{
return HostToNetworkOrder(network);
}
#endif
}
}
| |
/*
* 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 OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Physics.POSPlugin
{
public class POSPrim : PhysicsActor
{
private OpenMetaverse.Vector3 _position;
private OpenMetaverse.Vector3 _velocity;
private OpenMetaverse.Vector3 _acceleration;
private OpenMetaverse.Vector3 _size;
private OpenMetaverse.Vector3 m_rotationalVelocity = OpenMetaverse.Vector3.Zero;
private Quaternion _orientation;
private bool iscolliding;
public POSPrim()
{
_velocity = new OpenMetaverse.Vector3();
_position = new OpenMetaverse.Vector3();
_acceleration = new OpenMetaverse.Vector3();
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Prim; }
set { return; }
}
public override OpenMetaverse.Vector3 RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool IsColliding
{
get { return iscolliding; }
set { iscolliding = value; }
}
public override bool CollidingGround
{
get { return false; }
set { return; }
}
public override bool CollidingObj
{
get { return false; }
set { return; }
}
public override bool Stopped
{
get { return false; }
}
public override OpenMetaverse.Vector3 Position
{
get { return _position; }
set { _position = value; }
}
public override OpenMetaverse.Vector3 Size
{
get { return _size; }
set { _size = value; }
}
public override float Mass
{
get { return 0f; }
}
public override OpenMetaverse.Vector3 Force
{
get { return OpenMetaverse.Vector3.Zero; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, OpenMetaverse.Vector3 value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void SetVolumeDetect(int param)
{
}
public override OpenMetaverse.Vector3 CenterOfMass
{
get { return OpenMetaverse.Vector3.Zero; }
}
public override OpenMetaverse.Vector3 GeometricCenter
{
get { return OpenMetaverse.Vector3.Zero; }
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override OpenMetaverse.Vector3 Velocity
{
get { return _velocity; }
set { _velocity = value; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return _orientation; }
set { _orientation = value; }
}
public override OpenMetaverse.Vector3 Acceleration
{
get { return _acceleration; }
}
public override bool Kinematic
{
get { return true; }
set { }
}
public void SetAcceleration(OpenMetaverse.Vector3 accel)
{
_acceleration = accel;
}
public override void AddForce(OpenMetaverse.Vector3 force, bool pushforce)
{
}
public override void AddAngularForce(OpenMetaverse.Vector3 force, bool pushforce)
{
}
public override OpenMetaverse.Vector3 Torque
{
get { return OpenMetaverse.Vector3.Zero; }
set { return; }
}
public override void SetMomentum(OpenMetaverse.Vector3 momentum)
{
}
public override bool Flying
{
get { return false; }
set { }
}
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override uint LocalID
{
set { return; }
}
public override bool Grabbed
{
set { return; }
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(OpenMetaverse.Vector3 axis)
{
}
public override bool Selected
{
set { return; }
}
public override void CrossingFailure()
{
}
public override OpenMetaverse.Vector3 PIDTarget
{
set { return; }
}
public override bool PIDActive
{
set { return; }
}
public override float PIDTau
{
set { return; }
}
public override float PIDHoverHeight
{
set { return; }
}
public override bool PIDHoverActive
{
set { return; }
}
public override PIDHoverType PIDHoverType
{
set { return; }
}
public override float PIDHoverTau
{
set { return; }
}
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.Runtime;
using System.Xml.Xsl.XPath;
namespace System.Xml.Xsl.Xslt
{
using FunctionInfo = XPathBuilder.FunctionInfo<QilGenerator.FuncId>;
using T = XmlQueryTypeFactory;
internal partial class QilGenerator : IXPathEnvironment
{
// Everywhere in this code in case of error in the stylesheet we should throw XslLoadException.
// This helper IErrorHelper implementation is used to wrap XmlException's into XslLoadException's.
private struct ThrowErrorHelper : IErrorHelper
{
public void ReportError(string res, params string[] args)
{
Debug.Assert(args == null || args.Length == 0, "Error message must already be composed in res");
throw new XslLoadException(SR.Xml_UserException, res);
}
public void ReportWarning(string res, params string[] args)
{
Debug.Fail("Should never get here");
}
}
// -------------------------------- IXPathEnvironment --------------------------------
// IXPathEnvironment represents static context (namespaces, focus) and most naturaly implemented by QilGenerator itself
// $var current() key()
// */@select or */@test + + +
// template/@match - - +
// key/@match - - -
// key/@use - + -
// number/@count + - +
// number/@from + - +
private bool _allowVariables = true;
private bool _allowCurrent = true;
private bool _allowKey = true;
private void SetEnvironmentFlags(bool allowVariables, bool allowCurrent, bool allowKey)
{
_allowVariables = allowVariables;
_allowCurrent = allowCurrent;
_allowKey = allowKey;
}
XPathQilFactory IXPathEnvironment.Factory { get { return _f; } }
// IXPathEnvironment interface
QilNode IFocus.GetCurrent() { return this.GetCurrentNode(); }
QilNode IFocus.GetPosition() { return this.GetCurrentPosition(); }
QilNode IFocus.GetLast() { return this.GetLastPosition(); }
string IXPathEnvironment.ResolvePrefix(string prefix)
{
return ResolvePrefixThrow(true, prefix);
}
QilNode IXPathEnvironment.ResolveVariable(string prefix, string name)
{
if (!_allowVariables)
{
throw new XslLoadException(SR.Xslt_VariablesNotAllowed);
}
string ns = ResolvePrefixThrow(/*ignoreDefaultNs:*/true, prefix);
Debug.Assert(ns != null);
// Look up in params and variables of the current scope and all outer ones
QilNode var = _scope.LookupVariable(name, ns);
if (var == null)
{
throw new XslLoadException(SR.Xslt_InvalidVariable, Compiler.ConstructQName(prefix, name));
}
// All Node* parameters are guaranteed to be in document order with no duplicates, so TypeAssert
// this so that optimizer can use this information to avoid redundant sorts and duplicate removal.
XmlQueryType varType = var.XmlType;
if (var.NodeType == QilNodeType.Parameter && varType.IsNode && varType.IsNotRtf && varType.MaybeMany && !varType.IsDod)
{
var = _f.TypeAssert(var, XmlQueryTypeFactory.NodeSDod);
}
return var;
}
// NOTE: DO NOT call QilNode.Clone() while executing this method since fixup nodes cannot be cloned
QilNode IXPathEnvironment.ResolveFunction(string prefix, string name, IList<QilNode> args, IFocus env)
{
Debug.Assert(!args.IsReadOnly, "Writable collection expected");
if (prefix.Length == 0)
{
FunctionInfo func;
if (FunctionTable.TryGetValue(name, out func))
{
func.CastArguments(args, name, _f);
switch (func.id)
{
case FuncId.Current:
if (!_allowCurrent)
{
throw new XslLoadException(SR.Xslt_CurrentNotAllowed);
}
// NOTE: This is the only place where the current node (and not the context node) must be used
return ((IXPathEnvironment)this).GetCurrent();
case FuncId.Key:
if (!_allowKey)
{
throw new XslLoadException(SR.Xslt_KeyNotAllowed);
}
return CompileFnKey(args[0], args[1], env);
case FuncId.Document: return CompileFnDocument(args[0], args.Count > 1 ? args[1] : null);
case FuncId.FormatNumber: return CompileFormatNumber(args[0], args[1], args.Count > 2 ? args[2] : null);
case FuncId.UnparsedEntityUri: return CompileUnparsedEntityUri(args[0]);
case FuncId.GenerateId: return CompileGenerateId(args.Count > 0 ? args[0] : env.GetCurrent());
case FuncId.SystemProperty: return CompileSystemProperty(args[0]);
case FuncId.ElementAvailable: return CompileElementAvailable(args[0]);
case FuncId.FunctionAvailable: return CompileFunctionAvailable(args[0]);
default:
Debug.Fail(func.id + " is present in the function table, but absent from the switch");
return null;
}
}
else
{
throw new XslLoadException(SR.Xslt_UnknownXsltFunction, Compiler.ConstructQName(prefix, name));
}
}
else
{
string ns = ResolvePrefixThrow(/*ignoreDefaultNs:*/true, prefix);
Debug.Assert(ns != null);
if (ns == XmlReservedNs.NsMsxsl)
{
if (name == "node-set")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return CompileMsNodeSet(args[0]);
}
else if (name == "string-compare")
{
FunctionInfo.CheckArity(/*minArg:*/2, /*maxArg:*/4, name, args.Count);
return _f.InvokeMsStringCompare(
/*x: */_f.ConvertToString(args[0]),
/*y: */_f.ConvertToString(args[1]),
/*lang: */2 < args.Count ? _f.ConvertToString(args[2]) : _f.String(string.Empty),
/*options:*/3 < args.Count ? _f.ConvertToString(args[3]) : _f.String(string.Empty)
);
}
else if (name == "utc")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return _f.InvokeMsUtc(/*datetime:*/_f.ConvertToString(args[0]));
}
else if (name == "format-date" || name == "format-time")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/3, name, args.Count);
bool fwdCompat = (_xslVersion == XslVersion.ForwardsCompatible);
return _f.InvokeMsFormatDateTime(
/*datetime:*/_f.ConvertToString(args[0]),
/*format: */1 < args.Count ? _f.ConvertToString(args[1]) : _f.String(string.Empty),
/*lang: */2 < args.Count ? _f.ConvertToString(args[2]) : _f.String(string.Empty),
/*isDate: */_f.Boolean(name == "format-date")
);
}
else if (name == "local-name")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return _f.InvokeMsLocalName(_f.ConvertToString(args[0]));
}
else if (name == "namespace-uri")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return _f.InvokeMsNamespaceUri(_f.ConvertToString(args[0]), env.GetCurrent());
}
else if (name == "number")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return _f.InvokeMsNumber(args[0]);
}
}
if (ns == XmlReservedNs.NsExsltCommon)
{
if (name == "node-set")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return CompileMsNodeSet(args[0]);
}
else if (name == "object-type")
{
FunctionInfo.CheckArity(/*minArg:*/1, /*maxArg:*/1, name, args.Count);
return EXslObjectType(args[0]);
}
}
// NOTE: If you add any function here, add it to IsFunctionAvailable as well
// Ensure that all node-set parameters are DocOrderDistinct
for (int i = 0; i < args.Count; i++)
args[i] = _f.SafeDocOrderDistinct(args[i]);
if (_compiler.Settings.EnableScript)
{
XmlExtensionFunction scrFunc = _compiler.Scripts.ResolveFunction(name, ns, args.Count, (IErrorHelper)this);
if (scrFunc != null)
{
return GenerateScriptCall(_f.QName(name, ns, prefix), scrFunc, args);
}
}
else
{
if (_compiler.Scripts.ScriptClasses.ContainsKey(ns))
{
ReportWarning(SR.Xslt_ScriptsProhibited);
return _f.Error(_lastScope.SourceLine, SR.Xslt_ScriptsProhibited);
}
}
return _f.XsltInvokeLateBound(_f.QName(name, ns, prefix), args);
}
}
private QilNode GenerateScriptCall(QilName name, XmlExtensionFunction scrFunc, IList<QilNode> args)
{
XmlQueryType xmlTypeFormalArg;
for (int i = 0; i < args.Count; i++)
{
xmlTypeFormalArg = scrFunc.GetXmlArgumentType(i);
switch (xmlTypeFormalArg.TypeCode)
{
case XmlTypeCode.Boolean: args[i] = _f.ConvertToBoolean(args[i]); break;
case XmlTypeCode.Double: args[i] = _f.ConvertToNumber(args[i]); break;
case XmlTypeCode.String: args[i] = _f.ConvertToString(args[i]); break;
case XmlTypeCode.Node: args[i] = xmlTypeFormalArg.IsSingleton ? _f.ConvertToNode(args[i]) : _f.ConvertToNodeSet(args[i]); break;
case XmlTypeCode.Item: break;
default: Debug.Fail("This XmlTypeCode should never be inferred from a Clr type: " + xmlTypeFormalArg.TypeCode); break;
}
}
return _f.XsltInvokeEarlyBound(name, scrFunc.Method, scrFunc.XmlReturnType, args);
}
private string ResolvePrefixThrow(bool ignoreDefaultNs, string prefix)
{
if (ignoreDefaultNs && prefix.Length == 0)
{
return string.Empty;
}
else
{
string ns = _scope.LookupNamespace(prefix);
if (ns == null)
{
if (prefix.Length != 0)
{
throw new XslLoadException(SR.Xslt_InvalidPrefix, prefix);
}
ns = string.Empty;
}
return ns;
}
}
//------------------------------------------------
// XSLT Functions
//------------------------------------------------
public enum FuncId
{
Current,
Document,
Key,
FormatNumber,
UnparsedEntityUri,
GenerateId,
SystemProperty,
ElementAvailable,
FunctionAvailable,
}
private static readonly XmlTypeCode[] s_argFnDocument = { XmlTypeCode.Item, XmlTypeCode.Node };
private static readonly XmlTypeCode[] s_argFnKey = { XmlTypeCode.String, XmlTypeCode.Item };
private static readonly XmlTypeCode[] s_argFnFormatNumber = { XmlTypeCode.Double, XmlTypeCode.String, XmlTypeCode.String };
public static Dictionary<string, FunctionInfo> FunctionTable = CreateFunctionTable();
private static Dictionary<string, FunctionInfo> CreateFunctionTable()
{
Dictionary<string, FunctionInfo> table = new Dictionary<string, FunctionInfo>(16);
table.Add("current", new FunctionInfo(FuncId.Current, 0, 0, null));
table.Add("document", new FunctionInfo(FuncId.Document, 1, 2, s_argFnDocument));
table.Add("key", new FunctionInfo(FuncId.Key, 2, 2, s_argFnKey));
table.Add("format-number", new FunctionInfo(FuncId.FormatNumber, 2, 3, s_argFnFormatNumber));
table.Add("unparsed-entity-uri", new FunctionInfo(FuncId.UnparsedEntityUri, 1, 1, XPathBuilder.argString));
table.Add("generate-id", new FunctionInfo(FuncId.GenerateId, 0, 1, XPathBuilder.argNodeSet));
table.Add("system-property", new FunctionInfo(FuncId.SystemProperty, 1, 1, XPathBuilder.argString));
table.Add("element-available", new FunctionInfo(FuncId.ElementAvailable, 1, 1, XPathBuilder.argString));
table.Add("function-available", new FunctionInfo(FuncId.FunctionAvailable, 1, 1, XPathBuilder.argString));
return table;
}
public static bool IsFunctionAvailable(string localName, string nsUri)
{
if (XPathBuilder.IsFunctionAvailable(localName, nsUri))
{
return true;
}
if (nsUri.Length == 0)
{
return FunctionTable.ContainsKey(localName) && localName != "unparsed-entity-uri";
}
if (nsUri == XmlReservedNs.NsMsxsl)
{
return (
localName == "node-set" ||
localName == "format-date" ||
localName == "format-time" ||
localName == "local-name" ||
localName == "namespace-uri" ||
localName == "number" ||
localName == "string-compare" ||
localName == "utc"
);
}
if (nsUri == XmlReservedNs.NsExsltCommon)
{
return localName == "node-set" || localName == "object-type";
}
return false;
}
public static bool IsElementAvailable(XmlQualifiedName name)
{
if (name.Namespace == XmlReservedNs.NsXslt)
{
string localName = name.Name;
return (
localName == "apply-imports" ||
localName == "apply-templates" ||
localName == "attribute" ||
localName == "call-template" ||
localName == "choose" ||
localName == "comment" ||
localName == "copy" ||
localName == "copy-of" ||
localName == "element" ||
localName == "fallback" ||
localName == "for-each" ||
localName == "if" ||
localName == "message" ||
localName == "number" ||
localName == "processing-instruction" ||
localName == "text" ||
localName == "value-of" ||
localName == "variable"
);
}
// NOTE: msxsl:script is not an "instruction", so we return false for it
return false;
}
private QilNode CompileFnKey(QilNode name, QilNode keys, IFocus env)
{
QilNode result;
QilIterator i, n, k;
if (keys.XmlType.IsNode)
{
if (keys.XmlType.IsSingleton)
{
result = CompileSingleKey(name, _f.ConvertToString(keys), env);
}
else
{
result = _f.Loop(i = _f.For(keys), CompileSingleKey(name, _f.ConvertToString(i), env));
}
}
else if (keys.XmlType.IsAtomicValue)
{
result = CompileSingleKey(name, _f.ConvertToString(keys), env);
}
else
{
result = _f.Loop(n = _f.Let(name), _f.Loop(k = _f.Let(keys),
_f.Conditional(_f.Not(_f.IsType(k, T.AnyAtomicType)),
_f.Loop(i = _f.For(_f.TypeAssert(k, T.NodeS)), CompileSingleKey(n, _f.ConvertToString(i), env)),
CompileSingleKey(n, _f.XsltConvert(k, T.StringX), env)
)
));
}
return _f.DocOrderDistinct(result);
}
private QilNode CompileSingleKey(QilNode name, QilNode key, IFocus env)
{
Debug.Assert(name.XmlType == T.StringX && key.XmlType == T.StringX);
QilNode result;
if (name.NodeType == QilNodeType.LiteralString)
{
string keyName = (string)(QilLiteral)name;
string prefix, local, nsUri;
_compiler.ParseQName(keyName, out prefix, out local, new ThrowErrorHelper());
nsUri = ResolvePrefixThrow(/*ignoreDefaultNs:*/true, prefix);
QilName qname = _f.QName(local, nsUri, prefix);
if (!_compiler.Keys.Contains(qname))
{
throw new XslLoadException(SR.Xslt_UndefinedKey, keyName);
}
result = CompileSingleKey(_compiler.Keys[qname], key, env);
}
else
{
if (_generalKey == null)
{
_generalKey = CreateGeneralKeyFunction();
}
QilIterator i = _f.Let(name);
QilNode resolvedName = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, i);
result = _f.Invoke(_generalKey, _f.ActualParameterList(i, resolvedName, key, env.GetCurrent()));
result = _f.Loop(i, result);
}
return result;
}
private QilNode CompileSingleKey(List<Key> defList, QilNode key, IFocus env)
{
Debug.Assert(defList != null && defList.Count > 0);
if (defList.Count == 1)
{
return _f.Invoke(defList[0].Function, _f.ActualParameterList(env.GetCurrent(), key));
}
QilIterator i = _f.Let(key);
QilNode result = _f.Sequence();
foreach (Key keyDef in defList)
{
result.Add(_f.Invoke(keyDef.Function, _f.ActualParameterList(env.GetCurrent(), i)));
}
return _f.Loop(i, result);
}
private QilNode CompileSingleKey(List<Key> defList, QilIterator key, QilIterator context)
{
Debug.Assert(defList != null && defList.Count > 0);
QilList result = _f.BaseFactory.Sequence();
QilNode keyRef = null;
foreach (Key keyDef in defList)
{
keyRef = _f.Invoke(keyDef.Function, _f.ActualParameterList(context, key));
result.Add(keyRef);
}
return defList.Count == 1 ? keyRef : result;
}
private QilFunction CreateGeneralKeyFunction()
{
QilIterator name = _f.Parameter(T.StringX);
QilIterator resolvedName = _f.Parameter(T.QNameX);
QilIterator key = _f.Parameter(T.StringX);
QilIterator context = _f.Parameter(T.NodeNotRtf);
QilNode fdef = _f.Error(SR.Xslt_UndefinedKey, name);
for (int idx = 0; idx < _compiler.Keys.Count; idx++)
{
fdef = _f.Conditional(_f.Eq(resolvedName, _compiler.Keys[idx][0].Name.DeepClone(_f.BaseFactory)),
CompileSingleKey(_compiler.Keys[idx], key, context),
fdef
);
}
QilFunction result = _f.Function(_f.FormalParameterList(name, resolvedName, key, context), fdef, _f.False());
result.DebugName = "key";
_functions.Add(result);
return result;
}
private QilNode CompileFnDocument(QilNode uris, QilNode baseNode)
{
QilNode result;
QilIterator i, j, u;
if (!_compiler.Settings.EnableDocumentFunction)
{
ReportWarning(SR.Xslt_DocumentFuncProhibited);
return _f.Error(_lastScope.SourceLine, SR.Xslt_DocumentFuncProhibited);
}
if (uris.XmlType.IsNode)
{
result = _f.DocOrderDistinct(_f.Loop(i = _f.For(uris),
CompileSingleDocument(_f.ConvertToString(i), baseNode ?? i)
));
}
else if (uris.XmlType.IsAtomicValue)
{
result = CompileSingleDocument(_f.ConvertToString(uris), baseNode);
}
else
{
u = _f.Let(uris);
j = (baseNode != null) ? _f.Let(baseNode) : null;
result = _f.Conditional(_f.Not(_f.IsType(u, T.AnyAtomicType)),
_f.DocOrderDistinct(_f.Loop(i = _f.For(_f.TypeAssert(u, T.NodeS)),
CompileSingleDocument(_f.ConvertToString(i), j ?? i)
)),
CompileSingleDocument(_f.XsltConvert(u, T.StringX), j)
);
result = (baseNode != null) ? _f.Loop(j, result) : result;
result = _f.Loop(u, result);
}
return result;
}
private QilNode CompileSingleDocument(QilNode uri, QilNode baseNode)
{
_f.CheckString(uri);
QilNode baseUri;
if (baseNode == null)
{
baseUri = _f.String(_lastScope.SourceLine.Uri);
}
else
{
_f.CheckNodeSet(baseNode);
if (baseNode.XmlType.IsSingleton)
{
baseUri = _f.InvokeBaseUri(baseNode);
}
else
{
// According to errata E14, it is an error if the second argument node-set is empty
// and the URI reference is relative. We pass an empty string as a baseUri to indicate
// that case.
QilIterator i;
baseUri = _f.StrConcat(_f.Loop(i = _f.FirstNode(baseNode), _f.InvokeBaseUri(i)));
}
}
_f.CheckString(baseUri);
return _f.DataSource(uri, baseUri);
}
private QilNode CompileFormatNumber(QilNode value, QilNode formatPicture, QilNode formatName)
{
_f.CheckDouble(value);
_f.CheckString(formatPicture);
XmlQualifiedName resolvedName;
if (formatName == null)
{
resolvedName = new XmlQualifiedName();
// formatName must be non-null in the f.InvokeFormatNumberDynamic() call below
formatName = _f.String(string.Empty);
}
else
{
_f.CheckString(formatName);
if (formatName.NodeType == QilNodeType.LiteralString)
{
resolvedName = ResolveQNameThrow(/*ignoreDefaultNs:*/true, formatName);
}
else
{
resolvedName = null;
}
}
if (resolvedName != null)
{
DecimalFormatDecl format;
if (_compiler.DecimalFormats.Contains(resolvedName))
{
format = _compiler.DecimalFormats[resolvedName];
}
else
{
if (resolvedName != DecimalFormatDecl.Default.Name)
{
throw new XslLoadException(SR.Xslt_NoDecimalFormat, (string)(QilLiteral)formatName);
}
format = DecimalFormatDecl.Default;
}
// If both formatPicture and formatName are literal strings, there is no need to reparse
// formatPicture on every execution of this format-number(). Instead, we create a DecimalFormatter
// object on the first execution, save its index into a global variable, and reuse that object
// on all subsequent executions.
if (formatPicture.NodeType == QilNodeType.LiteralString)
{
QilIterator fmtIdx = _f.Let(_f.InvokeRegisterDecimalFormatter(formatPicture, format));
fmtIdx.DebugName = _f.QName("formatter" + _formatterCnt++, XmlReservedNs.NsXslDebug).ToString();
_gloVars.Add(fmtIdx);
return _f.InvokeFormatNumberStatic(value, fmtIdx);
}
_formatNumberDynamicUsed = true;
QilNode name = _f.QName(resolvedName.Name, resolvedName.Namespace);
return _f.InvokeFormatNumberDynamic(value, formatPicture, name, formatName);
}
else
{
_formatNumberDynamicUsed = true;
QilIterator i = _f.Let(formatName);
QilNode name = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, i);
return _f.Loop(i, _f.InvokeFormatNumberDynamic(value, formatPicture, name, i));
}
}
private QilNode CompileUnparsedEntityUri(QilNode n)
{
_f.CheckString(n);
return _f.Error(_lastScope.SourceLine, SR.Xslt_UnsupportedXsltFunction, "unparsed-entity-uri");
}
private QilNode CompileGenerateId(QilNode n)
{
_f.CheckNodeSet(n);
if (n.XmlType.IsSingleton)
{
return _f.XsltGenerateId(n);
}
else
{
QilIterator i;
return _f.StrConcat(_f.Loop(i = _f.FirstNode(n), _f.XsltGenerateId(i)));
}
}
private XmlQualifiedName ResolveQNameThrow(bool ignoreDefaultNs, QilNode qilName)
{
string name = (string)(QilLiteral)qilName;
string prefix, local, nsUri;
_compiler.ParseQName(name, out prefix, out local, new ThrowErrorHelper());
nsUri = ResolvePrefixThrow(/*ignoreDefaultNs:*/ignoreDefaultNs, prefix);
return new XmlQualifiedName(local, nsUri);
}
private QilNode CompileSystemProperty(QilNode name)
{
_f.CheckString(name);
if (name.NodeType == QilNodeType.LiteralString)
{
XmlQualifiedName qname = ResolveQNameThrow(/*ignoreDefaultNs:*/true, name);
if (EvaluateFuncCalls)
{
XPathItem propValue = XsltFunctions.SystemProperty(qname);
if (propValue.ValueType == XsltConvert.StringType)
{
return _f.String(propValue.Value);
}
else
{
Debug.Assert(propValue.ValueType == XsltConvert.DoubleType);
return _f.Double((double)propValue.ValueAsDouble);
}
}
name = _f.QName(qname.Name, qname.Namespace);
}
else
{
name = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, name);
}
return _f.InvokeSystemProperty(name);
}
private QilNode CompileElementAvailable(QilNode name)
{
_f.CheckString(name);
if (name.NodeType == QilNodeType.LiteralString)
{
XmlQualifiedName qname = ResolveQNameThrow(/*ignoreDefaultNs:*/false, name);
if (EvaluateFuncCalls)
{
return _f.Boolean(IsElementAvailable(qname));
}
name = _f.QName(qname.Name, qname.Namespace);
}
else
{
name = ResolveQNameDynamic(/*ignoreDefaultNs:*/false, name);
}
return _f.InvokeElementAvailable(name);
}
private QilNode CompileFunctionAvailable(QilNode name)
{
_f.CheckString(name);
if (name.NodeType == QilNodeType.LiteralString)
{
XmlQualifiedName qname = ResolveQNameThrow(/*ignoreDefaultNs:*/true, name);
if (EvaluateFuncCalls)
{
// Script blocks and extension objects cannot implement neither null nor XSLT namespace
if (qname.Namespace.Length == 0 || qname.Namespace == XmlReservedNs.NsXslt)
{
return _f.Boolean(QilGenerator.IsFunctionAvailable(qname.Name, qname.Namespace));
}
// We might precalculate the result for script namespaces as well
}
name = _f.QName(qname.Name, qname.Namespace);
}
else
{
name = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, name);
}
return _f.InvokeFunctionAvailable(name);
}
private QilNode CompileMsNodeSet(QilNode n)
{
if (n.XmlType.IsNode && n.XmlType.IsNotRtf)
{
return n;
}
return _f.XsltConvert(n, T.NodeSDod);
}
//------------------------------------------------
// EXSLT Functions
//------------------------------------------------
private QilNode EXslObjectType(QilNode n)
{
if (EvaluateFuncCalls)
{
switch (n.XmlType.TypeCode)
{
case XmlTypeCode.Boolean: return _f.String("boolean");
case XmlTypeCode.Double: return _f.String("number");
case XmlTypeCode.String: return _f.String("string");
default:
if (n.XmlType.IsNode && n.XmlType.IsNotRtf)
{
return _f.String("node-set");
}
break;
}
}
return _f.InvokeEXslObjectType(n);
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Model
{
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using NPOI.HSSF.Record;
using NPOI.SS.Formula;
using NPOI.SS.Formula.PTG;
/**
* Link Table (OOO pdf reference: 4.10.3 ) <p/>
*
* The main data of all types of references is stored in the Link Table inside the Workbook Globals
* Substream (4.2.5). The Link Table itself is optional and occurs only, if there are any
* references in the document.
* <p/>
*
* In BIFF8 the Link Table consists of
* <ul>
* <li>zero or more EXTERNALBOOK Blocks<p/>
* each consisting of
* <ul>
* <li>exactly one EXTERNALBOOK (0x01AE) record</li>
* <li>zero or more EXTERNALNAME (0x0023) records</li>
* <li>zero or more CRN Blocks<p/>
* each consisting of
* <ul>
* <li>exactly one XCT (0x0059)record</li>
* <li>zero or more CRN (0x005A) records (documentation says one or more)</li>
* </ul>
* </li>
* </ul>
* </li>
* <li>zero or one EXTERNSHEET (0x0017) record</li>
* <li>zero or more DEFINEDNAME (0x0018) records</li>
* </ul>
*
*
* @author Josh Micich
*/
internal class LinkTable
{
// TODO make this class into a record aggregate
private static ExternSheetRecord ReadExtSheetRecord(RecordStream rs)
{
List<ExternSheetRecord> temp = new List<ExternSheetRecord>(2);
while (rs.PeekNextClass() == typeof(ExternSheetRecord))
{
temp.Add((ExternSheetRecord)rs.GetNext());
}
int nItems = temp.Count;
if (nItems < 1)
{
throw new Exception("Expected an EXTERNSHEET record but got ("
+ rs.PeekNextClass().Name + ")");
}
if (nItems == 1)
{
// this is the normal case. There should be just one ExternSheetRecord
return temp[0];
}
// Some apps generate multiple ExternSheetRecords (see bug 45698).
// It seems like the best thing to do might be to combine these into one
ExternSheetRecord[] esrs = new ExternSheetRecord[nItems];
esrs = temp.ToArray();
return ExternSheetRecord.Combine(esrs);
}
private class CRNBlock
{
private CRNCountRecord _countRecord;
private CRNRecord[] _crns;
public CRNBlock(RecordStream rs)
{
_countRecord = (CRNCountRecord)rs.GetNext();
int nCRNs = _countRecord.NumberOfCRNs;
CRNRecord[] crns = new CRNRecord[nCRNs];
for (int i = 0; i < crns.Length; i++)
{
crns[i] = (CRNRecord)rs.GetNext();
}
_crns = crns;
}
public CRNRecord[] GetCrns()
{
return (CRNRecord[])_crns.Clone();
}
}
private class ExternalBookBlock
{
private SupBookRecord _externalBookRecord;
private ExternalNameRecord[] _externalNameRecords;
private CRNBlock[] _crnBlocks;
/**
* Create a new block for registering add-in functions
*
* @see org.apache.poi.hssf.model.LinkTable#addNameXPtg(String)
*/
public ExternalBookBlock()
{
_externalBookRecord = SupBookRecord.CreateAddInFunctions();
_externalNameRecords = new ExternalNameRecord[0];
_crnBlocks = new CRNBlock[0];
}
public ExternalBookBlock(RecordStream rs)
{
_externalBookRecord = (SupBookRecord)rs.GetNext();
ArrayList temp = new ArrayList();
while (rs.PeekNextClass() == typeof(ExternalNameRecord))
{
temp.Add(rs.GetNext());
}
_externalNameRecords = (ExternalNameRecord[])temp.ToArray(typeof(ExternalNameRecord));
temp.Clear();
while (rs.PeekNextClass() == typeof(CRNCountRecord))
{
temp.Add(new CRNBlock(rs));
}
_crnBlocks = (CRNBlock[])temp.ToArray(typeof(CRNBlock));
}
public int NumberOfNames
{
get
{
return _externalNameRecords.Length;
}
}
public int AddExternalName(ExternalNameRecord rec)
{
ExternalNameRecord[] tmp = new ExternalNameRecord[_externalNameRecords.Length + 1];
Array.Copy(_externalNameRecords, 0, tmp, 0, _externalNameRecords.Length);
tmp[tmp.Length - 1] = rec;
_externalNameRecords = tmp;
return _externalNameRecords.Length - 1;
}
/**
* Create a new block for internal references. It is called when constructing a new LinkTable.
*
* @see org.apache.poi.hssf.model.LinkTable#LinkTable(int, WorkbookRecordList)
*/
public ExternalBookBlock(int numberOfSheets)
{
_externalBookRecord = SupBookRecord.CreateInternalReferences((short)numberOfSheets);
_externalNameRecords = new ExternalNameRecord[0];
_crnBlocks = new CRNBlock[0];
}
public SupBookRecord GetExternalBookRecord()
{
return _externalBookRecord;
}
public String GetNameText(int definedNameIndex)
{
return _externalNameRecords[definedNameIndex].Text;
}
/**
* Performs case-insensitive search
* @return -1 if not found
*/
public int GetIndexOfName(String name)
{
for (int i = 0; i < _externalNameRecords.Length; i++)
{
if (_externalNameRecords[i].Text.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return i;
}
}
return -1;
}
public int GetNameIx(int definedNameIndex)
{
return _externalNameRecords[definedNameIndex].Ix;
}
}
private ExternalBookBlock[] _externalBookBlocks;
private ExternSheetRecord _externSheetRecord;
private List<NameRecord> _definedNames;
private int _recordCount;
private WorkbookRecordList _workbookRecordList; // TODO - would be nice to Remove this
public LinkTable(List<Record> inputList, int startIndex, WorkbookRecordList workbookRecordList, Dictionary<String, NameCommentRecord> commentRecords)
{
_workbookRecordList = workbookRecordList;
RecordStream rs = new RecordStream(inputList, startIndex);
ArrayList temp = new ArrayList();
while (rs.PeekNextClass() == typeof(SupBookRecord))
{
temp.Add(new ExternalBookBlock(rs));
}
//_externalBookBlocks = new ExternalBookBlock[temp.Count];
_externalBookBlocks = (ExternalBookBlock[])temp.ToArray(typeof(ExternalBookBlock));
temp.Clear();
if (_externalBookBlocks.Length > 0)
{
// If any ExternalBookBlock present, there is always 1 of ExternSheetRecord
if (rs.PeekNextClass() != typeof(ExternSheetRecord))
{
// not quite - if written by google docs
_externSheetRecord = null;
}
else
{
_externSheetRecord = ReadExtSheetRecord(rs);
}
}
else
{
_externSheetRecord = null;
}
_definedNames = new List<NameRecord>();
// collect zero or more DEFINEDNAMEs id=0x18
while (true)
{
Type nextClass = rs.PeekNextClass();
if (nextClass == typeof(NameRecord))
{
NameRecord nr = (NameRecord)rs.GetNext();
_definedNames.Add(nr);
}
else if (nextClass == typeof(NameCommentRecord))
{
NameCommentRecord ncr = (NameCommentRecord)rs.GetNext();
commentRecords.Add(ncr.NameText, ncr);
}
else
{
break;
}
}
_recordCount = rs.GetCountRead();
for (int i = startIndex; i < startIndex + _recordCount; i++)
{
_workbookRecordList.Records.Add(inputList[i]);
}
}
public LinkTable(int numberOfSheets, WorkbookRecordList workbookRecordList)
{
_workbookRecordList = workbookRecordList;
_definedNames = new List<NameRecord>();
_externalBookBlocks = new ExternalBookBlock[] {
new ExternalBookBlock(numberOfSheets),
};
_externSheetRecord = new ExternSheetRecord();
_recordCount = 2;
// tell _workbookRecordList about the 2 new records
SupBookRecord supbook = _externalBookBlocks[0].GetExternalBookRecord();
int idx = FindFirstRecordLocBySid(CountryRecord.sid);
if (idx < 0)
{
throw new Exception("CountryRecord not found");
}
_workbookRecordList.Add(idx + 1, _externSheetRecord);
_workbookRecordList.Add(idx + 1, supbook);
}
/**
* TODO - would not be required if calling code used RecordStream or similar
*/
public int RecordCount
{
get { return _recordCount; }
}
public NameRecord GetSpecificBuiltinRecord(byte builtInCode, int sheetNumber)
{
IEnumerator iterator = _definedNames.GetEnumerator();
while (iterator.MoveNext())
{
NameRecord record = (NameRecord)iterator.Current;
//print areas are one based
if (record.BuiltInName == builtInCode && record.SheetNumber == sheetNumber)
{
return record;
}
}
return null;
}
public void RemoveBuiltinRecord(byte name, int sheetIndex)
{
//the name array is smaller so searching through it should be faster than
//using the FindFirstXXXX methods
NameRecord record = GetSpecificBuiltinRecord(name, sheetIndex);
if (record != null)
{
_definedNames.Remove(record);
}
// TODO - do we need "Workbook.records.Remove(...);" similar to that in Workbook.RemoveName(int namenum) {}?
}
/**
* @param extRefIndex as from a {@link Ref3DPtg} or {@link Area3DPtg}
* @return -1 if the reference is to an external book
*/
public int GetIndexToInternalSheet(int extRefIndex)
{
return _externSheetRecord.GetFirstSheetIndexFromRefIndex(extRefIndex);
}
public int NumNames
{
get
{
return _definedNames.Count;
}
}
private int FindRefIndexFromExtBookIndex(int extBookIndex)
{
return _externSheetRecord.FindRefIndexFromExtBookIndex(extBookIndex);
}
public NameXPtg GetNameXPtg(String name)
{
// first find any external book block that contains the name:
for (int i = 0; i < _externalBookBlocks.Length; i++)
{
int definedNameIndex = _externalBookBlocks[i].GetIndexOfName(name);
if (definedNameIndex < 0)
{
continue;
}
// found it.
int sheetRefIndex = FindRefIndexFromExtBookIndex(i);
if (sheetRefIndex >= 0)
{
return new NameXPtg(sheetRefIndex, definedNameIndex);
}
}
return null;
}
public NameRecord GetNameRecord(int index)
{
return (NameRecord)_definedNames[index];
}
public void AddName(NameRecord name)
{
_definedNames.Add(name);
// TODO - this Is messy
// Not the most efficient way but the other way was causing too many bugs
int idx = FindFirstRecordLocBySid(ExternSheetRecord.sid);
if (idx == -1) idx = FindFirstRecordLocBySid(SupBookRecord.sid);
if (idx == -1) idx = FindFirstRecordLocBySid(CountryRecord.sid);
int countNames = _definedNames.Count;
_workbookRecordList.Add(idx + countNames, name);
}
/**
* Register an external name in this workbook
*
* @param name the name to register
* @return a NameXPtg describing this name
*/
public NameXPtg AddNameXPtg(String name)
{
int extBlockIndex = -1;
ExternalBookBlock extBlock = null;
// find ExternalBlock for Add-In functions and remember its index
for (int i = 0; i < _externalBookBlocks.Length; i++)
{
SupBookRecord ebr = _externalBookBlocks[i].GetExternalBookRecord();
if (ebr.IsAddInFunctions)
{
extBlock = _externalBookBlocks[i];
extBlockIndex = i;
break;
}
}
// An ExternalBlock for Add-In functions was not found. Create a new one.
if (extBlock == null)
{
extBlock = new ExternalBookBlock();
ExternalBookBlock[] tmp = new ExternalBookBlock[_externalBookBlocks.Length + 1];
Array.Copy(_externalBookBlocks, 0, tmp, 0, _externalBookBlocks.Length);
tmp[tmp.Length - 1] = extBlock;
_externalBookBlocks = tmp;
extBlockIndex = _externalBookBlocks.Length - 1;
// add the created SupBookRecord before ExternSheetRecord
int idx = FindFirstRecordLocBySid(ExternSheetRecord.sid);
_workbookRecordList.Add(idx, extBlock.GetExternalBookRecord());
// register the SupBookRecord in the ExternSheetRecord
// -2 means that the scope of this name is Workbook and the reference applies to the entire workbook.
_externSheetRecord.AddRef(_externalBookBlocks.Length - 1, -2, -2);
}
// create a ExternalNameRecord that will describe this name
ExternalNameRecord extNameRecord = new ExternalNameRecord();
extNameRecord.Text = (name);
// The docs don't explain why Excel set the formula to #REF!
extNameRecord.SetParsedExpression(new Ptg[] { ErrPtg.REF_INVALID });
int nameIndex = extBlock.AddExternalName(extNameRecord);
int supLinkIndex = 0;
// find the posistion of the Add-In SupBookRecord in the workbook stream,
// the created ExternalNameRecord will be appended to it
for (IEnumerator iterator = _workbookRecordList.GetEnumerator(); iterator.MoveNext(); supLinkIndex++)
{
Record record = (Record)iterator.Current;
if (record is SupBookRecord)
{
if (((SupBookRecord)record).IsAddInFunctions) break;
}
}
int numberOfNames = extBlock.NumberOfNames;
// a new name is inserted in the end of the SupBookRecord, after the last name
_workbookRecordList.Add(supLinkIndex + numberOfNames, extNameRecord);
int ix = _externSheetRecord.GetRefIxForSheet(extBlockIndex, -2 /* the scope is workbook*/);
return new NameXPtg(ix, nameIndex);
}
public void RemoveName(int namenum)
{
_definedNames.RemoveAt(namenum);
}
public int GetSheetIndexFromExternSheetIndex(int extRefIndex)
{
if (extRefIndex >= _externSheetRecord.NumOfRefs)
{
return -1;
}
return _externSheetRecord.GetFirstSheetIndexFromRefIndex(extRefIndex);
}
private static int GetSheetIndex(String[] sheetNames, String sheetName)
{
for (int i = 0; i < sheetNames.Length; i++)
{
if (sheetNames[i].Equals(sheetName))
{
return i;
}
}
throw new InvalidOperationException("External workbook does not contain sheet '" + sheetName + "'");
}
public int GetExternalSheetIndex(String workbookName, String sheetName)
{
SupBookRecord ebrTarget = null;
int externalBookIndex = -1;
for (int i = 0; i < _externalBookBlocks.Length; i++)
{
SupBookRecord ebr = _externalBookBlocks[i].GetExternalBookRecord();
if (!ebr.IsExternalReferences)
{
continue;
}
if (workbookName.Equals(ebr.URL))
{ // not sure if 'equals()' works when url has a directory
ebrTarget = ebr;
externalBookIndex = i;
break;
}
}
if (ebrTarget == null)
{
throw new NullReferenceException("No external workbook with name '" + workbookName + "'");
}
int sheetIndex = GetSheetIndex(ebrTarget.SheetNames, sheetName);
int result = _externSheetRecord.GetRefIxForSheet(externalBookIndex, sheetIndex);
if (result < 0)
{
throw new InvalidOperationException("ExternSheetRecord does not contain combination ("
+ externalBookIndex + ", " + sheetIndex + ")");
}
return result;
}
public String[] GetExternalBookAndSheetName(int extRefIndex)
{
int ebIx = _externSheetRecord.GetExtbookIndexFromRefIndex(extRefIndex);
SupBookRecord ebr = _externalBookBlocks[ebIx].GetExternalBookRecord();
if (!ebr.IsExternalReferences)
{
return null;
}
int shIx = _externSheetRecord.GetFirstSheetIndexFromRefIndex(extRefIndex);
String usSheetName = null;
if (shIx >= 0)
{
usSheetName = (String)ebr.SheetNames.GetValue(shIx);
}
return new String[] {
ebr.URL,
usSheetName,
};
}
public int CheckExternSheet(int sheetIndex)
{
int thisWbIndex = -1; // this is probably always zero
for (int i = 0; i < _externalBookBlocks.Length; i++)
{
SupBookRecord ebr = _externalBookBlocks[i].GetExternalBookRecord();
if (ebr.IsInternalReferences)
{
thisWbIndex = i;
break;
}
}
if (thisWbIndex < 0)
{
throw new InvalidOperationException("Could not find 'internal references' EXTERNALBOOK");
}
//Trying to find reference to this sheet
int j = _externSheetRecord.GetRefIxForSheet(thisWbIndex, sheetIndex);
if (j >= 0)
{
return j;
}
//We haven't found reference to this sheet
return _externSheetRecord.AddRef(thisWbIndex, sheetIndex, sheetIndex);
}
/**
* copied from Workbook
*/
private int FindFirstRecordLocBySid(short sid)
{
int index = 0;
for (IEnumerator iterator = _workbookRecordList.GetEnumerator(); iterator.MoveNext(); )
{
Record record = (Record)iterator.Current;
if (record.Sid == sid)
{
return index;
}
index++;
}
return -1;
}
public String ResolveNameXText(int refIndex, int definedNameIndex)
{
int extBookIndex = _externSheetRecord.GetExtbookIndexFromRefIndex(refIndex);
return _externalBookBlocks[extBookIndex].GetNameText(definedNameIndex);
}
public int ResolveNameXIx(int refIndex, int definedNameIndex)
{
int extBookIndex = _externSheetRecord.GetExtbookIndexFromRefIndex(refIndex);
return _externalBookBlocks[extBookIndex].GetNameIx(definedNameIndex);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FrameApi.cs" company="Google LLC">
//
// Copyright 2017 Google LLC. 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.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCoreInternal
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using GoogleARCore;
using UnityEngine;
#if UNITY_IOS && !UNITY_EDITOR
using AndroidImport = GoogleARCoreInternal.DllImportNoop;
using IOSImport = System.Runtime.InteropServices.DllImportAttribute;
#else
using AndroidImport = System.Runtime.InteropServices.DllImportAttribute;
using IOSImport = GoogleARCoreInternal.DllImportNoop;
#endif
internal class FrameApi
{
private NativeSession m_NativeSession;
private float[,] m_AmbientSH = new float[9, 3];
public FrameApi(NativeSession nativeSession)
{
m_NativeSession = nativeSession;
}
public void Release(IntPtr frameHandle)
{
ExternApi.ArFrame_release(frameHandle);
}
public long GetTimestamp()
{
long timestamp = 0;
ExternApi.ArFrame_getTimestamp(
m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, ref timestamp);
return timestamp;
}
public IntPtr AcquireCamera()
{
IntPtr cameraHandle = IntPtr.Zero;
ExternApi.ArFrame_acquireCamera(
m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, ref cameraHandle);
return cameraHandle;
}
public CameraImageBytes AcquireCameraImageBytes()
{
IntPtr cameraImageHandle = IntPtr.Zero;
ApiArStatus status = ExternApi.ArFrame_acquireCameraImage(m_NativeSession.SessionHandle,
m_NativeSession.FrameHandle, ref cameraImageHandle);
if (status != ApiArStatus.Success)
{
Debug.LogWarningFormat("Failed to acquire camera image with status {0}.", status);
return new CameraImageBytes(IntPtr.Zero);
}
return new CameraImageBytes(cameraImageHandle);
}
public bool TryAcquirePointCloudHandle(out IntPtr pointCloudHandle)
{
pointCloudHandle = IntPtr.Zero;
ApiArStatus status = ExternApi.ArFrame_acquirePointCloud(m_NativeSession.SessionHandle,
m_NativeSession.FrameHandle, ref pointCloudHandle);
if (status != ApiArStatus.Success)
{
Debug.LogWarningFormat("Failed to acquire point cloud with status {0}", status);
return false;
}
return true;
}
public bool AcquireImageMetadata(ref IntPtr imageMetadataHandle)
{
var status = ExternApi.ArFrame_acquireImageMetadata(m_NativeSession.SessionHandle,
m_NativeSession.FrameHandle, ref imageMetadataHandle);
if (status != ApiArStatus.Success)
{
Debug.LogErrorFormat(
"Failed to aquire camera image metadata with status {0}", status);
return false;
}
return true;
}
public LightEstimate GetLightEstimate()
{
IntPtr lightEstimateHandle = m_NativeSession.LightEstimateApi.Create();
ExternApi.ArFrame_getLightEstimate(
m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, lightEstimateHandle);
LightEstimateState state =
m_NativeSession.LightEstimateApi.GetState(lightEstimateHandle);
Color colorCorrection =
m_NativeSession.LightEstimateApi.GetColorCorrection(lightEstimateHandle);
long timestamp = m_NativeSession.LightEstimateApi.GetTimestamp(
m_NativeSession.SessionHandle, lightEstimateHandle);
Quaternion mainLightRotation = Quaternion.identity;
Color mainLightColor = Color.black;
m_NativeSession.LightEstimateApi.GetMainDirectionalLight(
m_NativeSession.SessionHandle, lightEstimateHandle,
out mainLightRotation, out mainLightColor);
m_NativeSession.LightEstimateApi.GetAmbientSH(m_NativeSession.SessionHandle,
lightEstimateHandle, m_AmbientSH);
m_NativeSession.LightEstimateApi.Destroy(lightEstimateHandle);
return new LightEstimate(state, colorCorrection.a,
new Color(colorCorrection.r, colorCorrection.g, colorCorrection.b, 1f),
mainLightRotation, mainLightColor, m_AmbientSH, timestamp);
}
public Cubemap GetReflectionCubemap()
{
IntPtr lightEstimateHandle = m_NativeSession.LightEstimateApi.Create();
ExternApi.ArFrame_getLightEstimate(
m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, lightEstimateHandle);
LightEstimateState state =
m_NativeSession.LightEstimateApi.GetState(lightEstimateHandle);
if (state != LightEstimateState.Valid)
{
return null;
}
Cubemap cubemap = m_NativeSession.LightEstimateApi.GetReflectionCubemap(
m_NativeSession.SessionHandle, lightEstimateHandle);
m_NativeSession.LightEstimateApi.Destroy(lightEstimateHandle);
return cubemap;
}
public void TransformDisplayUvCoords(ref ApiDisplayUvCoords uv)
{
ApiDisplayUvCoords uvOut = new ApiDisplayUvCoords();
ExternApi.ArFrame_transformDisplayUvCoords(
m_NativeSession.SessionHandle, m_NativeSession.FrameHandle,
ApiDisplayUvCoords.NumFloats, ref uv, ref uvOut);
uv = uvOut;
}
public void TransformCoordinates2d(ref Vector2 uv, DisplayUvCoordinateType inputType,
DisplayUvCoordinateType outputType)
{
Vector2 uvOut = new Vector2(uv.x, uv.y);
ExternApi.ArFrame_transformCoordinates2d(
m_NativeSession.SessionHandle, m_NativeSession.FrameHandle,
inputType.ToApiCoordinates2dType(), 1, ref uv, outputType.ToApiCoordinates2dType(),
ref uvOut);
uv = uvOut;
}
public void GetUpdatedTrackables(List<Trackable> trackables)
{
IntPtr listHandle = m_NativeSession.TrackableListApi.Create();
ExternApi.ArFrame_getUpdatedTrackables(
m_NativeSession.SessionHandle, m_NativeSession.FrameHandle,
ApiTrackableType.BaseTrackable, listHandle);
trackables.Clear();
int count = m_NativeSession.TrackableListApi.GetCount(listHandle);
for (int i = 0; i < count; i++)
{
IntPtr trackableHandle =
m_NativeSession.TrackableListApi.AcquireItem(listHandle, i);
// TODO:: Remove conditional when b/75291352 is fixed.
ApiTrackableType trackableType =
m_NativeSession.TrackableApi.GetType(trackableHandle);
if ((int)trackableType == 0x41520105)
{
m_NativeSession.TrackableApi.Release(trackableHandle);
continue;
}
Trackable trackable = m_NativeSession.TrackableFactory(trackableHandle);
if (trackable != null)
{
trackables.Add(trackable);
}
else
{
m_NativeSession.TrackableApi.Release(trackableHandle);
}
}
m_NativeSession.TrackableListApi.Destroy(listHandle);
}
public int GetCameraTextureName()
{
int textureId = -1;
ExternApi.ArFrame_getCameraTextureName(
m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, ref textureId);
return textureId;
}
public DepthStatus UpdateDepthTexture(ref Texture2D depthTexture)
{
IntPtr depthImageHandle = IntPtr.Zero;
// Get the current depth image.
ApiArStatus status =
(ApiArStatus)ExternApi.ArFrame_acquireDepthImage(
m_NativeSession.SessionHandle,
m_NativeSession.FrameHandle,
ref depthImageHandle);
if (status != ApiArStatus.Success)
{
Debug.LogErrorFormat("[ARCore] failed to acquire depth image " +
"with status {0}", status.ToString());
return status.ToDepthStatus();
}
// Update the depth texture.
if (!_UpdateDepthTexture(ref depthTexture, depthImageHandle))
{
return DepthStatus.InternalError;
}
return DepthStatus.Success;
}
private bool _UpdateDepthTexture(
ref Texture2D depthTexture, IntPtr depthImageHandle)
{
// Get the size of the depth data.
int width = m_NativeSession.ImageApi.GetWidth(depthImageHandle);
int height = m_NativeSession.ImageApi.GetHeight(depthImageHandle);
// Access the depth image surface data.
IntPtr planeDoublePtr = IntPtr.Zero;
int planeSize = 0;
m_NativeSession.ImageApi.GetPlaneData(
depthImageHandle, 0, ref planeDoublePtr, ref planeSize);
IntPtr planeDataPtr = new IntPtr(planeDoublePtr.ToInt64());
// Resize the depth texture if needed.
if (width != depthTexture.width ||
height != depthTexture.height ||
depthTexture.format != TextureFormat.RGB565)
{
if (!depthTexture.Resize(
width, height, TextureFormat.RGB565, false))
{
Debug.LogErrorFormat("Unable to resize depth texture! " +
"Current: width {0} height {1} depthFormat {2} " +
"Desired: width {3} height {4} depthFormat {5} ",
depthTexture.width, depthTexture.height,
depthTexture.format.ToString(),
width, height,
TextureFormat.RGB565);
m_NativeSession.ImageApi.Release(depthImageHandle);
return false;
}
}
// Copy the raw depth data to the texture.
depthTexture.LoadRawTextureData(planeDataPtr, planeSize);
depthTexture.Apply();
m_NativeSession.ImageApi.Release(depthImageHandle);
return true;
}
private struct ExternApi
{
[DllImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_release(IntPtr frame);
[DllImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_getTimestamp(IntPtr sessionHandle,
IntPtr frame, ref long timestamp);
#pragma warning disable 626
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_acquireCamera(
IntPtr sessionHandle, IntPtr frameHandle, ref IntPtr cameraHandle);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern ApiArStatus ArFrame_acquireCameraImage(
IntPtr sessionHandle, IntPtr frameHandle, ref IntPtr imageHandle);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern ApiArStatus ArFrame_acquirePointCloud(
IntPtr sessionHandle, IntPtr frameHandle, ref IntPtr pointCloudHandle);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_transformDisplayUvCoords(
IntPtr session,
IntPtr frame,
int numElements,
ref ApiDisplayUvCoords uvsIn,
ref ApiDisplayUvCoords uvsOut);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_transformCoordinates2d(
IntPtr session,
IntPtr frame,
ApiCoordinates2dType inputType,
int numVertices,
ref Vector2 uvsIn,
ApiCoordinates2dType outputType,
ref Vector2 uvsOut);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_getUpdatedTrackables(
IntPtr sessionHandle, IntPtr frameHandle, ApiTrackableType filterType,
IntPtr outTrackableList);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_getLightEstimate(
IntPtr sessionHandle, IntPtr frameHandle, IntPtr lightEstimateHandle);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern ApiArStatus ArFrame_acquireImageMetadata(
IntPtr sessionHandle, IntPtr frameHandle, ref IntPtr outMetadata);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_getCameraTextureName(
IntPtr sessionHandle, IntPtr frameHandle, ref int outTextureId);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern ApiArStatus ArFrame_acquireDepthImage(
IntPtr sessionHandle, IntPtr frameHandle, ref IntPtr imageHandle);
#pragma warning restore 626
}
}
}
| |
//
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Resources
{
/// <summary>
/// Operations for managing providers.
/// </summary>
internal partial class ProviderOperations : IServiceOperations<ResourceManagementClient>, IProviderOperations
{
/// <summary>
/// Initializes a new instance of the ProviderOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ProviderOperations(ResourceManagementClient client)
{
this._client = client;
}
private ResourceManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Resources.ResourceManagementClient.
/// </summary>
public ResourceManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Gets a resource provider.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource provider information.
/// </returns>
public async Task<ProviderGetResult> GetAsync(string resourceProviderNamespace, CancellationToken cancellationToken)
{
// Validate
if (resourceProviderNamespace == null)
{
throw new ArgumentNullException("resourceProviderNamespace");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/providers/" + resourceProviderNamespace.Trim() + "?";
url = url + "api-version=2014-04-01-preview";
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)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ProviderGetResult result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProviderGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Provider providerInstance = new Provider();
result.Provider = providerInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
providerInstance.Id = idInstance;
}
JToken namespaceValue = responseDoc["namespace"];
if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
{
string namespaceInstance = ((string)namespaceValue);
providerInstance.Namespace = namespaceInstance;
}
JToken registrationStateValue = responseDoc["registrationState"];
if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
{
string registrationStateInstance = ((string)registrationStateValue);
providerInstance.RegistrationState = registrationStateInstance;
}
JToken resourceTypesArray = responseDoc["resourceTypes"];
if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
{
foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
{
ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
providerInstance.ResourceTypes.Add(providerResourceTypeInstance);
JToken resourceTypeValue = resourceTypesValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
providerResourceTypeInstance.Name = resourceTypeInstance;
}
JToken locationsArray = resourceTypesValue["locations"];
if (locationsArray != null && locationsArray.Type != JTokenType.Null)
{
foreach (JToken locationsValue in ((JArray)locationsArray))
{
providerResourceTypeInstance.Locations.Add(((string)locationsValue));
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a list of resource providers.
/// </summary>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns all
/// deployments.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of resource providers.
/// </returns>
public async Task<ProviderListResult> ListAsync(ProviderListParameters parameters, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/providers?";
if (parameters != null && parameters.Top != null)
{
url = url + "$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString());
}
url = url + "&api-version=2014-04-01-preview";
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)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ProviderListResult result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProviderListResult();
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))
{
Provider providerInstance = new Provider();
result.Providers.Add(providerInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
providerInstance.Id = idInstance;
}
JToken namespaceValue = valueValue["namespace"];
if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
{
string namespaceInstance = ((string)namespaceValue);
providerInstance.Namespace = namespaceInstance;
}
JToken registrationStateValue = valueValue["registrationState"];
if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
{
string registrationStateInstance = ((string)registrationStateValue);
providerInstance.RegistrationState = registrationStateInstance;
}
JToken resourceTypesArray = valueValue["resourceTypes"];
if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
{
foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
{
ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
providerInstance.ResourceTypes.Add(providerResourceTypeInstance);
JToken resourceTypeValue = resourceTypesValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
providerResourceTypeInstance.Name = resourceTypeInstance;
}
JToken locationsArray = resourceTypesValue["locations"];
if (locationsArray != null && locationsArray.Type != JTokenType.Null)
{
foreach (JToken locationsValue in ((JArray)locationsArray))
{
providerResourceTypeInstance.Locations.Add(((string)locationsValue));
}
}
}
}
}
}
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("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of resource providers.
/// </returns>
public async Task<ProviderListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
Tracing.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = nextLink.Trim();
// 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)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ProviderListResult result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProviderListResult();
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))
{
Provider providerInstance = new Provider();
result.Providers.Add(providerInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
providerInstance.Id = idInstance;
}
JToken namespaceValue = valueValue["namespace"];
if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
{
string namespaceInstance = ((string)namespaceValue);
providerInstance.Namespace = namespaceInstance;
}
JToken registrationStateValue = valueValue["registrationState"];
if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
{
string registrationStateInstance = ((string)registrationStateValue);
providerInstance.RegistrationState = registrationStateInstance;
}
JToken resourceTypesArray = valueValue["resourceTypes"];
if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
{
foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
{
ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
providerInstance.ResourceTypes.Add(providerResourceTypeInstance);
JToken resourceTypeValue = resourceTypesValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
providerResourceTypeInstance.Name = resourceTypeInstance;
}
JToken locationsArray = resourceTypesValue["locations"];
if (locationsArray != null && locationsArray.Type != JTokenType.Null)
{
foreach (JToken locationsValue in ((JArray)locationsArray))
{
providerResourceTypeInstance.Locations.Add(((string)locationsValue));
}
}
}
}
}
}
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("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Registers provider to be used with a subscription.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> RegisterAsync(string resourceProviderNamespace, CancellationToken cancellationToken)
{
// Validate
if (resourceProviderNamespace == null)
{
throw new ArgumentNullException("resourceProviderNamespace");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
Tracing.Enter(invocationId, this, "RegisterAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/providers/" + resourceProviderNamespace.Trim() + "/register?";
url = url + "api-version=2014-04-01-preview";
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);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Unregisters provider from a subscription.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> UnregisterAsync(string resourceProviderNamespace, CancellationToken cancellationToken)
{
// Validate
if (resourceProviderNamespace == null)
{
throw new ArgumentNullException("resourceProviderNamespace");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
Tracing.Enter(invocationId, this, "UnregisterAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/providers/" + resourceProviderNamespace.Trim() + "/unregister?";
url = url + "api-version=2014-04-01-preview";
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);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace NAudio.Wave
{
/// <summary>
/// Represents a wave out device
/// </summary>
public class WaveOut : IWavePlayer
{
private readonly WaveInterop.WaveCallback callback;
private readonly WaveCallbackInfo callbackInfo;
private readonly SynchronizationContext syncContext;
private readonly object waveOutLock;
private WaveOutBuffer[] buffers;
private IntPtr hWaveOut;
private volatile PlaybackState playbackState;
private int queuedBuffers;
private float volume = 1;
private IWaveProvider waveStream;
/// <summary>
/// Creates a default WaveOut device
/// Will use window callbacks if called from a GUI thread, otherwise function
/// callbacks
/// </summary>
public WaveOut()
: this(
SynchronizationContext.Current == null
? WaveCallbackInfo.FunctionCallback()
: WaveCallbackInfo.NewWindow())
{
}
/// <summary>
/// Creates a WaveOut device using the specified window handle for callbacks
/// </summary>
/// <param name="windowHandle">A valid window handle</param>
public WaveOut(IntPtr windowHandle)
: this(WaveCallbackInfo.ExistingWindow(windowHandle))
{
}
/// <summary>
/// Opens a WaveOut device
/// </summary>
public WaveOut(WaveCallbackInfo callbackInfo)
{
syncContext = SynchronizationContext.Current;
// set default values up
DeviceNumber = 0;
DesiredLatency = 300;
NumberOfBuffers = 2;
callback = Callback;
waveOutLock = new object();
this.callbackInfo = callbackInfo;
callbackInfo.Connect(callback);
}
/// <summary>
/// Returns the number of Wave Out devices available in the system
/// </summary>
public static Int32 DeviceCount
{
get { return WaveInterop.waveOutGetNumDevs(); }
}
/// <summary>
/// Gets or sets the desired latency in milliseconds
/// Should be set before a call to Init
/// </summary>
public int DesiredLatency { get; set; }
/// <summary>
/// Gets or sets the number of buffers used
/// Should be set before a call to Init
/// </summary>
public int NumberOfBuffers { get; set; }
/// <summary>
/// Gets or sets the device number
/// Should be set before a call to Init
/// This must be between 0 and <see>DeviceCount</see> - 1.
/// </summary>
public int DeviceNumber { get; set; }
/// <summary>
/// Indicates playback has stopped automatically
/// </summary>
public event EventHandler<StoppedEventArgs> PlaybackStopped;
/// <summary>
/// Initialises the WaveOut device
/// </summary>
/// <param name="waveProvider">WaveProvider to play</param>
public void Init(IWaveProvider waveProvider)
{
waveStream = waveProvider;
int bufferSize =
waveProvider.WaveFormat.ConvertLatencyToByteSize((DesiredLatency + NumberOfBuffers - 1)/NumberOfBuffers);
MmResult result;
lock (waveOutLock)
{
result = callbackInfo.WaveOutOpen(out hWaveOut, DeviceNumber, waveStream.WaveFormat, callback);
}
MmException.Try(result, "waveOutOpen");
buffers = new WaveOutBuffer[NumberOfBuffers];
playbackState = PlaybackState.Stopped;
for (int n = 0; n < NumberOfBuffers; n++)
{
buffers[n] = new WaveOutBuffer(hWaveOut, bufferSize, waveStream, waveOutLock);
}
}
/// <summary>
/// Start playing the audio from the WaveStream
/// </summary>
public void Play()
{
if (playbackState == PlaybackState.Stopped)
{
playbackState = PlaybackState.Playing;
Debug.Assert(queuedBuffers == 0, "Buffers already queued on play");
EnqueueBuffers();
}
else if (playbackState == PlaybackState.Paused)
{
EnqueueBuffers();
Resume();
playbackState = PlaybackState.Playing;
}
}
/// <summary>
/// Pause the audio
/// </summary>
public void Pause()
{
if (playbackState == PlaybackState.Playing)
{
MmResult result;
lock (waveOutLock)
{
result = WaveInterop.waveOutPause(hWaveOut);
}
if (result != MmResult.NoError)
{
throw new MmException(result, "waveOutPause");
}
playbackState = PlaybackState.Paused;
}
}
/// <summary>
/// Stop and reset the WaveOut device
/// </summary>
public void Stop()
{
if (playbackState != PlaybackState.Stopped)
{
// in the call to waveOutReset with function callbacks
// some drivers will block here until OnDone is called
// for every buffer
playbackState = PlaybackState.Stopped; // set this here to avoid a problem with some drivers whereby
MmResult result;
lock (waveOutLock)
{
result = WaveInterop.waveOutReset(hWaveOut);
}
if (result != MmResult.NoError)
{
throw new MmException(result, "waveOutReset");
}
// with function callbacks, waveOutReset will call OnDone,
// and so PlaybackStopped must not be raised from the handler
// we know playback has definitely stopped now, so raise callback
if (callbackInfo.Strategy == WaveCallbackStrategy.FunctionCallback)
{
RaisePlaybackStoppedEvent(null);
}
}
}
/// <summary>
/// Playback State
/// </summary>
public PlaybackState PlaybackState
{
get { return playbackState; }
}
/// <summary>
/// Volume for this device 1.0 is full scale
/// </summary>
public float Volume
{
get { return volume; }
set
{
volume = value;
float left = volume;
float right = volume;
int stereoVolume = (int) (left*0xFFFF) + ((int) (right*0xFFFF) << 16);
MmResult result;
lock (waveOutLock)
{
result = WaveInterop.waveOutSetVolume(hWaveOut, stereoVolume);
}
MmException.Try(result, "waveOutSetVolume");
}
}
#region Dispose Pattern
/// <summary>
/// Closes this WaveOut device
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
/// <summary>
/// Closes the WaveOut device and disposes of buffers
/// </summary>
/// <param name="disposing">True if called from <see>Dispose</see></param>
protected void Dispose(bool disposing)
{
Stop();
if (disposing)
{
if (buffers != null)
{
for (int n = 0; n < buffers.Length; n++)
{
if (buffers[n] != null)
{
buffers[n].Dispose();
}
}
buffers = null;
}
}
lock (waveOutLock)
{
WaveInterop.waveOutClose(hWaveOut);
}
if (disposing)
{
callbackInfo.Disconnect();
}
}
/// <summary>
/// Finalizer. Only called when user forgets to call <see>Dispose</see>
/// </summary>
~WaveOut()
{
Debug.Assert(false, "WaveOut device was not closed");
Dispose(false);
}
#endregion
/// <summary>
/// Retrieves the capabilities of a waveOut device
/// </summary>
/// <param name="devNumber">Device to test</param>
/// <returns>The WaveOut device capabilities</returns>
public static WaveOutCapabilities GetCapabilities(int devNumber)
{
var caps = new WaveOutCapabilities();
int structSize = Marshal.SizeOf(caps);
MmException.Try(WaveInterop.waveOutGetDevCaps((IntPtr) devNumber, out caps, structSize), "waveOutGetDevCaps");
return caps;
}
private void EnqueueBuffers()
{
for (int n = 0; n < NumberOfBuffers; n++)
{
if (!buffers[n].InQueue)
{
if (buffers[n].OnDone())
{
Interlocked.Increment(ref queuedBuffers);
}
else
{
playbackState = PlaybackState.Stopped;
break;
}
//Debug.WriteLine(String.Format("Resume from Pause: Buffer [{0}] requeued", n));
}
}
}
/// <summary>
/// Resume playing after a pause from the same position
/// </summary>
public void Resume()
{
if (playbackState == PlaybackState.Paused)
{
MmResult result;
lock (waveOutLock)
{
result = WaveInterop.waveOutRestart(hWaveOut);
}
if (result != MmResult.NoError)
{
throw new MmException(result, "waveOutRestart");
}
playbackState = PlaybackState.Playing;
}
}
/// <summary>
/// Gets the current position in bytes from the wave output device.
/// (n.b. this is not the same thing as the position within your reader
/// stream - it calls directly into waveOutGetPosition)
/// </summary>
/// <returns>Position in bytes</returns>
public long GetPosition()
{
lock (waveOutLock)
{
var mmTime = new MmTime();
mmTime.wType = MmTime.TIME_BYTES;
// request results in bytes, TODO: perhaps make this a little more flexible and support the other types?
MmException.Try(WaveInterop.waveOutGetPosition(hWaveOut, out mmTime, Marshal.SizeOf(mmTime)),
"waveOutGetPosition");
if (mmTime.wType != MmTime.TIME_BYTES)
throw new Exception(string.Format("waveOutGetPosition: wType -> Expected {0}, Received {1}",
MmTime.TIME_BYTES, mmTime.wType));
return mmTime.cb;
}
}
// made non-static so that playing can be stopped here
private void Callback(IntPtr hWaveOut, WaveInterop.WaveMessage uMsg, IntPtr dwInstance, WaveHeader wavhdr,
IntPtr dwReserved)
{
if (uMsg == WaveInterop.WaveMessage.WaveOutDone)
{
var hBuffer = (GCHandle) wavhdr.userData;
var buffer = (WaveOutBuffer) hBuffer.Target;
Interlocked.Decrement(ref queuedBuffers);
Exception exception = null;
// check that we're not here through pressing stop
if (PlaybackState == PlaybackState.Playing)
{
// to avoid deadlocks in Function callback mode,
// we lock round this whole thing, which will include the
// reading from the stream.
// this protects us from calling waveOutReset on another
// thread while a WaveOutWrite is in progress
lock (waveOutLock)
{
try
{
if (buffer.OnDone())
{
Interlocked.Increment(ref queuedBuffers);
}
}
catch (Exception e)
{
// one likely cause is soundcard being unplugged
exception = e;
}
}
}
if (queuedBuffers == 0)
{
if (callbackInfo.Strategy == WaveCallbackStrategy.FunctionCallback &&
playbackState == PlaybackState.Stopped)
{
// the user has pressed stop
// DO NOT raise the playback stopped event from here
// since on the main thread we are still in the waveOutReset function
// Playback stopped will be raised elsewhere
}
else
{
RaisePlaybackStoppedEvent(exception);
}
}
}
}
private void RaisePlaybackStoppedEvent(Exception e)
{
EventHandler<StoppedEventArgs> handler = PlaybackStopped;
if (handler != null)
{
if (syncContext == null)
{
handler(this, new StoppedEventArgs(e));
}
else
{
syncContext.Post(state => handler(this, new StoppedEventArgs(e)), null);
}
}
}
}
}
| |
/*
* 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.
*/
#pragma warning disable S2360 // Optional parameters should not be used
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Apache.Ignite.Core.Discovery;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Static;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Tests.Process;
using NUnit.Framework;
/// <summary>
/// Test utility methods.
/// </summary>
public static class TestUtils
{
/** Indicates long running and/or memory/cpu intensive test. */
public const string CategoryIntensive = "LONG_TEST";
/** */
public const int DfltBusywaitSleepInterval = 200;
/** */
private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess
? new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms1g",
"-Xmx4g",
"-ea"
}
: new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms512m",
"-Xmx512m",
"-ea",
"-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000"
};
/** */
private static readonly IList<string> JvmDebugOpts =
new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005" };
/** */
public static bool JvmDebug = true;
/** */
[ThreadStatic]
private static Random _random;
/** */
private static int _seed = Environment.TickCount;
/// <summary>
/// Kill Ignite processes.
/// </summary>
public static void KillProcesses()
{
IgniteProcess.KillAll();
}
/// <summary>
///
/// </summary>
public static Random Random
{
get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IList<string> TestJavaOptions(bool? jvmDebug = null)
{
IList<string> ops = new List<string>(TestJvmOpts);
if (jvmDebug ?? JvmDebug)
{
foreach (string opt in JvmDebugOpts)
ops.Add(opt);
}
return ops;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static string CreateTestClasspath()
{
return Classpath.CreateClasspath(forceTestClasspath: true);
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
public static void RunMultiThreaded(Action action, int threadNum)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
action();
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
/// <param name="duration">Duration of test execution in seconds</param>
public static void RunMultiThreaded(Action action, int threadNum, int duration)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
bool stop = false;
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
while (true)
{
Thread.MemoryBarrier();
// ReSharper disable once AccessToModifiedClosure
if (stop)
break;
action();
}
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
Thread.Sleep(duration * 1000);
stop = true;
Thread.MemoryBarrier();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
/// Wait for particular topology size.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="size">Size.</param>
/// <param name="timeout">Timeout.</param>
/// <returns>
/// <c>True</c> if topology took required size.
/// </returns>
public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000)
{
int left = timeout;
while (true)
{
if (grid.GetCluster().GetNodes().Count != size)
{
if (left > 0)
{
Thread.Sleep(100);
left -= 100;
}
else
break;
}
else
return true;
}
return false;
}
/// <summary>
/// Asserts that the handle registry is empty.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, 0, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, expectedCount, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="grid">The grid to check.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout)
{
var handleRegistry = ((Ignite)grid).HandleRegistry;
expectedCount++; // Skip default lifecycle bean
if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout))
return;
var items = handleRegistry.GetItems().Where(x => !(x.Value is LifecycleBeanHolder)).ToList();
if (items.Any())
Assert.Fail("HandleRegistry is not empty in grid '{0}':\n '{1}'", grid.Name,
items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y));
}
/// <summary>
/// Waits for condition, polling in busy wait loop.
/// </summary>
/// <param name="cond">Condition.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <returns>True if condition predicate returned true within interval; false otherwise.</returns>
public static bool WaitForCondition(Func<bool> cond, int timeout)
{
if (timeout <= 0)
return cond();
var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval);
while (DateTime.Now < maxTime)
{
if (cond())
return true;
Thread.Sleep(DfltBusywaitSleepInterval);
}
return false;
}
/// <summary>
/// Gets the static discovery.
/// </summary>
public static IDiscoverySpi GetStaticDiscovery()
{
return new TcpDiscoverySpi
{
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] { "127.0.0.1:47500" }
},
SocketTimeout = TimeSpan.FromSeconds(0.3)
};
}
/// <summary>
/// Gets the default code-based test configuration.
/// </summary>
public static IgniteConfiguration GetTestConfiguration(bool? jvmDebug = null)
{
return new IgniteConfiguration
{
DiscoverySpi = GetStaticDiscovery(),
Localhost = "127.0.0.1",
JvmOptions = TestJavaOptions(jvmDebug),
JvmClasspath = CreateTestClasspath()
};
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Provider;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// A base class for the commands that write content (set-content, add-content)
/// </summary>
public class WriteContentCommandBase : PassThroughContentCommandBase
{
#region Parameters
/// <summary>
/// The value of the content to set.
/// </summary>
/// <value>
/// This value type is determined by the InvokeProvider.
/// </value>
[Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[AllowNull]
[AllowEmptyCollection]
public object[] Value
{
get
{
return _content;
}
set
{
_content = value;
}
}
#endregion Parameters
#region parameter data
/// <summary>
/// The value of the content to be set.
/// </summary>
private object[] _content;
#endregion parameter data
#region private Data
/// <summary>
/// This bool is used to determine if the path
/// parameter was specified on the command line or via the pipeline.
/// </summary>
private bool _pipingPaths;
/// <summary>
/// True if the content writers have been open.
/// This is used in conjunction with pipingPaths
/// to determine if the content writers need to
/// be closed each time ProgressRecord is called.
/// </summary>
private bool _contentWritersOpen;
#endregion private Data
#region Command code
/// <summary>
/// Determines if the paths are specified on the command line
/// or being piped in.
/// </summary>
protected override void BeginProcessing()
{
if (Path != null && Path.Length > 0)
{
_pipingPaths = false;
}
else
{
_pipingPaths = true;
}
}
/// <summary>
/// Appends the content to the specified item.
/// </summary>
protected override void ProcessRecord()
{
CmdletProviderContext currentContext = GetCurrentContext();
// Initialize the content
if (_content == null)
{
_content = Array.Empty<object>();
}
if (_pipingPaths)
{
// Make sure to clean up the content writers that are already there
if (contentStreams != null && contentStreams.Count > 0)
{
CloseContent(contentStreams, false);
_contentWritersOpen = false;
contentStreams = new List<ContentHolder>();
}
}
if (!_contentWritersOpen)
{
// Since the paths are being pipelined in, we have
// to get new content writers for the new paths
string[] paths = GetAcceptedPaths(Path, currentContext);
if (paths.Length > 0)
{
BeforeOpenStreams(paths);
contentStreams = GetContentWriters(paths, currentContext);
SeekContentPosition(contentStreams);
}
_contentWritersOpen = true;
}
// Now write the content to the item
try
{
foreach (ContentHolder holder in contentStreams)
{
if (holder.Writer != null)
{
IList result = null;
try
{
result = holder.Writer.Write(_content);
}
catch (Exception e) // Catch-all OK. 3rd party callout
{
ProviderInvocationException providerException =
new(
"ProviderContentWriteError",
SessionStateStrings.ProviderContentWriteError,
holder.PathInfo.Provider,
holder.PathInfo.Path,
e);
// Log a provider health event
MshLog.LogProviderHealthEvent(
this.Context,
holder.PathInfo.Provider.Name,
providerException,
Severity.Warning);
WriteError(
new ErrorRecord(
providerException.ErrorRecord,
providerException));
continue;
}
if (result != null && result.Count > 0 && PassThru)
{
WriteContentObject(result, result.Count, holder.PathInfo, currentContext);
}
}
}
}
finally
{
// Need to close all the writers if the paths are being pipelined
if (_pipingPaths)
{
CloseContent(contentStreams, false);
_contentWritersOpen = false;
contentStreams = new List<ContentHolder>();
}
}
}
/// <summary>
/// Closes all the content writers.
/// </summary>
protected override void EndProcessing()
{
Dispose(true);
}
#endregion Command code
#region protected members
/// <summary>
/// This method is called by the base class after getting the content writer
/// from the provider. If the current position needs to be changed before writing
/// the content, this method should be overridden to do that.
/// </summary>
/// <param name="contentHolders">
/// The content holders that contain the writers to be moved.
/// </param>
internal virtual void SeekContentPosition(List<ContentHolder> contentHolders)
{
// default does nothing.
}
/// <summary>
/// Called by the base class before the streams are open for the path.
/// </summary>
/// <param name="paths">
/// The path to the items that will be opened for writing content.
/// </param>
internal virtual void BeforeOpenStreams(string[] paths)
{
}
/// <summary>
/// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets
/// that require dynamic parameters should override this method and return the
/// dynamic parameter object.
/// </summary>
/// <param name="context">
/// The context under which the command is running.
/// </param>
/// <returns>
/// An object representing the dynamic parameters for the cmdlet or null if there
/// are none.
/// </returns>
internal override object GetDynamicParameters(CmdletProviderContext context)
{
if (Path != null && Path.Length > 0)
{
return InvokeProvider.Content.GetContentWriterDynamicParameters(Path[0], context);
}
return InvokeProvider.Content.GetContentWriterDynamicParameters(".", context);
}
/// <summary>
/// Gets the IContentWriters for the current path(s)
/// </summary>
/// <returns>
/// An array of IContentWriters for the current path(s)
/// </returns>
internal List<ContentHolder> GetContentWriters(
string[] writerPaths,
CmdletProviderContext currentCommandContext)
{
// Resolve all the paths into PathInfo objects
Collection<PathInfo> pathInfos = ResolvePaths(writerPaths, true, false, currentCommandContext);
// Create the results array
List<ContentHolder> results = new();
foreach (PathInfo pathInfo in pathInfos)
{
// For each path, get the content writer
Collection<IContentWriter> writers = null;
try
{
writers =
InvokeProvider.Content.GetWriter(
pathInfo.Path,
currentCommandContext);
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
continue;
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
continue;
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
continue;
}
catch (ItemNotFoundException pathNotFound)
{
WriteError(
new ErrorRecord(
pathNotFound.ErrorRecord,
pathNotFound));
continue;
}
if (writers != null && writers.Count > 0)
{
if (writers.Count == 1 && writers[0] != null)
{
ContentHolder holder =
new(pathInfo, null, writers[0]);
results.Add(holder);
}
}
}
return results;
}
/// <summary>
/// Gets the list of paths accepted by the user.
/// </summary>
/// <param name="unfilteredPaths">The list of unfiltered paths.</param>
/// <param name="currentContext">The current context.</param>
/// <returns>The list of paths accepted by the user.</returns>
private string[] GetAcceptedPaths(string[] unfilteredPaths, CmdletProviderContext currentContext)
{
Collection<PathInfo> pathInfos = ResolvePaths(unfilteredPaths, true, false, currentContext);
var paths = new List<string>();
foreach (PathInfo pathInfo in pathInfos)
{
if (CallShouldProcess(pathInfo.Path))
{
paths.Add(pathInfo.Path);
}
}
return paths.ToArray();
}
#endregion protected members
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.IO;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.ServiceAuth;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using log4net;
using OpenMetaverse;
using System.Threading;
namespace OpenSim.Server.Handlers.Inventory
{
public class XInventoryInConnector : ServiceConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IInventoryService m_InventoryService;
private string m_ConfigName = "InventoryService";
public XInventoryInConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server, configName)
{
if (configName != String.Empty)
m_ConfigName = configName;
m_log.DebugFormat("[XInventoryInConnector]: Starting with config name {0}", m_ConfigName);
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null)
throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string inventoryService = serverConfig.GetString("LocalServiceModule",
String.Empty);
if (inventoryService == String.Empty)
throw new Exception("No InventoryService in config file");
Object[] args = new Object[] { config, m_ConfigName };
m_InventoryService =
ServerUtils.LoadPlugin<IInventoryService>(inventoryService, args);
IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName);
server.AddStreamHandler(new XInventoryConnectorPostHandler(m_InventoryService, auth));
}
}
public class XInventoryConnectorPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IInventoryService m_InventoryService;
public XInventoryConnectorPostHandler(IInventoryService service, IServiceAuth auth) :
base("POST", "/xinventory", auth)
{
m_InventoryService = service;
}
protected override byte[] ProcessRequest(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"].ToString();
request.Remove("METHOD");
switch (method)
{
case "CREATEUSERINVENTORY":
return HandleCreateUserInventory(request);
case "GETINVENTORYSKELETON":
return HandleGetInventorySkeleton(request);
case "GETROOTFOLDER":
return HandleGetRootFolder(request);
case "GETFOLDERFORTYPE":
return HandleGetFolderForType(request);
case "GETFOLDERCONTENT":
return HandleGetFolderContent(request);
case "GETMULTIPLEFOLDERSCONTENT":
return HandleGetMultipleFoldersContent(request);
case "GETFOLDERITEMS":
return HandleGetFolderItems(request);
case "ADDFOLDER":
return HandleAddFolder(request);
case "UPDATEFOLDER":
return HandleUpdateFolder(request);
case "MOVEFOLDER":
return HandleMoveFolder(request);
case "DELETEFOLDERS":
return HandleDeleteFolders(request);
case "PURGEFOLDER":
return HandlePurgeFolder(request);
case "ADDITEM":
return HandleAddItem(request);
case "UPDATEITEM":
return HandleUpdateItem(request);
case "MOVEITEMS":
return HandleMoveItems(request);
case "DELETEITEMS":
return HandleDeleteItems(request);
case "GETITEM":
return HandleGetItem(request);
case "GETMULTIPLEITEMS":
return HandleGetMultipleItems(request);
case "GETFOLDER":
return HandleGetFolder(request);
case "GETACTIVEGESTURES":
return HandleGetActiveGestures(request);
case "GETASSETPERMISSIONS":
return HandleGetAssetPermissions(request);
}
m_log.DebugFormat("[XINVENTORY HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.Error(string.Format("[XINVENTORY HANDLER]: Exception {0} ", e.Message), e);
}
return FailureResult();
}
private byte[] FailureResult()
{
return BoolResult(false);
}
private byte[] SuccessResult()
{
return BoolResult(true);
}
private byte[] BoolResult(bool value)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "RESULT", "");
result.AppendChild(doc.CreateTextNode(value.ToString()));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
byte[] HandleCreateUserInventory(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
if (!request.ContainsKey("PRINCIPAL"))
return FailureResult();
if (m_InventoryService.CreateUserInventory(new UUID(request["PRINCIPAL"].ToString())))
result["RESULT"] = "True";
else
result["RESULT"] = "False";
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetInventorySkeleton(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
if (!request.ContainsKey("PRINCIPAL"))
return FailureResult();
List<InventoryFolderBase> folders = m_InventoryService.GetInventorySkeleton(new UUID(request["PRINCIPAL"].ToString()));
Dictionary<string, object> sfolders = new Dictionary<string, object>();
if (folders != null)
{
int i = 0;
foreach (InventoryFolderBase f in folders)
{
sfolders["folder_" + i.ToString()] = EncodeFolder(f);
i++;
}
}
result["FOLDERS"] = sfolders;
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetRootFolder(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
InventoryFolderBase rfolder = m_InventoryService.GetRootFolder(principal);
if (rfolder != null)
result["folder"] = EncodeFolder(rfolder);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetFolderForType(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
int type = 0;
Int32.TryParse(request["TYPE"].ToString(), out type);
InventoryFolderBase folder = m_InventoryService.GetFolderForType(principal, (FolderType)type);
if (folder != null)
result["folder"] = EncodeFolder(folder);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetFolderContent(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
UUID folderID = UUID.Zero;
UUID.TryParse(request["FOLDER"].ToString(), out folderID);
InventoryCollection icoll = m_InventoryService.GetFolderContent(principal, folderID);
if (icoll != null)
{
result["FID"] = icoll.FolderID.ToString();
result["VERSION"] = icoll.Version.ToString();
Dictionary<string, object> folders = new Dictionary<string, object>();
int i = 0;
if (icoll.Folders != null)
{
foreach (InventoryFolderBase f in icoll.Folders)
{
folders["folder_" + i.ToString()] = EncodeFolder(f);
i++;
}
result["FOLDERS"] = folders;
}
if (icoll.Items != null)
{
i = 0;
Dictionary<string, object> items = new Dictionary<string, object>();
foreach (InventoryItemBase it in icoll.Items)
{
items["item_" + i.ToString()] = EncodeItem(it);
i++;
}
result["ITEMS"] = items;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetMultipleFoldersContent(Dictionary<string, object> request)
{
Dictionary<string, object> resultSet = new Dictionary<string, object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
string folderIDstr = request["FOLDERS"].ToString();
int count = 0;
Int32.TryParse(request["COUNT"].ToString(), out count);
UUID[] fids = new UUID[count];
string[] uuids = folderIDstr.Split(',');
int i = 0;
foreach (string id in uuids)
{
UUID fid = UUID.Zero;
if (UUID.TryParse(id, out fid))
fids[i] = fid;
i += 1;
}
count = 0;
InventoryCollection[] icollList = m_InventoryService.GetMultipleFoldersContent(principal, fids);
if (icollList != null && icollList.Length > 0)
{
foreach (InventoryCollection icoll in icollList)
{
Dictionary<string, object> result = new Dictionary<string, object>();
result["FID"] = icoll.FolderID.ToString();
result["VERSION"] = icoll.Version.ToString();
result["OWNER"] = icoll.OwnerID.ToString();
Dictionary<string, object> folders = new Dictionary<string, object>();
i = 0;
if (icoll.Folders != null)
{
foreach (InventoryFolderBase f in icoll.Folders)
{
folders["folder_" + i.ToString()] = EncodeFolder(f);
i++;
}
result["FOLDERS"] = folders;
}
i = 0;
if (icoll.Items != null)
{
Dictionary<string, object> items = new Dictionary<string, object>();
foreach (InventoryItemBase it in icoll.Items)
{
items["item_" + i.ToString()] = EncodeItem(it);
i++;
}
result["ITEMS"] = items;
}
resultSet["F_" + fids[count++]] = result;
//m_log.DebugFormat("[XXX]: Sending {0} {1}", fids[count-1], icoll.FolderID);
}
}
string xmlString = ServerUtils.BuildXmlResponse(resultSet);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetFolderItems(Dictionary<string, object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
UUID folderID = UUID.Zero;
UUID.TryParse(request["FOLDER"].ToString(), out folderID);
List<InventoryItemBase> items = m_InventoryService.GetFolderItems(principal, folderID);
Dictionary<string, object> sitems = new Dictionary<string, object>();
if (items != null)
{
int i = 0;
foreach (InventoryItemBase item in items)
{
sitems["item_" + i.ToString()] = EncodeItem(item);
i++;
}
}
result["ITEMS"] = sitems;
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleAddFolder(Dictionary<string,object> request)
{
InventoryFolderBase folder = BuildFolder(request);
if (m_InventoryService.AddFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleUpdateFolder(Dictionary<string,object> request)
{
InventoryFolderBase folder = BuildFolder(request);
if (m_InventoryService.UpdateFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleMoveFolder(Dictionary<string,object> request)
{
UUID parentID = UUID.Zero;
UUID.TryParse(request["ParentID"].ToString(), out parentID);
UUID folderID = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out folderID);
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
InventoryFolderBase folder = new InventoryFolderBase(folderID, "", principal, parentID);
if (m_InventoryService.MoveFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleDeleteFolders(Dictionary<string,object> request)
{
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<string> slist = (List<string>)request["FOLDERS"];
List<UUID> uuids = new List<UUID>();
foreach (string s in slist)
{
UUID u = UUID.Zero;
if (UUID.TryParse(s, out u))
uuids.Add(u);
}
if (m_InventoryService.DeleteFolders(principal, uuids))
return SuccessResult();
else
return
FailureResult();
}
byte[] HandlePurgeFolder(Dictionary<string,object> request)
{
UUID folderID = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out folderID);
InventoryFolderBase folder = new InventoryFolderBase(folderID);
if (m_InventoryService.PurgeFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleAddItem(Dictionary<string,object> request)
{
InventoryItemBase item = BuildItem(request);
if (m_InventoryService.AddItem(item))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleUpdateItem(Dictionary<string,object> request)
{
InventoryItemBase item = BuildItem(request);
if (m_InventoryService.UpdateItem(item))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleMoveItems(Dictionary<string,object> request)
{
List<string> idlist = (List<string>)request["IDLIST"];
List<string> destlist = (List<string>)request["DESTLIST"];
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<InventoryItemBase> items = new List<InventoryItemBase>();
int n = 0;
try
{
foreach (string s in idlist)
{
UUID u = UUID.Zero;
if (UUID.TryParse(s, out u))
{
UUID fid = UUID.Zero;
if (UUID.TryParse(destlist[n++], out fid))
{
InventoryItemBase item = new InventoryItemBase(u, principal);
item.Folder = fid;
items.Add(item);
}
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[XINVENTORY IN CONNECTOR]: Exception in HandleMoveItems: {0}", e.Message);
return FailureResult();
}
if (m_InventoryService.MoveItems(principal, items))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleDeleteItems(Dictionary<string,object> request)
{
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<string> slist = (List<string>)request["ITEMS"];
List<UUID> uuids = new List<UUID>();
foreach (string s in slist)
{
UUID u = UUID.Zero;
if (UUID.TryParse(s, out u))
uuids.Add(u);
}
if (m_InventoryService.DeleteItems(principal, uuids))
return SuccessResult();
else
return
FailureResult();
}
byte[] HandleGetItem(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID id = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out id);
InventoryItemBase item = new InventoryItemBase(id);
item = m_InventoryService.GetItem(item);
if (item != null)
result["item"] = EncodeItem(item);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetMultipleItems(Dictionary<string, object> request)
{
Dictionary<string, object> resultSet = new Dictionary<string, object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
string itemIDstr = request["ITEMS"].ToString();
int count = 0;
Int32.TryParse(request["COUNT"].ToString(), out count);
UUID[] fids = new UUID[count];
string[] uuids = itemIDstr.Split(',');
int i = 0;
foreach (string id in uuids)
{
UUID fid = UUID.Zero;
if (UUID.TryParse(id, out fid))
fids[i] = fid;
i += 1;
}
InventoryItemBase[] itemsList = m_InventoryService.GetMultipleItems(principal, fids);
if (itemsList != null && itemsList.Length > 0)
{
count = 0;
foreach (InventoryItemBase item in itemsList)
resultSet["item_" + count++] = (item == null) ? (object)"NULL" : EncodeItem(item);
}
string xmlString = ServerUtils.BuildXmlResponse(resultSet);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetFolder(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
UUID id = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out id);
InventoryFolderBase folder = new InventoryFolderBase(id);
folder = m_InventoryService.GetFolder(folder);
if (folder != null)
result["folder"] = EncodeFolder(folder);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetActiveGestures(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(principal);
Dictionary<string, object> items = new Dictionary<string, object>();
if (gestures != null)
{
int i = 0;
foreach (InventoryItemBase item in gestures)
{
items["item_" + i.ToString()] = EncodeItem(item);
i++;
}
}
result["ITEMS"] = items;
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetAssetPermissions(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
UUID assetID = UUID.Zero;
UUID.TryParse(request["ASSET"].ToString(), out assetID);
int perms = m_InventoryService.GetAssetPermissions(principal, assetID);
result["RESULT"] = perms.ToString();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
private Dictionary<string, object> EncodeFolder(InventoryFolderBase f)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
ret["ParentID"] = f.ParentID.ToString();
ret["Type"] = f.Type.ToString();
ret["Version"] = f.Version.ToString();
ret["Name"] = f.Name;
ret["Owner"] = f.Owner.ToString();
ret["ID"] = f.ID.ToString();
return ret;
}
private Dictionary<string, object> EncodeItem(InventoryItemBase item)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
ret["AssetID"] = item.AssetID.ToString();
ret["AssetType"] = item.AssetType.ToString();
ret["BasePermissions"] = item.BasePermissions.ToString();
ret["CreationDate"] = item.CreationDate.ToString();
if (item.CreatorId != null)
ret["CreatorId"] = item.CreatorId.ToString();
else
ret["CreatorId"] = String.Empty;
if (item.CreatorData != null)
ret["CreatorData"] = item.CreatorData;
else
ret["CreatorData"] = String.Empty;
ret["CurrentPermissions"] = item.CurrentPermissions.ToString();
ret["Description"] = item.Description.ToString();
ret["EveryOnePermissions"] = item.EveryOnePermissions.ToString();
ret["Flags"] = item.Flags.ToString();
ret["Folder"] = item.Folder.ToString();
ret["GroupID"] = item.GroupID.ToString();
ret["GroupOwned"] = item.GroupOwned.ToString();
ret["GroupPermissions"] = item.GroupPermissions.ToString();
ret["ID"] = item.ID.ToString();
ret["InvType"] = item.InvType.ToString();
ret["Name"] = item.Name.ToString();
ret["NextPermissions"] = item.NextPermissions.ToString();
ret["Owner"] = item.Owner.ToString();
ret["SalePrice"] = item.SalePrice.ToString();
ret["SaleType"] = item.SaleType.ToString();
return ret;
}
private InventoryFolderBase BuildFolder(Dictionary<string,object> data)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ParentID = new UUID(data["ParentID"].ToString());
folder.Type = short.Parse(data["Type"].ToString());
folder.Version = ushort.Parse(data["Version"].ToString());
folder.Name = data["Name"].ToString();
folder.Owner = new UUID(data["Owner"].ToString());
folder.ID = new UUID(data["ID"].ToString());
return folder;
}
private InventoryItemBase BuildItem(Dictionary<string,object> data)
{
InventoryItemBase item = new InventoryItemBase();
item.AssetID = new UUID(data["AssetID"].ToString());
item.AssetType = int.Parse(data["AssetType"].ToString());
item.Name = data["Name"].ToString();
item.Owner = new UUID(data["Owner"].ToString());
item.ID = new UUID(data["ID"].ToString());
item.InvType = int.Parse(data["InvType"].ToString());
item.Folder = new UUID(data["Folder"].ToString());
item.CreatorId = data["CreatorId"].ToString();
item.CreatorData = data["CreatorData"].ToString();
item.Description = data["Description"].ToString();
item.NextPermissions = uint.Parse(data["NextPermissions"].ToString());
item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString());
item.BasePermissions = uint.Parse(data["BasePermissions"].ToString());
item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString());
item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString());
item.GroupID = new UUID(data["GroupID"].ToString());
item.GroupOwned = bool.Parse(data["GroupOwned"].ToString());
item.SalePrice = int.Parse(data["SalePrice"].ToString());
item.SaleType = byte.Parse(data["SaleType"].ToString());
item.Flags = uint.Parse(data["Flags"].ToString());
item.CreationDate = int.Parse(data["CreationDate"].ToString());
return item;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ServiceStack.Logging;
using ServiceStack.Messaging;
using ServiceStack.Service;
using ServiceStack.Text;
namespace ServiceStack.Redis.Messaging
{
/// <summary>
/// Creates an MQ Host that processes all messages on a single background thread.
/// i.e. If you register 3 handlers it will only create 1 background thread.
///
/// The same background thread that listens to the Redis MQ Subscription for new messages
/// also cycles through each registered handler processing all pending messages one-at-a-time:
/// first in the message PriorityQ, then in the normal message InQ.
///
/// The Start/Stop methods are idempotent i.e. It's safe to call them repeatedly on multiple threads
/// and the Redis MQ Host will only have Started/Stopped once.
/// </summary>
[Obsolete("RedisMqServer is maintained and preferred over RedisMqHost")]
public class RedisMqHost : IMessageService
{
private static readonly ILog Log = LogManager.GetLogger(typeof(RedisMqHost));
public const int DefaultRetryCount = 2; //Will be a total of 3 attempts
public IMessageFactory MessageFactory { get; private set; }
readonly Random rand = new Random(Environment.TickCount);
private void SleepBackOffMultiplier(int continuousErrorsCount)
{
if (continuousErrorsCount == 0) return;
const int MaxSleepMs = 60 * 1000;
//exponential/random retry back-off.
var nextTry = Math.Min(
rand.Next((int)Math.Pow(continuousErrorsCount, 3), (int)Math.Pow(continuousErrorsCount + 1, 3) + 1),
MaxSleepMs);
Log.Debug("Sleeping for {0}ms after {1} continuous errors".Fmt(nextTry, continuousErrorsCount));
Thread.Sleep(nextTry);
}
//Stats
private long timesStarted = 0;
private long noOfErrors = 0;
private int noOfContinuousErrors = 0;
private string lastExMsg = null;
private int status;
private long bgThreadCount = 0;
public long BgThreadCount
{
get { return Interlocked.CompareExchange(ref bgThreadCount, 0, 0); }
}
public int RetryCount { get; protected set; }
public TimeSpan? RequestTimeOut { get; protected set; }
/// <summary>
/// Inject your own Reply Client Factory to handle custom Message.ReplyTo urls.
/// </summary>
public Func<string, IOneWayClient> ReplyClientFactory { get; set; }
public Func<IMessage, IMessage> RequestFilter { get; set; }
public Func<object, object> ResponseFilter { get; set; }
public Action<Exception> ErrorHandler { get; set; }
private readonly IRedisClientsManager clientsManager; //Thread safe redis client/conn factory
public IMessageQueueClient CreateMessageQueueClient()
{
return new RedisMessageQueueClient(this.clientsManager);
}
public RedisMqHost(IRedisClientsManager clientsManager,
int retryCount = DefaultRetryCount, TimeSpan? requestTimeOut = null)
{
this.clientsManager = clientsManager;
this.RetryCount = retryCount;
this.RequestTimeOut = requestTimeOut;
this.MessageFactory = new RedisMessageFactory(clientsManager);
this.ErrorHandler = ex => Log.Error("Exception in Background Thread: " + ex.Message, ex);
}
private readonly Dictionary<Type, IMessageHandlerFactory> handlerMap
= new Dictionary<Type, IMessageHandlerFactory>();
public List<Type> RegisteredTypes
{
get { return handlerMap.Keys.ToList(); }
}
private IMessageHandler[] messageHandlers;
private string[] inQueueNames;
public string Title
{
get { return string.Join(", ", inQueueNames); }
}
public void RegisterHandler<T>(Func<IMessage<T>, object> processMessageFn)
{
RegisterHandler(processMessageFn, null);
}
public void RegisterHandler<T>(Func<IMessage<T>, object> processMessageFn, Action<IMessage<T>, Exception> processExceptionEx)
{
if (handlerMap.ContainsKey(typeof(T)))
{
throw new ArgumentException("Message handler has already been registered for type: " + typeof(T).Name);
}
handlerMap[typeof(T)] = CreateMessageHandlerFactory(processMessageFn, processExceptionEx);
}
protected IMessageHandlerFactory CreateMessageHandlerFactory<T>(Func<IMessage<T>, object> processMessageFn, Action<IMessage<T>, Exception> processExceptionEx)
{
return new MessageHandlerFactory<T>(this, processMessageFn, processExceptionEx) {
RequestFilter = this.RequestFilter,
ResponseFilter = this.ResponseFilter,
RetryCount = RetryCount,
};
}
private void RunLoop()
{
if (Interlocked.CompareExchange(ref status, WorkerStatus.Started, WorkerStatus.Starting) != WorkerStatus.Starting) return;
Interlocked.Increment(ref timesStarted);
try
{
while (true)
{
//Pass in a new MQ Client that may be used by message handlers
using (var mqClient = CreateMessageQueueClient())
{
foreach (var handler in messageHandlers)
{
if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Stopping) == WorkerStatus.Stopping)
{
Log.Debug("MQ Host is stopping, exiting RunLoop()...");
return;
}
if (Interlocked.CompareExchange(ref status, 0, 0) != WorkerStatus.Started)
{
Log.Error("MQ Host is in an invalid state '{0}', exiting RunLoop()...".Fmt(GetStatus()));
return;
}
handler.Process(mqClient);
}
//Record that we had a good run...
Interlocked.CompareExchange(ref noOfContinuousErrors, 0, noOfContinuousErrors);
var cmd = mqClient.WaitForNotifyOnAny(QueueNames.TopicIn);
if (cmd == WorkerStatus.StopCommand)
{
Log.Debug("Stop Command Issued");
if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Started) != WorkerStatus.Started)
Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Stopping);
return;
}
}
}
}
catch (Exception ex)
{
lastExMsg = ex.Message;
Interlocked.Increment(ref noOfErrors);
Interlocked.Increment(ref noOfContinuousErrors);
if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Started) != WorkerStatus.Started)
Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Stopping);
if (this.ErrorHandler != null) this.ErrorHandler(ex);
}
}
private Thread bgThread;
public virtual void Start()
{
if (Interlocked.CompareExchange(ref status, 0, 0) == WorkerStatus.Started) return;
if (Interlocked.CompareExchange(ref status, 0, 0) == WorkerStatus.Disposed)
throw new ObjectDisposedException("MQ Host has been disposed");
if (Interlocked.CompareExchange(ref status, WorkerStatus.Starting, WorkerStatus.Stopped) == WorkerStatus.Stopped) //Should only be 1 thread past this point
{
try
{
Init();
if (this.messageHandlers == null || this.messageHandlers.Length == 0)
{
Log.Warn("Cannot start a MQ Host with no Message Handlers registered, ignoring.");
Interlocked.CompareExchange(ref status, WorkerStatus.Stopped, WorkerStatus.Starting);
return;
}
SleepBackOffMultiplier(Interlocked.CompareExchange(ref noOfContinuousErrors, 0, 0));
KillBgThreadIfExists();
bgThread = new Thread(RunLoop) {
IsBackground = true,
Name = "Redis MQ Host " + Interlocked.Increment(ref bgThreadCount)
};
bgThread.Start();
Log.Debug("Started Background Thread: " + bgThread.Name);
}
catch (Exception ex)
{
if (this.ErrorHandler != null) this.ErrorHandler(ex);
}
}
}
private void KillBgThreadIfExists()
{
if (bgThread != null && bgThread.IsAlive)
{
//give it a small chance to die gracefully
if (!bgThread.Join(500))
{
//Ideally we shouldn't get here, but lets try our hardest to clean it up
Log.Warn("Interrupting previous Background Thread: " + bgThread.Name);
bgThread.Interrupt();
if (!bgThread.Join(TimeSpan.FromSeconds(3)))
{
Log.Warn(bgThread.Name + " just wont die, so we're now aborting it...");
bgThread.Abort();
}
}
bgThread = null;
}
}
private void Init()
{
if (this.messageHandlers == null)
{
this.messageHandlers = this.handlerMap.Values.ToList()
.ConvertAll(x => x.CreateMessageHandler()).ToArray();
}
if (inQueueNames == null)
{
inQueueNames = this.handlerMap.Keys.ToList()
.ConvertAll(x => new QueueNames(x).In).ToArray();
}
}
public string GetStatus()
{
switch (Interlocked.CompareExchange(ref status, 0, 0))
{
case WorkerStatus.Disposed:
return "Disposed";
case WorkerStatus.Stopped:
return "Stopped";
case WorkerStatus.Stopping:
return "Stopping";
case WorkerStatus.Starting:
return "Starting";
case WorkerStatus.Started:
return "Started";
}
return null;
}
public IMessageHandlerStats GetStats()
{
lock (messageHandlers)
{
var total = new MessageHandlerStats("All Handlers");
messageHandlers.ToList().ForEach(x => total.Add(x.GetStats()));
return total;
}
}
public string GetStatsDescription()
{
lock (messageHandlers)
{
var sb = new StringBuilder("#MQ HOST STATS:\n");
sb.AppendLine("===============");
sb.AppendLine("For: " + this.Title);
sb.AppendLine("Current Status: " + GetStatus());
sb.AppendLine("Listening On: " + string.Join(", ", inQueueNames));
sb.AppendLine("Times Started: " + Interlocked.CompareExchange(ref timesStarted, 0, 0));
sb.AppendLine("Num of Errors: " + Interlocked.CompareExchange(ref noOfErrors, 0, 0));
sb.AppendLine("Num of Continuous Errors: " + Interlocked.CompareExchange(ref noOfContinuousErrors, 0, 0));
sb.AppendLine("Last ErrorMsg: " + lastExMsg);
sb.AppendLine("===============");
foreach (var messageHandler in messageHandlers)
{
sb.AppendLine(messageHandler.GetStats().ToString());
sb.AppendLine("---------------\n");
}
return sb.ToString();
}
}
public virtual void Stop()
{
if (Interlocked.CompareExchange(ref status, 0, 0) == WorkerStatus.Disposed)
throw new ObjectDisposedException("MQ Host has been disposed");
if (Interlocked.CompareExchange(ref status, WorkerStatus.Stopping, WorkerStatus.Started) == WorkerStatus.Started)
{
Log.Debug("Stopping MQ Host...");
//Unblock current bgthread by issuing StopCommand
try
{
using (var redis = clientsManager.GetClient())
{
redis.PublishMessage(QueueNames.TopicIn, WorkerStatus.StopCommand);
}
}
catch (Exception ex)
{
if (this.ErrorHandler != null) this.ErrorHandler(ex);
Log.Warn("Could not send STOP message to bg thread: " + ex.Message);
}
}
}
public virtual void Dispose()
{
if (Interlocked.CompareExchange(ref status, 0, 0) == WorkerStatus.Disposed)
return;
Stop();
if (Interlocked.CompareExchange(ref status, WorkerStatus.Disposed, WorkerStatus.Stopped) != WorkerStatus.Stopped)
Interlocked.CompareExchange(ref status, WorkerStatus.Disposed, WorkerStatus.Stopping);
try
{
KillBgThreadIfExists();
}
catch (Exception ex)
{
if (this.ErrorHandler != null) this.ErrorHandler(ex);
}
}
}
}
| |
using PublicApiGeneratorTests.Examples;
using System.Threading;
using Xunit;
namespace PublicApiGeneratorTests
{
public class Method_parameters : ApiGeneratorTestsBase
{
[Fact]
public void Should_handle_no_parameters()
{
AssertPublicApi<MethodWithNoParameters>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithNoParameters
{
public MethodWithNoParameters() { }
public void Method() { }
}
}");
}
[Fact]
public void Should_output_parameter_name()
{
AssertPublicApi<MethodWithSingleParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithSingleParameter
{
public MethodWithSingleParameter() { }
public void Method(int value) { }
}
}");
}
[Fact]
public void Should_output_primitive_parameter()
{
AssertPublicApi<MethodWithSingleParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithSingleParameter
{
public MethodWithSingleParameter() { }
public void Method(int value) { }
}
}");
}
[Fact]
public void Should_use_fully_qualified_type_name_for_parameter()
{
AssertPublicApi<MethodWithComplexTypeParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithComplexTypeParameter
{
public MethodWithComplexTypeParameter() { }
public void Method(PublicApiGeneratorTests.Examples.ComplexType value) { }
}
}");
}
[Fact]
public void Should_output_generic_type()
{
AssertPublicApi<MethodWithGenericTypeParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithGenericTypeParameter
{
public MethodWithGenericTypeParameter() { }
public void Method(PublicApiGeneratorTests.Examples.GenericType<int> value) { }
}
}");
}
[Fact]
public void Should_output_generic_ref_type()
{
AssertPublicApi<MethodWithGenericRefTypeParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithGenericRefTypeParameter
{
public MethodWithGenericRefTypeParameter() { }
public void Method(ref PublicApiGeneratorTests.Examples.GenericType<int> value) { }
}
}");
}
[Fact]
public void Should_output_generic_in_type()
{
AssertPublicApi<MethodWithGenericInTypeParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithGenericInTypeParameter
{
public MethodWithGenericInTypeParameter() { }
public void Method(in PublicApiGeneratorTests.Examples.GenericType<int> value) { }
}
}");
}
[Fact]
public void Should_output_fully_qualified_type_name_for_generic_parameter()
{
AssertPublicApi<MethodWithGenericTypeOfComplexTypeParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithGenericTypeOfComplexTypeParameter
{
public MethodWithGenericTypeOfComplexTypeParameter() { }
public void Method(PublicApiGeneratorTests.Examples.GenericType<PublicApiGeneratorTests.Examples.ComplexType> value) { }
}
}");
}
[Fact]
public void Should_output_generic_type_of_generic_type()
{
AssertPublicApi<MethodWithGenericTypeOfGenericTypeParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithGenericTypeOfGenericTypeParameter
{
public MethodWithGenericTypeOfGenericTypeParameter() { }
public void Method(PublicApiGeneratorTests.Examples.GenericType<PublicApiGeneratorTests.Examples.GenericType<int>> value) { }
}
}");
}
[Fact]
public void Should_output_generic_with_multiple_type_parameters()
{
AssertPublicApi<MethodWithGenericTypeWithMultipleTypeArgumentsParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithGenericTypeWithMultipleTypeArgumentsParameter
{
public MethodWithGenericTypeWithMultipleTypeArgumentsParameter() { }
public void Method(PublicApiGeneratorTests.Examples.GenericTypeExtra<int, string, PublicApiGeneratorTests.Examples.ComplexType> value) { }
}
}");
}
[Fact]
public void Should_handle_multiple_parameters()
{
AssertPublicApi<MethodWithMultipleParameters>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithMultipleParameters
{
public MethodWithMultipleParameters() { }
public void Method(int value1, string value2, PublicApiGeneratorTests.Examples.ComplexType value3) { }
}
}");
}
[Fact]
public void Should_output_default_values_in_class()
{
AssertPublicApi<MethodWithDefaultValues>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithDefaultValues
{
public MethodWithDefaultValues() { }
public void Method1(int value1 = 42, string value2 = ""hello world"", System.Threading.CancellationToken token = default, int value3 = 0, string value4 = null) { }
public TType Method2<TType>(string name, TType defaultValue = null)
where TType : class { }
public TType Method3<TType>(string name, TType defaultValue = default)
where TType : struct { }
public TType Method4<TType>(string name, TType defaultValue = default) { }
}
}");
}
[Fact]
public void Should_output_default_values_in_interface()
{
AssertPublicApi<InterfaceWithDefaultValues>(
@"namespace PublicApiGeneratorTests.Examples
{
public interface InterfaceWithDefaultValues
{
void Method1(int value1 = 42, string value2 = ""hello world"", System.Threading.CancellationToken token = default, int value3 = 0, string value4 = null);
TType Method2<TType>(string name, TType defaultValue = null)
where TType : class;
TType Method3<TType>(string name, TType defaultValue = default)
where TType : struct;
TType Method4<TType>(string name, TType defaultValue = default);
}
}");
}
[Fact]
public void Should_output_default_values_even_if_they_look_like_attributes()
{
AssertPublicApi<MethodWithDefaultThatLooksLikeAnAttribute>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithDefaultThatLooksLikeAnAttribute
{
public MethodWithDefaultThatLooksLikeAnAttribute() { }
public void Method(string value2 = ""MyAttribute[()]"") { }
}
}");
}
[Fact]
public void Should_output_ref_parameters()
{
AssertPublicApi<MethodWithRefParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithRefParameter
{
public MethodWithRefParameter() { }
public void Method(ref string value) { }
}
}");
}
[Fact]
public void Should_output_in_parameters()
{
AssertPublicApi<MethodWithInParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithInParameter
{
public MethodWithInParameter() { }
public void Method(in string value) { }
}
}");
}
[Fact]
public void Should_output_out_parameters()
{
AssertPublicApi<MethodWithOutParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithOutParameter
{
public MethodWithOutParameter() { }
public void Method(out string value) { }
}
}");
}
[Fact]
public void Should_output_out_parameter_with_generic_type()
{
AssertPublicApi<MethodWithOutGenericTypeParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithOutGenericTypeParameter
{
public MethodWithOutGenericTypeParameter() { }
public void Method(out PublicApiGeneratorTests.Examples.GenericType<int> value) { }
}
}");
}
[Fact]
public void Should_output_out_parameter_with_generic_enumerable()
{
AssertPublicApi<MethodWithOutGenericTypeParameterEnumerable>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithOutGenericTypeParameterEnumerable
{
public MethodWithOutGenericTypeParameterEnumerable() { }
public void Method(out System.Collections.Generic.IEnumerable<int> value) { }
}
}");
}
[Fact]
public void Should_output_out_parameter_fully_qualified_type_name_for_generic_parameter()
{
AssertPublicApi<MethodWithOutGenericTypeOfComplexTypeParameter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithOutGenericTypeOfComplexTypeParameter
{
public MethodWithOutGenericTypeOfComplexTypeParameter() { }
public void Method(out PublicApiGeneratorTests.Examples.GenericType<PublicApiGeneratorTests.Examples.ComplexType> value) { }
}
}");
}
//
[Fact]
public void Should_output_params_keyword()
{
AssertPublicApi<MethodWithParams>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MethodWithParams
{
public MethodWithParams() { }
public void Method(string format, params object[] values) { }
}
}");
}
}
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedParameter.Global
// ReSharper disable ClassNeverInstantiated.Global
namespace Examples
{
public class MethodWithNoParameters
{
public void Method()
{
}
}
public class MethodWithSingleParameter
{
public void Method(int value)
{
}
}
public class MethodWithComplexTypeParameter
{
public void Method(ComplexType value)
{
}
}
public class MethodWithGenericTypeParameter
{
public void Method(GenericType<int> value)
{
}
}
public class MethodWithGenericRefTypeParameter
{
public void Method(ref GenericType<int> value)
{
}
}
public class MethodWithGenericInTypeParameter
{
public void Method(in GenericType<int> value)
{
}
}
public class MethodWithGenericTypeOfComplexTypeParameter
{
public void Method(GenericType<ComplexType> value)
{
}
}
public class MethodWithGenericTypeOfGenericTypeParameter
{
public void Method(GenericType<GenericType<int>> value)
{
}
}
public class MethodWithGenericTypeWithMultipleTypeArgumentsParameter
{
public void Method(GenericTypeExtra<int, string, ComplexType> value)
{
}
}
public class MethodWithMultipleParameters
{
public void Method(int value1, string value2, ComplexType value3)
{
}
}
public class MethodWithDefaultValues
{
public void Method1(int value1 = 42, string value2 = "hello world", CancellationToken token = default, int value3 = default, string value4 = default!)
{
}
public TType Method2<TType>(string name, TType defaultValue = null) where TType : class => default;
public TType Method3<TType>(string name, TType defaultValue = default) where TType : struct => default;
public TType Method4<TType>(string name, TType defaultValue = default) => default;
}
public interface InterfaceWithDefaultValues
{
void Method1(int value1 = 42, string value2 = "hello world", CancellationToken token = default, int value3 = default, string value4 = default!);
TType Method2<TType>(string name, TType defaultValue = null) where TType : class;
TType Method3<TType>(string name, TType defaultValue = default) where TType : struct;
TType Method4<TType>(string name, TType defaultValue = default);
}
public class MethodWithDefaultThatLooksLikeAnAttribute
{
public void Method(string value2 = "MyAttribute[()]")
{
}
}
public class MethodWithRefParameter
{
public void Method(ref string value)
{
}
}
public class MethodWithInParameter
{
public void Method(in string value)
{
}
}
public class MethodWithOutParameter
{
public void Method(out string value)
{
value = null!;
}
}
public class MethodWithOutGenericTypeParameter
{
public void Method(out GenericType<int> value)
{
value = null!;
}
}
public class MethodWithOutGenericTypeParameterEnumerable
{
public void Method(out System.Collections.Generic.IEnumerable<int> value)
{
value = null!;
}
}
public class MethodWithOutGenericTypeOfComplexTypeParameter
{
public void Method(out GenericType<ComplexType> value)
{
value = null!;
}
}
public class MethodWithParams
{
public void Method(string format, params object[] values)
{
}
}
}
// ReSharper restore ClassNeverInstantiated.Global
// ReSharper restore UnusedParameter.Global
// ReSharper restore UnusedMember.Global
}
| |
/*==============================================================================================================
[ cNetworkDrive - Network Drive API Class ]
-------------------------------------------
Copyright (c)2006 aejw.com
http://www.aejw.com/
Build: 0017 - May 2006
Thanks To: 'jsantos98' from CodeProject.com for his update allowing the local / drive not to specifyed
EULA: Creative Commons - Attribution-ShareAlike 2.5
http://creativecommons.org/licenses/by-sa/2.5/
Disclaimer: THIS FILES / SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "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 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 FILES / SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. USE AT YOUR OWN RISK.
==============================================================================================================*/
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace aejw.Network
{
/// <summary>
/// Network Drive Interface
/// </summary>
public class NetworkDrive
{
#region API
[DllImport("mpr.dll")] private static extern int WNetAddConnection2A(ref structNetResource pstNetRes, string psPassword, string psUsername, int piFlags);
[DllImport("mpr.dll")] private static extern int WNetCancelConnection2A(string psName, int piFlags, int pfForce);
[DllImport("mpr.dll")] private static extern int WNetConnectionDialog(int phWnd, int piType);
[DllImport("mpr.dll")] private static extern int WNetDisconnectDialog(int phWnd, int piType);
[DllImport("mpr.dll")] private static extern int WNetRestoreConnectionW(int phWnd, string psLocalDrive);
[StructLayout(LayoutKind.Sequential)]
private struct structNetResource{
public int iScope;
public int iType;
public int iDisplayType;
public int iUsage;
public string sLocalName;
public string sRemoteName;
public string sComment;
public string sProvider;
}
private const int RESOURCETYPE_DISK = 0x1;
//Standard
private const int CONNECT_INTERACTIVE = 0x00000008;
private const int CONNECT_PROMPT = 0x00000010;
private const int CONNECT_UPDATE_PROFILE = 0x00000001;
//IE4+
private const int CONNECT_REDIRECT = 0x00000080;
//NT5 only
private const int CONNECT_COMMANDLINE = 0x00000800;
private const int CONNECT_CMD_SAVECRED = 0x00001000;
#endregion
#region Propertys and options
private bool lf_SaveCredentials = false;
/// <summary>
/// Option to save credentials are reconnection...
/// </summary>
public bool SaveCredentials{
get{return(lf_SaveCredentials);}
set{lf_SaveCredentials=value;}
}
private bool lf_Persistent = false;
/// <summary>
/// Option to reconnect drive after log off / reboot ...
/// </summary>
public bool Persistent{
get{return(lf_Persistent);}
set{lf_Persistent=value;}
}
private bool lf_Force = false;
/// <summary>
/// Option to force connection if drive is already mapped...
/// or force disconnection if network path is not responding...
/// </summary>
public bool Force{
get{return(lf_Force);}
set{lf_Force=value;}
}
private bool ls_PromptForCredentials = false;
/// <summary>
/// Option to prompt for user credintals when mapping a drive
/// </summary>
public bool PromptForCredentials{
get{return(ls_PromptForCredentials);}
set{ls_PromptForCredentials=value;}
}
private string ls_Drive = "s:";
/// <summary>
/// Drive to be used in mapping / unmapping...
/// </summary>
public string LocalDrive{
get{return(ls_Drive);}
set{
if(value.Length>=1) {
ls_Drive=value.Substring(0,1)+":";
}else{
ls_Drive="";
}
}
}
private string ls_ShareName = "\\\\Computer\\C$";
/// <summary>
/// Share address to map drive to.
/// </summary>
public string ShareName{
get{return(ls_ShareName);}
set{ls_ShareName=value;}
}
#endregion
#region Function mapping
/// <summary>
/// Map network drive
/// </summary>
public void MapDrive(){zMapDrive(null, null);}
/// <summary>
/// Map network drive (using supplied Password)
/// </summary>
public void MapDrive(string Password){zMapDrive(null, Password);}
/// <summary>
/// Map network drive (using supplied Username and Password)
/// </summary>
public void MapDrive(string Username, string Password){zMapDrive(Username, Password);}
/// <summary>
/// Unmap network drive
/// </summary>
public void UnMapDrive(){zUnMapDrive(this.lf_Force);}
/// <summary>
/// Check / restore persistent network drive
/// </summary>
public void RestoreDrives(){zRestoreDrive();}
/// <summary>
/// Display windows dialog for mapping a network drive
/// </summary>
public void ShowConnectDialog(Form ParentForm){zDisplayDialog(ParentForm,1);}
/// <summary>
/// Display windows dialog for disconnecting a network drive
/// </summary>
public void ShowDisconnectDialog(Form ParentForm){zDisplayDialog(ParentForm,2);}
#endregion
#region Core functions
// Map network drive
private void zMapDrive(string psUsername, string psPassword){
//create struct data
structNetResource stNetRes = new structNetResource();
stNetRes.iScope=2;
stNetRes.iType=RESOURCETYPE_DISK;
stNetRes.iDisplayType=3;
stNetRes.iUsage=1;
stNetRes.sRemoteName=ls_ShareName;
stNetRes.sLocalName=ls_Drive;
//prepare params
int iFlags=0;
if(lf_SaveCredentials){iFlags+=CONNECT_CMD_SAVECRED;}
if(lf_Persistent){iFlags+=CONNECT_UPDATE_PROFILE;}
if(ls_PromptForCredentials){iFlags+=CONNECT_INTERACTIVE+CONNECT_PROMPT;}
if(psUsername==""){psUsername=null;}
if(psPassword==""){psPassword=null;}
//if force, unmap ready for new connection
if(lf_Force){try{zUnMapDrive(true);}catch{}}
//call and return
int i = WNetAddConnection2A(ref stNetRes, psPassword, psUsername, iFlags);
if(i>0){throw new System.ComponentModel.Win32Exception(i);}
}
// Unmap network drive
private void zUnMapDrive(bool pfForce){
//call unmap and return
int iFlags=0;
if(lf_Persistent){iFlags+=CONNECT_UPDATE_PROFILE;}
int i = WNetCancelConnection2A(ls_Drive, iFlags, Convert.ToInt32(pfForce));
if(i!=0) i=WNetCancelConnection2A(ls_ShareName, iFlags, Convert.ToInt32(pfForce)); //disconnect if localname was null
if(i>0){throw new System.ComponentModel.Win32Exception(i);}
}
// Check / Restore a network drive
private void zRestoreDrive()
{
//call restore and return
int i = WNetRestoreConnectionW(0, null);
if(i>0){throw new System.ComponentModel.Win32Exception(i);}
}
// Display windows dialog
private void zDisplayDialog(Form poParentForm, int piDialog)
{
int i = -1;
int iHandle = 0;
//get parent handle
if(poParentForm!=null)
{
iHandle = poParentForm.Handle.ToInt32();
}
//show dialog
if(piDialog==1)
{
i = WNetConnectionDialog(iHandle, RESOURCETYPE_DISK);
}else if(piDialog==2)
{
i = WNetDisconnectDialog(iHandle, RESOURCETYPE_DISK);
}
if(i>0){throw new System.ComponentModel.Win32Exception(i);}
//set focus on parent form
poParentForm.BringToFront();
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Diagnostics.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Diagnostics
{
public delegate void DataReceivedEventHandler(Object sender, DataReceivedEventArgs e);
public delegate void EntryWrittenEventHandler(Object sender, EntryWrittenEventArgs e);
public enum EventLogEntryType
{
Error = 1,
Warning = 2,
Information = 4,
SuccessAudit = 8,
FailureAudit = 16,
}
public enum EventLogPermissionAccess
{
None = 0,
Write = 16,
Administer = 48,
Browse = 2,
Instrument = 6,
Audit = 10,
}
public enum OverflowAction
{
DoNotOverwrite = -1,
OverwriteAsNeeded = 0,
OverwriteOlder = 1,
}
public enum PerformanceCounterCategoryType
{
Unknown = -1,
SingleInstance = 0,
MultiInstance = 1,
}
public enum PerformanceCounterInstanceLifetime
{
Global = 0,
Process = 1,
}
public enum PerformanceCounterPermissionAccess
{
Browse = 1,
Instrument = 3,
None = 0,
Read = 1,
Write = 2,
Administer = 7,
}
public enum PerformanceCounterType
{
NumberOfItems32 = 65536,
NumberOfItems64 = 65792,
NumberOfItemsHEX32 = 0,
NumberOfItemsHEX64 = 256,
RateOfCountsPerSecond32 = 272696320,
RateOfCountsPerSecond64 = 272696576,
CountPerTimeInterval32 = 4523008,
CountPerTimeInterval64 = 4523264,
RawFraction = 537003008,
RawBase = 1073939459,
AverageTimer32 = 805438464,
AverageBase = 1073939458,
AverageCount64 = 1073874176,
SampleFraction = 549585920,
SampleCounter = 4260864,
SampleBase = 1073939457,
CounterTimer = 541132032,
CounterTimerInverse = 557909248,
Timer100Ns = 542180608,
Timer100NsInverse = 558957824,
ElapsedTime = 807666944,
CounterMultiTimer = 574686464,
CounterMultiTimerInverse = 591463680,
CounterMultiTimer100Ns = 575735040,
CounterMultiTimer100NsInverse = 592512256,
CounterMultiBase = 1107494144,
CounterDelta32 = 4195328,
CounterDelta64 = 4195584,
}
public enum ProcessPriorityClass
{
Normal = 32,
Idle = 64,
High = 128,
RealTime = 256,
BelowNormal = 16384,
AboveNormal = 32768,
}
public enum ProcessWindowStyle
{
Normal = 0,
Hidden = 1,
Minimized = 2,
Maximized = 3,
}
public enum SourceLevels
{
Off = 0,
Critical = 1,
Error = 3,
Warning = 7,
Information = 15,
Verbose = 31,
ActivityTracing = 65280,
All = -1,
}
public enum ThreadPriorityLevel
{
Idle = -15,
Lowest = -2,
BelowNormal = -1,
Normal = 0,
AboveNormal = 1,
Highest = 2,
TimeCritical = 15,
}
public enum ThreadState
{
Initialized = 0,
Ready = 1,
Running = 2,
Standby = 3,
Terminated = 4,
Wait = 5,
Transition = 6,
Unknown = 7,
}
public enum ThreadWaitReason
{
Executive = 0,
FreePage = 1,
PageIn = 2,
SystemAllocation = 3,
ExecutionDelay = 4,
Suspended = 5,
UserRequest = 6,
EventPairHigh = 7,
EventPairLow = 8,
LpcReceive = 9,
LpcReply = 10,
VirtualMemory = 11,
PageOut = 12,
Unknown = 13,
}
public enum TraceEventType
{
Critical = 1,
Error = 2,
Warning = 4,
Information = 8,
Verbose = 16,
Start = 256,
Stop = 512,
Suspend = 1024,
Resume = 2048,
Transfer = 4096,
}
public enum TraceLevel
{
Off = 0,
Error = 1,
Warning = 2,
Info = 3,
Verbose = 4,
}
public enum TraceOptions
{
None = 0,
LogicalOperationStack = 1,
DateTime = 2,
Timestamp = 4,
ProcessId = 8,
ThreadId = 16,
Callstack = 32,
}
}
| |
// 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 defines an internal class used to throw exceptions in BCL code.
// The main purpose is to reduce code size.
//
// The old way to throw an exception generates quite a lot IL code and assembly code.
// Following is an example:
// C# source
// throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
// IL code:
// IL_0003: ldstr "key"
// IL_0008: ldstr "ArgumentNull_Key"
// IL_000d: call string System.Environment::GetResourceString(string)
// IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string)
// IL_0017: throw
// which is 21bytes in IL.
//
// So we want to get rid of the ldstr and call to Environment.GetResource in IL.
// In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the
// argument name and resource name in a small integer. The source code will be changed to
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key);
//
// The IL code will be 7 bytes.
// IL_0008: ldc.i4.4
// IL_0009: ldc.i4.4
// IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument)
// IL_000f: ldarg.0
//
// This will also reduce the Jitted code size a lot.
//
// It is very important we do this for generic classes because we can easily generate the same code
// multiple times for different instantiation.
//
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace System
{
[StackTraceHidden]
internal static class ThrowHelper
{
[DoesNotReturn]
internal static void ThrowArrayTypeMismatchException()
{
throw new ArrayTypeMismatchException();
}
[DoesNotReturn]
internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeWithPointersNotSupported, targetType));
}
[DoesNotReturn]
internal static void ThrowIndexOutOfRangeException()
{
throw new IndexOutOfRangeException();
}
[DoesNotReturn]
internal static void ThrowArgumentOutOfRangeException()
{
throw new ArgumentOutOfRangeException();
}
[DoesNotReturn]
internal static void ThrowArgumentException_DestinationTooShort()
{
throw new ArgumentException(SR.Argument_DestinationTooShort, "destination");
}
[DoesNotReturn]
internal static void ThrowArgumentException_OverlapAlignmentMismatch()
{
throw new ArgumentException(SR.Argument_OverlapAlignmentMismatch);
}
[DoesNotReturn]
internal static void ThrowArgumentException_CannotExtractScalar(ExceptionArgument argument)
{
throw GetArgumentException(ExceptionResource.Argument_CannotExtractScalar, argument);
}
[DoesNotReturn]
internal static void ThrowArgumentOutOfRange_IndexException()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.index,
ExceptionResource.ArgumentOutOfRange_Index);
}
[DoesNotReturn]
internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.index,
ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
[DoesNotReturn]
internal static void ThrowValueArgumentOutOfRange_NeedNonNegNumException()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.value,
ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
[DoesNotReturn]
internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.length,
ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
[DoesNotReturn]
internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex,
ExceptionResource.ArgumentOutOfRange_Index);
}
[DoesNotReturn]
internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.count,
ExceptionResource.ArgumentOutOfRange_Count);
}
[DoesNotReturn]
internal static void ThrowWrongKeyTypeArgumentException<T>(T key, Type targetType)
{
// Generic key to move the boxing to the right hand side of throw
throw GetWrongKeyTypeArgumentException((object?)key, targetType);
}
[DoesNotReturn]
internal static void ThrowWrongValueTypeArgumentException<T>(T value, Type targetType)
{
// Generic key to move the boxing to the right hand side of throw
throw GetWrongValueTypeArgumentException((object?)value, targetType);
}
private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object? key)
{
return new ArgumentException(SR.Format(SR.Argument_AddingDuplicateWithKey, key));
}
[DoesNotReturn]
internal static void ThrowAddingDuplicateWithKeyArgumentException<T>(T key)
{
// Generic key to move the boxing to the right hand side of throw
throw GetAddingDuplicateWithKeyArgumentException((object?)key);
}
[DoesNotReturn]
internal static void ThrowKeyNotFoundException<T>(T key)
{
// Generic key to move the boxing to the right hand side of throw
throw GetKeyNotFoundException((object?)key);
}
[DoesNotReturn]
internal static void ThrowArgumentException(ExceptionResource resource)
{
throw GetArgumentException(resource);
}
[DoesNotReturn]
internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument)
{
throw GetArgumentException(resource, argument);
}
private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument)
{
return new ArgumentNullException(GetArgumentName(argument));
}
[DoesNotReturn]
internal static void ThrowArgumentNullException(ExceptionArgument argument)
{
throw GetArgumentNullException(argument);
}
[DoesNotReturn]
internal static void ThrowArgumentNullException(ExceptionResource resource)
{
throw new ArgumentNullException(GetResourceString(resource));
}
[DoesNotReturn]
internal static void ThrowArgumentNullException(ExceptionArgument argument, ExceptionResource resource)
{
throw new ArgumentNullException(GetArgumentName(argument), GetResourceString(resource));
}
[DoesNotReturn]
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument)
{
throw new ArgumentOutOfRangeException(GetArgumentName(argument));
}
[DoesNotReturn]
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
{
throw GetArgumentOutOfRangeException(argument, resource);
}
[DoesNotReturn]
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource)
{
throw GetArgumentOutOfRangeException(argument, paramNumber, resource);
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException()
{
throw new InvalidOperationException();
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException(ExceptionResource resource)
{
throw GetInvalidOperationException(resource);
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException_OutstandingReferences()
{
throw new InvalidOperationException(SR.Memory_OutstandingReferences);
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e)
{
throw new InvalidOperationException(GetResourceString(resource), e);
}
[DoesNotReturn]
internal static void ThrowSerializationException(ExceptionResource resource)
{
throw new SerializationException(GetResourceString(resource));
}
[DoesNotReturn]
internal static void ThrowSecurityException(ExceptionResource resource)
{
throw new System.Security.SecurityException(GetResourceString(resource));
}
[DoesNotReturn]
internal static void ThrowRankException(ExceptionResource resource)
{
throw new RankException(GetResourceString(resource));
}
[DoesNotReturn]
internal static void ThrowNotSupportedException(ExceptionResource resource)
{
throw new NotSupportedException(GetResourceString(resource));
}
[DoesNotReturn]
internal static void ThrowUnauthorizedAccessException(ExceptionResource resource)
{
throw new UnauthorizedAccessException(GetResourceString(resource));
}
[DoesNotReturn]
internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource)
{
throw new ObjectDisposedException(objectName, GetResourceString(resource));
}
[DoesNotReturn]
internal static void ThrowObjectDisposedException(ExceptionResource resource)
{
throw new ObjectDisposedException(null, GetResourceString(resource));
}
[DoesNotReturn]
internal static void ThrowNotSupportedException()
{
throw new NotSupportedException();
}
[DoesNotReturn]
internal static void ThrowAggregateException(List<Exception> exceptions)
{
throw new AggregateException(exceptions);
}
[DoesNotReturn]
internal static void ThrowOutOfMemoryException()
{
throw new OutOfMemoryException();
}
[DoesNotReturn]
internal static void ThrowArgumentException_Argument_InvalidArrayType()
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException_InvalidOperation_EnumNotStarted()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException_InvalidOperation_EnumEnded()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException_EnumCurrent(int index)
{
throw GetInvalidOperationException_EnumCurrent(index);
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException_InvalidOperation_NoValue()
{
throw new InvalidOperationException(SR.InvalidOperation_NoValue);
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException_ConcurrentOperationsNotSupported()
{
throw new InvalidOperationException(SR.InvalidOperation_ConcurrentOperationsNotSupported);
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException_HandleIsNotInitialized()
{
throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotInitialized);
}
[DoesNotReturn]
internal static void ThrowInvalidOperationException_HandleIsNotPinned()
{
throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotPinned);
}
[DoesNotReturn]
internal static void ThrowArraySegmentCtorValidationFailedExceptions(Array? array, int offset, int count)
{
throw GetArraySegmentCtorValidationFailedException(array, offset, count);
}
[DoesNotReturn]
internal static void ThrowFormatException_BadFormatSpecifier()
{
throw new FormatException(SR.Argument_BadFormatSpecifier);
}
[DoesNotReturn]
internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge()
{
throw new ArgumentOutOfRangeException("precision", SR.Format(SR.Argument_PrecisionTooLarge, StandardFormat.MaxPrecision));
}
[DoesNotReturn]
internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit()
{
throw new ArgumentOutOfRangeException("symbol", SR.Argument_BadFormatSpecifier);
}
private static Exception GetArraySegmentCtorValidationFailedException(Array? array, int offset, int count)
{
if (array == null)
return new ArgumentNullException(nameof(array));
if (offset < 0)
return new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
return new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
Debug.Assert(array.Length - offset < count);
return new ArgumentException(SR.Argument_InvalidOffLen);
}
private static ArgumentException GetArgumentException(ExceptionResource resource)
{
return new ArgumentException(GetResourceString(resource));
}
private static InvalidOperationException GetInvalidOperationException(ExceptionResource resource)
{
return new InvalidOperationException(GetResourceString(resource));
}
private static ArgumentException GetWrongKeyTypeArgumentException(object? key, Type targetType)
{
return new ArgumentException(SR.Format(SR.Arg_WrongType, key, targetType), nameof(key));
}
private static ArgumentException GetWrongValueTypeArgumentException(object? value, Type targetType)
{
return new ArgumentException(SR.Format(SR.Arg_WrongType, value, targetType), nameof(value));
}
private static KeyNotFoundException GetKeyNotFoundException(object? key)
{
return new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key));
}
private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
{
return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource));
}
private static ArgumentException GetArgumentException(ExceptionResource resource, ExceptionArgument argument)
{
return new ArgumentException(GetResourceString(resource), GetArgumentName(argument));
}
private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource)
{
return new ArgumentOutOfRangeException(GetArgumentName(argument) + "[" + paramNumber.ToString() + "]", GetResourceString(resource));
}
private static InvalidOperationException GetInvalidOperationException_EnumCurrent(int index)
{
return new InvalidOperationException(
index < 0 ?
SR.InvalidOperation_EnumNotStarted :
SR.InvalidOperation_EnumEnded);
}
// Allow nulls for reference types and Nullable<U>, but not for value types.
// Aggressively inline so the jit evaluates the if in place and either drops the call altogether
// Or just leaves null test and call to the Non-returning ThrowHelper.ThrowArgumentNullException
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void IfNullAndNullsAreIllegalThenThrow<T>(object? value, ExceptionArgument argName)
{
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
if (!(default(T)! == null) && value == null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
ThrowHelper.ThrowArgumentNullException(argName);
}
// Throws if 'T' is disallowed in Vector<T> / Vector128<T> / other related types in the
// Numerics or Intrinsics namespaces. If 'T' is allowed, no-ops. JIT will elide the method
// entirely if 'T' is supported and we're on an optimized release build.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void ThrowForUnsupportedVectorBaseType<T>() where T : struct
{
if (typeof(T) != typeof(byte) && typeof(T) != typeof(sbyte) &&
typeof(T) != typeof(short) && typeof(T) != typeof(ushort) &&
typeof(T) != typeof(int) && typeof(T) != typeof(uint) &&
typeof(T) != typeof(long) && typeof(T) != typeof(ulong) &&
typeof(T) != typeof(float) && typeof(T) != typeof(double))
{
ThrowNotSupportedException(ExceptionResource.Arg_TypeNotSupported);
}
}
#if false // Reflection-based implementation does not work for CoreRT/ProjectN
// This function will convert an ExceptionArgument enum value to the argument name string.
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetArgumentName(ExceptionArgument argument)
{
Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
"The enum value is not defined, please check the ExceptionArgument Enum.");
return argument.ToString();
}
#endif
private static string GetArgumentName(ExceptionArgument argument)
{
switch (argument)
{
case ExceptionArgument.obj:
return "obj";
case ExceptionArgument.dictionary:
return "dictionary";
case ExceptionArgument.array:
return "array";
case ExceptionArgument.info:
return "info";
case ExceptionArgument.key:
return "key";
case ExceptionArgument.text:
return "text";
case ExceptionArgument.values:
return "values";
case ExceptionArgument.value:
return "value";
case ExceptionArgument.startIndex:
return "startIndex";
case ExceptionArgument.task:
return "task";
case ExceptionArgument.bytes:
return "bytes";
case ExceptionArgument.byteIndex:
return "byteIndex";
case ExceptionArgument.byteCount:
return "byteCount";
case ExceptionArgument.ch:
return "ch";
case ExceptionArgument.chars:
return "chars";
case ExceptionArgument.charIndex:
return "charIndex";
case ExceptionArgument.charCount:
return "charCount";
case ExceptionArgument.s:
return "s";
case ExceptionArgument.input:
return "input";
case ExceptionArgument.ownedMemory:
return "ownedMemory";
case ExceptionArgument.list:
return "list";
case ExceptionArgument.index:
return "index";
case ExceptionArgument.capacity:
return "capacity";
case ExceptionArgument.collection:
return "collection";
case ExceptionArgument.item:
return "item";
case ExceptionArgument.converter:
return "converter";
case ExceptionArgument.match:
return "match";
case ExceptionArgument.count:
return "count";
case ExceptionArgument.action:
return "action";
case ExceptionArgument.comparison:
return "comparison";
case ExceptionArgument.exceptions:
return "exceptions";
case ExceptionArgument.exception:
return "exception";
case ExceptionArgument.pointer:
return "pointer";
case ExceptionArgument.start:
return "start";
case ExceptionArgument.format:
return "format";
case ExceptionArgument.culture:
return "culture";
case ExceptionArgument.comparer:
return "comparer";
case ExceptionArgument.comparable:
return "comparable";
case ExceptionArgument.source:
return "source";
case ExceptionArgument.state:
return "state";
case ExceptionArgument.length:
return "length";
case ExceptionArgument.comparisonType:
return "comparisonType";
case ExceptionArgument.manager:
return "manager";
case ExceptionArgument.sourceBytesToCopy:
return "sourceBytesToCopy";
case ExceptionArgument.callBack:
return "callBack";
case ExceptionArgument.creationOptions:
return "creationOptions";
case ExceptionArgument.function:
return "function";
case ExceptionArgument.scheduler:
return "scheduler";
case ExceptionArgument.continuationAction:
return "continuationAction";
case ExceptionArgument.continuationFunction:
return "continuationFunction";
case ExceptionArgument.tasks:
return "tasks";
case ExceptionArgument.asyncResult:
return "asyncResult";
case ExceptionArgument.beginMethod:
return "beginMethod";
case ExceptionArgument.endMethod:
return "endMethod";
case ExceptionArgument.endFunction:
return "endFunction";
case ExceptionArgument.cancellationToken:
return "cancellationToken";
case ExceptionArgument.continuationOptions:
return "continuationOptions";
case ExceptionArgument.delay:
return "delay";
case ExceptionArgument.millisecondsDelay:
return "millisecondsDelay";
case ExceptionArgument.millisecondsTimeout:
return "millisecondsTimeout";
case ExceptionArgument.stateMachine:
return "stateMachine";
case ExceptionArgument.timeout:
return "timeout";
case ExceptionArgument.type:
return "type";
case ExceptionArgument.sourceIndex:
return "sourceIndex";
case ExceptionArgument.sourceArray:
return "sourceArray";
case ExceptionArgument.destinationIndex:
return "destinationIndex";
case ExceptionArgument.destinationArray:
return "destinationArray";
case ExceptionArgument.pHandle:
return "pHandle";
case ExceptionArgument.other:
return "other";
case ExceptionArgument.newSize:
return "newSize";
case ExceptionArgument.lowerBounds:
return "lowerBounds";
case ExceptionArgument.lengths:
return "lengths";
case ExceptionArgument.len:
return "len";
case ExceptionArgument.keys:
return "keys";
case ExceptionArgument.indices:
return "indices";
case ExceptionArgument.index1:
return "index1";
case ExceptionArgument.index2:
return "index2";
case ExceptionArgument.index3:
return "index3";
case ExceptionArgument.length1:
return "length1";
case ExceptionArgument.length2:
return "length2";
case ExceptionArgument.length3:
return "length3";
case ExceptionArgument.endIndex:
return "endIndex";
case ExceptionArgument.elementType:
return "elementType";
case ExceptionArgument.arrayIndex:
return "arrayIndex";
default:
Debug.Fail("The enum value is not defined, please check the ExceptionArgument Enum.");
return "";
}
}
#if false // Reflection-based implementation does not work for CoreRT/ProjectN
// This function will convert an ExceptionResource enum value to the resource string.
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetResourceString(ExceptionResource resource)
{
Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
"The enum value is not defined, please check the ExceptionResource Enum.");
return SR.GetResourceString(resource.ToString());
}
#endif
private static string GetResourceString(ExceptionResource resource)
{
switch (resource)
{
case ExceptionResource.ArgumentOutOfRange_Index:
return SR.ArgumentOutOfRange_Index;
case ExceptionResource.ArgumentOutOfRange_IndexCount:
return SR.ArgumentOutOfRange_IndexCount;
case ExceptionResource.ArgumentOutOfRange_IndexCountBuffer:
return SR.ArgumentOutOfRange_IndexCountBuffer;
case ExceptionResource.ArgumentOutOfRange_Count:
return SR.ArgumentOutOfRange_Count;
case ExceptionResource.Arg_ArrayPlusOffTooSmall:
return SR.Arg_ArrayPlusOffTooSmall;
case ExceptionResource.NotSupported_ReadOnlyCollection:
return SR.NotSupported_ReadOnlyCollection;
case ExceptionResource.Arg_RankMultiDimNotSupported:
return SR.Arg_RankMultiDimNotSupported;
case ExceptionResource.Arg_NonZeroLowerBound:
return SR.Arg_NonZeroLowerBound;
case ExceptionResource.ArgumentOutOfRange_ListInsert:
return SR.ArgumentOutOfRange_ListInsert;
case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum:
return SR.ArgumentOutOfRange_NeedNonNegNum;
case ExceptionResource.ArgumentOutOfRange_SmallCapacity:
return SR.ArgumentOutOfRange_SmallCapacity;
case ExceptionResource.Argument_InvalidOffLen:
return SR.Argument_InvalidOffLen;
case ExceptionResource.Argument_CannotExtractScalar:
return SR.Argument_CannotExtractScalar;
case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection:
return SR.ArgumentOutOfRange_BiggerThanCollection;
case ExceptionResource.Serialization_MissingKeys:
return SR.Serialization_MissingKeys;
case ExceptionResource.Serialization_NullKey:
return SR.Serialization_NullKey;
case ExceptionResource.NotSupported_KeyCollectionSet:
return SR.NotSupported_KeyCollectionSet;
case ExceptionResource.NotSupported_ValueCollectionSet:
return SR.NotSupported_ValueCollectionSet;
case ExceptionResource.InvalidOperation_NullArray:
return SR.InvalidOperation_NullArray;
case ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted:
return SR.TaskT_TransitionToFinal_AlreadyCompleted;
case ExceptionResource.TaskCompletionSourceT_TrySetException_NullException:
return SR.TaskCompletionSourceT_TrySetException_NullException;
case ExceptionResource.TaskCompletionSourceT_TrySetException_NoExceptions:
return SR.TaskCompletionSourceT_TrySetException_NoExceptions;
case ExceptionResource.NotSupported_StringComparison:
return SR.NotSupported_StringComparison;
case ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported:
return SR.ConcurrentCollection_SyncRoot_NotSupported;
case ExceptionResource.Task_MultiTaskContinuation_NullTask:
return SR.Task_MultiTaskContinuation_NullTask;
case ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple:
return SR.InvalidOperation_WrongAsyncResultOrEndCalledMultiple;
case ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList:
return SR.Task_MultiTaskContinuation_EmptyTaskList;
case ExceptionResource.Task_Start_TaskCompleted:
return SR.Task_Start_TaskCompleted;
case ExceptionResource.Task_Start_Promise:
return SR.Task_Start_Promise;
case ExceptionResource.Task_Start_ContinuationTask:
return SR.Task_Start_ContinuationTask;
case ExceptionResource.Task_Start_AlreadyStarted:
return SR.Task_Start_AlreadyStarted;
case ExceptionResource.Task_RunSynchronously_Continuation:
return SR.Task_RunSynchronously_Continuation;
case ExceptionResource.Task_RunSynchronously_Promise:
return SR.Task_RunSynchronously_Promise;
case ExceptionResource.Task_RunSynchronously_TaskCompleted:
return SR.Task_RunSynchronously_TaskCompleted;
case ExceptionResource.Task_RunSynchronously_AlreadyStarted:
return SR.Task_RunSynchronously_AlreadyStarted;
case ExceptionResource.AsyncMethodBuilder_InstanceNotInitialized:
return SR.AsyncMethodBuilder_InstanceNotInitialized;
case ExceptionResource.Task_ContinueWith_ESandLR:
return SR.Task_ContinueWith_ESandLR;
case ExceptionResource.Task_ContinueWith_NotOnAnything:
return SR.Task_ContinueWith_NotOnAnything;
case ExceptionResource.Task_Delay_InvalidDelay:
return SR.Task_Delay_InvalidDelay;
case ExceptionResource.Task_Delay_InvalidMillisecondsDelay:
return SR.Task_Delay_InvalidMillisecondsDelay;
case ExceptionResource.Task_Dispose_NotCompleted:
return SR.Task_Dispose_NotCompleted;
case ExceptionResource.Task_ThrowIfDisposed:
return SR.Task_ThrowIfDisposed;
case ExceptionResource.Task_WaitMulti_NullTask:
return SR.Task_WaitMulti_NullTask;
case ExceptionResource.ArgumentException_OtherNotArrayOfCorrectLength:
return SR.ArgumentException_OtherNotArrayOfCorrectLength;
case ExceptionResource.ArgumentNull_Array:
return SR.ArgumentNull_Array;
case ExceptionResource.ArgumentNull_SafeHandle:
return SR.ArgumentNull_SafeHandle;
case ExceptionResource.ArgumentOutOfRange_EndIndexStartIndex:
return SR.ArgumentOutOfRange_EndIndexStartIndex;
case ExceptionResource.ArgumentOutOfRange_Enum:
return SR.ArgumentOutOfRange_Enum;
case ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported:
return SR.ArgumentOutOfRange_HugeArrayNotSupported;
case ExceptionResource.Argument_AddingDuplicate:
return SR.Argument_AddingDuplicate;
case ExceptionResource.Argument_InvalidArgumentForComparison:
return SR.Argument_InvalidArgumentForComparison;
case ExceptionResource.Arg_LowerBoundsMustMatch:
return SR.Arg_LowerBoundsMustMatch;
case ExceptionResource.Arg_MustBeType:
return SR.Arg_MustBeType;
case ExceptionResource.Arg_Need1DArray:
return SR.Arg_Need1DArray;
case ExceptionResource.Arg_Need2DArray:
return SR.Arg_Need2DArray;
case ExceptionResource.Arg_Need3DArray:
return SR.Arg_Need3DArray;
case ExceptionResource.Arg_NeedAtLeast1Rank:
return SR.Arg_NeedAtLeast1Rank;
case ExceptionResource.Arg_RankIndices:
return SR.Arg_RankIndices;
case ExceptionResource.Arg_RanksAndBounds:
return SR.Arg_RanksAndBounds;
case ExceptionResource.InvalidOperation_IComparerFailed:
return SR.InvalidOperation_IComparerFailed;
case ExceptionResource.NotSupported_FixedSizeCollection:
return SR.NotSupported_FixedSizeCollection;
case ExceptionResource.Rank_MultiDimNotSupported:
return SR.Rank_MultiDimNotSupported;
case ExceptionResource.Arg_TypeNotSupported:
return SR.Arg_TypeNotSupported;
default:
Debug.Fail("The enum value is not defined, please check the ExceptionResource Enum.");
return "";
}
}
}
//
// The convention for this enum is using the argument name as the enum name
//
internal enum ExceptionArgument
{
obj,
dictionary,
array,
info,
key,
text,
values,
value,
startIndex,
task,
bytes,
byteIndex,
byteCount,
ch,
chars,
charIndex,
charCount,
s,
input,
ownedMemory,
list,
index,
capacity,
collection,
item,
converter,
match,
count,
action,
comparison,
exceptions,
exception,
pointer,
start,
format,
culture,
comparer,
comparable,
source,
state,
length,
comparisonType,
manager,
sourceBytesToCopy,
callBack,
creationOptions,
function,
scheduler,
continuationAction,
continuationFunction,
tasks,
asyncResult,
beginMethod,
endMethod,
endFunction,
cancellationToken,
continuationOptions,
delay,
millisecondsDelay,
millisecondsTimeout,
stateMachine,
timeout,
type,
sourceIndex,
sourceArray,
destinationIndex,
destinationArray,
pHandle,
other,
newSize,
lowerBounds,
lengths,
len,
keys,
indices,
index1,
index2,
index3,
length1,
length2,
length3,
endIndex,
elementType,
arrayIndex,
}
//
// The convention for this enum is using the resource name as the enum name
//
internal enum ExceptionResource
{
ArgumentOutOfRange_Index,
ArgumentOutOfRange_IndexCount,
ArgumentOutOfRange_IndexCountBuffer,
ArgumentOutOfRange_Count,
Arg_ArrayPlusOffTooSmall,
NotSupported_ReadOnlyCollection,
Arg_RankMultiDimNotSupported,
Arg_NonZeroLowerBound,
ArgumentOutOfRange_ListInsert,
ArgumentOutOfRange_NeedNonNegNum,
ArgumentOutOfRange_SmallCapacity,
Argument_InvalidOffLen,
Argument_CannotExtractScalar,
ArgumentOutOfRange_BiggerThanCollection,
Serialization_MissingKeys,
Serialization_NullKey,
NotSupported_KeyCollectionSet,
NotSupported_ValueCollectionSet,
InvalidOperation_NullArray,
TaskT_TransitionToFinal_AlreadyCompleted,
TaskCompletionSourceT_TrySetException_NullException,
TaskCompletionSourceT_TrySetException_NoExceptions,
NotSupported_StringComparison,
ConcurrentCollection_SyncRoot_NotSupported,
Task_MultiTaskContinuation_NullTask,
InvalidOperation_WrongAsyncResultOrEndCalledMultiple,
Task_MultiTaskContinuation_EmptyTaskList,
Task_Start_TaskCompleted,
Task_Start_Promise,
Task_Start_ContinuationTask,
Task_Start_AlreadyStarted,
Task_RunSynchronously_Continuation,
Task_RunSynchronously_Promise,
Task_RunSynchronously_TaskCompleted,
Task_RunSynchronously_AlreadyStarted,
AsyncMethodBuilder_InstanceNotInitialized,
Task_ContinueWith_ESandLR,
Task_ContinueWith_NotOnAnything,
Task_Delay_InvalidDelay,
Task_Delay_InvalidMillisecondsDelay,
Task_Dispose_NotCompleted,
Task_ThrowIfDisposed,
Task_WaitMulti_NullTask,
ArgumentException_OtherNotArrayOfCorrectLength,
ArgumentNull_Array,
ArgumentNull_SafeHandle,
ArgumentOutOfRange_EndIndexStartIndex,
ArgumentOutOfRange_Enum,
ArgumentOutOfRange_HugeArrayNotSupported,
Argument_AddingDuplicate,
Argument_InvalidArgumentForComparison,
Arg_LowerBoundsMustMatch,
Arg_MustBeType,
Arg_Need1DArray,
Arg_Need2DArray,
Arg_Need3DArray,
Arg_NeedAtLeast1Rank,
Arg_RankIndices,
Arg_RanksAndBounds,
InvalidOperation_IComparerFailed,
NotSupported_FixedSizeCollection,
Rank_MultiDimNotSupported,
Arg_TypeNotSupported,
}
}
| |
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using ReactNative.Bridge.Queue;
using System;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Threading;
using System.Threading.Tasks;
using static ReactNative.Tests.DispatcherHelpers;
namespace ReactNative.Tests.Bridge.Queue
{
[TestClass]
public class ActionQueueTests
{
[TestMethod]
public void ActionQueue_ArgumentChecks()
{
AssertEx.Throws<ArgumentNullException>(
() => new ActionQueue(null),
ex => Assert.AreEqual("onError", ex.ParamName));
AssertEx.Throws<ArgumentNullException>(
() => new ActionQueue(null, Scheduler.Default),
ex => Assert.AreEqual("onError", ex.ParamName));
AssertEx.Throws<ArgumentNullException>(
() => new ActionQueue(ex => { }, null),
ex => Assert.AreEqual("scheduler", ex.ParamName));
AssertEx.Throws<ArgumentNullException>(
() => new LimitedConcurrencyActionQueue(null),
ex => Assert.AreEqual("onError", ex.ParamName));
var actionQueue = new ActionQueue(ex => { });
AssertEx.Throws<ArgumentNullException>(
() => actionQueue.Dispatch(null),
ex => Assert.AreEqual("action", ex.ParamName));
}
[TestMethod]
public async Task ActionQueue_IsOnThread()
{
var thrown = 0;
var onError = new Action<Exception>(ex => thrown++);
var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError));
var layoutThread = await CallOnDispatcherAsync(() => new LayoutActionQueue(onError));
var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default);
var taskPoolThread = new ActionQueue(onError);
var limitedConcurrencyThread = new LimitedConcurrencyActionQueue(onError);
var queueThreads = new IActionQueue[]
{
uiThread,
layoutThread,
backgroundThread,
taskPoolThread,
limitedConcurrencyThread
};
using (new CompositeDisposable(queueThreads))
{
var countdown = new CountdownEvent(queueThreads.Length);
foreach (var queueThread in queueThreads)
{
queueThread.Dispatch(() =>
{
Assert.IsTrue(queueThread.IsOnThread());
countdown.Signal();
});
}
Assert.IsTrue(countdown.Wait(5000));
Assert.AreEqual(0, thrown);
}
}
[TestMethod]
public async Task ActionQueue_HandlesException()
{
var exception = new Exception();
var countdown = new CountdownEvent(1);
var onError = new Action<Exception>(ex =>
{
Assert.AreSame(exception, ex);
countdown.Signal();
});
var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError));
var layoutThread = await CallOnDispatcherAsync(() => new LayoutActionQueue(onError));
var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default);
var taskPoolThread = new ActionQueue(onError);
var limitedConcurrencyThread = new LimitedConcurrencyActionQueue(onError);
var queueThreads = new IActionQueue[]
{
uiThread,
layoutThread,
backgroundThread,
taskPoolThread,
limitedConcurrencyThread
};
using (new CompositeDisposable(queueThreads))
{
countdown.AddCount(queueThreads.Length - 1);
foreach (var queueThread in queueThreads)
{
queueThread.Dispatch(() => { throw exception; });
}
Assert.IsTrue(countdown.Wait(5000));
}
}
[TestMethod]
public async Task ActionQueue_OneAtATime()
{
var enter = new AutoResetEvent(false);
var exit = new AutoResetEvent(false);
var onError = new Action<Exception>(ex => Assert.Fail());
var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError));
var layoutThread = await CallOnDispatcherAsync(() => new LayoutActionQueue(onError));
var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default);
var taskPoolThread = new ActionQueue(onError);
var limitedConcurrencyThread = new LimitedConcurrencyActionQueue(onError);
var queueThreads = new IActionQueue[]
{
uiThread,
layoutThread,
backgroundThread,
taskPoolThread,
limitedConcurrencyThread
};
using (new CompositeDisposable(queueThreads))
{
foreach (var queueThread in queueThreads)
{
var count = 10;
for (var i = 0; i < count; ++i)
{
queueThread.Dispatch(() => { enter.Set(); exit.WaitOne(); });
}
for (var i = 0; i < count; ++i)
{
Assert.IsTrue(enter.WaitOne());
Assert.IsFalse(enter.WaitOne(100));
exit.Set();
}
}
}
}
[TestMethod]
public async Task ActionQueue_DispatchToSelf()
{
var onError = new Action<Exception>(ex => Assert.Fail());
var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError));
var layoutThread = await CallOnDispatcherAsync(() => new LayoutActionQueue(onError));
var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default);
var taskPoolThread = new ActionQueue(onError);
var limitedConcurrencyThread = new LimitedConcurrencyActionQueue(onError);
var queueThreads = new IActionQueue[]
{
uiThread,
layoutThread,
backgroundThread,
taskPoolThread,
limitedConcurrencyThread
};
using (new CompositeDisposable(queueThreads))
{
foreach (var queue in queueThreads)
{
var waitHandle = new AutoResetEvent(false);
queue.Dispatch(() =>
queue.Dispatch(() =>
waitHandle.Set()));
Assert.IsTrue(waitHandle.WaitOne());
}
}
}
[TestMethod]
public async Task ActionQueue_RunAsync_Throws()
{
var onError = new Action<Exception>(ex => Assert.Fail());
var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError));
var layoutThread = await CallOnDispatcherAsync(() => new LayoutActionQueue(onError));
var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default);
var taskPoolThread = new ActionQueue(onError);
var limitedConcurrencyThread = new LimitedConcurrencyActionQueue(onError);
var queueThreads = new IActionQueue[]
{
uiThread,
layoutThread,
backgroundThread,
taskPoolThread,
limitedConcurrencyThread
};
using (new CompositeDisposable(queueThreads))
{
foreach (var queue in queueThreads)
{
var exception = new InvalidOperationException();
await AssertEx.ThrowsAsync<InvalidOperationException>(
() => queue.RunAsync(() => throw exception),
ex => Assert.AreSame(exception, ex));
}
}
}
[TestMethod]
public async Task ActionQueue_Dispose()
{
var onError = new Action<Exception>(ex => Assert.Fail());
var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError));
var layoutThread = await CallOnDispatcherAsync(() => new LayoutActionQueue(onError));
var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default);
var taskPoolThread = new ActionQueue(onError);
var limitedConcurrencyThread = new LimitedConcurrencyActionQueue(onError);
var queueThreads = new IActionQueue[]
{
uiThread,
layoutThread,
backgroundThread,
taskPoolThread,
limitedConcurrencyThread
};
using (new CompositeDisposable(queueThreads))
{
var waitHandle = new AutoResetEvent(false);
foreach (var queueThread in queueThreads)
{
queueThread.Dispose();
queueThread.Dispatch(() => waitHandle.Set());
Assert.IsFalse(waitHandle.WaitOne(100));
}
}
}
[TestMethod]
public async Task ActionQueue_Dispose_Idempotent()
{
var onError = new Action<Exception>(ex => Assert.Fail());
var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError));
var layoutThread = await CallOnDispatcherAsync(() => new LayoutActionQueue(onError));
var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default);
var taskPoolThread = new ActionQueue(onError);
var limitedConcurrencyThread = new LimitedConcurrencyActionQueue(onError);
var queueThreads = new IActionQueue[]
{
uiThread,
layoutThread,
backgroundThread,
taskPoolThread,
limitedConcurrencyThread
};
using (new CompositeDisposable(queueThreads))
{
var waitHandle = new AutoResetEvent(false);
foreach (var queueThread in queueThreads)
{
queueThread.Dispose();
queueThread.Dispose();
queueThread.Dispatch(() => waitHandle.Set());
Assert.IsFalse(waitHandle.WaitOne(100));
}
}
}
[TestMethod]
public async Task ActionQueue_DisposeSelf()
{
var onError = new Action<Exception>(ex => Assert.Fail());
var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError));
var layoutThread = await CallOnDispatcherAsync(() => new LayoutActionQueue(onError));
var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default);
var taskPoolThread = new ActionQueue(onError);
var limitedConcurrencyThread = new LimitedConcurrencyActionQueue(onError);
var queueThreads = new IActionQueue[]
{
uiThread,
layoutThread,
backgroundThread,
taskPoolThread,
limitedConcurrencyThread
};
using (new CompositeDisposable(queueThreads))
{
foreach (var queue in queueThreads)
{
var disposeTask = queue.RunAsync(() =>
{
queue.Dispose();
return true;
});
var task = await Task.WhenAny(disposeTask, Task.Delay(5000));
Assert.AreSame(disposeTask, task);
var wontRunTask = queue.RunAsync(() =>
{
return true;
});
task = await Task.WhenAny(wontRunTask, Task.Delay(500));
Assert.AreNotSame(wontRunTask, task);
}
}
}
[TestMethod]
public async Task ActionQueue_Dispose_WhileRunning()
{
var onError = new Action<Exception>(ex => Assert.Fail());
var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError));
var layoutThread = await CallOnDispatcherAsync(() => new LayoutActionQueue(onError));
var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default);
var taskPoolThread = new ActionQueue(onError);
var limitedConcurrencyThread = new LimitedConcurrencyActionQueue(onError);
var queueThreads = new IActionQueue[]
{
uiThread,
layoutThread,
backgroundThread,
taskPoolThread,
limitedConcurrencyThread
};
using (new CompositeDisposable(queueThreads))
{
foreach (var queue in queueThreads)
{
var enter = new AutoResetEvent(false);
var wait = new AutoResetEvent(false);
queue.Dispatch(() =>
{
enter.Set();
wait.WaitOne();
});
enter.WaitOne();
var task = Task.Run(() => queue.Dispose());
var anyTask = Task.WhenAny(task, Task.Delay(100));
Assert.AreNotSame(task, anyTask);
Assert.IsFalse(task.IsCompleted);
wait.Set();
await task;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using WebApplication.Data;
namespace WebApplication.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc3")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("WebApplication.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
using Microsoft.Extensions.Logging;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using Orleans.CodeGenerator.Utilities;
using Orleans.Serialization;
using Orleans.Utilities;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Orleans.ApplicationParts;
using Orleans.Metadata;
using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils;
using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace Orleans.CodeGenerator
{
/// <summary>
/// Implements a code generator using the Roslyn C# compiler.
/// </summary>
public class RoslynCodeGenerator
{
private const string SerializerNamespacePrefix = "OrleansGeneratedCode";
/// <summary>
/// The logger.
/// </summary>
private readonly ILogger logger;
/// <summary>
/// The serializer generation manager.
/// </summary>
private readonly SerializerGenerationManager serializableTypes;
private readonly TypeCollector typeCollector = new TypeCollector();
private readonly HashSet<string> knownTypes;
private readonly HashSet<Type> knownGrainTypes;
/// <summary>
/// Initializes a new instance of the <see cref="RoslynCodeGenerator"/> class.
/// </summary>
/// <param name="partManager"></param>
/// <param name="loggerFactory">The logger factory.</param>
public RoslynCodeGenerator(IApplicationPartManager partManager, ILoggerFactory loggerFactory)
{
var serializerFeature = partManager.CreateAndPopulateFeature<SerializerFeature>();
var grainClassFeature = partManager.CreateAndPopulateFeature<GrainClassFeature>();
var grainInterfaceFeature = partManager.CreateAndPopulateFeature<GrainInterfaceFeature>();
this.knownTypes = GetKnownTypes();
this.serializableTypes = new SerializerGenerationManager(GetExistingSerializers(), loggerFactory);
this.logger = loggerFactory.CreateLogger<RoslynCodeGenerator>();
var knownInterfaces = grainInterfaceFeature.Interfaces.Select(i => i.InterfaceType);
var knownClasses = grainClassFeature.Classes.Select(c => c.ClassType);
this.knownGrainTypes = new HashSet<Type>(knownInterfaces.Concat(knownClasses));
HashSet<string> GetKnownTypes()
{
var result = new HashSet<string>();
foreach (var kt in serializerFeature.KnownTypes) result.Add(kt.Type);
foreach (var serializer in serializerFeature.SerializerTypes)
{
result.Add(RuntimeTypeNameFormatter.Format(serializer.Target));
result.Add(RuntimeTypeNameFormatter.Format(serializer.Serializer));
}
foreach (var serializer in serializerFeature.SerializerDelegates)
{
result.Add(RuntimeTypeNameFormatter.Format(serializer.Target));
}
return result;
}
HashSet<Type> GetExistingSerializers()
{
var result = new HashSet<Type>();
foreach (var serializer in serializerFeature.SerializerDelegates)
{
result.Add(serializer.Target);
}
foreach (var serializer in serializerFeature.SerializerTypes)
{
result.Add(serializer.Target);
}
return result;
}
}
/// <summary>
/// Generates, compiles, and loads the
/// </summary>
/// <param name="assemblies">
/// The assemblies to generate code for.
/// </param>
public Assembly GenerateAndLoadForAssemblies(IEnumerable<Assembly> assemblies)
{
var assemblyList = assemblies.Where(ShouldGenerateCodeForAssembly).ToList();
try
{
var timer = Stopwatch.StartNew();
var generated = this.GenerateCode(targetAssembly: null, assemblies: assemblyList);
Assembly generatedAssembly;
if (generated.Syntax != null)
{
var emitDebugSymbols = assemblyList.Any(RuntimeVersion.IsAssemblyDebugBuild);
generatedAssembly = this.CompileAssembly(generated, "OrleansCodeGen", emitDebugSymbols);
}
else
{
generatedAssembly = null;
}
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.Debug(
ErrorCode.CodeGenCompilationSucceeded,
"Generated code for 1 assembly in {0}ms",
timer.ElapsedMilliseconds);
}
return generatedAssembly;
}
catch (Exception exception)
{
var message =
$"Exception generating code for input assemblies {string.Join(",", assemblyList.Select(asm => asm.GetName().FullName))}\nException: {LogFormatter.PrintException(exception)}";
this.logger.Warn(ErrorCode.CodeGenCompilationFailed, message, exception);
throw;
}
}
/// <summary>
/// Generates source code for the provided assembly.
/// </summary>
/// <param name="input">
/// The assembly to generate source for.
/// </param>
/// <returns>
/// The generated source.
/// </returns>
public string GenerateSourceForAssembly(Assembly input)
{
if (input.GetCustomAttributes<OrleansCodeGenerationTargetAttribute>().Any()
|| input.GetCustomAttributes<SkipCodeGenerationAttribute>().Any())
{
return string.Empty;
}
var generated = this.GenerateCode(input, new[] { input }.ToList());
if (generated.Syntax == null)
{
return string.Empty;
}
return CodeGeneratorCommon.GenerateSourceCode(CodeGeneratorCommon.AddGeneratedCodeAttribute(generated));
}
/// <summary>
/// Generates a syntax tree for the provided assemblies.
/// </summary>
/// <param name="targetAssembly">The assemblies used for accessibility checks, or <see langword="null"/> during runtime code generation.</param>
/// <param name="assemblies">The assemblies to generate code for.</param>
/// <returns>The generated syntax tree.</returns>
private GeneratedSyntax GenerateCode(Assembly targetAssembly, List<Assembly> assemblies)
{
var features = new FeatureDescriptions();
var members = new List<MemberDeclarationSyntax>();
// Expand the list of included assemblies and types.
var knownAssemblies =
new Dictionary<Assembly, KnownAssemblyAttribute>(
assemblies.ToDictionary(k => k, k => default(KnownAssemblyAttribute)));
foreach (var attribute in assemblies.SelectMany(asm => asm.GetCustomAttributes<KnownAssemblyAttribute>()))
{
knownAssemblies[attribute.Assembly] = attribute;
}
if (logger.IsEnabled(LogLevel.Information))
{
logger.Info($"Generating code for assemblies: {string.Join(", ", knownAssemblies.Keys.Select(a => a.FullName))}");
}
// Get types from assemblies which reference Orleans and are not generated assemblies.
var grainClasses = new HashSet<Type>();
var grainInterfaces = new HashSet<Type>();
foreach (var pair in knownAssemblies)
{
var assembly = pair.Key;
var treatTypesAsSerializable = pair.Value?.TreatTypesAsSerializable ?? false;
foreach (var type in TypeUtils.GetDefinedTypes(assembly, this.logger))
{
if (treatTypesAsSerializable || type.IsSerializable || TypeHasKnownBase(type))
{
string logContext = null;
if (logger.IsEnabled(LogLevel.Trace))
{
if (treatTypesAsSerializable)
logContext = $"known assembly {assembly.GetName().Name} where 'TreatTypesAsSerializable' = true";
else if (type.IsSerializable)
logContext = $"known assembly {assembly.GetName().Name} where type is [Serializable]";
else if (type.IsSerializable)
logContext = $"known assembly {assembly.GetName().Name} where type has known base type.";
}
serializableTypes.RecordType(type, targetAssembly, logContext);
}
// Include grain interfaces and classes.
var isGrainInterface = GrainInterfaceUtils.IsGrainInterface(type);
var isGrainClass = TypeUtils.IsConcreteGrainClass(type);
if (isGrainInterface || isGrainClass)
{
// If code generation is being performed at runtime, the interface must be accessible to the generated code.
if (!TypeUtilities.IsAccessibleFromAssembly(type, targetAssembly))
{
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.Debug("Skipping inaccessible grain type, {0}", type.GetParseableName());
}
continue;
}
// Attempt to generate serializers for grain state classes, i.e, T in Grain<T>.
var baseType = type.BaseType;
if (baseType != null && baseType.IsConstructedGenericType)
{
foreach (var arg in baseType.GetGenericArguments())
{
string logContext = null;
if (logger.IsEnabled(LogLevel.Trace)) logContext = "generic base type of " + type.GetLogFormat();
this.serializableTypes.RecordType(arg, targetAssembly, logContext);
}
}
// Skip classes generated by this generator.
if (IsOrleansGeneratedCode(type))
{
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.Debug("Skipping generated grain type, {0}", type.GetParseableName());
}
continue;
}
if (this.knownGrainTypes.Contains(type))
{
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.Debug("Skipping grain type {0} since it already has generated code.", type.GetParseableName());
}
continue;
}
if (isGrainClass)
{
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.Info("Found grain implementation class: {0}", type.GetParseableName());
}
grainClasses.Add(type);
}
if (isGrainInterface)
{
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.Info("Found grain interface: {0}", type.GetParseableName());
}
GrainInterfaceUtils.ValidateInterfaceRules(type);
grainInterfaces.Add(type);
}
}
}
}
// Group the types by namespace and generate the required code in each namespace.
foreach (var groupedGrainInterfaces in grainInterfaces.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_)))
{
var namespaceName = groupedGrainInterfaces.Key;
var namespaceMembers = new List<MemberDeclarationSyntax>();
foreach (var grainInterface in groupedGrainInterfaces)
{
var referenceTypeName = GrainReferenceGenerator.GetGeneratedClassName(grainInterface);
var invokerTypeName = GrainMethodInvokerGenerator.GetGeneratedClassName(grainInterface);
namespaceMembers.Add(
GrainReferenceGenerator.GenerateClass(
grainInterface,
referenceTypeName,
encounteredType =>
{
string logContext = null;
if (logger.IsEnabled(LogLevel.Trace)) logContext = "used by grain type " + grainInterface.GetLogFormat();
this.serializableTypes.RecordType(encounteredType, targetAssembly, logContext);
}));
namespaceMembers.Add(GrainMethodInvokerGenerator.GenerateClass(grainInterface, invokerTypeName));
var genericTypeSuffix = GetGenericTypeSuffix(grainInterface.GetGenericArguments().Length);
features.GrainInterfaces.Add(
new GrainInterfaceDescription
{
Interface = grainInterface.GetTypeSyntax(includeGenericParameters: false),
Reference = SF.ParseTypeName(namespaceName + '.' + referenceTypeName + genericTypeSuffix),
Invoker = SF.ParseTypeName(namespaceName + '.' + invokerTypeName + genericTypeSuffix),
InterfaceId = GrainInterfaceUtils.GetGrainInterfaceId(grainInterface)
});
}
members.Add(CreateNamespace(namespaceName, namespaceMembers));
}
foreach (var type in grainClasses)
{
features.GrainClasses.Add(
new GrainClassDescription
{
ClassType = type.GetTypeSyntax(includeGenericParameters: false)
});
}
// Generate serializers into their own namespace.
var serializerNamespace = this.GenerateSerializers(targetAssembly, features);
members.Add(serializerNamespace);
// Add serialization metadata for the types which were encountered.
this.AddSerializationTypes(features.Serializers, targetAssembly, knownAssemblies.Keys.ToList());
foreach (var attribute in knownAssemblies.Keys.SelectMany(asm => asm.GetCustomAttributes<ConsiderForCodeGenerationAttribute>()))
{
this.serializableTypes.RecordType(attribute.Type, targetAssembly, "[ConsiderForCodeGeneration]");
if (attribute.ThrowOnFailure && !this.serializableTypes.IsTypeRecorded(attribute.Type) && !this.serializableTypes.IsTypeIgnored(attribute.Type))
{
throw new CodeGenerationException(
$"Found {attribute.GetType().Name} for type {attribute.Type.GetParseableName()}, but code" +
" could not be generated. Ensure that the type is accessible.");
}
}
// Generate metadata directives for all of the relevant types.
var (attributeDeclarations, memberDeclarations) = FeaturePopulatorGenerator.GenerateSyntax(targetAssembly, features);
members.AddRange(memberDeclarations);
var compilationUnit = SF.CompilationUnit().AddAttributeLists(attributeDeclarations.ToArray()).AddMembers(members.ToArray());
return new GeneratedSyntax
{
SourceAssemblies = knownAssemblies.Keys.ToList(),
Syntax = compilationUnit
};
}
/// <summary>
/// Returns true if the provided type has a base type which is marked with <see cref="KnownBaseTypeAttribute"/>.
/// </summary>
/// <param name="type">The type.</param>
private static bool TypeHasKnownBase(Type type)
{
if (type == null) return false;
if (type.GetCustomAttribute<KnownBaseTypeAttribute>() != null) return true;
if (TypeHasKnownBase(type.BaseType)) return true;
var interfaces = type.GetInterfaces();
foreach (var iface in interfaces)
{
if (TypeHasKnownBase(iface)) return true;
}
return false;
}
private NamespaceDeclarationSyntax GenerateSerializers(Assembly targetAssembly, FeatureDescriptions features)
{
var serializerNamespaceMembers = new List<MemberDeclarationSyntax>();
var serializerNamespaceName = $"{SerializerNamespacePrefix}{targetAssembly?.GetName().Name.GetHashCode():X}";
while (this.serializableTypes.GetNextTypeToProcess(out var toGen))
{
if (this.logger.IsEnabled(LogLevel.Trace))
{
this.logger.Trace("Generating serializer for type {0}", toGen.GetParseableName());
}
var type = toGen;
var generatedSerializerName = SerializerGenerator.GetGeneratedClassName(toGen);
serializerNamespaceMembers.Add(SerializerGenerator.GenerateClass(generatedSerializerName, toGen, encounteredType =>
{
string logContext = null;
if (logger.IsEnabled(LogLevel.Trace)) logContext = "generated serializer for " + type.GetLogFormat();
this.serializableTypes.RecordType(encounteredType, targetAssembly, logContext);
}));
var qualifiedSerializerName = serializerNamespaceName + '.' + generatedSerializerName + GetGenericTypeSuffix(toGen.GetGenericArguments().Length);
features.Serializers.SerializerTypes.Add(
new SerializerTypeDescription
{
Serializer = SF.ParseTypeName(qualifiedSerializerName),
Target = toGen.GetTypeSyntax(includeGenericParameters: false)
});
}
// Add all generated serializers to their own namespace.
return CreateNamespace(serializerNamespaceName, serializerNamespaceMembers);
}
/// <summary>
/// Adds serialization type descriptions from <paramref name="targetAssembly"/> to <paramref name="serializationTypes"/>.
/// </summary>
/// <param name="serializationTypes">The serialization type descriptions.</param>
/// <param name="targetAssembly">The target assembly for generated code.</param>
/// <param name="assemblies"></param>
private void AddSerializationTypes(SerializationTypeDescriptions serializationTypes, Assembly targetAssembly, List<Assembly> assemblies)
{
// Only types which exist in assemblies referenced by the target assembly can be referenced.
var references = new HashSet<string>(
assemblies.SelectMany(asm =>
asm.GetReferencedAssemblies()
.Select(referenced => referenced.Name)
.Concat(new[] { asm.GetName().Name })));
bool IsAssemblyReferenced(Type type)
{
// If the target doesn't reference this type's assembly, it cannot reference a type within that assembly.
return references.Contains(type.Assembly.GetName().Name);
}
// Visit all types in other assemblies for serialization metadata.
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (!references.Contains(assembly.GetName().Name)) continue;
foreach (var type in TypeUtils.GetDefinedTypes(assembly, this.logger))
{
this.typeCollector.RecordEncounteredType(type);
}
}
// Returns true if a type can be accessed from source and false otherwise.
bool IsAccessibleType(Type type) => TypeUtilities.IsAccessibleFromAssembly(type, targetAssembly);
foreach (var type in this.typeCollector.EncounteredTypes)
{
// Skip types which can not or should not be referenced.
if (type.IsGenericParameter) continue;
if (!IsAssemblyReferenced(type)) continue;
if (type.IsNestedPrivate) continue;
if (type.GetCustomAttribute<CompilerGeneratedAttribute>() != null) continue;
if (IsOrleansGeneratedCode(type)) continue;
var qualifiedTypeName = RuntimeTypeNameFormatter.Format(type);
if (this.knownTypes.Contains(qualifiedTypeName)) continue;
var typeKeyString = type.OrleansTypeKeyString();
serializationTypes.KnownTypes.Add(new KnownTypeDescription
{
Type = qualifiedTypeName,
TypeKey = typeKeyString
});
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.Debug(
"Found type {0} with type key \"{1}\"",
type.GetParseableName(),
typeKeyString);
}
if (!IsAccessibleType(type)) continue;
var typeSyntax = type.GetTypeSyntax(includeGenericParameters: false);
var serializerAttributes = type.GetCustomAttributes<SerializerAttribute>().ToList();
if (serializerAttributes.Count > 0)
{
// Account for serializer types.
foreach (var serializerAttribute in serializerAttributes)
{
if (!IsAccessibleType(serializerAttribute.TargetType)) continue;
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.Info(
"Found type {0} is a serializer for type {1}",
type.GetParseableName(),
serializerAttribute.TargetType.GetParseableName());
}
serializationTypes.SerializerTypes.Add(
new SerializerTypeDescription
{
Serializer = typeSyntax,
Target = serializerAttribute.TargetType.GetTypeSyntax(includeGenericParameters: false)
});
}
}
else
{
// Account for self-serializing types.
SerializationManager.GetSerializationMethods(type, out var copier, out var serializer, out var deserializer);
if (copier != null || serializer != null || deserializer != null)
{
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.Info(
"Found type {0} is self-serializing.",
type.GetParseableName());
}
serializationTypes.SerializerTypes.Add(
new SerializerTypeDescription
{
Serializer = typeSyntax,
Target = typeSyntax
});
}
}
}
}
/// <summary>
/// Generates and compiles an assembly for the provided syntax.
/// </summary>
/// <param name="generatedSyntax">
/// The generated code.
/// </param>
/// <param name="assemblyName">
/// The name for the generated assembly.
/// </param>
/// <param name="emitDebugSymbols">
/// Whether or not to emit debug symbols for the generated assembly.
/// </param>
/// <returns>
/// The raw assembly.
/// </returns>
/// <exception cref="CodeGenerationException">
/// An error occurred generating code.
/// </exception>
private Assembly CompileAssembly(GeneratedSyntax generatedSyntax, string assemblyName, bool emitDebugSymbols)
{
// Add the generated code attribute.
var code = CodeGeneratorCommon.AddGeneratedCodeAttribute(generatedSyntax);
// Reference everything which can be referenced.
var assemblies =
AppDomain.CurrentDomain.GetAssemblies()
.Where(asm => !asm.IsDynamic && !string.IsNullOrWhiteSpace(asm.Location))
.Select(asm => MetadataReference.CreateFromFile(asm.Location))
.Cast<MetadataReference>()
.ToArray();
// Generate the code.
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
#if NETSTANDARD2_0
// CoreFX bug https://github.com/dotnet/corefx/issues/5540
// to workaround it, we are calling internal WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)
// TODO: this API will be public in the future releases of Roslyn.
// This work is tracked in https://github.com/dotnet/roslyn/issues/5855
// Once it's public, we should replace the internal reflection API call by the public one.
var method = typeof(CSharpCompilationOptions).GetMethod("WithTopLevelBinderFlags", BindingFlags.NonPublic | BindingFlags.Instance);
// we need to pass BinderFlags.IgnoreCorLibraryDuplicatedTypes, but it's an internal class
// http://source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/Binder/BinderFlags.cs,00f268571bb66b73
options = (CSharpCompilationOptions)method.Invoke(options, new object[] { 1u << 26 });
#endif
string source = null;
if (this.logger.IsEnabled(LogLevel.Debug))
{
source = CodeGeneratorCommon.GenerateSourceCode(code);
// Compile the code and load the generated assembly.
this.logger.Debug(
ErrorCode.CodeGenSourceGenerated,
"Generating assembly {0} with source:\n{1}",
assemblyName,
source);
}
var compilation =
CSharpCompilation.Create(assemblyName)
.AddSyntaxTrees(code.SyntaxTree)
.AddReferences(assemblies)
.WithOptions(options);
using (var outputStream = new MemoryStream())
{
var emitOptions = new EmitOptions()
.WithEmitMetadataOnly(false)
.WithIncludePrivateMembers(true);
if (emitDebugSymbols)
{
emitOptions = emitOptions.WithDebugInformationFormat(DebugInformationFormat.Embedded);
}
var compilationResult = compilation.Emit(outputStream, options: emitOptions);
if (!compilationResult.Success)
{
source = source ?? CodeGeneratorCommon.GenerateSourceCode(code);
var errors = string.Join("\n", compilationResult.Diagnostics.Select(_ => _.ToString()));
this.logger.Warn(
ErrorCode.CodeGenCompilationFailed,
"Compilation of assembly {0} failed with errors:\n{1}\nGenerated Source Code:\n{2}",
assemblyName,
errors,
source);
throw new CodeGenerationException(errors);
}
this.logger.Debug(
ErrorCode.CodeGenCompilationSucceeded,
"Compilation of assembly {0} succeeded.",
assemblyName);
return Assembly.Load(outputStream.ToArray());
}
}
private static string GetGenericTypeSuffix(int numParams)
{
if (numParams == 0) return string.Empty;
return '<' + new string(',', numParams - 1) + '>';
}
private static NamespaceDeclarationSyntax CreateNamespace(string namespaceName, IEnumerable<MemberDeclarationSyntax> namespaceMembers)
{
return
SF.NamespaceDeclaration(SF.ParseName(namespaceName))
.AddUsings(
TypeUtils.GetNamespaces(typeof(GrainExtensions), typeof(IntrospectionExtensions))
.Select(_ => SF.UsingDirective(SF.ParseName(_)))
.ToArray())
.AddMembers(namespaceMembers.ToArray());
}
/// <summary>
/// Returns a value indicating whether or not code should be generated for the provided assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>A value indicating whether or not code should be generated for the provided assembly.</returns>
private bool ShouldGenerateCodeForAssembly(Assembly assembly)
{
return !assembly.IsDynamic
&& TypeUtils.IsOrleansOrReferencesOrleans(assembly)
&& !assembly.GetCustomAttributes<OrleansCodeGenerationTargetAttribute>().Any()
&& !assembly.GetCustomAttributes<SkipCodeGenerationAttribute>().Any();
}
private bool IsOrleansGeneratedCode(MemberInfo type) =>
string.Equals(type.GetCustomAttribute<GeneratedCodeAttribute>()?.Tool, CodeGeneratorCommon.ToolName, StringComparison.Ordinal);
}
}
| |
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2017 Daniel Liew
//
// This file is licensed under the MIT license.
// See LICENSE.txt for details.
//------------------------------------------------------------------------------
using System;
using NUnit.Framework;
using Symbooglix;
using Microsoft.Boogie;
using System.Collections.Generic;
using BPLType = Microsoft.Boogie.Type;
using System.Linq;
namespace SymbooglixLibTests
{
[TestFixture()]
public class MapProxyTests
{
public MapProxyTests()
{
// HACK:
SymbooglixLibTests.SymbooglixTest.SetupCmdLineParser();
SymbooglixLibTests.SymbooglixTest.SetupDebug();
}
protected BPLType GetMapVariable(BPLType resultTyp, params BPLType[] indices)
{
var mapType = new MapType(Token.NoToken,
new List<Microsoft.Boogie.TypeVariable>(),
indices.ToList(),
resultTyp);
return mapType;
}
protected MapProxy GetMapProxy(Expr initialValue)
{
return new MapProxy(initialValue, 0);
}
// FIXME: move somewhere central
public static Variable GetVariable(string name, BPLType type)
{
var v = new GlobalVariable(Token.NoToken, new TypedIdent(Token.NoToken, name, type));
return v;
}
public IExprBuilder GetSimpleExprBuilder()
{
return new SimpleExprBuilder(/*immutable=*/true);
}
[Test()]
public void SymbolicWriteForcesStoresToBeDropped()
{
// Build var m:[int]bool;
var mapTy = GetMapVariable(BPLType.Int, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", mapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
// m[0] := false
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(0) }, builder.ConstantInt(99));
// m[2] := true
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(2) }, builder.ConstantInt(101));
// m[5] := false
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(5) }, builder.ConstantInt(25));
// Read back
Assert.AreEqual(builder.ConstantInt(99), mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) }));
Assert.AreEqual(builder.ConstantInt(101), mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(2) }));
Assert.AreEqual(builder.ConstantInt(25), mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(5) }));
// Now write to a symbolic location. This should cause all the stores to flushed
// and then dropped
var symIndex = GetVariable("symIndex", BPLType.Int);
mp.WriteMapAt(new List<Expr>() {builder.Identifier(symIndex)}, builder.ConstantInt(11));
// Read back
var m0AfterFlush = mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) });
Assert.IsNull(ExprUtil.AsLiteral(m0AfterFlush));
Assert.AreEqual("map[0 := 99][2 := 101][5 := 25][symIndex := 11][0]", m0AfterFlush.ToString());
var m2AfterFlush = mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(2) });
Assert.IsNull(ExprUtil.AsLiteral(m2AfterFlush));
Assert.AreEqual("map[0 := 99][2 := 101][5 := 25][symIndex := 11][2]", m2AfterFlush.ToString());
var m5AfterFlush = mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(5) });
Assert.IsNull(ExprUtil.AsLiteral(m5AfterFlush));
Assert.AreEqual("map[0 := 99][2 := 101][5 := 25][symIndex := 11][5]", m5AfterFlush.ToString());
}
[Test()]
public void ReadAtIndexMis()
{
// Build var m:[int][int,bool]bool
var innerMapTy = GetMapVariable(BPLType.Bool, BPLType.Int, BPLType.Bool);
var outerMapTy = GetMapVariable(innerMapTy, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", outerMapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
// There are no stores so we should get a map select
var indices = new List<Expr>() {
builder.ConstantInt(0),
builder.ConstantInt(1), builder.False
};
var read = mp.ReadMapAt(indices);
var asMapSelect = ExprUtil.AsMapSelect(read);
Assert.IsNotNull(asMapSelect);
Assert.AreEqual("map[0][1, false]", asMapSelect.ToString());
// Do concrete store
mp.WriteMapAt(indices, builder.True);
// Try reading back (should get constant back)
var readBack = mp.ReadMapAt(indices);
Assert.AreEqual(builder.True, readBack);
// Force flushing by doing a read
read = mp.Read();
Assert.AreEqual("map[0 := map[0][1, false := true]]", read.ToString());
// Should still be ble to read back directly
readBack = mp.ReadMapAt(indices);
Assert.AreEqual(builder.True, readBack);
}
[Test()]
public void DirectWriteDropsConstantStores()
{
// Build var m:[int]bool;
var mapTy = GetMapVariable(BPLType.Bool, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", mapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
// m[0] := false
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(0) }, builder.False);
// m[2] := true
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(2) }, builder.True);
// The above stores aren't flushed. Do a direct write and then read
// the stores should not be flushed.
mp.Write(mapId);
Assert.AreEqual("map", mp.Read().ToString());
}
[Test()]
public void DirectWriteDropsNonAliasingSymbolicStores()
{
// Build var m:[int]bool;
var mapTy = GetMapVariable(BPLType.Bool, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", mapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
var sym = builder.Identifier(GetVariable("sym", BPLType.Int));
// m[1 + sym] := true
mp.WriteMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym) }, builder.True);
// Read back directly
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym)}));
var sym2 = builder.Identifier(GetVariable("sym2", BPLType.Int));
// m[sym2] := true
mp.WriteMapAt(new List<Expr>() { sym2 }, builder.True);
// The above stores aren't flushed. Do a direct write and then read
// the stores should not be flushed.
mp.Write(mapId);
Assert.AreEqual("map", mp.Read().ToString());
}
[Test()]
public void WriteMakesStoresInaccessible()
{
// Build var m:[int]bool;
var mapTy = GetMapVariable(BPLType.Bool, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", mapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
// m[0] := false
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(0) }, builder.False);
// m[2] := true
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(2) }, builder.True);
// Read back
Assert.AreEqual(builder.False, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) }));
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(2) }));
// Write at symbolic location should make reading the stores directly fail
// and instead return the flushed expression
var symIndex = builder.Identifier(GetVariable("symIndex", BPLType.Int));
mp.WriteMapAt(new List<Expr>() { symIndex }, builder.False);
Assert.AreEqual("map[0 := false][2 := true][symIndex := false][0]", mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) }).ToString());
Assert.AreEqual("map[0 := false][2 := true][symIndex := false][2]", mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(2) }).ToString());
}
[Test()]
public void WritesAndMisRead()
{
// Build var m:[int]bool;
var mapTy = GetMapVariable(BPLType.Bool, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", mapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
// m[0] := false
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(0) }, builder.False);
// m[2] := true
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(2) }, builder.True);
// Read back
Assert.AreEqual(builder.False, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) }));
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(2) }));
// Read from location not stored. Should cause stores to be flushed
var readAtNonStoredLocation = mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(1) });
Assert.IsNotNull(ExprUtil.AsMapSelect(readAtNonStoredLocation));
Assert.AreEqual("map[0 := false][2 := true][1]", readAtNonStoredLocation.ToString());
// Check read again
Assert.AreEqual("map[0 := false][2 := true]", mp.Read().ToString());
// Try reading from another location
var readAtStoredLocation = mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(2) });
Assert.AreEqual(builder.True, readAtStoredLocation);
// This definitely isn't known about
var read3AtNonStoredLocation = mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(18) });
Assert.IsNotNull(ExprUtil.AsMapSelect(read3AtNonStoredLocation));
Assert.AreEqual("map[0 := false][2 := true][18]", read3AtNonStoredLocation.ToString());
// Do another write and check we can read it back direcly
// m[18] := false
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(18) }, builder.False);
// Read back
Assert.AreEqual(builder.False, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(18) }));
}
[Test()]
public void MultipleWritesAndClone()
{
// Build var m:[int]bool;
var mapTy = GetMapVariable(BPLType.Bool, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", mapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
// m[0] := false
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(0) }, builder.False);
// m[2] := true
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(2) }, builder.True);
// Read back
Assert.AreEqual(builder.False, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) }));
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(2) }));
// Clone and make sure we can read the same
var clonedMp = mp.Clone(1);
Assert.AreEqual(builder.False, clonedMp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) }));
Assert.AreEqual(builder.True, clonedMp.ReadMapAt(new List<Expr>() { builder.ConstantInt(2) }));
// Modify the original and check the clone is unchanged
var symBool = builder.Identifier(GetVariable("symBool", BPLType.Bool));
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(0) }, symBool);
Assert.AreEqual(symBool, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) }));
Assert.AreEqual(builder.False, clonedMp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) }));
Assert.AreEqual("map[0 := symBool][2 := true]", mp.Read().ToString());
Assert.AreEqual("map[0 := false][2 := true]", clonedMp.Read().ToString());
// Modify the clone and check the original is unchanged
clonedMp.WriteMapAt(new List<Expr>() { builder.ConstantInt(2) }, symBool);
Assert.AreEqual(symBool, clonedMp.ReadMapAt(new List<Expr>() { builder.ConstantInt(2) }));
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(2) }));
Assert.AreEqual("map[0 := false][2 := symBool]", clonedMp.Read().ToString());
Assert.AreEqual("map[0 := symBool][2 := true]", mp.Read().ToString());
}
[Test()]
public void AliasingSymbolicWrites()
{
// Build var m:[int]bool;
var mapTy = GetMapVariable(BPLType.Bool, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", mapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
var sym = builder.Identifier(GetVariable("sym", BPLType.Int));
var sym2 = builder.Identifier(GetVariable("sym2", BPLType.Int));
// m[sym + sym2] := true
mp.WriteMapAt(new List<Expr>() { builder.Add(sym2, sym) }, builder.True);
// Read back
Assert.AreEqual("true", mp.ReadMapAt(new List<Expr>() { builder.Add(sym2, sym) }).ToString());
// Read back should give fully flushed expression
Assert.AreEqual("map[sym2 + sym := true][sym2 + sym2]", mp.ReadMapAt(new List<Expr>() { builder.Add(sym2, sym2) }).ToString());
}
[Test()]
public void MultipleNonAliasingSymbolicWritesAndClone()
{
// Build var m:[int]bool;
var mapTy = GetMapVariable(BPLType.Bool, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", mapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
var sym = builder.Identifier(GetVariable("sym", BPLType.Int));
// m[1 + sym] := true
mp.WriteMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym) }, builder.True);
// m[sym] := false
mp.WriteMapAt(new List<Expr>() { sym }, builder.False);
// Read back
Assert.AreEqual(builder.False, mp.ReadMapAt(new List<Expr>() { sym }));
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym) }));
// Clone and make sure we can read the same
var clonedMp = mp.Clone(1);
Assert.AreEqual(builder.False, clonedMp.ReadMapAt(new List<Expr>() { sym }));
Assert.AreEqual(builder.True, clonedMp.ReadMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym) }));
// Modify the original and check the clone is unchanged
var symBool = builder.Identifier(GetVariable("symBool", BPLType.Bool));
mp.WriteMapAt(new List<Expr>() { sym }, symBool);
Assert.AreEqual(symBool, mp.ReadMapAt(new List<Expr>() { sym }));
Assert.AreEqual(builder.False, clonedMp.ReadMapAt(new List<Expr>() { sym }));
// FIXME: Non-determinstically fails due to non determinisic ordering of stores
//Assert.AreEqual("map[1 + sym := true][sym := symBool]", mp.Read().ToString());
//Assert.AreEqual("map[1 + sym := true][sym := false]", clonedMp.Read().ToString());
// Modify the clone and check the original is unchanged
clonedMp.WriteMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym) }, symBool);
Assert.AreEqual(symBool, clonedMp.ReadMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym) }));
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym) }));
// FIXME: Check the ouput of Read(). Can't really do it due to non-deterministic ordering
}
[Test()]
public void FlushMultipleWrites()
{
// Build var m:[int]bool;
var mapTy = GetMapVariable(BPLType.Bool, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", mapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
// m[0] := false
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(0) }, builder.False);
// m[2] := true
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(2) }, builder.True);
// m[5] := false
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(5) }, builder.False);
// Overwrite
// m[5] := true
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(5) }, builder.True);
// Read back
Assert.AreEqual(builder.False, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) }));
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(2) }));
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(5) }));
// Force flush
var fullResult = mp.Read();
var asMapStore = ExprUtil.AsMapStore(fullResult);
Assert.IsNotNull(asMapStore);
Assert.AreEqual("map[0 := false][2 := true][5 := true]", asMapStore.ToString());
// Do again check we get the same
fullResult = mp.Read();
asMapStore = ExprUtil.AsMapStore(fullResult);
Assert.IsNotNull(asMapStore);
Assert.AreEqual("map[0 := false][2 := true][5 := true]", asMapStore.ToString());
// The read should not clear the stores so we will read back the stored expression
Assert.AreEqual(builder.False, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) }));
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(2) }));
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(5) }));
// Reading at a index not stored should give full expression
Assert.AreEqual("map[0 := false][2 := true][5 := true][1]", mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(1) }).ToString());
Assert.AreEqual("map[0 := false][2 := true][5 := true][3]", mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(3) }).ToString());
Assert.AreEqual("map[0 := false][2 := true][5 := true][4]", mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(4) }).ToString());
}
[Test()]
public void WriteAtConstantIndicesDoIndexedReadThenFlush()
{
// Build var m:[int][int][int]bool
var innerMapTy = GetMapVariable(BPLType.Bool, BPLType.Int);
var middleMapTy = GetMapVariable(innerMapTy, BPLType.Int);
var outerMapTy = GetMapVariable(middleMapTy, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", outerMapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
// do m[1][2][3] := False
var indices = new List<Expr>() { builder.ConstantInt(1), builder.ConstantInt(2), builder.ConstantInt(3) };
mp.WriteMapAt(indices, builder.False);
// Read back by index
var indexedRead = mp.ReadMapAt(indices);
Assert.AreEqual(builder.False, indexedRead);
// Force the expressions to be flushed
var fullRead = mp.Read();
var asMapStore = ExprUtil.AsMapStore(fullRead);
Assert.IsNotNull(asMapStore);
Assert.AreEqual("map[1 := map[1][2 := map[1][2][3 := false]]]", asMapStore.ToString());
// We only did a read so should still be able to get the stored expression
Assert.AreEqual(builder.False, mp.ReadMapAt(indices));
}
[Test()]
public void WriteSymbolicIndexNestedMapAndReadBack()
{
// Build var m:[int][int,bool]bool
var innerMapTy = GetMapVariable(BPLType.Bool, BPLType.Int, BPLType.Bool);
var outerMapTy = GetMapVariable(innerMapTy, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", outerMapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
// Build indicies, deliberately make sure that it would be difficult
// to tell if they could alias.
var x = builder.Identifier(GetVariable("x", BPLType.Bool));
var y = builder.Identifier(GetVariable("y", BPLType.Bool));
var boolIndex = builder.And(x, y);
var a = builder.Identifier(GetVariable("a", BPLType.Int));
var b = builder.Identifier(GetVariable("b", BPLType.Int));
var firstIntIndex = builder.Add(a, b);
var e = builder.Identifier(GetVariable("e", BPLType.Int));
var f = builder.Identifier(GetVariable("f", BPLType.Int));
var secondIntIndex = builder.Add(e, f);
var indices = new List<Expr>() { firstIntIndex, secondIntIndex, boolIndex };
// m[ a + b := m[a+b][e+f, x+y := true]
mp.WriteMapAt(indices, builder.True);
// Read back and check
var result = mp.Read();
Assert.AreEqual("map[a + b := map[a + b][e + f, x && y := true]]", result.ToString());
}
[Test()]
public void WriteAtSymbolicNonAliasingIndices()
{
// Build var m:[int]bool;
var mapTy = GetMapVariable(BPLType.Bool, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", mapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
var sym = builder.Identifier(GetVariable("sym", BPLType.Int));
// m[sym] := false
mp.WriteMapAt(new List<Expr>() { sym }, builder.False);
// m[1 + sym] := true
mp.WriteMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym) }, builder.True);
// Read back directly
Assert.AreEqual(builder.False, mp.ReadMapAt(new List<Expr>() { sym }));
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym)}));
// Overwrite
// m[1 + sym] := false
mp.WriteMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym) }, builder.False);
Assert.AreEqual(builder.False, mp.ReadMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym)}));
// FIXME: We probably don't want non-determinism in symbooglix
// Get full expression, we have to do it this way because there's no explicit ordering of the stores.
// and the ordering appears to be random
var fullExprAsString = mp.Read().ToString();
if (fullExprAsString != "map[1 + sym := false][sym := false]" && fullExprAsString != "map[sym := false][1 + sym := false]")
Assert.Fail("wrong result");
//Assert.AreEqual("map[1 + sym := true][sym := false]", mp.Read().ToString());
// Check we can still read back directly
Assert.AreEqual(builder.False, mp.ReadMapAt(new List<Expr>() { sym }));
Assert.AreEqual(builder.False, mp.ReadMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym)}));
// Try reading from a location not stored.
var mOffsetTwo = mp.ReadMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(2), sym) });
Assert.AreEqual(fullExprAsString + "[2 + sym]", mOffsetTwo.ToString());
}
[Test()]
public void WriteAtSymbolicNonAliasingIndicesThenConcrete()
{
// Build var m:[int]bool;
var mapTy = GetMapVariable(BPLType.Bool, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", mapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
var sym = builder.Identifier(GetVariable("sym", BPLType.Int));
// m[1 + sym] := true
mp.WriteMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym) }, builder.True);
// Read back directly
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym)}));
// Now write to a concrete location
// This should flush the stores at the symbolic locations
// m[0] := false
mp.WriteMapAt(new List<Expr>() { builder.ConstantInt(0) }, builder.False);
// Read back directly
Assert.AreEqual(builder.False, mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) }));
// Read back at the symbolic location. It shouldn't be directly accessible anymore and
// we should get the fully flushed expression
Assert.AreEqual("map[1 + sym := true][0 := false][1 + sym]", mp.ReadMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym)}).ToString());
// Read back full expression
Assert.AreEqual("map[1 + sym := true][0 := false]", mp.Read().ToString());
// Now write to a symbolic location
// This should flush the stores at concrete locations
// m[3 + sym] := false
mp.WriteMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(3), sym) }, builder.True);
// Should be a flushed expression rather than "false"
Assert.AreEqual("map[1 + sym := true][0 := false][3 + sym := true][0]", mp.ReadMapAt(new List<Expr>() { builder.ConstantInt(0) }).ToString());
}
[Test()]
public void WriteAtSymbolicNonAliasAndThenWriteAtNewAliasingLocations()
{
// Build var m:[int]bool;
var mapTy = GetMapVariable(BPLType.Bool, BPLType.Int);
// Build map variable variable
var builder = GetSimpleExprBuilder();
var mv = GetVariable("map", mapTy);
var mapId = builder.Identifier(mv);
var mp = GetMapProxy(mapId);
var sym = builder.Identifier(GetVariable("sym", BPLType.Int));
// m[1 + sym] := true
mp.WriteMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym) }, builder.True);
// Read back directly
Assert.AreEqual(builder.True, mp.ReadMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(1), sym)}));
var sym2 = builder.Identifier(GetVariable("sym2", BPLType.Int));
// m[sym2] := true
mp.WriteMapAt(new List<Expr>() { sym2 }, builder.True);
// Note the ConstantFoldingExprBuilder manages to extract the true for us
Assert.AreEqual("true", mp.ReadMapAt( new List<Expr>() {sym2}).ToString());
// Read from symoblic location where we don't know if it aliases with existing stores. This
// will force full flush
Assert.AreEqual("map[1 + sym := true][sym2 := true][sym]", mp.ReadMapAt( new List<Expr>() {sym}).ToString());
// The next write to this non-aliasing location should be readable directly
// m[3 + sym2] := true
mp.WriteMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(3), sym2) }, builder.True);
Assert.AreEqual(builder.True, mp.ReadMapAt( new List<Expr>() {builder.Add(builder.ConstantInt(3), sym2)}));
mp.WriteMapAt(new List<Expr>() { builder.Add(builder.ConstantInt(2), sym2) }, builder.False);
Assert.AreEqual(builder.False, mp.ReadMapAt( new List<Expr>() {builder.Add(builder.ConstantInt(2), sym2)}));
}
}
}
| |
using System;
using Loon.Utils;
using Loon.Java;
using System.Text;
namespace Loon.Foundation {
public class NSNumber : NSObject {
public const int INTEGER = 0;
public const int REAL = 1;
public const int BOOLEAN = 2;
private int type;
private long longValue;
private double doubleValue;
private bool boolValue;
protected static internal long ParseUnsignedInt(byte[] bytes) {
long l = 0;
foreach (byte b in bytes) {
l <<= 8;
l |= (uint)b & 0xFF;
}
l &= 0xFFFFFFFFL;
return l;
}
protected static internal long ParseLong(byte[] bytes) {
long l = 0;
foreach (byte b in bytes) {
l <<= 8;
l |= (uint)b & 0xFF;
}
return l;
}
protected static internal double ParseDouble(byte[] bytes) {
if (bytes.Length != 8) {
throw new ArgumentException("bad byte array length "
+ bytes.Length);
}
return BitConverter.Int64BitsToDouble(ParseLong(bytes));
}
public NSNumber(byte[] bytes, int type_0) {
switch (type_0) {
case INTEGER: {
doubleValue = longValue = ParseLong(bytes);
break;
}
case REAL: {
doubleValue = ParseDouble(bytes);
longValue = (long) doubleValue;
break;
}
default: {
throw new ArgumentException("Type argument is not valid.");
}
}
this.type = type_0;
}
public NSNumber(String text) {
if (text.Equals("yes",StringComparison.InvariantCultureIgnoreCase) || text.Equals("true",StringComparison.InvariantCultureIgnoreCase)) {
boolValue = true;
doubleValue = longValue = 1;
type = BOOLEAN;
return;
} else if (text.Equals("no",StringComparison.InvariantCultureIgnoreCase)
|| text.Equals("false",StringComparison.InvariantCultureIgnoreCase)) {
boolValue = false;
doubleValue = longValue = 0;
type = BOOLEAN;
return;
}
if (!MathUtils.IsNan(text)) {
throw new ArgumentException("[" + text
+ "] value must be a boolean or numeric !");
}
if (StringUtils.IsAlphabetNumeric(text) && text.IndexOf('.') == -1) {
long l = ((Int64 )Int64.Parse(text,System.Globalization.NumberStyles.Integer));
doubleValue = longValue = l;
type = INTEGER;
} else if (StringUtils.IsAlphabetNumeric(text)
&& text.IndexOf('.') != -1) {
double d = ((Double )Double.Parse(text,JavaRuntime.NumberFormat));
longValue = (long) (doubleValue = d);
type = REAL;
} else {
try {
long l_0 = ((Int64 )Int64.Parse(text,System.Globalization.NumberStyles.Integer));
doubleValue = longValue = l_0;
type = INTEGER;
} catch (Exception) {
try {
double d_1 = ((Double)Double.Parse(text, JavaRuntime.NumberFormat));
longValue = (long) (doubleValue = d_1);
type = REAL;
} catch (Exception) {
try {
boolValue = Boolean.Parse(text);
doubleValue = longValue = (boolValue) ? 1 : 0;
} catch (Exception) {
throw new ArgumentException(
"Given text neither represents a double, int nor boolean value.");
}
}
}
}
}
public NSNumber(int i) {
type = INTEGER;
doubleValue = longValue = i;
}
public NSNumber(double d) {
longValue = (long) (doubleValue = d);
type = REAL;
}
public NSNumber(bool b) {
boolValue = b;
doubleValue = longValue = (b) ? 1 : 0;
type = BOOLEAN;
}
public int Type() {
return type;
}
public bool BooleanValue() {
if (type == BOOLEAN) {
return boolValue;
} else {
return longValue != 0;
}
}
public long LongValue() {
return longValue;
}
public int IntValue() {
return (int) longValue;
}
public double DoubleValue() {
return doubleValue;
}
public override bool Equals(Object obj) {
return obj.GetType().Equals(typeof(NSNumber))
&& obj.GetHashCode() == GetHashCode();
}
public override int GetHashCode() {
int hash = 3;
hash = 37 * hash + (int) (this.longValue ^ ((long) (((ulong) this.longValue) >> 32)));
hash = 37
* hash
+ (int)(BitConverter.DoubleToInt64Bits(this.doubleValue) ^ ((long)(((ulong)BitConverter.DoubleToInt64Bits(this.doubleValue)) >> 32)));
hash = 37 * hash + ((BooleanValue()) ? 1 : 0);
return hash;
}
public override String ToString() {
switch (type) {
case INTEGER: {
return LongValue().ToString();
}
case REAL: {
return DoubleValue().ToString();
}
case BOOLEAN: {
return BooleanValue().ToString();
}
default: {
return base.ToString();
}
}
}
protected internal override void AddSequence(StringBuilder sbr, string indent)
{
sbr.Append(indent);
switch (type) {
case INTEGER:
sbr.Append("<integer>");
sbr.Append(longValue.ToString());
sbr.Append("</integer>");
return;
case REAL:
sbr.Append("<real>");
sbr.Append(doubleValue.ToString());
sbr.Append("</real>");
return;
case BOOLEAN:
if (boolValue) {
sbr.Append("<true/>");
return;
} else {
sbr.Append("<false/>");
return;
}
default:
return;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Utilities class for handling configuration.
/// </summary>
public static class ConfigUtilities
{
internal static void ParseAdditionalAssemblyDirectories(IDictionary<string, SearchOption> directories, XmlElement root)
{
foreach (var node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if (grandchild == null)
{
continue;
}
else
{
if (!grandchild.HasAttribute("Path"))
throw new FormatException("Missing 'Path' attribute on Directory element.");
// default to recursive
var recursive = true;
if (grandchild.HasAttribute("IncludeSubFolders"))
{
if (!bool.TryParse(grandchild.Attributes["IncludeSubFolders"].Value, out recursive))
throw new FormatException("Attribute 'IncludeSubFolders' has invalid value.");
directories[grandchild.Attributes["Path"].Value] = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
}
}
}
}
internal static void ParseTelemetry(XmlElement root)
{
foreach (var node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if (grandchild == null) continue;
if (!grandchild.LocalName.Equals("TelemetryConsumer"))
{
continue;
}
else
{
if (!grandchild.HasAttribute("Type"))
throw new FormatException("Missing 'Type' attribute on TelemetryConsumer element.");
if (!grandchild.HasAttribute("Assembly"))
throw new FormatException("Missing 'Type' attribute on TelemetryConsumer element.");
var className = grandchild.Attributes["Type"].Value;
var assemblyName = new AssemblyName(grandchild.Attributes["Assembly"].Value);
Assembly assembly = null;
try
{
assembly = Assembly.Load(assemblyName);
var pluginType = assembly.GetType(className);
if (pluginType == null) throw new TypeLoadException("Cannot locate plugin class " + className + " in assembly " + assembly.FullName);
var args = grandchild.Attributes.Cast<XmlAttribute>().Where(a => a.LocalName != "Type" && a.LocalName != "Assembly").ToArray();
var plugin = Activator.CreateInstance(pluginType, args);
if (plugin is ITelemetryConsumer)
{
LogManager.TelemetryConsumers.Add(plugin as ITelemetryConsumer);
}
else
{
throw new InvalidCastException("TelemetryConsumer class " + className + " must implement one of Orleans.Runtime.ITelemetryConsumer based interfaces");
}
}
catch (Exception exc)
{
throw new TypeLoadException("Cannot load TelemetryConsumer class " + className + " from assembly " + assembly + " - Error=" + exc);
}
}
}
}
internal static void ParseTracing(ITraceConfiguration config, XmlElement root, string nodeName)
{
if (root.HasAttribute("DefaultTraceLevel"))
{
config.DefaultTraceLevel = ParseSeverity(root.GetAttribute("DefaultTraceLevel"),
"Invalid trace level DefaultTraceLevel attribute value on Tracing element for " + nodeName);
}
if (root.HasAttribute("TraceToConsole"))
{
config.TraceToConsole = ParseBool(root.GetAttribute("TraceToConsole"),
"Invalid boolean value for TraceToConsole attribute on Tracing element for " + nodeName);
}
if (root.HasAttribute("TraceToFile"))
{
config.TraceFilePattern = root.GetAttribute("TraceToFile");
}
if (root.HasAttribute("LargeMessageWarningThreshold"))
{
config.LargeMessageWarningThreshold = ParseInt(root.GetAttribute("LargeMessageWarningThreshold"),
"Invalid boolean value for LargeMessageWarningThresholdattribute on Tracing element for " + nodeName);
}
if (root.HasAttribute("PropagateActivityId"))
{
config.PropagateActivityId = ParseBool(root.GetAttribute("PropagateActivityId"),
"Invalid boolean value for PropagateActivityId attribute on Tracing element for " + nodeName);
}
if (root.HasAttribute("BulkMessageLimit"))
{
config.BulkMessageLimit = ParseInt(root.GetAttribute("BulkMessageLimit"),
"Invalid int value for BulkMessageLimit attribute on Tracing element for " + nodeName);
}
foreach (XmlNode node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if (grandchild == null) continue;
if (grandchild.LocalName.Equals("TraceLevelOverride") && grandchild.HasAttribute("TraceLevel") && grandchild.HasAttribute("LogPrefix"))
{
config.TraceLevelOverrides.Add(new Tuple<string, Severity>(grandchild.GetAttribute("LogPrefix"),
ParseSeverity(grandchild.GetAttribute("TraceLevel"),
"Invalid trace level TraceLevel attribute value on TraceLevelOverride element for " + nodeName + " prefix " +
grandchild.GetAttribute("LogPrefix"))));
}
else if (grandchild.LocalName.Equals("LogConsumer"))
{
var className = grandchild.InnerText;
Assembly assembly = null;
try
{
int pos = className.IndexOf(',');
if (pos > 0)
{
var assemblyName = className.Substring(pos + 1).Trim();
className = className.Substring(0, pos).Trim();
assembly = Assembly.Load(new AssemblyName(assemblyName));
}
else
{
assembly = typeof(ConfigUtilities).GetTypeInfo().Assembly;
}
var pluginType = assembly.GetType(className);
if (pluginType == null) throw new TypeLoadException("Cannot locate plugin class " + className + " in assembly " + assembly.FullName);
var plugin = Activator.CreateInstance(pluginType);
if (plugin is ILogConsumer)
{
LogManager.LogConsumers.Add(plugin as ILogConsumer);
}
else
{
throw new InvalidCastException("LogConsumer class " + className + " must implement Orleans.ILogConsumer interface");
}
}
catch (Exception exc)
{
throw new TypeLoadException("Cannot load LogConsumer class " + className + " from assembly " + assembly + " - Error=" + exc);
}
}
}
SetTraceFileName(config, nodeName, DateTime.UtcNow);
}
internal static void ParseStatistics(IStatisticsConfiguration config, XmlElement root, string nodeName)
{
if (root.HasAttribute("ProviderType"))
{
config.StatisticsProviderName = root.GetAttribute("ProviderType");
}
if (root.HasAttribute("MetricsTableWriteInterval"))
{
config.StatisticsMetricsTableWriteInterval = ParseTimeSpan(root.GetAttribute("MetricsTableWriteInterval"),
"Invalid TimeSpan value for Statistics.MetricsTableWriteInterval attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("PerfCounterWriteInterval"))
{
config.StatisticsPerfCountersWriteInterval = ParseTimeSpan(root.GetAttribute("PerfCounterWriteInterval"),
"Invalid TimeSpan value for Statistics.PerfCounterWriteInterval attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("LogWriteInterval"))
{
config.StatisticsLogWriteInterval = ParseTimeSpan(root.GetAttribute("LogWriteInterval"),
"Invalid TimeSpan value for Statistics.LogWriteInterval attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("WriteLogStatisticsToTable"))
{
config.StatisticsWriteLogStatisticsToTable = ParseBool(root.GetAttribute("WriteLogStatisticsToTable"),
"Invalid bool value for Statistics.WriteLogStatisticsToTable attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("StatisticsCollectionLevel"))
{
config.StatisticsCollectionLevel = ConfigUtilities.ParseEnum<StatisticsLevel>(root.GetAttribute("StatisticsCollectionLevel"),
"Invalid value of for Statistics.StatisticsCollectionLevel attribute on Statistics element for " + nodeName);
}
}
internal static void ParseLimitValues(LimitManager limitManager, XmlElement root, string nodeName)
{
foreach (XmlNode node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if (grandchild == null) continue;
if (grandchild.LocalName.Equals("Limit") && grandchild.HasAttribute("Name")
&& (grandchild.HasAttribute("SoftLimit") || grandchild.HasAttribute("HardLimit")))
{
var limitName = grandchild.GetAttribute("Name");
limitManager.AddLimitValue(limitName, new LimitValue
{
Name = limitName,
SoftLimitThreshold = ParseInt(grandchild.GetAttribute("SoftLimit"),
"Invalid integer value for the SoftLimit attribute on the Limit element"),
HardLimitThreshold = grandchild.HasAttribute("HardLimit") ? ParseInt(grandchild.GetAttribute("HardLimit"),
"Invalid integer value for the HardLimit attribute on the Limit element") : 0,
});
}
}
}
internal static void SetTraceFileName(ITraceConfiguration config, string nodeName, DateTime timestamp)
{
const string dateFormat = "yyyy-MM-dd-HH.mm.ss.fffZ";
if (config == null) throw new ArgumentNullException("config");
if (config.TraceFilePattern == null
|| string.IsNullOrWhiteSpace(config.TraceFilePattern)
|| config.TraceFilePattern.Equals("false", StringComparison.OrdinalIgnoreCase)
|| config.TraceFilePattern.Equals("none", StringComparison.OrdinalIgnoreCase))
{
config.TraceFileName = null;
}
else if (string.Empty.Equals(config.TraceFileName))
{
config.TraceFileName = null; // normalize
}
else
{
string traceFileDir = Path.GetDirectoryName(config.TraceFilePattern);
if (!String.IsNullOrEmpty(traceFileDir) && !Directory.Exists(traceFileDir))
{
string traceFileName = Path.GetFileName(config.TraceFilePattern);
string[] alternateDirLocations = { "appdir", "." };
foreach (var d in alternateDirLocations)
{
if (Directory.Exists(d))
{
config.TraceFilePattern = Path.Combine(d, traceFileName);
break;
}
}
}
config.TraceFileName = String.Format(config.TraceFilePattern, nodeName, timestamp.ToUniversalTime().ToString(dateFormat), Dns.GetHostName());
}
}
internal static int ParseInt(string input, string errorMessage)
{
int p;
if (!Int32.TryParse(input, out p))
{
throw new FormatException(errorMessage);
}
return p;
}
internal static long ParseLong(string input, string errorMessage)
{
long p;
if (!Int64.TryParse(input, out p))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return p;
}
internal static bool ParseBool(string input, string errorMessage)
{
bool p;
if (Boolean.TryParse(input, out p)) return p;
switch (input)
{
case "0":
p = false;
break;
case "1":
p = true;
break;
default:
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return p;
}
internal static double ParseDouble(string input, string errorMessage)
{
double p;
if (!Double.TryParse(input, out p))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return p;
}
internal static Guid ParseGuid(string input, string errorMessage)
{
Guid p;
if (!Guid.TryParse(input, out p))
{
throw new FormatException(errorMessage);
}
return p;
}
internal static Type ParseFullyQualifiedType(string input, string errorMessage)
{
Type returnValue;
try
{
returnValue = Type.GetType(input);
}
catch (Exception e)
{
throw new FormatException(errorMessage, e);
}
if (returnValue == null)
{
throw new FormatException(errorMessage);
}
return returnValue;
}
internal static void ValidateSerializationProvider(TypeInfo type)
{
if (type.IsClass == false)
{
throw new FormatException(string.Format("The serialization provider type {0} was not a class", type.FullName));
}
if (type.IsAbstract)
{
throw new FormatException(string.Format("The serialization provider type {0} was an abstract class", type.FullName));
}
if (type.IsPublic == false)
{
throw new FormatException(string.Format("The serialization provider type {0} is not public", type.FullName));
}
if (type.IsGenericType && type.IsConstructedGenericType() == false)
{
throw new FormatException(string.Format("The serialization provider type {0} is generic and has a missing type parameter specification", type.FullName));
}
var constructor = type.GetConstructor(Type.EmptyTypes);
if (constructor == null)
{
throw new FormatException(string.Format("The serialization provider type {0} does not have a parameterless constructor", type.FullName));
}
if (constructor.IsPublic == false)
{
throw new FormatException(string.Format("The serialization provider type {0} has a non-public parameterless constructor", type.FullName));
}
}
// Time spans are entered as a string of decimal digits, optionally followed by a unit string: "ms", "s", "m", "hr"
internal static TimeSpan ParseTimeSpan(string input, string errorMessage)
{
long unitSize;
string numberInput;
var trimmedInput = input.Trim().ToLowerInvariant();
if (trimmedInput.EndsWith("ms", StringComparison.Ordinal))
{
unitSize = 10000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 2).Trim();
}
else if (trimmedInput.EndsWith("s", StringComparison.Ordinal))
{
unitSize = 1000 * 10000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 1).Trim();
}
else if (trimmedInput.EndsWith("m", StringComparison.Ordinal))
{
unitSize = 60 * 1000 * 10000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 1).Trim();
}
else if (trimmedInput.EndsWith("hr", StringComparison.Ordinal))
{
unitSize = 60 * 60 * 1000 * 10000L;
numberInput = trimmedInput.Remove(trimmedInput.Length - 2).Trim();
}
else
{
unitSize = 1000 * 10000; // Default is seconds
numberInput = trimmedInput;
}
decimal rawTimeSpan;
if (!decimal.TryParse(numberInput, NumberStyles.Any, CultureInfo.InvariantCulture, out rawTimeSpan))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return TimeSpan.FromTicks((long)(rawTimeSpan * unitSize));
}
internal static string ToParseableTimeSpan(TimeSpan input)
{
return $"{input.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)}ms";
}
internal static byte[] ParseSubnet(string input, string errorMessage)
{
return string.IsNullOrEmpty(input) ? null : input.Split('.').Select(s => (byte)ParseInt(s, errorMessage)).ToArray();
}
internal static T ParseEnum<T>(string input, string errorMessage)
where T : struct // really, where T : enum, but there's no way to require that in C#
{
T s;
if (!Enum.TryParse<T>(input, out s))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return s;
}
internal static Severity ParseSeverity(string input, string errorMessage)
{
Severity s;
if (!Enum.TryParse<Severity>(input, out s))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return s;
}
internal static async Task<IPEndPoint> ParseIPEndPoint(XmlElement root, byte[] subnet = null)
{
if (!root.HasAttribute("Address")) throw new FormatException("Missing Address attribute for " + root.LocalName + " element");
if (!root.HasAttribute("Port")) throw new FormatException("Missing Port attribute for " + root.LocalName + " element");
var family = AddressFamily.InterNetwork;
if (root.HasAttribute("Subnet"))
{
subnet = ParseSubnet(root.GetAttribute("Subnet"), "Invalid subnet");
}
if (root.HasAttribute("PreferredFamily"))
{
family = ParseEnum<AddressFamily>(root.GetAttribute("PreferredFamily"),
"Invalid preferred addressing family for " + root.LocalName + " element");
}
IPAddress addr = await ClusterConfiguration.ResolveIPAddress(root.GetAttribute("Address"), subnet, family);
int port = ParseInt(root.GetAttribute("Port"), "Invalid Port attribute for " + root.LocalName + " element");
return new IPEndPoint(addr, port);
}
internal static string TraceConfigurationToString(ITraceConfiguration config)
{
var sb = new StringBuilder();
sb.Append(" Tracing: ").AppendLine();
sb.Append(" Default Trace Level: ").Append(config.DefaultTraceLevel).AppendLine();
if (config.TraceLevelOverrides.Count > 0)
{
sb.Append(" TraceLevelOverrides:").AppendLine();
foreach (var over in config.TraceLevelOverrides)
{
sb.Append(" ").Append(over.Item1).Append(" ==> ").Append(over.Item2.ToString()).AppendLine();
}
}
else
{
sb.Append(" TraceLevelOverrides: None").AppendLine();
}
sb.Append(" Trace to Console: ").Append(config.TraceToConsole).AppendLine();
sb.Append(" Trace File Name: ").Append(string.IsNullOrWhiteSpace(config.TraceFileName) ? "" : Path.GetFullPath(config.TraceFileName)).AppendLine();
sb.Append(" LargeMessageWarningThreshold: ").Append(config.LargeMessageWarningThreshold).AppendLine();
sb.Append(" PropagateActivityId: ").Append(config.PropagateActivityId).AppendLine();
sb.Append(" BulkMessageLimit: ").Append(config.BulkMessageLimit).AppendLine();
return sb.ToString();
}
internal static string IStatisticsConfigurationToString(IStatisticsConfiguration config)
{
var sb = new StringBuilder();
sb.Append(" Statistics: ").AppendLine();
sb.Append(" MetricsTableWriteInterval: ").Append(config.StatisticsMetricsTableWriteInterval).AppendLine();
sb.Append(" PerfCounterWriteInterval: ").Append(config.StatisticsPerfCountersWriteInterval).AppendLine();
sb.Append(" LogWriteInterval: ").Append(config.StatisticsLogWriteInterval).AppendLine();
sb.Append(" WriteLogStatisticsToTable: ").Append(config.StatisticsWriteLogStatisticsToTable).AppendLine();
sb.Append(" StatisticsCollectionLevel: ").Append(config.StatisticsCollectionLevel).AppendLine();
#if TRACK_DETAILED_STATS
sb.Append(" TRACK_DETAILED_STATS: true").AppendLine();
#endif
if (!string.IsNullOrEmpty(config.StatisticsProviderName))
sb.Append(" StatisticsProviderName:").Append(config.StatisticsProviderName).AppendLine();
return sb.ToString();
}
/// <summary>
/// Prints the the DataConnectionString,
/// without disclosing any credential info
/// such as the Azure Storage AccountKey, SqlServer password or AWS SecretKey.
/// </summary>
/// <param name="connectionString">The connection string to print.</param>
/// <returns>The string representation of the DataConnectionString with account credential info redacted.</returns>
public static string RedactConnectionStringInfo(string connectionString)
{
string[] secretKeys =
{
"AccountKey=", // Azure Storage
"SharedAccessSignature=", // Many Azure services
"SharedAccessKey=", "SharedSecretValue=", // ServiceBus
"Password=", // SQL
"SecretKey=", "SessionToken=", // DynamoDb
};
if (String.IsNullOrEmpty(connectionString)) return "null";
string connectionInfo = connectionString;
// Remove any secret keys from connection string info written to log files
foreach (var secretKey in secretKeys)
{
int keyPos = connectionInfo.IndexOf(secretKey, StringComparison.OrdinalIgnoreCase);
if (keyPos >= 0)
{
connectionInfo = connectionInfo.Remove(keyPos + secretKey.Length) + "<--SNIP-->";
}
}
return connectionInfo;
}
public static TimeSpan ParseCollectionAgeLimit(XmlElement xmlElement)
{
if (xmlElement.LocalName != "Deactivation")
throw new ArgumentException("The XML element must be a <Deactivate/> element.");
if (!xmlElement.HasAttribute("AgeLimit"))
throw new ArgumentException("The AgeLimit attribute is required for a <Deactivate/> element.");
return ParseTimeSpan(xmlElement.GetAttribute("AgeLimit"), "Invalid TimeSpan value for Deactivation.AgeLimit");
}
private static readonly string[] defaultClientConfigFileNames = { "ClientConfiguration.xml", "OrleansClientConfiguration.xml", "Client.config", "Client.xml" };
private static readonly string[] defaultSiloConfigFileNames = { "OrleansConfiguration.xml", "orleans.config", "config.xml", "orleans.config.xml" };
private static readonly string[] defaultConfigDirs =
{
null, // Will be filled in with directory location for this executing assembly
"approot", // Azure AppRoot directory
".", // Current directory
".." // Parent directory
};
public static string FindConfigFile(bool isSilo)
{
// Add directory containing Orleans binaries to the search locations for config files
defaultConfigDirs[0] = Path.GetDirectoryName(typeof(ConfigUtilities).GetTypeInfo().Assembly.Location);
var notFound = new List<string>();
foreach (string dir in defaultConfigDirs)
{
foreach (string file in isSilo ? defaultSiloConfigFileNames : defaultClientConfigFileNames)
{
var fileName = Path.GetFullPath(Path.Combine(dir, file));
if (File.Exists(fileName)) return fileName;
notFound.Add(fileName);
}
}
var whereWeLooked = new StringBuilder();
whereWeLooked.AppendFormat("Cannot locate Orleans {0} config file.", isSilo ? "silo" : "client").AppendLine();
whereWeLooked.AppendLine("Searched locations:");
foreach (var i in notFound)
{
whereWeLooked.AppendFormat("\t- {0}", i).AppendLine();
}
throw new FileNotFoundException(whereWeLooked.ToString());
}
/// <summary>
/// Returns the Runtime Version information.
/// </summary>
/// <returns>the Runtime Version information</returns>
public static string RuntimeVersionInfo()
{
var sb = new StringBuilder();
sb.Append(" Orleans version: ").AppendLine(RuntimeVersion.Current);
#if !NETSTANDARD_TODO
// TODO: could use Microsoft.Extensions.PlatformAbstractions package to get this info
sb.Append(" .NET version: ").AppendLine(Environment.Version.ToString());
sb.Append(" OS version: ").AppendLine(Environment.OSVersion.ToString());
sb.Append(" App config file: ").AppendLine(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
#endif
sb.AppendFormat(" GC Type={0} GCLatencyMode={1}",
GCSettings.IsServerGC ? "Server" : "Client",
Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode))
.AppendLine();
return sb.ToString();
}
}
}
| |
// $Id$
#region The MIT License
/*
Copyright (c) 2009 [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
namespace OreEfficiencyCalc {
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() {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.queryButton = new System.Windows.Forms.Button();
this.resultGridView = new System.Windows.Forms.DataGridView();
this.AsteroidColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.IncomeColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.EfficiencyColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.pricesProgressBar = new System.Windows.Forms.ProgressBar();
this.customFit = new System.Windows.Forms.CheckBox();
this.tradeHub = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.mainMenu = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aPIToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pricesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.minerFitGroupBox = new System.Windows.Forms.GroupBox();
this.label9 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.implant10 = new System.Windows.Forms.ComboBox();
this.implant7 = new System.Windows.Forms.ComboBox();
this.label7 = new System.Windows.Forms.Label();
this.drone5 = new System.Windows.Forms.ComboBox();
this.drone4 = new System.Windows.Forms.ComboBox();
this.drone3 = new System.Windows.Forms.ComboBox();
this.drone2 = new System.Windows.Forms.ComboBox();
this.drone1 = new System.Windows.Forms.ComboBox();
this.label6 = new System.Windows.Forms.Label();
this.rig3 = new System.Windows.Forms.ComboBox();
this.rig2 = new System.Windows.Forms.ComboBox();
this.rig1 = new System.Windows.Forms.ComboBox();
this.label5 = new System.Windows.Forms.Label();
this.ship = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.low2 = new System.Windows.Forms.ComboBox();
this.low1 = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.high = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.mainGroupBox = new System.Windows.Forms.GroupBox();
this.harvestingTypeGroupBox = new OreEfficiencyCalc.RadioGroupBox();
this.gasRadioButton = new System.Windows.Forms.RadioButton();
this.iceRadioButton = new System.Windows.Forms.RadioButton();
this.mercoxitRadioButton = new System.Windows.Forms.RadioButton();
this.oreRadioButton = new System.Windows.Forms.RadioButton();
((System.ComponentModel.ISupportInitialize) (this.resultGridView)).BeginInit();
this.mainMenu.SuspendLayout();
this.minerFitGroupBox.SuspendLayout();
this.mainGroupBox.SuspendLayout();
this.harvestingTypeGroupBox.SuspendLayout();
this.SuspendLayout();
//
// queryButton
//
this.queryButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (204)));
this.queryButton.Location = new System.Drawing.Point(111, 468);
this.queryButton.Name = "queryButton";
this.queryButton.Size = new System.Drawing.Size(127, 23);
this.queryButton.TabIndex = 0;
this.queryButton.Text = "Query";
this.queryButton.UseVisualStyleBackColor = true;
this.queryButton.Click += new System.EventHandler(this.queryButton_Click);
//
// resultGridView
//
this.resultGridView.AllowUserToAddRows = false;
this.resultGridView.AllowUserToDeleteRows = false;
this.resultGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.resultGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.resultGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.AsteroidColumn,
this.IncomeColumn,
this.EfficiencyColumn});
this.resultGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically;
this.resultGridView.Location = new System.Drawing.Point(12, 19);
this.resultGridView.Name = "resultGridView";
this.resultGridView.Size = new System.Drawing.Size(339, 382);
this.resultGridView.TabIndex = 3;
//
// AsteroidColumn
//
this.AsteroidColumn.HeaderText = "Asteroid type";
this.AsteroidColumn.Name = "AsteroidColumn";
//
// IncomeColumn
//
this.IncomeColumn.HeaderText = "Income";
this.IncomeColumn.Name = "IncomeColumn";
//
// EfficiencyColumn
//
this.EfficiencyColumn.HeaderText = "Efficiency";
this.EfficiencyColumn.Name = "EfficiencyColumn";
//
// pricesProgressBar
//
this.pricesProgressBar.Location = new System.Drawing.Point(12, 407);
this.pricesProgressBar.Maximum = 8;
this.pricesProgressBar.Name = "pricesProgressBar";
this.pricesProgressBar.Size = new System.Drawing.Size(339, 23);
this.pricesProgressBar.TabIndex = 4;
//
// customFit
//
this.customFit.AutoSize = true;
this.customFit.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (204)));
this.customFit.Location = new System.Drawing.Point(269, 438);
this.customFit.Name = "customFit";
this.customFit.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.customFit.Size = new System.Drawing.Size(82, 17);
this.customFit.TabIndex = 13;
this.customFit.Text = "Custom fit";
this.customFit.UseVisualStyleBackColor = true;
this.customFit.CheckedChanged += new System.EventHandler(this.checkBox_CheckedChanged);
//
// tradeHub
//
this.tradeHub.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.tradeHub.FormattingEnabled = true;
this.tradeHub.Location = new System.Drawing.Point(81, 436);
this.tradeHub.Name = "tradeHub";
this.tradeHub.Size = new System.Drawing.Size(97, 21);
this.tradeHub.TabIndex = 12;
this.tradeHub.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (204)));
this.label3.Location = new System.Drawing.Point(10, 439);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(65, 13);
this.label3.TabIndex = 11;
this.label3.Text = "Trade hub";
//
// mainMenu
//
this.mainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.optionsToolStripMenuItem,
this.helpToolStripMenuItem});
this.mainMenu.Location = new System.Drawing.Point(0, 0);
this.mainMenu.Name = "mainMenu";
this.mainMenu.Size = new System.Drawing.Size(762, 24);
this.mainMenu.TabIndex = 15;
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(92, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aPIToolStripMenuItem,
this.pricesToolStripMenuItem});
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(56, 20);
this.optionsToolStripMenuItem.Text = "&Options";
//
// aPIToolStripMenuItem
//
this.aPIToolStripMenuItem.Name = "aPIToolStripMenuItem";
this.aPIToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.aPIToolStripMenuItem.Text = "&API...";
this.aPIToolStripMenuItem.Click += new System.EventHandler(this.aPIToolStripMenuItem_Click);
//
// pricesToolStripMenuItem
//
this.pricesToolStripMenuItem.Name = "pricesToolStripMenuItem";
this.pricesToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.pricesToolStripMenuItem.Text = "&Prices...";
this.pricesToolStripMenuItem.Click += new System.EventHandler(this.pricesToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(115, 22);
this.aboutToolStripMenuItem.Text = "&About...";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// minerFitGroupBox
//
this.minerFitGroupBox.Controls.Add(this.label9);
this.minerFitGroupBox.Controls.Add(this.label8);
this.minerFitGroupBox.Controls.Add(this.implant10);
this.minerFitGroupBox.Controls.Add(this.implant7);
this.minerFitGroupBox.Controls.Add(this.label7);
this.minerFitGroupBox.Controls.Add(this.drone5);
this.minerFitGroupBox.Controls.Add(this.drone4);
this.minerFitGroupBox.Controls.Add(this.drone3);
this.minerFitGroupBox.Controls.Add(this.drone2);
this.minerFitGroupBox.Controls.Add(this.drone1);
this.minerFitGroupBox.Controls.Add(this.label6);
this.minerFitGroupBox.Controls.Add(this.rig3);
this.minerFitGroupBox.Controls.Add(this.rig2);
this.minerFitGroupBox.Controls.Add(this.rig1);
this.minerFitGroupBox.Controls.Add(this.label5);
this.minerFitGroupBox.Controls.Add(this.ship);
this.minerFitGroupBox.Controls.Add(this.label4);
this.minerFitGroupBox.Controls.Add(this.low2);
this.minerFitGroupBox.Controls.Add(this.low1);
this.minerFitGroupBox.Controls.Add(this.label2);
this.minerFitGroupBox.Controls.Add(this.high);
this.minerFitGroupBox.Controls.Add(this.label1);
this.minerFitGroupBox.Location = new System.Drawing.Point(378, 27);
this.minerFitGroupBox.Name = "minerFitGroupBox";
this.minerFitGroupBox.Size = new System.Drawing.Size(379, 390);
this.minerFitGroupBox.TabIndex = 17;
this.minerFitGroupBox.TabStop = false;
this.minerFitGroupBox.Text = "Miner fit";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(330, 331);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(32, 13);
this.label9.TabIndex = 21;
this.label9.Text = "slot 7";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(330, 356);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(38, 13);
this.label8.TabIndex = 20;
this.label8.Text = "slot 10";
//
// implant10
//
this.implant10.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.implant10.FormattingEnabled = true;
this.implant10.Items.AddRange(new object[] {
"<none>"});
this.implant10.Location = new System.Drawing.Point(70, 353);
this.implant10.Name = "implant10";
this.implant10.Size = new System.Drawing.Size(258, 21);
this.implant10.TabIndex = 19;
this.implant10.Tag = "10";
this.implant10.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// implant7
//
this.implant7.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.implant7.FormattingEnabled = true;
this.implant7.Items.AddRange(new object[] {
"<none>"});
this.implant7.Location = new System.Drawing.Point(70, 328);
this.implant7.Name = "implant7";
this.implant7.Size = new System.Drawing.Size(258, 21);
this.implant7.TabIndex = 18;
this.implant7.Tag = "7";
this.implant7.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(11, 331);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(46, 13);
this.label7.TabIndex = 17;
this.label7.Text = "Implants";
//
// drone5
//
this.drone5.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.drone5.FormattingEnabled = true;
this.drone5.Items.AddRange(new object[] {
"<none>"});
this.drone5.Location = new System.Drawing.Point(70, 303);
this.drone5.Name = "drone5";
this.drone5.Size = new System.Drawing.Size(258, 21);
this.drone5.TabIndex = 16;
this.drone5.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// drone4
//
this.drone4.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.drone4.FormattingEnabled = true;
this.drone4.Items.AddRange(new object[] {
"<none>"});
this.drone4.Location = new System.Drawing.Point(70, 278);
this.drone4.Name = "drone4";
this.drone4.Size = new System.Drawing.Size(258, 21);
this.drone4.TabIndex = 15;
this.drone4.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// drone3
//
this.drone3.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.drone3.FormattingEnabled = true;
this.drone3.Items.AddRange(new object[] {
"<none>"});
this.drone3.Location = new System.Drawing.Point(70, 253);
this.drone3.Name = "drone3";
this.drone3.Size = new System.Drawing.Size(258, 21);
this.drone3.TabIndex = 14;
this.drone3.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// drone2
//
this.drone2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.drone2.FormattingEnabled = true;
this.drone2.Items.AddRange(new object[] {
"<none>"});
this.drone2.Location = new System.Drawing.Point(70, 228);
this.drone2.Name = "drone2";
this.drone2.Size = new System.Drawing.Size(258, 21);
this.drone2.TabIndex = 13;
this.drone2.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// drone1
//
this.drone1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.drone1.FormattingEnabled = true;
this.drone1.Items.AddRange(new object[] {
"<none>"});
this.drone1.Location = new System.Drawing.Point(70, 203);
this.drone1.Name = "drone1";
this.drone1.Size = new System.Drawing.Size(258, 21);
this.drone1.TabIndex = 12;
this.drone1.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(11, 206);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(41, 13);
this.label6.TabIndex = 11;
this.label6.Text = "Drones";
//
// rig3
//
this.rig3.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.rig3.FormattingEnabled = true;
this.rig3.Items.AddRange(new object[] {
"<none>"});
this.rig3.Location = new System.Drawing.Point(70, 178);
this.rig3.Name = "rig3";
this.rig3.Size = new System.Drawing.Size(258, 21);
this.rig3.TabIndex = 10;
this.rig3.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// rig2
//
this.rig2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.rig2.FormattingEnabled = true;
this.rig2.Items.AddRange(new object[] {
"<none>"});
this.rig2.Location = new System.Drawing.Point(70, 153);
this.rig2.Name = "rig2";
this.rig2.Size = new System.Drawing.Size(258, 21);
this.rig2.TabIndex = 9;
this.rig2.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// rig1
//
this.rig1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.rig1.FormattingEnabled = true;
this.rig1.Items.AddRange(new object[] {
"<none>"});
this.rig1.Location = new System.Drawing.Point(70, 128);
this.rig1.Name = "rig1";
this.rig1.Size = new System.Drawing.Size(258, 21);
this.rig1.TabIndex = 8;
this.rig1.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(11, 131);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(28, 13);
this.label5.TabIndex = 7;
this.label5.Text = "Rigs";
//
// ship
//
this.ship.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.ship.FormattingEnabled = true;
this.ship.Location = new System.Drawing.Point(70, 28);
this.ship.Name = "ship";
this.ship.Size = new System.Drawing.Size(258, 21);
this.ship.TabIndex = 6;
this.ship.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(11, 31);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(28, 13);
this.label4.TabIndex = 5;
this.label4.Text = "Ship";
//
// low2
//
this.low2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.low2.FormattingEnabled = true;
this.low2.Items.AddRange(new object[] {
"<none>"});
this.low2.Location = new System.Drawing.Point(70, 103);
this.low2.Name = "low2";
this.low2.Size = new System.Drawing.Size(258, 21);
this.low2.TabIndex = 4;
this.low2.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// low1
//
this.low1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.low1.FormattingEnabled = true;
this.low1.Items.AddRange(new object[] {
"<none>"});
this.low1.Location = new System.Drawing.Point(70, 78);
this.low1.Name = "low1";
this.low1.Size = new System.Drawing.Size(258, 21);
this.low1.TabIndex = 3;
this.low1.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(11, 82);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(51, 13);
this.label2.TabIndex = 2;
this.label2.Text = "Low slots";
//
// high
//
this.high.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.high.FormattingEnabled = true;
this.high.Location = new System.Drawing.Point(70, 53);
this.high.Name = "high";
this.high.Size = new System.Drawing.Size(258, 21);
this.high.TabIndex = 1;
this.high.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(11, 56);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(53, 13);
this.label1.TabIndex = 0;
this.label1.Text = "High slots";
//
// mainGroupBox
//
this.mainGroupBox.Controls.Add(this.customFit);
this.mainGroupBox.Controls.Add(this.tradeHub);
this.mainGroupBox.Controls.Add(this.label3);
this.mainGroupBox.Controls.Add(this.pricesProgressBar);
this.mainGroupBox.Controls.Add(this.resultGridView);
this.mainGroupBox.Controls.Add(this.queryButton);
this.mainGroupBox.Location = new System.Drawing.Point(12, 27);
this.mainGroupBox.Name = "mainGroupBox";
this.mainGroupBox.Size = new System.Drawing.Size(360, 504);
this.mainGroupBox.TabIndex = 18;
this.mainGroupBox.TabStop = false;
this.mainGroupBox.Text = "Calculation results";
//
// harvestingTypeGroupBox
//
this.harvestingTypeGroupBox.Controls.Add(this.gasRadioButton);
this.harvestingTypeGroupBox.Controls.Add(this.iceRadioButton);
this.harvestingTypeGroupBox.Controls.Add(this.mercoxitRadioButton);
this.harvestingTypeGroupBox.Controls.Add(this.oreRadioButton);
this.harvestingTypeGroupBox.Location = new System.Drawing.Point(379, 423);
this.harvestingTypeGroupBox.Name = "harvestingTypeGroupBox";
this.harvestingTypeGroupBox.Size = new System.Drawing.Size(377, 107);
this.harvestingTypeGroupBox.TabIndex = 19;
this.harvestingTypeGroupBox.TabStop = false;
this.harvestingTypeGroupBox.Text = "Harvesting type";
//
// gasRadioButton
//
this.gasRadioButton.AutoSize = true;
this.gasRadioButton.Enabled = false;
this.gasRadioButton.Location = new System.Drawing.Point(178, 29);
this.gasRadioButton.Name = "gasRadioButton";
this.gasRadioButton.Size = new System.Drawing.Size(44, 17);
this.gasRadioButton.TabIndex = 3;
this.gasRadioButton.TabStop = true;
this.gasRadioButton.Tag = "4";
this.gasRadioButton.Text = "Gas";
this.gasRadioButton.UseVisualStyleBackColor = true;
this.gasRadioButton.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged);
//
// iceRadioButton
//
this.iceRadioButton.AutoSize = true;
this.iceRadioButton.Location = new System.Drawing.Point(132, 29);
this.iceRadioButton.Name = "iceRadioButton";
this.iceRadioButton.Size = new System.Drawing.Size(40, 17);
this.iceRadioButton.TabIndex = 2;
this.iceRadioButton.TabStop = true;
this.iceRadioButton.Tag = "3";
this.iceRadioButton.Text = "Ice";
this.iceRadioButton.UseVisualStyleBackColor = true;
this.iceRadioButton.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged);
//
// mercoxitRadioButton
//
this.mercoxitRadioButton.AutoSize = true;
this.mercoxitRadioButton.Location = new System.Drawing.Point(61, 29);
this.mercoxitRadioButton.Name = "mercoxitRadioButton";
this.mercoxitRadioButton.Size = new System.Drawing.Size(65, 17);
this.mercoxitRadioButton.TabIndex = 1;
this.mercoxitRadioButton.TabStop = true;
this.mercoxitRadioButton.Tag = "2";
this.mercoxitRadioButton.Text = "Mercoxit";
this.mercoxitRadioButton.UseVisualStyleBackColor = true;
this.mercoxitRadioButton.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged);
//
// oreRadioButton
//
this.oreRadioButton.AutoSize = true;
this.oreRadioButton.Location = new System.Drawing.Point(13, 29);
this.oreRadioButton.Name = "oreRadioButton";
this.oreRadioButton.Size = new System.Drawing.Size(42, 17);
this.oreRadioButton.TabIndex = 0;
this.oreRadioButton.TabStop = true;
this.oreRadioButton.Tag = "1";
this.oreRadioButton.Text = "Ore";
this.oreRadioButton.UseVisualStyleBackColor = true;
this.oreRadioButton.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(762, 543);
this.Controls.Add(this.harvestingTypeGroupBox);
this.Controls.Add(this.mainGroupBox);
this.Controls.Add(this.minerFitGroupBox);
this.Controls.Add(this.mainMenu);
this.Icon = ((System.Drawing.Icon) (resources.GetObject("$this.Icon")));
this.Name = "MainForm";
this.Text = "Ore efficiency calc";
this.Activated += new System.EventHandler(this.MainForm_Activated);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
((System.ComponentModel.ISupportInitialize) (this.resultGridView)).EndInit();
this.mainMenu.ResumeLayout(false);
this.mainMenu.PerformLayout();
this.minerFitGroupBox.ResumeLayout(false);
this.minerFitGroupBox.PerformLayout();
this.mainGroupBox.ResumeLayout(false);
this.mainGroupBox.PerformLayout();
this.harvestingTypeGroupBox.ResumeLayout(false);
this.harvestingTypeGroupBox.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button queryButton;
private System.Windows.Forms.DataGridView resultGridView;
private System.Windows.Forms.ProgressBar pricesProgressBar;
private System.Windows.Forms.CheckBox customFit;
private System.Windows.Forms.ComboBox tradeHub;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.MenuStrip mainMenu;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aPIToolStripMenuItem;
private System.Windows.Forms.GroupBox minerFitGroupBox;
private System.Windows.Forms.ComboBox low1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox high;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox mainGroupBox;
private System.Windows.Forms.ComboBox ship;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.ComboBox low2;
private System.Windows.Forms.DataGridViewTextBoxColumn AsteroidColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn IncomeColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn EfficiencyColumn;
private System.Windows.Forms.ComboBox drone5;
private System.Windows.Forms.ComboBox drone4;
private System.Windows.Forms.ComboBox drone3;
private System.Windows.Forms.ComboBox drone2;
private System.Windows.Forms.ComboBox drone1;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ComboBox rig3;
private System.Windows.Forms.ComboBox rig2;
private System.Windows.Forms.ComboBox rig1;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.ComboBox implant10;
private System.Windows.Forms.ComboBox implant7;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.RadioButton gasRadioButton;
private System.Windows.Forms.RadioButton iceRadioButton;
private System.Windows.Forms.RadioButton mercoxitRadioButton;
private System.Windows.Forms.RadioButton oreRadioButton;
private RadioGroupBox harvestingTypeGroupBox;
private System.Windows.Forms.ToolStripMenuItem pricesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
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.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SpatialAnalysis.Data.Statistics
{
/// <summary>
/// Interaction logic for DataStatVisualHost.xaml
/// </summary>
public partial class DataStatVisualHost : UserControl
{
#region XAxisName definition
/// <summary>
/// The x axis name property
/// </summary>
public static DependencyProperty XAxisNameProperty =
DependencyProperty.Register("X", typeof(string), typeof(DataStatVisualHost),
new FrameworkPropertyMetadata(null, DataStatVisualHost.XAxisNamePropertyChanged,
DataStatVisualHost.PropertyCoerce));
/// <summary>
/// Gets or sets the name of the x axis.
/// </summary>
/// <value>The name of the x axis.</value>
public string XAxisName
{
get { return (string)GetValue(XAxisNameProperty); }
set { SetValue(XAxisNameProperty, value); }
}
private static void XAxisNamePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DataStatVisualHost graph = (DataStatVisualHost)obj;
graph.XAxisName = (string)args.NewValue;
graph.Data1Name.Text = graph.XAxisName;
}
#endregion
#region YAxisName definition
/// <summary>
/// The y axis name property
/// </summary>
public static DependencyProperty YAxisNameProperty =
DependencyProperty.Register("Y", typeof(string), typeof(DataStatVisualHost),
new FrameworkPropertyMetadata(null, DataStatVisualHost.YAxisNamePropertyChanged,
DataStatVisualHost.PropertyCoerce));
/// <summary>
/// Gets or sets the name of the y axis.
/// </summary>
/// <value>The name of the y axis.</value>
public string YAxisName
{
get { return (string)GetValue(YAxisNameProperty); }
set { SetValue(YAxisNameProperty, value); }
}
private static void YAxisNamePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DataStatVisualHost graph = (DataStatVisualHost)obj;
graph.YAxisName = (string)args.NewValue;
graph.Data2Name.Text = graph.YAxisName;
}
#endregion
#region XMIN definition
/// <summary>
/// The xmin property
/// </summary>
public static DependencyProperty XMINProperty =
DependencyProperty.Register("XMIN", typeof(string), typeof(DataStatVisualHost),
new FrameworkPropertyMetadata(null, DataStatVisualHost.XMINPropertyChanged,
DataStatVisualHost.PropertyCoerce));
/// <summary>
/// Gets or sets the xmin.
/// </summary>
/// <value>Minimum of X values.</value>
public string XMIN
{
get { return (string)GetValue(XMINProperty); }
set { SetValue(XMINProperty, value); }
}
private static void XMINPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DataStatVisualHost graph = (DataStatVisualHost)obj;
graph.XMIN = (string)args.NewValue;
graph._xMin.Text = graph.XMIN;
}
#endregion
#region XMAX definition
/// <summary>
/// The xmax property
/// </summary>
public static DependencyProperty XMAXProperty =
DependencyProperty.Register("XMAX", typeof(string), typeof(DataStatVisualHost),
new FrameworkPropertyMetadata(null, DataStatVisualHost.XMAXPropertyChanged,
DataStatVisualHost.PropertyCoerce));
/// <summary>
/// Gets or sets the xmax.
/// </summary>
/// <value>The maximum of X values.</value>
public string XMAX
{
get { return (string)GetValue(XMAXProperty); }
set { SetValue(XMAXProperty, value); }
}
private static void XMAXPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DataStatVisualHost graph = (DataStatVisualHost)obj;
graph.XMAX = (string)args.NewValue;
graph._xMax.Text = graph.XMAX;
}
#endregion
#region YMIN definition
/// <summary>
/// The ymin property
/// </summary>
public static DependencyProperty YMINProperty =
DependencyProperty.Register("YMIN", typeof(string), typeof(DataStatVisualHost),
new FrameworkPropertyMetadata(null, DataStatVisualHost.YMINPropertyChanged,
DataStatVisualHost.PropertyCoerce));
/// <summary>
/// Gets or sets the ymin.
/// </summary>
/// <value>The minimum of Y values.</value>
public string YMIN
{
get { return (string)GetValue(YMINProperty); }
set { SetValue(YMINProperty, value); }
}
private static void YMINPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DataStatVisualHost graph = (DataStatVisualHost)obj;
graph.YMIN = (string)args.NewValue;
graph._yMin.Text = graph.YMIN;
}
#endregion
#region YMAX definition
/// <summary>
/// The ymax property
/// </summary>
public static DependencyProperty YMAXProperty =
DependencyProperty.Register("YMAX", typeof(string), typeof(DataStatVisualHost),
new FrameworkPropertyMetadata(null, DataStatVisualHost.YMAXPropertyChanged,
DataStatVisualHost.PropertyCoerce));
/// <summary>
/// Gets or sets the ymax.
/// </summary>
/// <value>The maximum of Y values.</value>
public string YMAX
{
get { return (string)GetValue(YMAXProperty); }
set { SetValue(YMAXProperty, value); }
}
private static void YMAXPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DataStatVisualHost graph = (DataStatVisualHost)obj;
graph.YMAX = (string)args.NewValue;
graph._yMax.Text = graph.YMAX;
}
#endregion
private static object PropertyCoerce(DependencyObject obj, object value)
{
return value;
}
/// <summary>
/// Initializes a new instance of the <see cref="DataStatVisualHost"/> class.
/// </summary>
public DataStatVisualHost()
{
InitializeComponent();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.AppService.Fluent
{
using Microsoft.Azure.Management.KeyVault.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System.Threading;
using System.Threading.Tasks;
internal partial class AppServiceCertificateOrderImpl
{
/// <summary>
/// Specifies the valid years of the certificate.
/// </summary>
/// <param name="years">Minimum 1 year, and maximum 3 years.</param>
/// <return>The next stage of the definition.</return>
AppServiceCertificateOrder.Definition.IWithCreate AppServiceCertificateOrder.Definition.IWithValidYears.WithValidYears(int years)
{
return this.WithValidYears(years);
}
/// <summary>
/// Specifies the SKU of the certificate to be standard. It will only provide
/// SSL support to the hostname, and www.hostname. Wildcard type will provide
/// SSL support to any sub-domain under the hostname.
/// </summary>
/// <return>The next stage of the definition.</return>
AppServiceCertificateOrder.Definition.IWithDomainVerificationFromWebApp AppServiceCertificateOrder.Definition.IWithCertificateSku.WithStandardSku()
{
return this.WithStandardSku();
}
/// <summary>
/// Specifies the SKU of the certificate to be wildcard. It will provide
/// SSL support to any sub-domain under the hostname.
/// </summary>
/// <return>The next stage of the definition.</return>
AppServiceCertificateOrder.Definition.IWithDomainVerification AppServiceCertificateOrder.Definition.IWithCertificateSku.WithWildcardSku()
{
return this.WithWildcardSku();
}
/// <summary>
/// Specifies the Azure managed domain to verify the ownership of the domain.
/// </summary>
/// <param name="domain">The Azure managed domain.</param>
/// <return>The next stage of the definition.</return>
AppServiceCertificateOrder.Definition.IWithKeyVault AppServiceCertificateOrder.Definition.IWithDomainVerification.WithDomainVerification(IAppServiceDomain domain)
{
return this.WithDomainVerification(domain);
}
/// <summary>
/// Specifies the hostname the certificate binds to.
/// </summary>
/// <param name="hostName">The bare host name, without "www". Use . prefix if it's a wild card certificate.</param>
/// <return>The next stage of the definition.</return>
AppServiceCertificateOrder.Definition.IWithCertificateSku AppServiceCertificateOrder.Definition.IWithHostName.WithHostName(string hostName)
{
return this.WithHostName(hostName);
}
/// <summary>
/// Specifies the web app to verify the ownership of the domain. The web app needs to
/// be bound to the hostname for the certificate.
/// </summary>
/// <param name="webApp">The web app bound to the hostname.</param>
/// <return>The next stage of the definition.</return>
AppServiceCertificateOrder.Definition.IWithKeyVault AppServiceCertificateOrder.Definition.IWithDomainVerificationFromWebApp.WithWebAppVerification(IWebAppBase webApp)
{
return this.WithWebAppVerification(webApp);
}
/// <summary>
/// Creates a new key vault to store the certificate private key.
/// DO NOT use this method if you are logged in from an identity without access
/// to the Active Directory Graph.
/// </summary>
/// <param name="vaultName">The name of the new key vault.</param>
/// <param name="region">The region to create the vault.</param>
/// <return>The next stage of the definition.</return>
AppServiceCertificateOrder.Definition.IWithCreate AppServiceCertificateOrder.Definition.IWithKeyVault.WithNewKeyVault(string vaultName, Region region)
{
return this.WithNewKeyVault(vaultName, region);
}
/// <summary>
/// Specifies an existing key vault to store the certificate private key.
/// The vault MUST allow 2 service principals to read/write secrets:
/// f3c21649-0979-4721-ac85-b0216b2cf413 and abfa0a7c-a6b6-4736-8310-5855508787cd.
/// If they don't have access, an attempt will be made to grant access. If you are
/// logged in from an identity without access to the Active Directory Graph, this
/// attempt will fail.
/// </summary>
/// <param name="vault">The vault to store the private key.</param>
/// <return>The next stage of the definition.</return>
AppServiceCertificateOrder.Definition.IWithCreate AppServiceCertificateOrder.Definition.IWithKeyVault.WithExistingKeyVault(IVault vault)
{
return this.WithExistingKeyVault(vault);
}
/// <summary>
/// Specifies if the certificate should be auto-renewed.
/// </summary>
/// <param name="enabled">True if the certificate order should be auto-renewed.</param>
/// <return>The next stage of the update.</return>
AppServiceCertificateOrder.Update.IUpdate AppServiceCertificateOrder.Update.IWithAutoRenew.WithAutoRenew(bool enabled)
{
return this.WithAutoRenew(enabled);
}
/// <summary>
/// Specifies if the certificate should be auto-renewed.
/// </summary>
/// <param name="enabled">True if the certificate order should be auto-renewed.</param>
/// <return>The next stage of the definition.</return>
AppServiceCertificateOrder.Definition.IWithCreate AppServiceCertificateOrder.Definition.IWithAutoRenew.WithAutoRenew(bool enabled)
{
return this.WithAutoRenew(enabled);
}
/// <summary>
/// Gets last issuance time.
/// </summary>
System.DateTime? Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.LastCertificateIssuanceTime
{
get
{
return this.LastCertificateIssuanceTime();
}
}
/// <summary>
/// Gets if the certificate should be automatically renewed upon expiration.
/// </summary>
bool Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.AutoRenew
{
get
{
return this.AutoRenew();
}
}
/// <summary>
/// Gets expiration time.
/// </summary>
System.DateTime? Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.ExpirationTime
{
get
{
return this.ExpirationTime();
}
}
/// <summary>
/// Gets the certificate product type.
/// </summary>
Models.CertificateProductType Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.ProductType
{
get
{
return this.ProductType();
}
}
/// <summary>
/// Gets last certificate signing request that was created for this order.
/// </summary>
string Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.CertificateSigningRequest
{
get
{
return this.CertificateSigningRequest();
}
}
/// <summary>
/// Gets the domain verification token.
/// </summary>
string Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.DomainVerificationToken
{
get
{
return this.DomainVerificationToken();
}
}
/// <summary>
/// Gets the certificate key size.
/// </summary>
int Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.KeySize
{
get
{
return this.KeySize();
}
}
/// <summary>
/// Gets the root certificate.
/// </summary>
Models.CertificateDetails Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.Root
{
get
{
return this.Root();
}
}
/// <summary>
/// Verifies the ownership of the domain by providing the Azure purchased domain.
/// </summary>
/// <param name="domain">The Azure managed domain.</param>
/// <return>An Observable to the result.</return>
async Task Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.VerifyDomainOwnershipAsync(IAppServiceDomain domain, CancellationToken cancellationToken)
{
await this.VerifyDomainOwnershipAsync(domain, cancellationToken);
}
/// <summary>
/// Gets current order status.
/// </summary>
Models.CertificateOrderStatus Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.Status
{
get
{
return this.Status();
}
}
/// <summary>
/// Gets the intermediate certificate.
/// </summary>
Models.CertificateDetails Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.Intermediate
{
get
{
return this.Intermediate();
}
}
/// <summary>
/// Bind a Key Vault secret to a certificate store that will be used for storing the certificate once it's ready.
/// </summary>
/// <param name="certificateName">The name of the Key Vault Secret.</param>
/// <param name="vault">The key vault to store the certificate.</param>
/// <return>A binding containing the key vault information.</return>
Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateKeyVaultBinding Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.CreateKeyVaultBinding(string certificateName, IVault vault)
{
return this.CreateKeyVaultBinding(certificateName, vault);
}
/// <summary>
/// Gets certificate's distinguished name.
/// </summary>
string Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.DistinguishedName
{
get
{
return this.DistinguishedName();
}
}
/// <return>The state of the Key Vault secret.</return>
async Task<Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateKeyVaultBinding> Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.GetKeyVaultBindingAsync(CancellationToken cancellationToken)
{
return await this.GetKeyVaultBindingAsync(cancellationToken);
}
/// <return>The state of the Key Vault secret.</return>
Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateKeyVaultBinding Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.GetKeyVaultBinding()
{
return this.GetKeyVaultBinding();
}
/// <summary>
/// Bind a Key Vault secret to a certificate store that will be used for storing the certificate once it's ready.
/// </summary>
/// <param name="certificateName">The name of the Key Vault Secret.</param>
/// <param name="vault">The key vault to store the certificate.</param>
/// <return>A binding containing the key vault information.</return>
async Task<Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateKeyVaultBinding> Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.CreateKeyVaultBindingAsync(string certificateName, IVault vault, CancellationToken cancellationToken)
{
return await this.CreateKeyVaultBindingAsync(certificateName, vault, cancellationToken);
}
/// <summary>
/// Gets current serial number of the certificate.
/// </summary>
string Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.SerialNumber
{
get
{
return this.SerialNumber();
}
}
/// <summary>
/// Verifies the ownership of the domain by providing the Azure purchased domain.
/// </summary>
/// <param name="domain">The Azure managed domain.</param>
void Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.VerifyDomainOwnership(IAppServiceDomain domain)
{
this.VerifyDomainOwnership(domain);
}
/// <summary>
/// Gets duration in years (must be between 1 and 3).
/// </summary>
int Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.ValidityInYears
{
get
{
return this.ValidityInYears();
}
}
/// <summary>
/// Gets the signed certificate.
/// </summary>
Models.CertificateDetails Microsoft.Azure.Management.AppService.Fluent.IAppServiceCertificateOrder.SignedCertificate
{
get
{
return this.SignedCertificate();
}
}
}
}
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.widget.AdapterView_))]
public abstract partial class AdapterView : android.view.ViewGroup
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected AdapterView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public partial class AdapterContextMenuInfo : java.lang.Object, android.view.ContextMenu_ContextMenuInfo
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected AdapterContextMenuInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public AdapterContextMenuInfo(android.view.View arg0, int arg1, long arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.AdapterView.AdapterContextMenuInfo._m0.native == global::System.IntPtr.Zero)
global::android.widget.AdapterView.AdapterContextMenuInfo._m0 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.AdapterContextMenuInfo.staticClass, "<init>", "(Landroid/view/View;IJ)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AdapterView.AdapterContextMenuInfo.staticClass, global::android.widget.AdapterView.AdapterContextMenuInfo._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _targetView6035;
public global::android.view.View targetView
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetObjectField(this.JvmHandle, _targetView6035)) as android.view.View;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _position6036;
public int position
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.GetIntField(this.JvmHandle, _position6036);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _id6037;
public long id
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.GetLongField(this.JvmHandle, _id6037);
}
set
{
}
}
static AdapterContextMenuInfo()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AdapterView.AdapterContextMenuInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView$AdapterContextMenuInfo"));
global::android.widget.AdapterView.AdapterContextMenuInfo._targetView6035 = @__env.GetFieldIDNoThrow(global::android.widget.AdapterView.AdapterContextMenuInfo.staticClass, "targetView", "Landroid/view/View;");
global::android.widget.AdapterView.AdapterContextMenuInfo._position6036 = @__env.GetFieldIDNoThrow(global::android.widget.AdapterView.AdapterContextMenuInfo.staticClass, "position", "I");
global::android.widget.AdapterView.AdapterContextMenuInfo._id6037 = @__env.GetFieldIDNoThrow(global::android.widget.AdapterView.AdapterContextMenuInfo.staticClass, "id", "J");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.AdapterView.OnItemClickListener_))]
public partial interface OnItemClickListener : global::MonoJavaBridge.IJavaObject
{
void onItemClick(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.AdapterView.OnItemClickListener))]
internal sealed partial class OnItemClickListener_ : java.lang.Object, OnItemClickListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnItemClickListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.widget.AdapterView.OnItemClickListener.onItemClick(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.OnItemClickListener_.staticClass, "onItemClick", "(Landroid/widget/AdapterView;Landroid/view/View;IJ)V", ref global::android.widget.AdapterView.OnItemClickListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
static OnItemClickListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AdapterView.OnItemClickListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView$OnItemClickListener"));
}
}
public delegate void OnItemClickListenerDelegate(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3);
internal partial class OnItemClickListenerDelegateWrapper : java.lang.Object, OnItemClickListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected OnItemClickListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public OnItemClickListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.AdapterView.OnItemClickListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.widget.AdapterView.OnItemClickListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.OnItemClickListenerDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AdapterView.OnItemClickListenerDelegateWrapper.staticClass, global::android.widget.AdapterView.OnItemClickListenerDelegateWrapper._m0);
Init(@__env, handle);
}
static OnItemClickListenerDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AdapterView.OnItemClickListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView_OnItemClickListenerDelegateWrapper"));
}
}
internal partial class OnItemClickListenerDelegateWrapper
{
private OnItemClickListenerDelegate myDelegate;
public void onItemClick(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3)
{
myDelegate(arg0, arg1, arg2, arg3);
}
public static implicit operator OnItemClickListenerDelegateWrapper(OnItemClickListenerDelegate d)
{
global::android.widget.AdapterView.OnItemClickListenerDelegateWrapper ret = new global::android.widget.AdapterView.OnItemClickListenerDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.AdapterView.OnItemLongClickListener_))]
public partial interface OnItemLongClickListener : global::MonoJavaBridge.IJavaObject
{
bool onItemLongClick(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.AdapterView.OnItemLongClickListener))]
internal sealed partial class OnItemLongClickListener_ : java.lang.Object, OnItemLongClickListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnItemLongClickListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
bool android.widget.AdapterView.OnItemLongClickListener.onItemLongClick(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.AdapterView.OnItemLongClickListener_.staticClass, "onItemLongClick", "(Landroid/widget/AdapterView;Landroid/view/View;IJ)Z", ref global::android.widget.AdapterView.OnItemLongClickListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
static OnItemLongClickListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AdapterView.OnItemLongClickListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView$OnItemLongClickListener"));
}
}
public delegate bool OnItemLongClickListenerDelegate(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3);
internal partial class OnItemLongClickListenerDelegateWrapper : java.lang.Object, OnItemLongClickListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected OnItemLongClickListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public OnItemLongClickListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.AdapterView.OnItemLongClickListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.widget.AdapterView.OnItemLongClickListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.OnItemLongClickListenerDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AdapterView.OnItemLongClickListenerDelegateWrapper.staticClass, global::android.widget.AdapterView.OnItemLongClickListenerDelegateWrapper._m0);
Init(@__env, handle);
}
static OnItemLongClickListenerDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AdapterView.OnItemLongClickListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView_OnItemLongClickListenerDelegateWrapper"));
}
}
internal partial class OnItemLongClickListenerDelegateWrapper
{
private OnItemLongClickListenerDelegate myDelegate;
public bool onItemLongClick(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3)
{
return myDelegate(arg0, arg1, arg2, arg3);
}
public static implicit operator OnItemLongClickListenerDelegateWrapper(OnItemLongClickListenerDelegate d)
{
global::android.widget.AdapterView.OnItemLongClickListenerDelegateWrapper ret = new global::android.widget.AdapterView.OnItemLongClickListenerDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.AdapterView.OnItemSelectedListener_))]
public partial interface OnItemSelectedListener : global::MonoJavaBridge.IJavaObject
{
void onItemSelected(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3);
void onNothingSelected(android.widget.AdapterView arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.AdapterView.OnItemSelectedListener))]
internal sealed partial class OnItemSelectedListener_ : java.lang.Object, OnItemSelectedListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnItemSelectedListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.widget.AdapterView.OnItemSelectedListener.onItemSelected(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.OnItemSelectedListener_.staticClass, "onItemSelected", "(Landroid/widget/AdapterView;Landroid/view/View;IJ)V", ref global::android.widget.AdapterView.OnItemSelectedListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m1;
void android.widget.AdapterView.OnItemSelectedListener.onNothingSelected(android.widget.AdapterView arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.OnItemSelectedListener_.staticClass, "onNothingSelected", "(Landroid/widget/AdapterView;)V", ref global::android.widget.AdapterView.OnItemSelectedListener_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static OnItemSelectedListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AdapterView.OnItemSelectedListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView$OnItemSelectedListener"));
}
}
private static global::MonoJavaBridge.MethodId _m0;
public override bool dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.AdapterView.staticClass, "dispatchPopulateAccessibilityEvent", "(Landroid/view/accessibility/AccessibilityEvent;)Z", ref global::android.widget.AdapterView._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public override void addView(android.view.View arg0, int arg1, android.view.ViewGroup.LayoutParams arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "addView", "(Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;)V", ref global::android.widget.AdapterView._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m2;
public override void addView(android.view.View arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "addView", "(Landroid/view/View;)V", ref global::android.widget.AdapterView._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
public override void addView(android.view.View arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "addView", "(Landroid/view/View;I)V", ref global::android.widget.AdapterView._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m4;
public override void addView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "addView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V", ref global::android.widget.AdapterView._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m5;
public override void removeView(android.view.View arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "removeView", "(Landroid/view/View;)V", ref global::android.widget.AdapterView._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public override void setOnClickListener(android.view.View.OnClickListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "setOnClickListener", "(Landroid/view/View$OnClickListener;)V", ref global::android.widget.AdapterView._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setOnClickListener(global::android.view.View.OnClickListenerDelegate arg0)
{
setOnClickListener((global::android.view.View.OnClickListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m7;
public override void setFocusable(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "setFocusable", "(Z)V", ref global::android.widget.AdapterView._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m8;
public override void setFocusableInTouchMode(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "setFocusableInTouchMode", "(Z)V", ref global::android.widget.AdapterView._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m9;
protected override void dispatchSaveInstanceState(android.util.SparseArray arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "dispatchSaveInstanceState", "(Landroid/util/SparseArray;)V", ref global::android.widget.AdapterView._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
protected override void dispatchRestoreInstanceState(android.util.SparseArray arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "dispatchRestoreInstanceState", "(Landroid/util/SparseArray;)V", ref global::android.widget.AdapterView._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m11;
protected override void onLayout(bool arg0, int arg1, int arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "onLayout", "(ZIIII)V", ref global::android.widget.AdapterView._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual int getCount()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.AdapterView.staticClass, "getCount", "()I", ref global::android.widget.AdapterView._m12);
}
private static global::MonoJavaBridge.MethodId _m13;
public override void removeViewAt(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "removeViewAt", "(I)V", ref global::android.widget.AdapterView._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m14;
public override void removeAllViews()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "removeAllViews", "()V", ref global::android.widget.AdapterView._m14);
}
private static global::MonoJavaBridge.MethodId _m15;
protected override bool canAnimate()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.AdapterView.staticClass, "canAnimate", "()Z", ref global::android.widget.AdapterView._m15);
}
private static global::MonoJavaBridge.MethodId _m16;
public abstract void setAdapter(android.widget.Adapter arg0);
private static global::MonoJavaBridge.MethodId _m17;
public virtual void setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "setOnItemSelectedListener", "(Landroid/widget/AdapterView$OnItemSelectedListener;)V", ref global::android.widget.AdapterView._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual void setOnItemClickListener(android.widget.AdapterView.OnItemClickListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "setOnItemClickListener", "(Landroid/widget/AdapterView$OnItemClickListener;)V", ref global::android.widget.AdapterView._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setOnItemClickListener(global::android.widget.AdapterView.OnItemClickListenerDelegate arg0)
{
setOnItemClickListener((global::android.widget.AdapterView.OnItemClickListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual global::android.widget.AdapterView.OnItemClickListener getOnItemClickListener()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.widget.AdapterView.OnItemClickListener>(this, global::android.widget.AdapterView.staticClass, "getOnItemClickListener", "()Landroid/widget/AdapterView$OnItemClickListener;", ref global::android.widget.AdapterView._m19) as android.widget.AdapterView.OnItemClickListener;
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual bool performItemClick(android.view.View arg0, int arg1, long arg2)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.AdapterView.staticClass, "performItemClick", "(Landroid/view/View;IJ)Z", ref global::android.widget.AdapterView._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual void setOnItemLongClickListener(android.widget.AdapterView.OnItemLongClickListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "setOnItemLongClickListener", "(Landroid/widget/AdapterView$OnItemLongClickListener;)V", ref global::android.widget.AdapterView._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setOnItemLongClickListener(global::android.widget.AdapterView.OnItemLongClickListenerDelegate arg0)
{
setOnItemLongClickListener((global::android.widget.AdapterView.OnItemLongClickListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual global::android.widget.AdapterView.OnItemLongClickListener getOnItemLongClickListener()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.widget.AdapterView.OnItemLongClickListener>(this, global::android.widget.AdapterView.staticClass, "getOnItemLongClickListener", "()Landroid/widget/AdapterView$OnItemLongClickListener;", ref global::android.widget.AdapterView._m22) as android.widget.AdapterView.OnItemLongClickListener;
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual global::android.widget.AdapterView.OnItemSelectedListener getOnItemSelectedListener()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.widget.AdapterView.OnItemSelectedListener>(this, global::android.widget.AdapterView.staticClass, "getOnItemSelectedListener", "()Landroid/widget/AdapterView$OnItemSelectedListener;", ref global::android.widget.AdapterView._m23) as android.widget.AdapterView.OnItemSelectedListener;
}
private static global::MonoJavaBridge.MethodId _m24;
public abstract global::android.widget.Adapter getAdapter();
private static global::MonoJavaBridge.MethodId _m25;
public virtual int getSelectedItemPosition()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.AdapterView.staticClass, "getSelectedItemPosition", "()I", ref global::android.widget.AdapterView._m25);
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual long getSelectedItemId()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.widget.AdapterView.staticClass, "getSelectedItemId", "()J", ref global::android.widget.AdapterView._m26);
}
private static global::MonoJavaBridge.MethodId _m27;
public abstract global::android.view.View getSelectedView();
private static global::MonoJavaBridge.MethodId _m28;
public virtual global::java.lang.Object getSelectedItem()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.AdapterView.staticClass, "getSelectedItem", "()Ljava/lang/Object;", ref global::android.widget.AdapterView._m28) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual int getPositionForView(android.view.View arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.AdapterView.staticClass, "getPositionForView", "(Landroid/view/View;)I", ref global::android.widget.AdapterView._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m30;
public virtual int getFirstVisiblePosition()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.AdapterView.staticClass, "getFirstVisiblePosition", "()I", ref global::android.widget.AdapterView._m30);
}
private static global::MonoJavaBridge.MethodId _m31;
public virtual int getLastVisiblePosition()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.AdapterView.staticClass, "getLastVisiblePosition", "()I", ref global::android.widget.AdapterView._m31);
}
private static global::MonoJavaBridge.MethodId _m32;
public abstract void setSelection(int arg0);
private static global::MonoJavaBridge.MethodId _m33;
public virtual void setEmptyView(android.view.View arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView.staticClass, "setEmptyView", "(Landroid/view/View;)V", ref global::android.widget.AdapterView._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m34;
public virtual global::android.view.View getEmptyView()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.AdapterView.staticClass, "getEmptyView", "()Landroid/view/View;", ref global::android.widget.AdapterView._m34) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m35;
public virtual global::java.lang.Object getItemAtPosition(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.AdapterView.staticClass, "getItemAtPosition", "(I)Ljava/lang/Object;", ref global::android.widget.AdapterView._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m36;
public virtual long getItemIdAtPosition(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.widget.AdapterView.staticClass, "getItemIdAtPosition", "(I)J", ref global::android.widget.AdapterView._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m37;
public AdapterView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.AdapterView._m37.native == global::System.IntPtr.Zero)
global::android.widget.AdapterView._m37 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AdapterView.staticClass, global::android.widget.AdapterView._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m38;
public AdapterView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.AdapterView._m38.native == global::System.IntPtr.Zero)
global::android.widget.AdapterView._m38 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AdapterView.staticClass, global::android.widget.AdapterView._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m39;
public AdapterView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.AdapterView._m39.native == global::System.IntPtr.Zero)
global::android.widget.AdapterView._m39 = @__env.GetMethodIDNoThrow(global::android.widget.AdapterView.staticClass, "<init>", "(Landroid/content/Context;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AdapterView.staticClass, global::android.widget.AdapterView._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
public static int ITEM_VIEW_TYPE_IGNORE
{
get
{
return -1;
}
}
public static int ITEM_VIEW_TYPE_HEADER_OR_FOOTER
{
get
{
return -2;
}
}
public static int INVALID_POSITION
{
get
{
return -1;
}
}
public static long INVALID_ROW_ID
{
get
{
return -9223372036854775808L;
}
}
static AdapterView()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AdapterView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.AdapterView))]
internal sealed partial class AdapterView_ : android.widget.AdapterView
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal AdapterView_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override void setAdapter(android.widget.Adapter arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView_.staticClass, "setAdapter", "(Landroid/widget/Adapter;)V", ref global::android.widget.AdapterView_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public override global::android.widget.Adapter getAdapter()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.widget.Adapter>(this, global::android.widget.AdapterView_.staticClass, "getAdapter", "()Landroid/widget/Adapter;", ref global::android.widget.AdapterView_._m1) as android.widget.Adapter;
}
private static global::MonoJavaBridge.MethodId _m2;
public override global::android.view.View getSelectedView()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.AdapterView_.staticClass, "getSelectedView", "()Landroid/view/View;", ref global::android.widget.AdapterView_._m2) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m3;
public override void setSelection(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.AdapterView_.staticClass, "setSelection", "(I)V", ref global::android.widget.AdapterView_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static AdapterView_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AdapterView_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AdapterView"));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Data.Common;
namespace System.Data.OleDb
{
internal enum DBStatus
{ // from 4214.0
S_OK = 0,
E_BADACCESSOR = 1,
E_CANTCONVERTVALUE = 2,
S_ISNULL = 3,
S_TRUNCATED = 4,
E_SIGNMISMATCH = 5,
E_DATAOVERFLOW = 6,
E_CANTCREATE = 7,
E_UNAVAILABLE = 8,
E_PERMISSIONDENIED = 9,
E_INTEGRITYVIOLATION = 10,
E_SCHEMAVIOLATION = 11,
E_BADSTATUS = 12,
S_DEFAULT = 13,
S_CELLEMPTY = 14, // 2.0
S_IGNORE = 15, // 2.0
E_DOESNOTEXIST = 16, // 2.1
E_INVALIDURL = 17, // 2.1
E_RESOURCELOCKED = 18, // 2.1
E_RESOURCEEXISTS = 19, // 2.1
E_CANNOTCOMPLETE = 20, // 2.1
E_VOLUMENOTFOUND = 21, // 2.1
E_OUTOFSPACE = 22, // 2.1
S_CANNOTDELETESOURCE = 23, // 2.1
E_READONLY = 24, // 2.1
E_RESOURCEOUTOFSCOPE = 25, // 2.1
S_ALREADYEXISTS = 26, // 2.1
E_CANCELED = 27, // 2.5
E_NOTCOLLECTION = 28, // 2.5
S_ROWSETCOLUMN = 29, // 2.6
}
internal sealed class NativeDBType
{ // from 4214.0
// Variant compatible
internal const short EMPTY = 0; //
internal const short NULL = 1; //
internal const short I2 = 2; //
internal const short I4 = 3; //
internal const short R4 = 4; //
internal const short R8 = 5; //
internal const short CY = 6; //
internal const short DATE = 7; //
internal const short BSTR = 8; //
internal const short IDISPATCH = 9; //
internal const short ERROR = 10; //
internal const short BOOL = 11; //
internal const short VARIANT = 12; //
internal const short IUNKNOWN = 13; //
internal const short DECIMAL = 14; //
internal const short I1 = 16; //
internal const short UI1 = 17; //
internal const short UI2 = 18; //
internal const short UI4 = 19; //
internal const short I8 = 20; //
internal const short UI8 = 21; //
internal const short FILETIME = 64; // 2.0
internal const short DBUTCDATETIME = 65; // 9.0
internal const short DBTIME_EX = 66; // 9.0
internal const short GUID = 72; //
internal const short BYTES = 128; //
internal const short STR = 129; //
internal const short WSTR = 130; //
internal const short NUMERIC = 131; // with potential overflow
internal const short UDT = 132; // should never be encountered
internal const short DBDATE = 133; //
internal const short DBTIME = 134; //
internal const short DBTIMESTAMP = 135; // granularity reduced from 1ns to 100ns (sql is 3.33 milli seconds)
internal const short HCHAPTER = 136; // 1.5
internal const short PROPVARIANT = 138; // 2.0 - as variant
internal const short VARNUMERIC = 139; // 2.0 - as string else ConversionException
internal const short XML = 141; // 9.0
internal const short VECTOR = unchecked((short)0x1000);
internal const short ARRAY = unchecked((short)0x2000);
internal const short BYREF = unchecked((short)0x4000); //
internal const short RESERVED = unchecked((short)0x8000); // SystemException
// high mask
internal const short HighMask = unchecked((short)0xf000);
private const string S_BINARY = "DBTYPE_BINARY"; // DBTYPE_BYTES
private const string S_BOOL = "DBTYPE_BOOL";
private const string S_BSTR = "DBTYPE_BSTR";
private const string S_CHAR = "DBTYPE_CHAR"; // DBTYPE_STR
private const string S_CY = "DBTYPE_CY";
private const string S_DATE = "DBTYPE_DATE";
private const string S_DBDATE = "DBTYPE_DBDATE";
private const string S_DBTIME = "DBTYPE_DBTIME";
private const string S_DBTIMESTAMP = "DBTYPE_DBTIMESTAMP";
private const string S_DECIMAL = "DBTYPE_DECIMAL";
private const string S_ERROR = "DBTYPE_ERROR";
private const string S_FILETIME = "DBTYPE_FILETIME";
private const string S_GUID = "DBTYPE_GUID";
private const string S_I1 = "DBTYPE_I1";
private const string S_I2 = "DBTYPE_I2";
private const string S_I4 = "DBTYPE_I4";
private const string S_I8 = "DBTYPE_I8";
private const string S_IDISPATCH = "DBTYPE_IDISPATCH";
private const string S_IUNKNOWN = "DBTYPE_IUNKNOWN";
private const string S_LONGVARBINARY = "DBTYPE_LONGVARBINARY"; // DBTYPE_BYTES
private const string S_LONGVARCHAR = "DBTYPE_LONGVARCHAR"; // DBTYPE_STR
private const string S_NUMERIC = "DBTYPE_NUMERIC";
private const string S_PROPVARIANT = "DBTYPE_PROPVARIANT";
private const string S_R4 = "DBTYPE_R4";
private const string S_R8 = "DBTYPE_R8";
private const string S_UDT = "DBTYPE_UDT";
private const string S_UI1 = "DBTYPE_UI1";
private const string S_UI2 = "DBTYPE_UI2";
private const string S_UI4 = "DBTYPE_UI4";
private const string S_UI8 = "DBTYPE_UI8";
private const string S_VARBINARY = "DBTYPE_VARBINARY"; // DBTYPE_BYTES
private const string S_VARCHAR = "DBTYPE_VARCHAR"; // DBTYPE_STR
private const string S_VARIANT = "DBTYPE_VARIANT";
private const string S_VARNUMERIC = "DBTYPE_VARNUMERIC";
private const string S_WCHAR = "DBTYPE_WCHAR"; // DBTYPE_WSTR
private const string S_WVARCHAR = "DBTYPE_WVARCHAR"; // DBTYPE_WSTR
private const string S_WLONGVARCHAR = "DBTYPE_WLONGVARCHAR"; // DBTYPE_WSTR
private const string S_XML = "DBTYPE_XML";
private static readonly NativeDBType D_Binary = new NativeDBType(0xff, -1, true, false, OleDbType.Binary, NativeDBType.BYTES, S_BINARY, typeof(byte[]), NativeDBType.BYTES, DbType.Binary); // 0
private static readonly NativeDBType D_Boolean = new NativeDBType(0xff, 2, true, false, OleDbType.Boolean, NativeDBType.BOOL, S_BOOL, typeof(bool), NativeDBType.BOOL, DbType.Boolean); // 1 - integer2 (variant_bool)
private static readonly NativeDBType D_BSTR = new NativeDBType(0xff, ADP.PtrSize, false, false, OleDbType.BSTR, NativeDBType.BSTR, S_BSTR, typeof(string), NativeDBType.BSTR, DbType.String); // 2 - integer4 (pointer)
private static readonly NativeDBType D_Char = new NativeDBType(0xff, -1, true, false, OleDbType.Char, NativeDBType.STR, S_CHAR, typeof(string), NativeDBType.WSTR/*STR*/, DbType.AnsiStringFixedLength); // 3 - (ansi pointer)
private static readonly NativeDBType D_Currency = new NativeDBType(19, 8, true, false, OleDbType.Currency, NativeDBType.CY, S_CY, typeof(decimal), NativeDBType.CY, DbType.Currency); // 4 - integer8
private static readonly NativeDBType D_Date = new NativeDBType(0xff, 8, true, false, OleDbType.Date, NativeDBType.DATE, S_DATE, typeof(System.DateTime), NativeDBType.DATE, DbType.DateTime); // 5 - double
private static readonly NativeDBType D_DBDate = new NativeDBType(0xff, 6, true, false, OleDbType.DBDate, NativeDBType.DBDATE, S_DBDATE, typeof(System.DateTime), NativeDBType.DBDATE, DbType.Date); // 6 - (tagDBDate)
private static readonly NativeDBType D_DBTime = new NativeDBType(0xff, 6, true, false, OleDbType.DBTime, NativeDBType.DBTIME, S_DBTIME, typeof(System.TimeSpan), NativeDBType.DBTIME, DbType.Time); // 7 - (tagDBTime)
private static readonly NativeDBType D_DBTimeStamp = new NativeDBType(0xff, 16, true, false, OleDbType.DBTimeStamp, NativeDBType.DBTIMESTAMP, S_DBTIMESTAMP, typeof(System.DateTime), NativeDBType.DBTIMESTAMP, DbType.DateTime); // 8 - (tagDBTIMESTAMP)
private static readonly NativeDBType D_Decimal = new NativeDBType(28, 16, true, false, OleDbType.Decimal, NativeDBType.DECIMAL, S_DECIMAL, typeof(decimal), NativeDBType.DECIMAL, DbType.Decimal); // 9 - (tagDec)
private static readonly NativeDBType D_Error = new NativeDBType(0xff, 4, true, false, OleDbType.Error, NativeDBType.ERROR, S_ERROR, typeof(int), NativeDBType.ERROR, DbType.Int32); // 10 - integer4
private static readonly NativeDBType D_Filetime = new NativeDBType(0xff, 8, true, false, OleDbType.Filetime, NativeDBType.FILETIME, S_FILETIME, typeof(System.DateTime), NativeDBType.FILETIME, DbType.DateTime); // 11 - integer8
private static readonly NativeDBType D_Guid = new NativeDBType(0xff, 16, true, false, OleDbType.Guid, NativeDBType.GUID, S_GUID, typeof(System.Guid), NativeDBType.GUID, DbType.Guid); // 12 - ubyte[16]
private static readonly NativeDBType D_TinyInt = new NativeDBType(3, 1, true, false, OleDbType.TinyInt, NativeDBType.I1, S_I1, typeof(short), NativeDBType.I1, DbType.SByte); // 13 - integer1
private static readonly NativeDBType D_SmallInt = new NativeDBType(5, 2, true, false, OleDbType.SmallInt, NativeDBType.I2, S_I2, typeof(short), NativeDBType.I2, DbType.Int16); // 14 - integer2
private static readonly NativeDBType D_Integer = new NativeDBType(10, 4, true, false, OleDbType.Integer, NativeDBType.I4, S_I4, typeof(int), NativeDBType.I4, DbType.Int32); // 15 - integer4
private static readonly NativeDBType D_BigInt = new NativeDBType(19, 8, true, false, OleDbType.BigInt, NativeDBType.I8, S_I8, typeof(long), NativeDBType.I8, DbType.Int64); // 16 - integer8
private static readonly NativeDBType D_IDispatch = new NativeDBType(0xff, ADP.PtrSize, true, false, OleDbType.IDispatch, NativeDBType.IDISPATCH, S_IDISPATCH, typeof(object), NativeDBType.IDISPATCH, DbType.Object); // 17 - integer4 (pointer)
private static readonly NativeDBType D_IUnknown = new NativeDBType(0xff, ADP.PtrSize, true, false, OleDbType.IUnknown, NativeDBType.IUNKNOWN, S_IUNKNOWN, typeof(object), NativeDBType.IUNKNOWN, DbType.Object); // 18 - integer4 (pointer)
private static readonly NativeDBType D_LongVarBinary = new NativeDBType(0xff, -1, false, true, OleDbType.LongVarBinary, NativeDBType.BYTES, S_LONGVARBINARY, typeof(byte[]), NativeDBType.BYTES, DbType.Binary); // 19
private static readonly NativeDBType D_LongVarChar = new NativeDBType(0xff, -1, false, true, OleDbType.LongVarChar, NativeDBType.STR, S_LONGVARCHAR, typeof(string), NativeDBType.WSTR/*STR*/, DbType.AnsiString); // 20 - (ansi pointer)
private static readonly NativeDBType D_Numeric = new NativeDBType(28, 19, true, false, OleDbType.Numeric, NativeDBType.NUMERIC, S_NUMERIC, typeof(decimal), NativeDBType.NUMERIC, DbType.Decimal); // 21 - (tagDB_Numeric)
private static readonly unsafe NativeDBType D_PropVariant = new NativeDBType(0xff, sizeof(PROPVARIANT),
true, false, OleDbType.PropVariant, NativeDBType.PROPVARIANT, S_PROPVARIANT, typeof(object), NativeDBType.VARIANT, DbType.Object); // 22
private static readonly NativeDBType D_Single = new NativeDBType(7, 4, true, false, OleDbType.Single, NativeDBType.R4, S_R4, typeof(float), NativeDBType.R4, DbType.Single); // 23 - single
private static readonly NativeDBType D_Double = new NativeDBType(15, 8, true, false, OleDbType.Double, NativeDBType.R8, S_R8, typeof(double), NativeDBType.R8, DbType.Double); // 24 - double
private static readonly NativeDBType D_UnsignedTinyInt = new NativeDBType(3, 1, true, false, OleDbType.UnsignedTinyInt, NativeDBType.UI1, S_UI1, typeof(byte), NativeDBType.UI1, DbType.Byte); // 25 - byte7
private static readonly NativeDBType D_UnsignedSmallInt = new NativeDBType(5, 2, true, false, OleDbType.UnsignedSmallInt, NativeDBType.UI2, S_UI2, typeof(int), NativeDBType.UI2, DbType.UInt16); // 26 - unsigned integer2
private static readonly NativeDBType D_UnsignedInt = new NativeDBType(10, 4, true, false, OleDbType.UnsignedInt, NativeDBType.UI4, S_UI4, typeof(long), NativeDBType.UI4, DbType.UInt32); // 27 - unsigned integer4
private static readonly NativeDBType D_UnsignedBigInt = new NativeDBType(20, 8, true, false, OleDbType.UnsignedBigInt, NativeDBType.UI8, S_UI8, typeof(decimal), NativeDBType.UI8, DbType.UInt64); // 28 - unsigned integer8
private static readonly NativeDBType D_VarBinary = new NativeDBType(0xff, -1, false, false, OleDbType.VarBinary, NativeDBType.BYTES, S_VARBINARY, typeof(byte[]), NativeDBType.BYTES, DbType.Binary); // 29
private static readonly NativeDBType D_VarChar = new NativeDBType(0xff, -1, false, false, OleDbType.VarChar, NativeDBType.STR, S_VARCHAR, typeof(string), NativeDBType.WSTR/*STR*/, DbType.AnsiString); // 30 - (ansi pointer)
private static readonly NativeDBType D_Variant = new NativeDBType(0xff, ODB.SizeOf_Variant, true, false, OleDbType.Variant, NativeDBType.VARIANT, S_VARIANT, typeof(object), NativeDBType.VARIANT, DbType.Object); // 31 - ubyte[16] (variant)
private static readonly NativeDBType D_VarNumeric = new NativeDBType(255, 16, true, false, OleDbType.VarNumeric, NativeDBType.VARNUMERIC, S_VARNUMERIC, typeof(decimal), NativeDBType.DECIMAL, DbType.VarNumeric); // 32 - (unicode pointer)
private static readonly NativeDBType D_WChar = new NativeDBType(0xff, -1, true, false, OleDbType.WChar, NativeDBType.WSTR, S_WCHAR, typeof(string), NativeDBType.WSTR, DbType.StringFixedLength); // 33 - (unicode pointer)
private static readonly NativeDBType D_VarWChar = new NativeDBType(0xff, -1, false, false, OleDbType.VarWChar, NativeDBType.WSTR, S_WVARCHAR, typeof(string), NativeDBType.WSTR, DbType.String); // 34 - (unicode pointer)
private static readonly NativeDBType D_LongVarWChar = new NativeDBType(0xff, -1, false, true, OleDbType.LongVarWChar, NativeDBType.WSTR, S_WLONGVARCHAR, typeof(string), NativeDBType.WSTR, DbType.String); // 35 - (unicode pointer)
private static readonly NativeDBType D_Chapter = new NativeDBType(0xff, ADP.PtrSize, false, false, OleDbType.Empty, NativeDBType.HCHAPTER, S_UDT, typeof(IDataReader), NativeDBType.HCHAPTER, DbType.Object); // 36 - (hierarchical chaper)
private static readonly NativeDBType D_Empty = new NativeDBType(0xff, 0, false, false, OleDbType.Empty, NativeDBType.EMPTY, "", null, NativeDBType.EMPTY, DbType.Object); // 37 - invalid param default
private static readonly NativeDBType D_Xml = new NativeDBType(0xff, -1, false, false, OleDbType.VarWChar, NativeDBType.XML, S_XML, typeof(string), NativeDBType.WSTR, DbType.String); // 38 - (unicode pointer)
private static readonly NativeDBType D_Udt = new NativeDBType(0xff, -1, false, false, OleDbType.VarBinary, NativeDBType.UDT, S_BINARY, typeof(byte[]), NativeDBType.BYTES, DbType.Binary); // 39 - (unicode pointer)
internal static readonly NativeDBType Default = D_VarWChar;
internal static readonly byte MaximumDecimalPrecision = D_Decimal.maxpre;
private const int FixedDbPart = /*DBPART_VALUE*/0x1 | /*DBPART_STATUS*/0x4;
private const int VarblDbPart = /*DBPART_VALUE*/0x1 | /*DBPART_LENGTH*/0x2 | /*DBPART_STATUS*/0x4;
internal readonly OleDbType enumOleDbType; // enum System.Data.OleDb.OleDbType
internal readonly DbType enumDbType; // enum System.Data.DbType
internal readonly short dbType; // OLE DB DBTYPE_
internal readonly short wType; // OLE DB DBTYPE_ we ask OleDB Provider to bind as
internal readonly Type dataType; // CLR Type
internal readonly int dbPart; // the DBPart w or w/out length
internal readonly bool isfixed; // IsFixedLength
internal readonly bool islong; // IsLongLength
internal readonly byte maxpre; // maxium precision for numeric types // $CONSIDER - are we going to use this?
internal readonly int fixlen; // fixed length size in bytes (-1 for variable)
internal readonly string dataSourceType; // ICommandWithParameters.SetParameterInfo standard type name
internal readonly StringMemHandle dbString; // ptr to native allocated memory for dataSourceType string
private NativeDBType(byte maxpre, int fixlen, bool isfixed, bool islong, OleDbType enumOleDbType, short dbType, string dbstring, Type dataType, short wType, DbType enumDbType)
{
this.enumOleDbType = enumOleDbType;
this.dbType = dbType;
this.dbPart = (-1 == fixlen) ? VarblDbPart : FixedDbPart;
this.isfixed = isfixed;
this.islong = islong;
this.maxpre = maxpre;
this.fixlen = fixlen;
this.wType = wType;
this.dataSourceType = dbstring;
this.dbString = new StringMemHandle(dbstring);
this.dataType = dataType;
this.enumDbType = enumDbType;
}
internal bool IsVariableLength
{
get
{
return (-1 == fixlen);
}
}
#if DEBUG
public override string ToString()
{
return enumOleDbType.ToString();
}
#endif
internal static NativeDBType FromDataType(OleDbType enumOleDbType) =>
enumOleDbType switch
{
OleDbType.Empty => D_Empty, // 0
OleDbType.SmallInt => D_SmallInt, // 2
OleDbType.Integer => D_Integer, // 3
OleDbType.Single => D_Single, // 4
OleDbType.Double => D_Double, // 5
OleDbType.Currency => D_Currency, // 6
OleDbType.Date => D_Date, // 7
OleDbType.BSTR => D_BSTR, // 8
OleDbType.IDispatch => D_IDispatch, // 9
OleDbType.Error => D_Error, // 10
OleDbType.Boolean => D_Boolean, // 11
OleDbType.Variant => D_Variant, // 12
OleDbType.IUnknown => D_IUnknown, // 13
OleDbType.Decimal => D_Decimal, // 14
OleDbType.TinyInt => D_TinyInt, // 16
OleDbType.UnsignedTinyInt => D_UnsignedTinyInt, // 17
OleDbType.UnsignedSmallInt => D_UnsignedSmallInt, // 18
OleDbType.UnsignedInt => D_UnsignedInt, // 19
OleDbType.BigInt => D_BigInt, // 20
OleDbType.UnsignedBigInt => D_UnsignedBigInt, // 21
OleDbType.Filetime => D_Filetime, // 64
OleDbType.Guid => D_Guid, // 72
OleDbType.Binary => D_Binary, // 128
OleDbType.Char => D_Char, // 129
OleDbType.WChar => D_WChar, // 130
OleDbType.Numeric => D_Numeric, // 131
OleDbType.DBDate => D_DBDate, // 133
OleDbType.DBTime => D_DBTime, // 134
OleDbType.DBTimeStamp => D_DBTimeStamp, // 135
OleDbType.PropVariant => D_PropVariant, // 138
OleDbType.VarNumeric => D_VarNumeric, // 139
OleDbType.VarChar => D_VarChar, // 200
OleDbType.LongVarChar => D_LongVarChar, // 201
OleDbType.VarWChar => D_VarWChar, // 202: ORA-12704: character set mismatch
OleDbType.LongVarWChar => D_LongVarWChar, // 203
OleDbType.VarBinary => D_VarBinary, // 204
OleDbType.LongVarBinary => D_LongVarBinary, // 205
_ => throw ODB.InvalidOleDbType(enumOleDbType),
};
internal static NativeDBType FromSystemType(object value)
{
IConvertible ic = (value as IConvertible);
if (null != ic)
{
return ic.GetTypeCode() switch
{
TypeCode.Empty => NativeDBType.D_Empty,
TypeCode.Object => NativeDBType.D_Variant,
TypeCode.DBNull => throw ADP.InvalidDataType(TypeCode.DBNull),
TypeCode.Boolean => NativeDBType.D_Boolean,
TypeCode.Char => NativeDBType.D_Char,
TypeCode.SByte => NativeDBType.D_TinyInt,
TypeCode.Byte => NativeDBType.D_UnsignedTinyInt,
TypeCode.Int16 => NativeDBType.D_SmallInt,
TypeCode.UInt16 => NativeDBType.D_UnsignedSmallInt,
TypeCode.Int32 => NativeDBType.D_Integer,
TypeCode.UInt32 => NativeDBType.D_UnsignedInt,
TypeCode.Int64 => NativeDBType.D_BigInt,
TypeCode.UInt64 => NativeDBType.D_UnsignedBigInt,
TypeCode.Single => NativeDBType.D_Single,
TypeCode.Double => NativeDBType.D_Double,
TypeCode.Decimal => NativeDBType.D_Decimal,
TypeCode.DateTime => NativeDBType.D_DBTimeStamp,
TypeCode.String => NativeDBType.D_VarWChar,
_ => throw ADP.UnknownDataTypeCode(value.GetType(), ic.GetTypeCode()),
};
}
else if (value is byte[])
{
return NativeDBType.D_VarBinary;
}
else if (value is System.Guid)
{
return NativeDBType.D_Guid;
}
else if (value is System.TimeSpan)
{
return NativeDBType.D_DBTime;
}
else
{
return NativeDBType.D_Variant;
}
//throw ADP.UnknownDataType(value.GetType());
}
internal static NativeDBType FromDbType(DbType dbType) =>
dbType switch
{
DbType.AnsiString => D_VarChar,
DbType.AnsiStringFixedLength => D_Char,
DbType.Binary => D_VarBinary,
DbType.Byte => D_UnsignedTinyInt,
DbType.Boolean => D_Boolean,
DbType.Currency => D_Currency,
DbType.Date => D_DBDate,
DbType.DateTime => D_DBTimeStamp,
DbType.Decimal => D_Decimal,
DbType.Double => D_Double,
DbType.Guid => D_Guid,
DbType.Int16 => D_SmallInt,
DbType.Int32 => D_Integer,
DbType.Int64 => D_BigInt,
DbType.Object => D_Variant,
DbType.SByte => D_TinyInt,
DbType.Single => D_Single,
DbType.String => D_VarWChar,
DbType.StringFixedLength => D_WChar,
DbType.Time => D_DBTime,
DbType.UInt16 => D_UnsignedSmallInt,
DbType.UInt32 => D_UnsignedInt,
DbType.UInt64 => D_UnsignedBigInt,
DbType.VarNumeric => D_VarNumeric,
DbType.Xml => D_Xml,
_ => throw ADP.DbTypeNotSupported(dbType, typeof(OleDbType)),
};
internal static NativeDBType FromDBType(short dbType, bool isLong, bool isFixed)
{
switch (dbType)
{
//case EMPTY:
//case NULL:
case I2:
return D_SmallInt;
case I4:
return D_Integer;
case R4:
return D_Single;
case R8:
return D_Double;
case CY:
return D_Currency;
case DATE:
return D_Date;
case BSTR:
return D_BSTR;
case IDISPATCH:
return D_IDispatch;
case ERROR:
return D_Error;
case BOOL:
return D_Boolean;
case VARIANT:
return D_Variant;
case IUNKNOWN:
return D_IUnknown;
case DECIMAL:
return D_Decimal;
case I1:
return D_TinyInt;
case UI1:
return D_UnsignedTinyInt;
case UI2:
return D_UnsignedSmallInt;
case UI4:
return D_UnsignedInt;
case I8:
return D_BigInt;
case UI8:
return D_UnsignedBigInt;
case FILETIME:
return D_Filetime;
case GUID:
return D_Guid;
case BYTES:
return (isLong) ? D_LongVarBinary : (isFixed) ? D_Binary : D_VarBinary;
case STR:
return (isLong) ? D_LongVarChar : (isFixed) ? D_Char : D_VarChar;
case WSTR:
return (isLong) ? D_LongVarWChar : (isFixed) ? D_WChar : D_VarWChar;
case NUMERIC:
return D_Numeric;
//case UDT:
case DBDATE:
return D_DBDate;
case DBTIME:
return D_DBTime;
case DBTIMESTAMP:
return D_DBTimeStamp;
case HCHAPTER:
return D_Chapter;
case PROPVARIANT:
return D_PropVariant;
case VARNUMERIC:
return D_VarNumeric;
case XML:
return D_Xml;
case UDT:
return D_Udt;
//case VECTOR:
//case ARRAY:
//case BYREF:
//case RESERVED:
default:
if (0 != (NativeDBType.VECTOR & dbType))
{
throw ODB.DBBindingGetVector();
}
return D_Variant;
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.TestingHost;
using Orleans.Utilities;
using Orleans.Internal;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
namespace Tester.HeterogeneousSilosTests
{
[TestCategory("Functional")]
public class HeterogeneousTests : OrleansTestingBase, IDisposable, IAsyncLifetime
{
private static readonly TimeSpan ClientRefreshDelay = TimeSpan.FromSeconds(1);
private static readonly TimeSpan RefreshInterval = TimeSpan.FromMilliseconds(200);
private TestCluster cluster;
private void SetupAndDeployCluster(Type defaultPlacementStrategy, params Type[] blackListedTypes)
{
cluster?.StopAllSilos();
var builder = new TestClusterBuilder(1)
{
CreateSiloAsync = AppDomainSiloHandle.Create
};
builder.Properties["DefaultPlacementStrategy"] = RuntimeTypeNameFormatter.Format(defaultPlacementStrategy);
builder.Properties["BlacklistedGrainTypes"] = string.Join("|", blackListedTypes.Select(t => t.FullName));
builder.AddSiloBuilderConfigurator<SiloConfigurator>();
builder.AddClientBuilderConfigurator<ClientConfigurator>();
cluster = builder.Build();
cluster.Deploy();
}
public class SiloConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.Configure<SiloMessagingOptions>(options => options.AssumeHomogenousSilosForTesting = false);
hostBuilder.Configure<TypeManagementOptions>(options => options.TypeMapRefreshInterval = RefreshInterval);
hostBuilder.Configure<GrainClassOptions>(options =>
{
var cfg = hostBuilder.GetConfiguration();
var siloOptions = new TestSiloSpecificOptions();
cfg.Bind(siloOptions);
// The blacklist is only intended for the primary silo in these tests.
if (string.Equals(siloOptions.SiloName, Silo.PrimarySiloName))
{
var blacklistedTypesList = cfg["BlacklistedGrainTypes"].Split('|').ToList();
options.ExcludedGrainTypes.AddRange(blacklistedTypesList);
}
});
hostBuilder.ConfigureServices(services =>
{
var defaultPlacementStrategy = Type.GetType(hostBuilder.GetConfiguration()["DefaultPlacementStrategy"]);
services.AddSingleton(typeof(PlacementStrategy), defaultPlacementStrategy);
});
}
}
public class ClientConfigurator : IClientBuilderConfigurator
{
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder.Configure<TypeManagementOptions>(options => options.TypeMapRefreshInterval = ClientRefreshDelay);
}
}
public void Dispose()
{
cluster?.StopAllSilos();
cluster = null;
}
[Fact]
public void GrainExcludedTest()
{
SetupAndDeployCluster(typeof(RandomPlacement), typeof(TestGrain));
// Should fail
var exception = Assert.Throws<ArgumentException>(() => this.cluster.GrainFactory.GetGrain<ITestGrain>(0));
Assert.Contains("Cannot find an implementation class for grain interface", exception.Message);
// Should not fail
this.cluster.GrainFactory.GetGrain<ISimpleGrainWithAsyncMethods>(0);
}
[Fact]
public async Task MergeGrainResolverTests()
{
await MergeGrainResolverTestsImpl<ITestGrain>(typeof(RandomPlacement), true, this.CallITestGrainMethod, typeof(TestGrain));
await MergeGrainResolverTestsImpl<ITestGrain>(typeof(PreferLocalPlacement), true, this.CallITestGrainMethod, typeof(TestGrain));
// TODO Check ActivationCountBasedPlacement in tests
//await MergeGrainResolverTestsImpl("ActivationCountBasedPlacement", typeof(TestGrain));
}
[Fact]
public async Task MergeGrainResolverWithClientRefreshTests()
{
await MergeGrainResolverTestsImpl<ITestGrain>(typeof(RandomPlacement), false, this.CallITestGrainMethod, typeof(TestGrain));
await MergeGrainResolverTestsImpl<ITestGrain>(typeof(PreferLocalPlacement), false, this.CallITestGrainMethod, typeof(TestGrain));
// TODO Check ActivationCountBasedPlacement in tests
//await MergeGrainResolverTestsImpl("ActivationCountBasedPlacement", typeof(TestGrain));
}
[Fact]
public async Task StatelessWorkerPlacementTests()
{
await MergeGrainResolverTestsImpl<IStatelessWorkerGrain>(typeof(RandomPlacement), true, this.CallIStatelessWorkerGrainMethod, typeof(StatelessWorkerGrain));
await MergeGrainResolverTestsImpl<IStatelessWorkerGrain>(typeof(PreferLocalPlacement), true, this.CallIStatelessWorkerGrainMethod, typeof(StatelessWorkerGrain));
}
[Fact]
public async Task StatelessWorkerPlacementWithClientRefreshTests()
{
await MergeGrainResolverTestsImpl<IStatelessWorkerGrain>(typeof(RandomPlacement), false, this.CallIStatelessWorkerGrainMethod, typeof(StatelessWorkerGrain));
await MergeGrainResolverTestsImpl<IStatelessWorkerGrain>(typeof(PreferLocalPlacement), false, this.CallIStatelessWorkerGrainMethod, typeof(StatelessWorkerGrain));
}
private async Task CallITestGrainMethod(IGrain grain)
{
var g = grain.Cast<ITestGrain>();
await g.SetLabel("Hello world");
}
private async Task CallIStatelessWorkerGrainMethod(IGrain grain)
{
var g = grain.Cast<IStatelessWorkerGrain>();
await g.GetCallStats();
}
private async Task MergeGrainResolverTestsImpl<T>(Type defaultPlacementStrategy, bool restartClient, Func<IGrain, Task> func, params Type[] blackListedTypes)
where T : IGrainWithIntegerKey
{
SetupAndDeployCluster(defaultPlacementStrategy, blackListedTypes);
var delayTimeout = RefreshInterval.Add(RefreshInterval);
// Should fail
var exception = Assert.Throws<ArgumentException>(() => this.cluster.GrainFactory.GetGrain<T>(0));
Assert.Contains("Cannot find an implementation class for grain interface", exception.Message);
// Start a new silo with TestGrain
await cluster.StartAdditionalSiloAsync();
await Task.Delay(delayTimeout);
if (restartClient)
{
// Disconnect/Reconnect the client
await cluster.Client.Close();
cluster.Client.Dispose();
cluster.InitializeClient();
}
else
{
await Task.Delay(ClientRefreshDelay.Multiply(3));
}
for (var i = 0; i < 5; i++)
{
// Success
var g = this.cluster.GrainFactory.GetGrain<T>(i);
await func(g);
}
// Stop the latest silos
await cluster.StopSecondarySilosAsync();
await Task.Delay(delayTimeout);
if (restartClient)
{
// Disconnect/Reconnect the client
await cluster.Client.Close();
cluster.Client.Dispose();
cluster.InitializeClient();
}
else
{
await Task.Delay(ClientRefreshDelay.Multiply(3));
}
// Should fail
exception = Assert.Throws<ArgumentException>(() => this.cluster.GrainFactory.GetGrain<T>(0));
Assert.Contains("Cannot find an implementation class for grain interface", exception.Message);
}
public Task InitializeAsync()
{
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
if (this.cluster == null) return;
await cluster.StopAllSilosAsync();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using Paket.Bootstrapper.HelperProxies;
namespace Paket.Bootstrapper.DownloadStrategies
{
internal class NugetDownloadStrategy : DownloadStrategy
{
internal class NugetApiHelper
{
private readonly string packageName;
private readonly string nugetSource;
const string NugetSourceAppSettingsKey = "NugetSource";
const string DefaultNugetSource = "https://www.nuget.org/api/v2";
const string GetPackageVersionTemplate = "{0}/package-versions/{1}";
const string GetLatestFromNugetUrlTemplate = "{0}/package/{1}";
const string GetSpecificFromNugetUrlTemplate = "{0}/package/{1}/{2}";
public NugetApiHelper(string packageName, string nugetSource)
{
this.packageName = packageName;
this.nugetSource = nugetSource ?? ConfigurationManager.AppSettings[NugetSourceAppSettingsKey] ?? DefaultNugetSource;
}
internal string GetAllPackageVersions(bool includePrerelease)
{
var request = String.Format(GetPackageVersionTemplate, nugetSource, packageName);
const string withPrereleases = "?includePrerelease=true";
if (includePrerelease)
request += withPrereleases;
return request;
}
internal string GetLatestPackage()
{
return String.Format(GetLatestFromNugetUrlTemplate, nugetSource, packageName);
}
internal string GetSpecificPackageVersion(string version)
{
return String.Format(GetSpecificFromNugetUrlTemplate, nugetSource, packageName, version);
}
}
private IWebRequestProxy WebRequestProxy { get; set; }
private IFileSystemProxy FileSystemProxy { get; set; }
private string Folder { get; set; }
private string NugetSource { get; set; }
private const string PaketNugetPackageName = "Paket";
private const string PaketBootstrapperNugetPackageName = "Paket.Bootstrapper";
public NugetDownloadStrategy(IWebRequestProxy webRequestProxy, IFileSystemProxy fileSystemProxy, string folder, string nugetSource)
{
WebRequestProxy = webRequestProxy;
FileSystemProxy = fileSystemProxy;
Folder = folder;
NugetSource = nugetSource;
}
public override string Name
{
get { return "Nuget"; }
}
public override bool CanDownloadHashFile
{
get { return false; }
}
protected override string GetLatestVersionCore(bool ignorePrerelease)
{
IEnumerable<string> allVersions = null;
if (FileSystemProxy.DirectoryExists(NugetSource))
{
var paketPrefix = "paket.";
allVersions = FileSystemProxy.
EnumerateFiles(NugetSource, "paket.*.nupkg", SearchOption.TopDirectoryOnly).
Select(x => Path.GetFileNameWithoutExtension(x)).
// If the specified character isn't a digit, then the file
// likely contains the bootstrapper or paket.core
Where(x => x.Length > paketPrefix.Length && Char.IsDigit(x[paketPrefix.Length])).
Select(x => x.Substring(paketPrefix.Length));
}
else
{
var apiHelper = new NugetApiHelper(PaketNugetPackageName, NugetSource);
var versionRequestUrl = apiHelper.GetAllPackageVersions(!ignorePrerelease);
var versions = WebRequestProxy.DownloadString(versionRequestUrl);
allVersions = versions.
Trim('[', ']').
Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).
Select(x => x.Trim('"'));
}
var latestVersion = allVersions.
Select(SemVer.Create).
Where(x => !ignorePrerelease || (x.PreRelease == null)).
OrderBy(x => x).
LastOrDefault(x => !String.IsNullOrWhiteSpace(x.Original));
return latestVersion != null ? latestVersion.Original : String.Empty;
}
protected override void DownloadVersionCore(string latestVersion, string target, string hashfile)
{
var apiHelper = new NugetApiHelper(PaketNugetPackageName, NugetSource);
const string paketNupkgFile = "paket.latest.nupkg";
const string paketNupkgFileTemplate = "paket.{0}.nupkg";
var paketDownloadUrl = apiHelper.GetLatestPackage();
var paketFile = paketNupkgFile;
if (!String.IsNullOrWhiteSpace(latestVersion))
{
paketDownloadUrl = apiHelper.GetSpecificPackageVersion(latestVersion);
paketFile = String.Format(paketNupkgFileTemplate, latestVersion);
}
var randomFullPath = Path.Combine(Folder, Path.GetRandomFileName());
FileSystemProxy.CreateDirectory(randomFullPath);
var paketPackageFile = Path.Combine(randomFullPath, paketFile);
if (FileSystemProxy.DirectoryExists(NugetSource))
{
if (String.IsNullOrWhiteSpace(latestVersion)) latestVersion = GetLatestVersion(false);
var sourcePath = Path.Combine(NugetSource, String.Format(paketNupkgFileTemplate, latestVersion));
ConsoleImpl.WriteInfo("Starting download from {0}", sourcePath);
FileSystemProxy.CopyFile(sourcePath, paketPackageFile);
}
else
{
ConsoleImpl.WriteInfo("Starting download from {0}", paketDownloadUrl);
try
{
WebRequestProxy.DownloadFile(paketDownloadUrl, paketPackageFile);
}
catch (WebException webException)
{
if (webException.Status == WebExceptionStatus.ProtocolError && !string.IsNullOrEmpty(latestVersion))
{
var response = (HttpWebResponse) webException.Response;
if (response.StatusCode == HttpStatusCode.NotFound)
{
throw new WebException(String.Format("Version {0} wasn't found (404)",latestVersion),
webException);
}
if (response.StatusCode == HttpStatusCode.BadRequest)
{
// For cases like "The package version is not a valid semantic version"
throw new WebException(String.Format("Unable to get version '{0}': {1}",latestVersion,response.StatusDescription),
webException);
}
}
Console.WriteLine(webException.ToString());
throw;
}
}
FileSystemProxy.ExtractToDirectory(paketPackageFile, randomFullPath);
var paketSourceFile = Path.Combine(randomFullPath, "tools", "paket.exe");
FileSystemProxy.CopyFile(paketSourceFile, target, true);
FileSystemProxy.DeleteDirectory(randomFullPath, true);
}
protected override void SelfUpdateCore(string latestVersion)
{
string target = Assembly.GetExecutingAssembly().Location;
var localVersion = FileSystemProxy.GetLocalFileVersion(target);
if (localVersion.StartsWith(latestVersion))
{
ConsoleImpl.WriteInfo("Bootstrapper is up to date. Nothing to do.");
return;
}
var apiHelper = new NugetApiHelper(PaketBootstrapperNugetPackageName, NugetSource);
const string paketNupkgFile = "paket.bootstrapper.latest.nupkg";
const string paketNupkgFileTemplate = "paket.bootstrapper.{0}.nupkg";
var getLatestFromNugetUrl = apiHelper.GetLatestPackage();
var paketDownloadUrl = getLatestFromNugetUrl;
var paketFile = paketNupkgFile;
if (!String.IsNullOrWhiteSpace(latestVersion))
{
paketDownloadUrl = apiHelper.GetSpecificPackageVersion(latestVersion);
paketFile = String.Format(paketNupkgFileTemplate, latestVersion);
}
var randomFullPath = Path.Combine(Folder, Path.GetRandomFileName());
FileSystemProxy.CreateDirectory(randomFullPath);
var paketPackageFile = Path.Combine(randomFullPath, paketFile);
if (FileSystemProxy.DirectoryExists(NugetSource))
{
if (String.IsNullOrWhiteSpace(latestVersion)) latestVersion = GetLatestVersion(false);
var sourcePath = Path.Combine(NugetSource, String.Format(paketNupkgFileTemplate, latestVersion));
ConsoleImpl.WriteInfo("Starting download from {0}", sourcePath);
FileSystemProxy.CopyFile(sourcePath, paketPackageFile);
}
else
{
ConsoleImpl.WriteInfo("Starting download from {0}", paketDownloadUrl);
WebRequestProxy.DownloadFile(paketDownloadUrl, paketPackageFile);
}
FileSystemProxy.ExtractToDirectory(paketPackageFile, randomFullPath);
var paketSourceFile = Path.Combine(randomFullPath, "tools", "paket.bootstrapper.exe");
var renamedPath = BootstrapperHelper.GetTempFile("oldBootstrapper");
try
{
FileSystemProxy.MoveFile(target, renamedPath);
FileSystemProxy.MoveFile(paketSourceFile, target);
ConsoleImpl.WriteInfo("Self update of bootstrapper was successful.");
}
catch (Exception)
{
ConsoleImpl.WriteInfo("Self update failed. Resetting bootstrapper.");
FileSystemProxy.MoveFile(renamedPath, target);
throw;
}
FileSystemProxy.DeleteDirectory(randomFullPath, true);
}
protected override string DownloadHashFileCore(string latestVersion)
{
// TODO: implement get hash file
return null;
}
}
}
| |
// Copyright 2020 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
//
// 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 DebuggerGrpcClient;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using YetiCommon;
using YetiCommon.SSH;
using YetiVSI.DebugEngine;
using YetiVSI.DebuggerOptions;
using LaunchOption = YetiVSI.DebugEngine.DebugEngine.LaunchOption;
using Microsoft.VisualStudio.Threading;
using YetiVSI.Util;
using System.Text;
using YetiVSI.DebugEngine.Exit;
using YetiVSI.DebugEngine.Interfaces;
namespace YetiVSI
{
public class YetiDebugTransportException : Exception, IUserVisibleError
{
public YetiDebugTransportException(string message) : base(message)
{
}
}
// Used by the debug engine in order to initialize Yeti-specific components.
public class YetiDebugTransport
{
public class GrpcSession
{
public GrpcConnection GrpcConnection { get; internal set; }
public ITransportSession TransportSession { get; internal set; }
public int GetLocalDebuggerPort() =>
TransportSession?.GetLocalDebuggerPort() ?? 0;
}
// An event indicating that the transprot has stopped.
public event Action<Exception> OnStop;
readonly object _thisLock = new object();
readonly JoinableTaskContext _taskContext;
readonly PipeCallInvokerFactory _grpcCallInvokerFactory;
readonly GrpcConnectionFactory _grpcConnectionFactory;
readonly Action _onAsyncRpcCompleted;
readonly ManagedProcess.Factory _managedProcessFactory;
readonly IVsOutputWindowPane _debugPane;
readonly IDialogUtil _dialogUtil;
readonly IYetiVSIService _yetiVSIService;
PipeCallInvoker _grpcCallInvoker;
ProcessManager _processManager;
GrpcSession _grpcSession;
public YetiDebugTransport(JoinableTaskContext taskContext,
PipeCallInvokerFactory grpcCallInvokerFactory,
GrpcConnectionFactory grpcConnectionFactory,
Action onAsyncRpcCompleted,
ManagedProcess.Factory managedProcessFactory,
IDialogUtil dialogUtil, IVsOutputWindow vsOutputWindow,
IYetiVSIService yetiVSIService)
{
taskContext.ThrowIfNotOnMainThread();
_taskContext = taskContext;
_grpcCallInvokerFactory = grpcCallInvokerFactory;
_grpcConnectionFactory = grpcConnectionFactory;
_onAsyncRpcCompleted = onAsyncRpcCompleted;
_managedProcessFactory = managedProcessFactory;
_dialogUtil = dialogUtil;
Guid debugPaneGuid = VSConstants.GUID_OutWindowDebugPane;
vsOutputWindow?.GetPane(ref debugPaneGuid, out _debugPane);
_yetiVSIService = yetiVSIService;
}
public GrpcSession StartGrpcServer()
{
lock (_thisLock)
{
// Try establishing an LLDB session.
var session = new LldbTransportSession();
if (!session.IsValid())
{
Trace.WriteLine("Unable to start the debug transport, invalid session.");
throw new YetiDebugTransportException(ErrorStrings.FailedToStartTransport);
}
_grpcSession = new GrpcSession
{
TransportSession = session
};
ProcessStartData grpcProcessData = CreateDebuggerGrpcServerProcessStartData();
if (!LaunchProcesses(new List<ProcessStartData>() { grpcProcessData },
"grpc-server"))
{
Stop(ExitReason.Unknown);
throw new YetiDebugTransportException(
"Failed to launch grpc server process");
}
Trace.WriteLine("Started debug transport. Session ID: " +
_grpcSession.TransportSession.GetSessionId());
// The transport class owns the Grpc session. However, it makes sense to return
// the session and force the caller to pass it as a parameter in all other methods
// to make it clearer that the Grpc server process should be started first.
return _grpcSession;
}
}
public void StartPreGame(LaunchOption launchOption, bool rgpEnabled, bool diveEnabled,
bool renderdocEnabled, SshTarget target,
GrpcSession session)
{
lock (_thisLock)
{
if (!LaunchPreGameProcesses(launchOption, rgpEnabled, diveEnabled, renderdocEnabled,
target, session))
{
Stop(ExitReason.Unknown);
throw new YetiDebugTransportException(
"Failed to launch all needed pre-game processes");
}
}
}
public void StartPostGame(LaunchOption launchOption, SshTarget target, uint remotePid)
{
lock (_thisLock)
{
if (_grpcSession == null)
{
Stop(ExitReason.Unknown);
throw new YetiDebugTransportException(
"Failed to start post-game processes. Transport session not started yet.");
}
if (!LaunchPostGameProcesses(launchOption, target, remotePid))
{
Stop(ExitReason.Unknown);
throw new YetiDebugTransportException(
"Failed to launch all needed post-game processes");
}
}
}
// Exits and disposes of all processes, the TransportSession, and GrpcConnection.
public void Stop(ExitReason exitReason)
{
lock (_thisLock)
{
// Stop the grpc connection first because it depends on the the grpc server process
// that is managed by the process manager.
_grpcSession?.GrpcConnection?.Shutdown();
_grpcCallInvoker?.Dispose();
_grpcCallInvoker = null;
_grpcSession?.TransportSession?.Dispose();
_grpcSession = null;
_processManager?.StopAll(exitReason);
_processManager = null;
}
}
void StopWithException(Exception ex)
{
// Synchronously pass the execution exception to the on stop handlers before calling
// stop. This is done because stopping processes can trigger other exceptions and
// we would like this to be the first one handled.
OnStop?.Invoke(ex);
Stop(ExitReason.Unknown);
}
// Launches a process, configured using Yeti project properties.
// If |monitorExit| is true, when the process exits the debugger will be stopped.
// Throws a ProcessException if the process fails to launch.
void LaunchYetiProcess(ProcessStartData startData)
{
startData.BeforeStart?.Invoke(startData.StartInfo);
Trace.WriteLine(
$"Command: {startData.StartInfo.FileName} {startData.StartInfo.WorkingDirectory}");
Trace.WriteLine($"Working Dir: {startData.StartInfo.WorkingDirectory}");
var process = _managedProcessFactory.Create(startData.StartInfo);
if (startData.OutputToConsole)
{
process.OutputDataReceived += (sender, data) =>
{
if (data != null)
{
_taskContext.Factory.Run(async () =>
{
await _taskContext.Factory.SwitchToMainThreadAsync();
_debugPane?.OutputString(data.Text + "\n");
});
}
};
}
if (startData.MonitorExit)
{
process.OnExit += _processManager.OnExit;
}
process.Start();
startData.AfterStart?.Invoke();
_processManager.AddProcess(process, startData.StopHandler);
}
/// <summary>
/// Launches all needed processes that can be launched before the game.
/// </summary>
/// <param name="launchOption">How the game will be launched</param>
/// <param name="rgpEnabled">Whether RPG is enabled</param>
/// <param name="diveEnabled">Whether Dive is enabled</param>
/// <param name="renderdocEnabled">Whether Renderdoc is enabled</param>
/// <param name="target">Remote instance</param>
/// <returns>
/// True if all processes launched successfully and false otherwise and we should abort.
/// </returns>
bool LaunchPreGameProcesses(LaunchOption launchOption, bool rgpEnabled, bool diveEnabled,
bool renderdocEnabled, SshTarget target,
GrpcSession session)
{
var processes = new List<ProcessStartData>();
if (launchOption == LaunchOption.LaunchGame ||
launchOption == LaunchOption.AttachToGame)
{
processes.Add(CreatePortForwardingProcessStartData(target, session));
processes.Add(CreateLldbServerProcessStartData(target, session));
}
if (launchOption == LaunchOption.LaunchGame)
{
if (renderdocEnabled)
{
processes.Add(CreateRenderDocPortForwardingProcessStartData(target));
}
if (rgpEnabled)
{
processes.Add(CreateRgpPortForwardingProcessStartData(target));
}
if (diveEnabled)
{
processes.Add(CreateDivePortForwardingProcessStartData(target));
}
}
return LaunchProcesses(processes, "pre-game");
}
/// <summary>
/// Launches all needed processes that can be launched after the game.
/// </summary>
/// <param name="launchOption">How the game will be launched</param>
/// <param name="target">Remote instance</param>
/// <param name="remotePid">Id of the remote process</param>
/// <returns>
/// True if all processes launched successfully and false otherwise and we should abort.
/// </returns>
bool LaunchPostGameProcesses(LaunchOption launchOption, SshTarget target, uint remotePid)
{
var processes = new List<ProcessStartData>();
if ((launchOption == LaunchOption.LaunchGame ||
launchOption == LaunchOption.AttachToGame) &&
_yetiVSIService.Options.CaptureGameOutput)
{
processes.Add(CreateTailLogsProcessStartData(target, remotePid));
}
return LaunchProcesses(processes, "post-game");
}
bool LaunchProcesses(List<ProcessStartData> processes, string name)
{
if (_processManager == null)
{
_processManager = new ProcessManager();
_processManager.OnProcessExit += (processName, exitCode) =>
StopWithException(new ProcessExecutionException(
$"{processName} exited with exit code {exitCode}",
exitCode));
}
foreach (var item in processes)
{
try
{
LaunchYetiProcess(item);
}
catch (ProcessException e)
{
Trace.WriteLine($"Failed to start {item.Name}: {e.Demystify()}");
_dialogUtil.ShowError(ErrorStrings.FailedToStartRequiredProcess(e.Message), e);
return false;
}
}
Trace.WriteLine($"Manager successfully started all {name} processes");
return true;
}
ProcessStartData CreatePortForwardingProcessStartData(SshTarget target, GrpcSession session)
{
var ports = new List<ProcessStartInfoBuilder.PortForwardEntry>()
{
new ProcessStartInfoBuilder.PortForwardEntry
{
LocalPort = session.TransportSession.GetLocalDebuggerPort(),
RemotePort = session.TransportSession.GetRemoteDebuggerPort(),
},
new ProcessStartInfoBuilder.PortForwardEntry
{
// LLDB returns the GDB server port to the LLDB client, so the local
// and remote port must match.
LocalPort = session.TransportSession.GetReservedLocalAndRemotePort(),
RemotePort = session.TransportSession.GetReservedLocalAndRemotePort(),
}
};
var startInfo = ProcessStartInfoBuilder.BuildForSshPortForward(ports, target);
return new ProcessStartData("lldb port forwarding", startInfo);
}
ProcessStartData CreateRenderDocPortForwardingProcessStartData(SshTarget target)
{
var ports = new List<ProcessStartInfoBuilder.PortForwardEntry>()
{
new ProcessStartInfoBuilder.PortForwardEntry
{
LocalPort = WorkstationPorts.RENDERDOC_LOCAL,
RemotePort = WorkstationPorts.RENDERDOC_REMOTE,
}
};
var startInfo = ProcessStartInfoBuilder.BuildForSshPortForward(ports, target);
return new ProcessStartData("renderdoc port forwarding", startInfo);
}
ProcessStartData CreateRgpPortForwardingProcessStartData(SshTarget target)
{
var ports = new List<ProcessStartInfoBuilder.PortForwardEntry>()
{
new ProcessStartInfoBuilder.PortForwardEntry
{
LocalPort = WorkstationPorts.RGP_LOCAL,
RemotePort = WorkstationPorts.RGP_REMOTE,
}
};
var startInfo = ProcessStartInfoBuilder.BuildForSshPortForward(ports, target);
return new ProcessStartData("rgp port forwarding", startInfo);
}
ProcessStartData CreateDivePortForwardingProcessStartData(SshTarget target)
{
var ports = new List<ProcessStartInfoBuilder.PortForwardEntry>() {
new ProcessStartInfoBuilder.PortForwardEntry {
LocalPort = WorkstationPorts.DIVE_LOCAL,
RemotePort = WorkstationPorts.DIVE_REMOTE,
}
};
var startInfo = ProcessStartInfoBuilder.BuildForSshPortForward(ports, target);
return new ProcessStartData("dive port forwarding", startInfo);
}
ProcessStartData CreateLldbServerProcessStartData(SshTarget target, GrpcSession session)
{
string lldbServerCommand = string.Format(
"{0} platform --listen 127.0.0.1:{1} --min-gdbserver-port={2} " +
"--max-gdbserver-port={3}",
Path.Combine(YetiConstants.LldbServerLinuxPath,
YetiConstants.LldbServerLinuxExecutable),
session.TransportSession.GetRemoteDebuggerPort(),
session.TransportSession.GetReservedLocalAndRemotePort(),
session.TransportSession.GetReservedLocalAndRemotePort() + 1);
List<string> lldbServerEnvironment = new List<string>();
if (_yetiVSIService.DebuggerOptions[DebuggerOption.SERVER_LOGGING] ==
DebuggerOptionState.ENABLED)
{
string channels = "lldb default:posix default:gdb-remote default";
// gdb-server.log
lldbServerEnvironment.Add(
"LLDB_DEBUGSERVER_LOG_FILE=/usr/local/cloudcast/log/gdb-server.log");
lldbServerEnvironment.Add("LLDB_SERVER_LOG_CHANNELS=\\\"" + channels + "\\\"");
// lldb-server.log
lldbServerCommand += " --log-file=/usr/local/cloudcast/log/lldb-server.log " +
"--log-channels=\\\"" + channels + "\\\"";
}
var startInfo = ProcessStartInfoBuilder.BuildForSsh(
lldbServerCommand, lldbServerEnvironment, target);
return new ProcessStartData("lldb server", startInfo);
}
ProcessStartData CreateTailLogsProcessStartData(SshTarget target, uint remotePid)
{
// If the game process exits, give the tail process a chance to shut down gracefully.
ProcessManager.ProcessStopHandler stopHandler = (process, reason) =>
{
// Did the game process, i.e. the process with pid |remotePid|, exit?
if (reason != ExitReason.ProcessExited &&
reason != ExitReason.DebuggerTerminated)
{
Trace.WriteLine("Game process did not exit, won't wait for tail process exit");
return;
}
// Give it a second to finish.
bool exited = process.WaitForExit(TimeSpan.FromSeconds(1));
// Emit a log message to help tracking down issues, just in case.
Trace.WriteLine($"Tail process {(exited ? "exited" : "did not exit")} gracefully");
};
var startInfo = ProcessStartInfoBuilder.BuildForSsh(
$"tail --pid={remotePid} -n +0 -F -q /var/game/stdout /var/game/stderr",
new List<string>(), target);
return new ProcessStartData("output tail", startInfo, monitorExit: false,
outputToConsole: true, stopHandler: stopHandler);
}
ProcessStartData CreateDebuggerGrpcServerProcessStartData()
{
var startInfo = new ProcessStartInfo
{
FileName = Path.Combine(YetiConstants.RootDir,
YetiConstants.DebuggerGrpcServerExecutable),
};
// (internal): grpcCallInvoker must be created right before the process is created!
// If it is created before the other processes are created, they'll hold on to the
// pipes and they won't get closed if the GRPC server shuts down.
void beforeStart(ProcessStartInfo processStartInfo)
{
_grpcCallInvoker = _grpcCallInvokerFactory.Create();
_grpcSession.GrpcConnection = _grpcConnectionFactory.Create(_grpcCallInvoker);
_grpcSession.GrpcConnection.RpcException += StopWithException;
_grpcSession.GrpcConnection.AsyncRpcCompleted += _onAsyncRpcCompleted;
_grpcCallInvoker.GetClientPipeHandles(out string[] inPipeHandles,
out string[] outPipeHandles);
// Note: The server's input pipes are the client's output pipes and vice versa.
processStartInfo.Arguments = $"-i {string.Join(",", outPipeHandles)} " +
$"-o {string.Join(",", inPipeHandles)}";
}
// Dispose client handles right after start. This is necessary so that pipes are closed
// when the server exits.
Action afterStart = () => { _grpcCallInvoker.DisposeLocalCopyOfClientPipeHandles(); };
var rootDir = YetiConstants.RootDir;
#if USE_LOCAL_PYTHON_AND_TOOLCHAIN
// This is gated by the <DeployPythonAndToolchainDependencies> project setting to speed
// up the build.
var pythonRoot = File.ReadAllText(Path.Combine(rootDir, "local_python_dir.txt")).Trim();
var toolchainDir = File.ReadAllText(Path.Combine(rootDir, "local_toolchain_dir.txt"))
.Trim();
var lldbSitePackagesDir = Path.Combine(toolchainDir, "windows", "lib", "site-packages");
var libLldbDir = Path.Combine(toolchainDir, "windows", "bin");
// Quick sanity check that all directories exist.
var notFoundDir = !Directory.Exists(pythonRoot) ? pythonRoot :
!Directory.Exists(lldbSitePackagesDir) ? lldbSitePackagesDir :
!Directory.Exists(libLldbDir) ? libLldbDir : null;
if (!string.IsNullOrEmpty(notFoundDir))
{
// Note: This error is only shown to internal VSI devs, not to external devs.
throw new YetiDebugTransportException(
"You have set the <DeployPythonAndToolchainDependencies> project setting to " +
$"False to speed up deployment, but the Python/toolchain dir {notFoundDir} " +
"moved. Either fix the wrong directory (preferred) or set " +
"<DeployPythonAndToolchainDependencies> to False.");
}
#else
var pythonRoot = Path.Combine(rootDir, "Python3");
var lldbSitePackagesDir = Path.Combine(YetiConstants.LldbDir, "site-packages");
var libLldbDir = Path.Combine(YetiConstants.LldbDir, "bin");
#endif
// Search paths for dLLs.
startInfo.Environment["PATH"] = string.Join(";", new string[]
{
rootDir,
pythonRoot,
libLldbDir
});
// Search paths for Python files.
startInfo.Environment["PYTHONPATH"] = string.Join(";", new string[]
{
Path.Combine(pythonRoot, "Lib"),
lldbSitePackagesDir
});
// Do not display console windows when launching processes. In our case,
// we do not want the scp process to show the console window.
startInfo.Environment["LLDB_LAUNCH_INFERIORS_WITHOUT_CONSOLE"] = "true";
Trace.WriteLine($"Starting {startInfo.FileName} with" + Environment.NewLine +
$"\tPATH={(startInfo.Environment["PATH"])}" + Environment.NewLine +
$"\tPYTHONPATH={(startInfo.Environment["PYTHONPATH"])}");
// Use the directory with the binary as working directory. Normally it doesn't matter,
// because the server doesn't load any files via relative paths and the dependent DLLs
// are available via PATH and PYTHONPATH. However when debugging or just running the
// extension from Visual Studio the working directory is set to the output build
// directory. The working directory has precedence for loading DLLs, so liblldb.dll is
// picked up from the build output directory, NOT the deployed extension.
startInfo.WorkingDirectory = Path.GetDirectoryName(startInfo.FileName);
// Uncomment to enable GRPC debug logging for DebuggerGrpcServer.exe.
// This is currently very verbose, and you will most likely want to restrict logging to
// a subset.
//
//lldbGrpcStartInfo.EnvironmentVariables["GRPC_TRACE"] = "all";
//lldbGrpcStartInfo.EnvironmentVariables["GRPC_VERBOSITY"] = "DEBUG";
return new ProcessStartData("lldb grpc server", startInfo, beforeStart: beforeStart,
afterStart: afterStart);
}
static void LogCapturedOutput(string streamName, object sender, string message)
{
if (!string.IsNullOrEmpty(message))
{
Trace.WriteLine(
((IProcess) sender).ProcessName + " >" + streamName + "> " + message);
}
}
static void LogStdOut(object sender, TextReceivedEventArgs data)
{
LogCapturedOutput("stdout", sender, data.Text);
}
static void LogStdErr(object sender, TextReceivedEventArgs data)
{
LogCapturedOutput("stderr", sender, data.Text);
}
class ProcessStartData
{
public ProcessStartData(string name, ProcessStartInfo startInfo,
bool monitorExit = true, bool outputToConsole = false,
Action<ProcessStartInfo> beforeStart = null,
Action afterStart = null,
ProcessManager.ProcessStopHandler stopHandler = null)
{
Name = name;
StartInfo = startInfo;
MonitorExit = monitorExit;
OutputToConsole = outputToConsole;
BeforeStart = beforeStart;
AfterStart = afterStart;
StopHandler = stopHandler;
if (OutputToConsole)
{
// Default to UTF8. If this is left null, it will default to the system's current
// code page, which is usually something like Windows-1252 and UTF8 won't render.
if (StartInfo.StandardOutputEncoding == null)
{
StartInfo.StandardOutputEncoding = Encoding.UTF8;
}
if (StartInfo.StandardErrorEncoding == null)
{
StartInfo.StandardErrorEncoding = Encoding.UTF8;
}
}
}
public string Name { get; }
public ProcessStartInfo StartInfo { get; }
public bool MonitorExit { get; }
public bool OutputToConsole { get; }
/// <summary>
/// Action called right before the process is started. May modify start info.
/// </summary>
public Action<ProcessStartInfo> BeforeStart { get; }
/// <summary>
/// Action called right after the process is started.
/// </summary>
public Action AfterStart { get; }
/// <summary>
/// Handler called when the process manager stops all processes. Gives the
/// process a chance for custom stop handling based on the exit reason.
/// If null, the process is killed.
/// </summary>
public ProcessManager.ProcessStopHandler StopHandler { get; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.StoreKit;
namespace FlowChaser
{
public enum ProductState
{
Unknown,
Invalid,
Loaded,
Purchasing,
Purchased
}
public interface IProductDetails
{
ProductState State { get; }
string GetLocalizedPrice();
string GetLocalisedTitle();
string GetLocalisedDescription();
void Purchase();
}
/// <summary>
/// Singleton class for managing app store comunication.
/// </summary>
/// <remarks>
/// Inspired by:
/// http://blog.fivelakesstudio.com/2013/04/ios-in-app-purchases.html#.UupN0Xd_t8z
/// </remarks>
public class StoreManager
{
private static readonly StoreManager SingleManager = new StoreManager();
private readonly SKPaymentQueue PaymentQueue = SKPaymentQueue.DefaultQueue;
private readonly ProductsRequestDelegate productsRequestDelegate = new ProductsRequestDelegate();
private readonly PaymentObserver paymentObserver = new PaymentObserver();
private readonly Dictionary<string, ProductDetails> products = new Dictionary<string, ProductDetails>();
private SKProductsRequest productsRequest;
private StoreManager()
{
foreach (var transaction in PaymentQueue.Transactions)
PaymentQueue.FinishTransaction(transaction);
PaymentQueue.AddTransactionObserver(this.paymentObserver);
}
public event EventHandler DetailsChanged;
public event EventHandler<TransactionFailedEventArgs> TransactionFailed;
/// <summary>
/// Singleton instance accessor.
/// </summary>
/// <value>The store manager.</value>
public static StoreManager Manager { get { return SingleManager; } }
/// <summary>
/// Gets a value indicating whether the user can make payments.
/// </summary>
/// <value><c>true</c> if the user can make payments; otherwise, <c>false</c>.</value>
public bool CanMakePayments { get { return SKPaymentQueue.CanMakePayments; } }
/// <summary>
/// Registers the product identifiers the application is interested in with the store manager class.
/// </summary>
/// <param name="productIdentifiers">The product identifiers to register.</param>
public void RegisterProducts(params string[] productIdentifiers)
{
foreach (var id in productIdentifiers)
{
if (!this.products.ContainsKey(id))
{
var product = new ProductDetails(id);
this.products [id] = product;
}
}
this.RequestProductDetails();
}
/// <summary>
/// Gets the product details for the given product ID.
/// </summary>
/// <param name="id">The product identifier.</param>
/// <returns>The product details.</returns>
public IProductDetails GetProductDetails(string id)
{
ProductDetails details;
if (this.products.TryGetValue(id, out details))
return details;
return null;
}
/// <summary>
/// Determines whether the specified identifiers product is purchased.
/// </summary>
/// <returns>Whether the product is purchased.</returns>
/// <param name="id">The product identifier.</param>
public bool IsPurchased(string id)
{
var details = this.GetProductDetails(id);
return details != null && details.State == ProductState.Purchased;
}
/// <summary>
/// Restores the purchased products.
/// </summary>
public void RestorePurchased()
{
PaymentQueue.RestoreCompletedTransactions();
}
private void RequestProductDetails()
{
if (this.products.Values.All(o => o.HasValidCache() || o.State == ProductState.Invalid || o.State == ProductState.Purchased))
return;
// If an existing request is in then progress cancel it
var currentRequest = this.productsRequest;
if (currentRequest != null)
currentRequest.Cancel();
var productIdentifiers = NSSet.MakeNSObjectSet<NSString>(
this.products.Where(o => o.Value.State == ProductState.Loaded || o.Value.State == ProductState.Unknown).Select(o => new NSString(o.Key)).ToArray());
this.productsRequest = new SKProductsRequest(productIdentifiers);
this.productsRequest.Delegate = this.productsRequestDelegate; // SKProductsRequestDelegate.ReceivedResponse
this.productsRequest.Start();
}
private void RaiseDetailsChanged()
{
var handler = this.DetailsChanged;
if (handler != null)
handler(this, EventArgs.Empty);
}
private void RaiseTransactionFailed(NSError error)
{
var handler = this.TransactionFailed;
if (handler != null)
handler(this, new TransactionFailedEventArgs("Transaction Failed: Code=" + error.Code + " " + error.LocalizedDescription));
}
private class ProductsRequestDelegate : SKProductsRequestDelegate
{
public override void ReceivedResponse(SKProductsRequest request, SKProductsResponse response)
{
if (SingleManager.productsRequest == request)
SingleManager.productsRequest = null;
var changed = false;
foreach (var product in response.Products)
{
ProductDetails details;
if (SingleManager.products.TryGetValue(product.ProductIdentifier, out details))
{
details.SetDetails(product);
changed = true;
}
}
foreach (var product in response.InvalidProducts)
{
ProductDetails details;
if (SingleManager.products.TryGetValue(product, out details))
{
details.SetInvalid();
changed = true;
}
}
// Check that all products have details - if not reload
SingleManager.RequestProductDetails();
if (changed)
SingleManager.RaiseDetailsChanged();
}
public override void RequestFailed(SKRequest request, NSError error)
{
// Retry the load - most likley case is no network
SingleManager.RequestProductDetails();
}
}
private class PaymentObserver : SKPaymentTransactionObserver
{
public override void UpdatedTransactions(SKPaymentQueue queue, SKPaymentTransaction[] transactions)
{
var purchaseChanged = false;
foreach (var transaction in transactions)
{
switch (transaction.TransactionState)
{
case SKPaymentTransactionState.Purchased:
{
ProductDetails details;
if (SingleManager.products.TryGetValue(transaction.Payment.ProductIdentifier, out details))
{
purchaseChanged = true;
details.SetPurchased();
}
SingleManager.PaymentQueue.FinishTransaction(transaction);
break;
}
case SKPaymentTransactionState.Restored:
{
ProductDetails details;
if (SingleManager.products.TryGetValue(transaction.OriginalTransaction.Payment.ProductIdentifier, out details))
{
purchaseChanged = true;
details.SetPurchased();
}
SingleManager.PaymentQueue.FinishTransaction(transaction);
break;
}
case SKPaymentTransactionState.Failed:
{
ProductDetails details;
if (SingleManager.products.TryGetValue(transaction.Payment.ProductIdentifier, out details))
{
purchaseChanged = true;
details.SetFailed();
}
if ((SKError)transaction.Error.Code != SKError.PaymentCancelled)
SingleManager.RaiseTransactionFailed(transaction.Error);
SingleManager.PaymentQueue.FinishTransaction(transaction);
break;
}
case SKPaymentTransactionState.Purchasing:
{
ProductDetails details;
if (SingleManager.products.TryGetValue(transaction.Payment.ProductIdentifier, out details))
{
purchaseChanged = true;
details.SetPurchasing();
}
break;
}
}
}
if (purchaseChanged)
SingleManager.RaiseDetailsChanged();
}
public override void RemovedTransactions(SKPaymentQueue queue, SKPaymentTransaction[] transactions)
{
foreach (var transaction in transactions)
SingleManager.PaymentQueue.FinishTransaction(transaction);
}
public override void RestoreCompletedTransactionsFailedWithError(SKPaymentQueue queue, NSError error) { }
public override void PaymentQueueRestoreCompletedTransactionsFinished(SKPaymentQueue queue) { }
}
private class ProductDetails : IProductDetails
{
private readonly string iapKey;
private SKProduct details;
private DateTime lastDetailsRequest = DateTime.MinValue;
public ProductDetails(string id)
{
this.iapKey = "IAP_" + id;
var purchased = NSUserDefaults.StandardUserDefaults.BoolForKey(this.iapKey); // If key does not exist returns false (which is perfect for us)
this.State = purchased ? ProductState.Purchased : ProductState.Unknown;
}
public ProductState State { get; private set; }
public bool HasValidCache()
{
return DateTime.Now - this.lastDetailsRequest < TimeSpan.FromDays(1);
}
public void SetDetails(SKProduct productDetails)
{
this.lastDetailsRequest = DateTime.Now;
this.details = productDetails;
if (this.State == ProductState.Unknown)
this.State = ProductState.Loaded;
}
public void SetInvalid() { this.State = ProductState.Invalid; }
public void SetFailed()
{
if (this.State == ProductState.Purchasing)
this.State = this.details == null ? ProductState.Unknown : ProductState.Loaded;
}
public void SetPurchasing() { this.State = ProductState.Purchasing; }
public string GetLocalizedPrice()
{
if (this.details == null)
return null;
var formatter = new NSNumberFormatter();
formatter.FormatterBehavior = NSNumberFormatterBehavior.Version_10_4;
formatter.NumberStyle = NSNumberFormatterStyle.Currency;
formatter.Locale = this.details.PriceLocale;
return formatter.StringFromNumber(this.details.Price);
}
public string GetLocalisedTitle() { return this.details == null ? null : this.details.LocalizedTitle; }
public string GetLocalisedDescription() { return this.details == null ? null : this.details.LocalizedDescription; }
public void Purchase()
{
SKPayment payment = SKPayment.PaymentWithProduct(this.details);
SingleManager.PaymentQueue.AddPayment(payment);
}
public void SetPurchased()
{
if (this.State == ProductState.Purchased)
return;
this.State = ProductState.Purchased;
// Whilst we could do something more secure than
// using NSUserDefaults here it is simple and the
// majority of people who would actually pay will
// not be looking to try and hack it in the first place.
NSUserDefaults.StandardUserDefaults.SetBool(true, this.iapKey);
NSUserDefaults.StandardUserDefaults.Synchronize();
}
}
}
public class TransactionFailedEventArgs : EventArgs
{
public TransactionFailedEventArgs(string message)
{
this.Message = message;
}
public string Message { get; private set; }
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics;
using System.Linq;
namespace Roslyn.Utilities
{
internal static class PathUtilities
{
private const string DirectorySeparatorStr = "\\";
internal const char DirectorySeparatorChar = '\\';
internal const char AltDirectorySeparatorChar = '/';
internal const char VolumeSeparatorChar = ':';
private static readonly char[] DirectorySeparators = new[]
{
DirectorySeparatorChar, AltDirectorySeparatorChar, VolumeSeparatorChar
};
private static readonly char[] InvalidFileNameChars =
{
'\"', '<', '>', '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7,
(char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16,
(char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25,
(char)26, (char)27, (char)28, (char)29, (char)30, (char)31, ':', '*', '?', '\\', '/'
};
internal static bool IsValidFileName(string fileName)
{
return fileName.IndexOfAny(InvalidFileNameChars) < 0;
}
internal static bool HasDirectorySeparators(string path)
{
return path.IndexOfAny(DirectorySeparators) >= 0;
}
/// <summary>
/// Trims all '.' and whitespaces from the end of the path
/// </summary>
internal static string RemoveTrailingSpacesAndDots(string path)
{
if (path == null)
{
return path;
}
int length = path.Length;
for (int i = length - 1; i >= 0; i--)
{
char c = path[i];
if (!char.IsWhiteSpace(c) && c != '.')
{
return i == (length - 1) ? path : path.Substring(0, i + 1);
}
}
return string.Empty;
}
/// <summary>
/// Returns the offset in <paramref name="path"/> where the dot that starts an extension is, or -1 if the path doesn't have an extension.
/// </summary>
/// <remarks>
/// Returns 0 for path ".foo".
/// Returns -1 for path "foo.".
/// </remarks>
private static int IndexOfExtension(string path)
{
if (path == null)
{
return -1;
}
int length = path.Length;
int i = length;
while (--i >= 0)
{
char c = path[i];
if (c == '.')
{
if (i != length - 1)
{
return i;
}
return -1;
}
if (c == DirectorySeparatorChar || c == AltDirectorySeparatorChar || c == VolumeSeparatorChar)
{
break;
}
}
return -1;
}
/// <summary>
/// Returns an extension of the specified path string.
/// </summary>
/// <remarks>
/// The same functionality as <see cref="M:System.IO.Path.GetExtension(string)"/> but doesn't throw an exception
/// if there are invalid characters in the path.
/// </remarks>
internal static string GetExtension(string path)
{
if (path == null)
{
return null;
}
int index = IndexOfExtension(path);
return (index >= 0) ? path.Substring(index) : string.Empty;
}
/// <summary>
/// Removes extension from path.
/// </summary>
/// <remarks>
/// Returns "foo" for path "foo.".
/// Returns "foo.." for path "foo...".
/// </remarks>
internal static string RemoveExtension(string path)
{
if (path == null)
{
return null;
}
int index = IndexOfExtension(path);
if (index >= 0)
{
return path.Substring(0, index);
}
// trim last ".", if present
if (path.Length > 0 && path[path.Length - 1] == '.')
{
return path.Substring(0, path.Length - 1);
}
return path;
}
/// <summary>
/// Returns path with the extenion changed to <paramref name="extension"/>.
/// </summary>
/// <returns>
/// Equivalent of <see cref="M:System.IO.Path.ChangeExtension"/>
///
/// If <paramref name="path"/> is null, returns null.
/// If path does not end with an extension, the new extension is appended to the path.
/// If extension is null, equivalent to <see cref="RemoveExtension"/>.
/// </returns>
internal static string ChangeExtension(string path, string extension)
{
if (path == null)
{
return null;
}
var pathWithoutExtension = RemoveExtension(path);
if (extension == null || path.Length == 0)
{
return pathWithoutExtension;
}
if (extension.Length == 0 || extension[0] != '.')
{
return pathWithoutExtension + "." + extension;
}
return pathWithoutExtension + extension;
}
/// <summary>
/// Returns the position in given path where the file name starts.
/// </summary>
/// <returns>-1 if path is null.</returns>
private static int IndexOfFileName(string path)
{
if (path == null)
{
return -1;
}
for (int i = path.Length - 1; i >= 0; i--)
{
char ch = path[i];
if (ch == DirectorySeparatorChar || ch == AltDirectorySeparatorChar || ch == VolumeSeparatorChar)
{
return i + 1;
}
}
return 0;
}
/// <summary>
/// Returns true if the string represents an unqualified file name.
/// </summary>
/// <param name="path">Path.</param>
/// <returns>True if <paramref name="path"/> is a simple file name, false if it is null or includes a directory specification.</returns>
internal static bool IsFileName(string path)
{
return IndexOfFileName(path) == 0;
}
/// <summary>
/// Get file name from path.
/// </summary>
/// <remarks>Unlike <see cref="M:System.IO.Path.GetFileName"/> doesn't check for invalid path characters.</remarks>
internal static string GetFileName(string path)
{
int fileNameStart = IndexOfFileName(path);
return (fileNameStart <= 0) ? path : path.Substring(fileNameStart);
}
/// <summary>
/// Get directory name from path.
/// </summary>
/// <remarks>
/// Unlike <see cref="M:System.IO.Path.GetDirectoryName"/> it
/// doesn't check for invalid path characters,
/// doesn't strip any trailing directory separators (TODO: tomat),
/// doesn't recognize UNC structure \\computer-name\share\directory-name\file-name (TODO: tomat).
/// </remarks>
/// <returns>Prefix of path that represents a directory. </returns>
internal static string GetDirectoryName(string path)
{
int fileNameStart = IndexOfFileName(path);
if (fileNameStart < 0)
{
return null;
}
return path.Substring(0, fileNameStart);
}
internal static PathKind GetPathKind(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
return PathKind.Empty;
}
// "C:\"
// "\\machine" (UNC)
if (IsAbsolute(path))
{
return PathKind.Absolute;
}
// "."
// ".."
// ".\"
// "..\"
if (path.Length > 0 && path[0] == '.')
{
if (path.Length == 1 || IsDirectorySeparator(path[1]))
{
return PathKind.RelativeToCurrentDirectory;
}
if (path[1] == '.')
{
if (path.Length == 2 || IsDirectorySeparator(path[2]))
{
return PathKind.RelativeToCurrentParent;
}
}
}
// "\"
// "\foo"
if (path.Length >= 1 && IsDirectorySeparator(path[0]))
{
return PathKind.RelativeToCurrentRoot;
}
// "C:foo"
if (path.Length >= 2 && path[1] == VolumeSeparatorChar && (path.Length <= 2 || !IsDirectorySeparator(path[2])))
{
return PathKind.RelativeToDriveDirectory;
}
// "foo.dll"
return PathKind.Relative;
}
internal static bool IsAbsolute(string path)
{
if (path == null)
{
return false;
}
// "C:\"
if (IsDriveRootedAbsolutePath(path))
{
// Including invalid paths (e.g. "*:\")
return true;
}
// "\\machine\share"
if (path.Length >= 2 && IsDirectorySeparator(path[0]) && IsDirectorySeparator(path[1]))
{
// Including invalid/incomplete UNC paths (e.g. "\\foo")
return true;
}
return false;
}
/// <summary>
/// Returns true if given path is absolute and starts with a drive specification ("C:\").
/// </summary>
private static bool IsDriveRootedAbsolutePath(string path)
{
return path.Length >= 3 && path[1] == VolumeSeparatorChar && IsDirectorySeparator(path[2]);
}
/// <summary>
/// Get a prefix of given path which is the root of the path.
/// </summary>
/// <returns>
/// Root of an absolute path or null if the path isn't absolute or has invalid format (e.g. "\\").
/// It may or may not end with a directory separator (e.g. "C:\", "C:\foo", "\\machine\share", etc.) .
/// </returns>
internal static string GetPathRoot(string path)
{
if (path == null)
{
return null;
}
int length = GetPathRootLength(path);
return (length != -1) ? path.Substring(0, length) : null;
}
private static int GetPathRootLength(string path)
{
Debug.Assert(path != null);
// "C:\"
if (IsDriveRootedAbsolutePath(path))
{
return 3;
}
// "\\machine\share"
return GetUncPathRootLength(path);
}
/// <summary>
/// Calculates the length of root of an UNC path.
/// </summary>
/// <remarks>
/// "\\server\share" is root of UNC path "\\server\share\dir1\dir2\file".
/// </remarks>
private static int GetUncPathRootLength(string path)
{
Debug.Assert(path != null);
// root:
// [directory-separator]{2,}[^directory-separator]+[directory-separator]+[^directory-separator]+
int serverIndex = IndexOfNonDirectorySeparator(path, 0);
if (serverIndex < 2)
{
return -1;
}
int separator = IndexOfDirectorySeparator(path, serverIndex);
if (separator == -1)
{
return -1;
}
int shareIndex = IndexOfNonDirectorySeparator(path, separator);
if (shareIndex == -1)
{
return -1;
}
int rootEnd = IndexOfDirectorySeparator(path, shareIndex);
return rootEnd == -1 ? path.Length : rootEnd;
}
private static int IndexOfDirectorySeparator(string path, int start)
{
for (int i = start; i < path.Length; i++)
{
if (IsDirectorySeparator(path[i]))
{
return i;
}
}
return -1;
}
private static int IndexOfNonDirectorySeparator(string path, int start)
{
for (int i = start; i < path.Length; i++)
{
if (!IsDirectorySeparator(path[i]))
{
return i;
}
}
return -1;
}
/// <summary>
/// Combines an absolute path with a relative.
/// </summary>
/// <param name="root">Absolute root path.</param>
/// <param name="relativePath">Relative path.</param>
/// <returns>
/// An absolute combined path, or null if <paramref name="relativePath"/> is
/// absolute (e.g. "C:\abc", "\\machine\share\abc"),
/// relative to the current root (e.g. "\abc"),
/// or relative to a drive directory (e.g. "C:abc\def").
/// </returns>
/// <seealso cref="CombinePossiblyRelativeAndRelativePaths"/>
internal static string CombineAbsoluteAndRelativePaths(string root, string relativePath)
{
Debug.Assert(IsAbsolute(root));
return CombinePossiblyRelativeAndRelativePaths(root, relativePath);
}
/// <summary>
/// Combine two paths, the first of which may be absolute.
/// </summary>
/// <param name="rootOpt">First path: absolute, relative, or null.</param>
/// <param name="relativePath">Second path: relative and non-null.</param>
/// <returns>null, if <paramref name="rootOpt"/> is null; a combined path, otherwise.</returns>
/// <seealso cref="CombineAbsoluteAndRelativePaths"/>
internal static string CombinePossiblyRelativeAndRelativePaths(string rootOpt, string relativePath)
{
if (string.IsNullOrEmpty(rootOpt))
{
return null;
}
switch (GetPathKind(relativePath))
{
case PathKind.Empty:
return rootOpt;
case PathKind.Absolute:
case PathKind.RelativeToCurrentRoot:
case PathKind.RelativeToDriveDirectory:
return null;
}
return CombinePathsUnchecked(rootOpt, relativePath);
}
internal static string CombinePathsUnchecked(string root, string relativePath)
{
Debug.Assert(!string.IsNullOrEmpty(root));
char c = root[root.Length - 1];
if (!IsDirectorySeparator(c) && c != VolumeSeparatorChar)
{
return root + DirectorySeparatorStr + relativePath;
}
return root + relativePath;
}
internal static bool IsDirectorySeparator(char c)
{
return c == DirectorySeparatorChar || c == AltDirectorySeparatorChar;
}
internal static string RemoveTrailingDirectorySeparator(string path)
{
if (path.Length > 0 && IsDirectorySeparator(path[path.Length - 1]))
{
return path.Substring(0, path.Length - 1);
}
else
{
return path;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SchemaImporter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization {
using System;
using System.Xml.Schema;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Configuration;
using System.Xml.Serialization.Configuration;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Security.Permissions;
using System.Xml.Serialization.Advanced;
#if DEBUG
using System.Diagnostics;
#endif
/// <include file='doc\SchemaImporter.uex' path='docs/doc[@for="SchemaImporter"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
public abstract class SchemaImporter {
XmlSchemas schemas;
StructMapping root;
CodeGenerationOptions options;
CodeDomProvider codeProvider;
TypeScope scope;
ImportContext context;
bool rootImported;
NameTable typesInUse;
NameTable groupsInUse;
SchemaImporterExtensionCollection extensions;
internal SchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, CodeDomProvider codeProvider, ImportContext context) {
if (!schemas.Contains(XmlSchema.Namespace)) {
schemas.AddReference(XmlSchemas.XsdSchema);
schemas.SchemaSet.Add(XmlSchemas.XsdSchema);
}
if (!schemas.Contains(XmlReservedNs.NsXml)) {
schemas.AddReference(XmlSchemas.XmlSchema);
schemas.SchemaSet.Add(XmlSchemas.XmlSchema);
}
this.schemas = schemas;
this.options = options;
this.codeProvider = codeProvider;
this.context = context;
Schemas.SetCache(Context.Cache, Context.ShareTypes);
#if CONFIGURATION_DEP
SchemaImporterExtensionsSection section = PrivilegedConfigurationManager.GetSection(ConfigurationStrings.SchemaImporterExtensionsSectionPath) as SchemaImporterExtensionsSection;
if (section != null)
extensions = section.SchemaImporterExtensionsInternal;
else
#endif
extensions = new SchemaImporterExtensionCollection();
}
internal ImportContext Context {
get {
if (context == null)
context = new ImportContext();
return context;
}
}
internal CodeDomProvider CodeProvider {
get {
if (codeProvider == null)
codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
return codeProvider;
}
}
public SchemaImporterExtensionCollection Extensions {
get {
if (extensions == null)
extensions = new SchemaImporterExtensionCollection();
return extensions;
}
}
internal Hashtable ImportedElements {
get { return Context.Elements; }
}
internal Hashtable ImportedMappings {
get { return Context.Mappings; }
}
internal CodeIdentifiers TypeIdentifiers {
get { return Context.TypeIdentifiers; }
}
internal XmlSchemas Schemas {
get {
if (schemas == null)
schemas = new XmlSchemas();
return schemas;
}
}
internal TypeScope Scope {
get {
if (scope == null)
scope = new TypeScope();
return scope;
}
}
internal NameTable GroupsInUse {
get {
if (groupsInUse == null)
groupsInUse = new NameTable();
return groupsInUse;
}
}
internal NameTable TypesInUse {
get {
if (typesInUse == null)
typesInUse = new NameTable();
return typesInUse;
}
}
internal CodeGenerationOptions Options {
get { return options; }
}
internal void MakeDerived(StructMapping structMapping, Type baseType, bool baseTypeCanBeIndirect) {
structMapping.ReferencedByTopLevelElement = true;
TypeDesc baseTypeDesc;
if (baseType != null) {
baseTypeDesc = Scope.GetTypeDesc(baseType);
if (baseTypeDesc != null) {
TypeDesc typeDescToChange = structMapping.TypeDesc;
if (baseTypeCanBeIndirect) {
// if baseTypeCanBeIndirect is true, we apply the supplied baseType to the top of the
// inheritance chain, not necessarily directly to the imported type.
while (typeDescToChange.BaseTypeDesc != null && typeDescToChange.BaseTypeDesc != baseTypeDesc)
typeDescToChange = typeDescToChange.BaseTypeDesc;
}
if (typeDescToChange.BaseTypeDesc != null && typeDescToChange.BaseTypeDesc != baseTypeDesc)
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidBaseType, structMapping.TypeDesc.FullName, baseType.FullName, typeDescToChange.BaseTypeDesc.FullName));
typeDescToChange.BaseTypeDesc = baseTypeDesc;
}
}
}
internal string GenerateUniqueTypeName(string typeName) {
typeName = CodeIdentifier.MakeValid(typeName);
return TypeIdentifiers.AddUnique(typeName, typeName);
}
StructMapping CreateRootMapping() {
TypeDesc typeDesc = Scope.GetTypeDesc(typeof(object));
StructMapping mapping = new StructMapping();
mapping.TypeDesc = typeDesc;
mapping.Members = new MemberMapping[0];
mapping.IncludeInSchema = false;
mapping.TypeName = Soap.UrType;
mapping.Namespace = XmlSchema.Namespace;
return mapping;
}
internal StructMapping GetRootMapping() {
if (root == null)
root = CreateRootMapping();
return root;
}
internal StructMapping ImportRootMapping() {
if (!rootImported) {
rootImported = true;
ImportDerivedTypes(XmlQualifiedName.Empty);
}
return GetRootMapping();
}
internal abstract void ImportDerivedTypes(XmlQualifiedName baseName);
internal void AddReference(XmlQualifiedName name, NameTable references, string error) {
if (name.Namespace == XmlSchema.Namespace)
return;
if (references[name] != null) {
throw new InvalidOperationException(Res.GetString(error, name.Name, name.Namespace));
}
references[name] = name;
}
internal void RemoveReference(XmlQualifiedName name, NameTable references) {
references[name] = null;
}
internal void AddReservedIdentifiersForDataBinding(CodeIdentifiers scope)
{
if ((options & CodeGenerationOptions.EnableDataBinding) != 0)
{
scope.AddReserved(CodeExporter.PropertyChangedEvent.Name);
scope.AddReserved(CodeExporter.RaisePropertyChangedEventMethod.Name);
}
}
}
}
| |
//
// https://github.com/NServiceKit/NServiceKit.Text
// NServiceKit.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot ([email protected])
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Linq;
using NServiceKit.Text.Json;
namespace NServiceKit.Text.Common
{
/// <summary>Dictionary of deserializes.</summary>
/// <typeparam name="TSerializer">Type of the serializer.</typeparam>
internal static class DeserializeDictionary<TSerializer>
where TSerializer : ITypeSerializer
{
/// <summary>The serializer.</summary>
private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
/// <summary>Zero-based index of the key.</summary>
const int KeyIndex = 0;
/// <summary>Zero-based index of the value.</summary>
const int ValueIndex = 1;
/// <summary>Gets parse method.</summary>
/// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or
/// illegal values.</exception>
/// <param name="type">The type.</param>
/// <returns>The parse method.</returns>
public static ParseStringDelegate GetParseMethod(Type type)
{
var mapInterface = type.GetTypeWithGenericInterfaceOf(typeof(IDictionary<,>));
if (mapInterface == null)
{
#if !SILVERLIGHT
if (type == typeof(Hashtable))
{
return ParseHashtable;
}
#endif
if (type == typeof(IDictionary))
{
return GetParseMethod(typeof(Dictionary<object, object>));
}
throw new ArgumentException(string.Format("Type {0} is not of type IDictionary<,>", type.FullName));
}
//optimized access for regularly used types
if (type == typeof(Dictionary<string, string>))
{
return ParseStringDictionary;
}
if (type == typeof(JsonObject))
{
return ParseJsonObject;
}
var dictionaryArgs = mapInterface.GenericTypeArguments();
var keyTypeParseMethod = Serializer.GetParseFn(dictionaryArgs[KeyIndex]);
if (keyTypeParseMethod == null) return null;
var valueTypeParseMethod = Serializer.GetParseFn(dictionaryArgs[ValueIndex]);
if (valueTypeParseMethod == null) return null;
var createMapType = type.HasAnyTypeDefinitionsOf(typeof(Dictionary<,>), typeof(IDictionary<,>))
? null : type;
return value => ParseDictionaryType(value, createMapType, dictionaryArgs, keyTypeParseMethod, valueTypeParseMethod);
}
/// <summary>Parse JSON object.</summary>
/// <param name="value">The value.</param>
/// <returns>A JsonObject.</returns>
public static JsonObject ParseJsonObject(string value)
{
var index = VerifyAndGetStartIndex(value, typeof(JsonObject));
var result = new JsonObject();
if (JsonTypeSerializer.IsEmptyMap(value, index)) return result;
var valueLength = value.Length;
while (index < valueLength)
{
var keyValue = Serializer.EatMapKey(value, ref index);
Serializer.EatMapKeySeperator(value, ref index);
var elementValue = Serializer.EatValue(value, ref index);
if (keyValue == null) continue;
var mapKey = keyValue;
var mapValue = elementValue;
result[mapKey] = mapValue;
Serializer.EatItemSeperatorOrMapEndChar(value, ref index);
}
return result;
}
#if !SILVERLIGHT
/// <summary>Parse hashtable.</summary>
/// <param name="value">The value.</param>
/// <returns>A Hashtable.</returns>
public static Hashtable ParseHashtable(string value)
{
var index = VerifyAndGetStartIndex(value, typeof(Hashtable));
var result = new Hashtable();
if (JsonTypeSerializer.IsEmptyMap(value, index)) return result;
var valueLength = value.Length;
while (index < valueLength)
{
var keyValue = Serializer.EatMapKey(value, ref index);
Serializer.EatMapKeySeperator(value, ref index);
var elementValue = Serializer.EatValue(value, ref index);
if (keyValue == null) continue;
var mapKey = keyValue;
var mapValue = elementValue;
result[mapKey] = mapValue;
Serializer.EatItemSeperatorOrMapEndChar(value, ref index);
}
return result;
}
#endif
/// <summary>Parse string dictionary.</summary>
/// <param name="value">The value.</param>
/// <returns>A Dictionary<string,string></returns>
public static Dictionary<string, string> ParseStringDictionary(string value)
{
var index = VerifyAndGetStartIndex(value, typeof(Dictionary<string, string>));
var result = new Dictionary<string, string>();
if (JsonTypeSerializer.IsEmptyMap(value, index)) return result;
var valueLength = value.Length;
while (index < valueLength)
{
var keyValue = Serializer.EatMapKey(value, ref index);
Serializer.EatMapKeySeperator(value, ref index);
var elementValue = Serializer.EatValue(value, ref index);
if (keyValue == null) continue;
var mapKey = Serializer.UnescapeString(keyValue);
var mapValue = Serializer.UnescapeString(elementValue);
result[mapKey] = mapValue;
Serializer.EatItemSeperatorOrMapEndChar(value, ref index);
}
return result;
}
/// <summary>Parse dictionary.</summary>
/// <typeparam name="TKey"> Type of the key.</typeparam>
/// <typeparam name="TValue">Type of the value.</typeparam>
/// <param name="value"> The value.</param>
/// <param name="createMapType">Type of the create map.</param>
/// <param name="parseKeyFn"> The parse key function.</param>
/// <param name="parseValueFn"> The parse value function.</param>
/// <returns>An IDictionary<TKey,TValue></returns>
public static IDictionary<TKey, TValue> ParseDictionary<TKey, TValue>(
string value, Type createMapType,
ParseStringDelegate parseKeyFn, ParseStringDelegate parseValueFn)
{
if (value == null) return null;
var tryToParseItemsAsDictionaries =
JsConfig.ConvertObjectTypesIntoStringDictionary && typeof(TValue) == typeof(object);
var tryToParseItemsAsPrimitiveTypes =
JsConfig.TryToParsePrimitiveTypeValues && typeof(TValue) == typeof(object);
var index = VerifyAndGetStartIndex(value, createMapType);
var to = (createMapType == null)
? new Dictionary<TKey, TValue>()
: (IDictionary<TKey, TValue>)createMapType.CreateInstance();
if (JsonTypeSerializer.IsEmptyMap(value, index)) return to;
var valueLength = value.Length;
while (index < valueLength)
{
var keyValue = Serializer.EatMapKey(value, ref index);
Serializer.EatMapKeySeperator(value, ref index);
var elementStartIndex = index;
var elementValue = Serializer.EatTypeValue(value, ref index);
if (keyValue == null) continue;
TKey mapKey = (TKey)parseKeyFn(keyValue);
if (tryToParseItemsAsDictionaries)
{
Serializer.EatWhitespace(value, ref elementStartIndex);
if (elementStartIndex < valueLength && value[elementStartIndex] == JsWriter.MapStartChar)
{
var tmpMap = ParseDictionary<TKey, TValue>(elementValue, createMapType, parseKeyFn, parseValueFn);
if (tmpMap != null && tmpMap.Count > 0)
{
to[mapKey] = (TValue)tmpMap;
}
}
else if (elementStartIndex < valueLength && value[elementStartIndex] == JsWriter.ListStartChar)
{
to[mapKey] = (TValue)DeserializeList<List<object>, TSerializer>.Parse(elementValue);
}
else
{
to[mapKey] = (TValue)(tryToParseItemsAsPrimitiveTypes && elementStartIndex < valueLength
? DeserializeType<TSerializer>.ParsePrimitive(elementValue, value[elementStartIndex])
: parseValueFn(elementValue));
}
}
else
{
if (tryToParseItemsAsPrimitiveTypes && elementStartIndex < valueLength)
{
Serializer.EatWhitespace(value, ref elementStartIndex);
to[mapKey] = (TValue)DeserializeType<TSerializer>.ParsePrimitive(elementValue, value[elementStartIndex]);
}
else
{
to[mapKey] = (TValue)parseValueFn(elementValue);
}
}
Serializer.EatItemSeperatorOrMapEndChar(value, ref index);
}
return to;
}
/// <summary>Verify and get start index.</summary>
/// <param name="value"> The value.</param>
/// <param name="createMapType">Type of the create map.</param>
/// <returns>An int.</returns>
private static int VerifyAndGetStartIndex(string value, Type createMapType)
{
var index = 0;
if (!Serializer.EatMapStartChar(value, ref index))
{
//Don't throw ex because some KeyValueDataContractDeserializer don't have '{}'
Tracer.Instance.WriteDebug("WARN: Map definitions should start with a '{0}', expecting serialized type '{1}', got string starting with: {2}",
JsWriter.MapStartChar, createMapType != null ? createMapType.Name : "Dictionary<,>", value.Substring(0, value.Length < 50 ? value.Length : 50));
}
return index;
}
/// <summary>The parse delegate cache.</summary>
private static Dictionary<string, ParseDictionaryDelegate> ParseDelegateCache
= new Dictionary<string, ParseDictionaryDelegate>();
/// <summary>Parse dictionary delegate.</summary>
/// <param name="value"> The value.</param>
/// <param name="createMapType">Type of the create map.</param>
/// <param name="keyParseFn"> The key parse function.</param>
/// <param name="valueParseFn"> The value parse function.</param>
/// <returns>An object.</returns>
private delegate object ParseDictionaryDelegate(string value, Type createMapType,
ParseStringDelegate keyParseFn, ParseStringDelegate valueParseFn);
/// <summary>Parse dictionary type.</summary>
/// <param name="value"> The value.</param>
/// <param name="createMapType">Type of the create map.</param>
/// <param name="argTypes"> List of types of the arguments.</param>
/// <param name="keyParseFn"> The key parse function.</param>
/// <param name="valueParseFn"> The value parse function.</param>
/// <returns>An object.</returns>
public static object ParseDictionaryType(string value, Type createMapType, Type[] argTypes,
ParseStringDelegate keyParseFn, ParseStringDelegate valueParseFn)
{
ParseDictionaryDelegate parseDelegate;
var key = GetTypesKey(argTypes);
if (ParseDelegateCache.TryGetValue(key, out parseDelegate))
return parseDelegate(value, createMapType, keyParseFn, valueParseFn);
var mi = typeof(DeserializeDictionary<TSerializer>).GetPublicStaticMethod("ParseDictionary");
var genericMi = mi.MakeGenericMethod(argTypes);
parseDelegate = (ParseDictionaryDelegate)genericMi.MakeDelegate(typeof(ParseDictionaryDelegate));
Dictionary<string, ParseDictionaryDelegate> snapshot, newCache;
do
{
snapshot = ParseDelegateCache;
newCache = new Dictionary<string, ParseDictionaryDelegate>(ParseDelegateCache);
newCache[key] = parseDelegate;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref ParseDelegateCache, newCache, snapshot), snapshot));
return parseDelegate(value, createMapType, keyParseFn, valueParseFn);
}
/// <summary>Gets types key.</summary>
/// <param name="types">A variable-length parameters list containing types.</param>
/// <returns>The types key.</returns>
private static string GetTypesKey(params Type[] types)
{
var sb = new StringBuilder(256);
foreach (var type in types)
{
if (sb.Length > 0)
sb.Append(">");
sb.Append(type.FullName);
}
return sb.ToString();
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.Events.Edir.EventData.GeneralDSEventData.cs
//
// Author:
// Anil Bhatia ([email protected])
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System.IO;
using System.Text;
using Novell.Directory.LDAP.VQ.Asn1;
namespace Novell.Directory.LDAP.VQ.Events.Edir.EventData
{
/// <summary>
/// The class represents the data for General DS Events.
/// </summary>
public class GeneralDSEventData : BaseEdirEventData
{
protected int ds_time;
public int DSTime
{
get
{
return ds_time;
}
}
protected int milli_seconds;
public int MilliSeconds
{
get
{
return milli_seconds;
}
}
protected int nVerb;
public int Verb
{
get
{
return nVerb;
}
}
protected int current_process;
public int CurrentProcess
{
get
{
return current_process;
}
}
protected string strPerpetratorDN;
public string PerpetratorDN
{
get
{
return strPerpetratorDN;
}
}
protected int[] integer_values;
public int[] IntegerValues
{
get
{
return integer_values;
}
}
protected string[] string_values;
public string[] StringValues
{
get
{
return string_values;
}
}
public GeneralDSEventData(EdirEventDataType eventDataType, Asn1Object message)
: base(eventDataType, message)
{
int[] length = new int[1];
ds_time = getTaggedIntValue(
(Asn1Tagged) decoder.decode(decodedData, length),
GeneralEventField.EVT_TAG_GEN_DSTIME);
milli_seconds = getTaggedIntValue(
(Asn1Tagged) decoder.decode(decodedData, length),
GeneralEventField.EVT_TAG_GEN_MILLISEC);
nVerb = getTaggedIntValue(
(Asn1Tagged) decoder.decode(decodedData, length),
GeneralEventField.EVT_TAG_GEN_VERB);
current_process = getTaggedIntValue(
(Asn1Tagged) decoder.decode(decodedData, length),
GeneralEventField.EVT_TAG_GEN_CURRPROC);
strPerpetratorDN = getTaggedStringValue(
(Asn1Tagged) decoder.decode(decodedData, length),
GeneralEventField.EVT_TAG_GEN_PERP);
Asn1Tagged temptaggedvalue =
((Asn1Tagged) decoder.decode(decodedData, length));
if (temptaggedvalue.getIdentifier().Tag
== (int) GeneralEventField.EVT_TAG_GEN_INTEGERS)
{
//Integer List.
Asn1Sequence inteseq = getTaggedSequence(temptaggedvalue, GeneralEventField.EVT_TAG_GEN_INTEGERS);
Asn1Object[] intobject = inteseq.toArray();
integer_values = new int[intobject.Length];
for (int i = 0; i < intobject.Length; i++)
{
integer_values[i] = ((Asn1Integer) intobject[i]).intValue();
}
//second decoding for Strings.
temptaggedvalue = ((Asn1Tagged) decoder.decode(decodedData, length));
}
else
{
integer_values = null;
}
if ((temptaggedvalue.getIdentifier().Tag
== (int) GeneralEventField.EVT_TAG_GEN_STRINGS)
&& (temptaggedvalue.getIdentifier().Constructed))
{
//String values.
Asn1Sequence inteseq =
getTaggedSequence(temptaggedvalue, GeneralEventField.EVT_TAG_GEN_STRINGS);
Asn1Object[] stringobject = inteseq.toArray();
string_values = new string[stringobject.Length];
for (int i = 0; i < stringobject.Length; i++)
{
string_values[i] =
((Asn1OctetString) stringobject[i]).stringValue();
}
}
else
{
string_values = null;
}
DataInitDone();
}
protected int getTaggedIntValue(Asn1Tagged tagvalue, GeneralEventField tagid)
{
Asn1Object obj = tagvalue.taggedValue();
if ((int)tagid != tagvalue.getIdentifier().Tag)
{
throw new IOException("Unknown Tagged Data");
}
byte[] dbytes = SupportClass.ToByteArray(((Asn1OctetString) obj).byteValue());
MemoryStream data = new MemoryStream(dbytes);
LBERDecoder dec = new LBERDecoder();
int length = dbytes.Length;
return (int)(dec.decodeNumeric(data, length));
}
protected string getTaggedStringValue(Asn1Tagged tagvalue, GeneralEventField tagid)
{
Asn1Object obj = tagvalue.taggedValue();
if ((int)tagid != tagvalue.getIdentifier().Tag)
{
throw new IOException("Unknown Tagged Data");
}
byte[] dbytes = SupportClass.ToByteArray(((Asn1OctetString) obj).byteValue());
MemoryStream data = new MemoryStream(dbytes);
LBERDecoder dec = new LBERDecoder();
int length = dbytes.Length;
return (string) dec.decodeCharacterString(data, length);
}
protected Asn1Sequence getTaggedSequence(Asn1Tagged tagvalue, GeneralEventField tagid)
{
Asn1Object obj = tagvalue.taggedValue();
if ((int)tagid != tagvalue.getIdentifier().Tag)
{
throw new IOException("Unknown Tagged Data");
}
byte[] dbytes = SupportClass.ToByteArray(((Asn1OctetString) obj).byteValue());
MemoryStream data = new MemoryStream(dbytes);
LBERDecoder dec = new LBERDecoder();
int length = dbytes.Length;
return new Asn1Sequence(dec, data, length);
}
/// <summary>
/// Returns a string representation of the object.
/// </summary>
public override string ToString()
{
StringBuilder buf = new StringBuilder();
buf.Append("[GeneralDSEventData");
buf.AppendFormat("(DSTime={0})", ds_time);
buf.AppendFormat("(MilliSeconds={0})", milli_seconds);
buf.AppendFormat("(verb={0})",nVerb);
buf.AppendFormat("(currentProcess={0})", current_process);
buf.AppendFormat("(PerpetartorDN={0})", strPerpetratorDN);
buf.AppendFormat("(Integer Values={0})", integer_values);
buf.AppendFormat("(String Values={0})", string_values);
buf.Append("]");
return buf.ToString();
}
}
}
| |
public class Grid3d {
public static List<Grid3d> list;
public static const int tileSize = 1;
public static const int pathFound = 1;
public static const int pathNotFound = 2;
public List<List<List<GridNode3d>>> nodes;
public List<GridNode3d> openedList;
public List<GridNode3d> closedList;
public List<GridNode3d> finalPath;
private Vector3 start, end;
string name;
public Vector3 size;
/** INITIALISING */
public static void initialiseInstances() {
list = new List<Grid>();
}
private void initialise() {
this.nodes = new List<List<List<GridNode3d>>>();
this.openedList = new List<GridNode3d>();
this.closedList = new List<GridNode3d>();
this.finalPath = new List<GridNode3d>();
this.start = new Vector3();
this.end = new Vector3();
this.name = "n/a";
this.size = new Vector3(0, 0, 0);
}
/** CREATING AND SETTING */
private Grid() {
this.initialise();
}
private void setUp(string name, Vector3 size) {
this.name = name;
this.size.x = size.x;
this.size.y = size.y;
this.size.z = size.z;
this.createNodes();
}
void createNodes() {
Vector3 nodePos = new Vector3();
for (int x = 0; x < this.size.x; x++) {
this.nodes.Add(new List<List<GridNode3d>>());
nodePos.x = x;
for (int y = 0; y < this.size.y; y++) {
this.nodes[x].Add(new List<GridNode3d>());
nodePos.y = y;
for (int z = 0; z < this.size.z; z++) {
this.nodes[x][y].Add(new GridNode3d(this.name, nodePos));
}
}
}
}
/** PATHFINDING */
static Vector3 openListPosition = new Vector3();
public int findPath() {
this.openedList.Clear();
this.closedList.Clear();
this.finalPath.Clear();
this.resetNodes();
if (this.start.x == -1 || this.start.y == -1 || this.start.z == -1
||this.end.x == -1 || this.end.y == -1 || this.end.z == -1) {
return pathNotFound;
} else if (this.start.x == this.end.x
&&this.start.y == this.end.y
&&this.start.z == this.end.z) {
return pathFound;
} else {
this.openedList.Add(
this.nodes[(int) start.x][(int) start.y][(int) start.z]
);
this.setOpenList(this.start);
this.closedList.Add(this.openedList[0]);
this.openedList.Remove(this.openedList[0]);
while (this.closedList[this.closedList.Count - 1] != this.getEndNode()) {
if (this.openedList.Count != 0) {
int bestFIndex = this.getBestFIndex();
if (bestFIndex != -1) {
this.closedList.Add(this.openedList[bestFIndex]);
this.openedList.Remove(this.openedList[bestFIndex]);
openListPosition.x = this.closedList[this.closedList.Count - 1].gridCoordinates.x;
openListPosition.y = this.closedList[this.closedList.Count - 1].gridCoordinates.y;
openListPosition.z = this.closedList[this.closedList.Count - 1].gridCoordinates.z;
this.setOpenList(openListPosition);
}else {
return pathNotFound;
}
}else {
return pathNotFound;
}
}
}
GridNode3d g = this.closedList[this.closedList.Count - 1];
this.finalPath.Add(g);
while (g != this.getStartNode()) {
g = g.parent;
this.finalPath.Add(g);
}
this.finalPath.Reverse();
return pathFound;
}
private void setOpenList(Vector3 gridCoordinates) {
bool ignoreLeft = (gridCoordinates.x - 1) < 0;
bool ignoreRight = (gridCoordinates.x + 1) >= this.size.x;
bool ignoreDown = (gridCoordinates.y - 1) < 0;
bool ignoreUp = (gridCoordinates.y + 1) >= this.size.y;
bool ignoreBack = (gridCoordinates.z - 1) < 0;
bool ignoreFront = (gridCoordinates.z + 1) >= this.size.z;
if (!ignoreLeft && !ignoreDown && !ignoreBack) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x - 1][(int)gridCoordinates.y - 1][(int)gridCoordinates.z - 1]);
}
if (!ignoreLeft && !ignoreDown) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x - 1][(int)gridCoordinates.y - 1][(int)gridCoordinates.z]);
}
if (!ignoreLeft && !ignoreDown && !ignoreFront) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x - 1][(int)gridCoordinates.y - 1][(int)gridCoordinates.z + 1]);
}
if (!ignoreDown && !ignoreBack) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y - 1][(int)gridCoordinates.z - 1]);
}
if (!ignoreDown) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y - 1][(int)gridCoordinates.z]);
}
if (!ignoreDown && !ignoreFront) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y - 1][(int)gridCoordinates.z + 1]);
}
if (!ignoreRight && !ignoreDown && !ignoreBack) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x + 1][(int)gridCoordinates.y - 1][(int)gridCoordinates.z - 1]);
}
if (!ignoreRight && !ignoreDown) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x + 1][(int)gridCoordinates.y - 1][(int)gridCoordinates.z]);
}
if (!ignoreRight && !ignoreDown && !ignoreFront) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x + 1][(int)gridCoordinates.y - 1][(int)gridCoordinates.z + 1]);
}
if (!ignoreLeft && !ignoreBack) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x - 1][(int)gridCoordinates.y][(int)gridCoordinates.z - 1]);
}
if (!ignoreLeft) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x - 1][(int)gridCoordinates.y][(int)gridCoordinates.z]);
}
if (!ignoreLeft && !ignoreFront) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x - 1][(int)gridCoordinates.y][(int)gridCoordinates.z + 1]);
}
if (!ignoreBack) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z - 1]);
}
if (!ignoreFront) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z + 1]);
}
if (!ignoreRight && !ignoreBack) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x + 1][(int)gridCoordinates.y][(int)gridCoordinates.z - 1]);
}
if (!ignoreRight) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x + 1][(int)gridCoordinates.y][(int)gridCoordinates.z]);
}
if (!ignoreRight && !ignoreFront) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x + 1][(int)gridCoordinates.y][(int)gridCoordinates.z + 1]);
}
if (!ignoreLeft && !ignoreUp && !ignoreBack) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x - 1][(int)gridCoordinates.y + 1][(int)gridCoordinates.z - 1]);
}
if (!ignoreLeft && !ignoreUp) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x - 1][(int)gridCoordinates.y + 1][(int)gridCoordinates.z]);
}
if (!ignoreLeft && !ignoreUp && !ignoreFront) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x - 1][(int)gridCoordinates.y + 1][(int)gridCoordinates.z + 1]);
}
if (!ignoreUp && !ignoreBack) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y + 1][(int)gridCoordinates.z - 1]);
}
if (!ignoreUp) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y + 1][(int)gridCoordinates.z]);
}
if (!ignoreUp && !ignoreFront) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y + 1][(int)gridCoordinates.z + 1]);
}
if (!ignoreRight && !ignoreUp && !ignoreBack) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x + 1][(int)gridCoordinates.y + 1][(int)gridCoordinates.z - 1]);
}
if (!ignoreRight && !ignoreUp) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x + 1][(int)gridCoordinates.y + 1][(int)gridCoordinates.z]);
}
if (!ignoreRight && !ignoreUp && !ignoreFront) {
lookNode(this.nodes[(int)gridCoordinates.x][(int)gridCoordinates.y][(int)gridCoordinates.z],
this.nodes[(int)gridCoordinates.x + 1][(int)gridCoordinates.y + 1][(int)gridCoordinates.z + 1]);
}
}
private void lookNode(GridNode3d parentNode, GridNode3d currentNode) {
if (currentNode.type != GridNode3d.Type.BLOCK &&
!(this.closedList.Contains(currentNode))) {
if (!(this.openedList.Contains(currentNode))) {
currentNode.calculateValues(parentNode, this.getEndNode());
this.openedList.Add(currentNode);
} else {
compareParentWithOpen(parentNode, currentNode);
}
}
}
private void compareParentWithOpen(GridNode3d parentNode, GridNode3d openNode) {
double tempG = openNode.G;
double xDistance = Mathf.Abs(openNode.gridCoordinates.x - parentNode.gridCoordinates.x) / tileSize;
double yDistance = Mathf.Abs(openNode.gridCoordinates.y - parentNode.gridCoordinates.y) / tileSize;
double zDistance = Mathf.Abs(openNode.gridCoordinates.z - parentNode.gridCoordinates.z) / tileSize;
if (xDistance == 1 && yDistance == 1 && zDistance == 1) {
tempG += 17;
}else if ((xDistance == 1 && yDistance == 1)
||(xDistance == 1 && zDistance == 1)
||(yDistance == 1 && zDistance == 1)) {
tempG += 14;
}else {
tempG += 10;
}
if (tempG < parentNode.G) {
openNode.calculateValues(parentNode, this.getEndNode());
this.openedList[this.openedList.IndexOf(openNode)] = openNode;
}
}
public void setGridNode(Vector3 position, GridNode.Type type) {
if (position.x >= 0 && position.x < this.size.x) {
if (position.y >= 0 && position.y < this.size.y) {
if (position.z >= 0 && position.z < this.size.z) {
if (type == GridNode.Type.START || type == GridNode.Type.END) {
for (int x = 0; x < this.size.x; x++) {
for (int y = 0; y < this.size.y; y++) {
for (int z = 0; z < this.size.z; z++) {
if (this.nodes[x][y][z].type == type) {
if (type == GridNode.Type.START) {
this.start.x = -1;
this.start.y = -1;
this.start.z = -1;
} else {
this.end.x = -1;
this.end.y = -1;
this.end.z = -1;
}
this.nodes[x][y][z].type = GridNode.Type.NONE;
}
}
}
}
}
}
}
}
if (this.nodes[(int)position.x][(int)position.y][(int)position.z].type == type) {
this.nodes[(int)position.x][(int)position.y][(int)position.z].type = GridNode.Type.NONE;
} else {
if (type == GridNode.Type.START) {
this.start.x = position.x;
this.start.y = position.y;
this.start.z = position.z;
} else if (type == GridNode.Type.END) {
this.end.x = position.x;
this.end.y = position.y;
this.end.z = position.z;
}
this.nodes[(int)position.x][(int)position.y][(int)position.z].type = type;
}
}
/** GETTERS / SETTERS */
public GridNode3d getStartNode() {
return this.nodes[(int) start.x][(int) start.y][(int) start.z];
}
public GridNode3d getEndNode() {
return this.nodes[(int) end.x][(int) end.y][(int) end.z];
}
private int getBestFIndex () {
double bestF = float.MaxValue;
int index = -1;
for (int i = 0; i < this.openedList.Count; i++) {
if (bestF > this.openedList[i].F) {
bestF = this.openedList[i].F;
index = i;
}
}
return index;
}
/** DISPOSING / RESETTING */
private void resetNodes() {
for (int x = 0; x < this.size.x; x++) {
for (int y = 0; y < this.size.y; y++) {
for (int z = 0; z < this.size.z; z++) {
this.nodes[x][y][z].reset();
}
}
}
}
}
| |
//
// Sample showing the core Element-based API to create a dialog
//
using System;
using System.Linq;
using MonoTouch.Dialog;
#if __UNIFIED__
using UIKit;
using CoreGraphics;
using Foundation;
#else
using MonoTouch.UIKit;
using MonoTouch.CoreGraphics;
using MonoTouch.Foundation;
#endif
namespace Sample
{
public partial class AppDelegate
{
public void DemoElementApi ()
{
var root = CreateRoot ();
var dv = new DialogViewController (root, true);
navigation.PushViewController (dv, true);
}
RootElement CreateRoot ()
{
return new RootElement ("Settings") {
new Section (){
new BooleanElement ("Airplane Mode", false),
new RootElement ("Notifications", 0, 0) {
new Section (null, "Turn off Notifications to disable Sounds\n" +
"Alerts and Home Screen Badges for the\napplications below."){
new BooleanElement ("Notifications", false)
}
}},
new Section (){
CreateSoundSection (),
new RootElement ("Brightness"){
new Section (){
#if !XAMCORE_2_0
new FloatElement (null, null, 0.5f),
#endif
new BooleanElement ("Auto-brightness", false),
}
},
new RootElement ("Wallpaper"){
new Section (){
new ImageElement (null),
new ImageElement (null),
new ImageElement (null)
}
}
},
new Section () {
new EntryElement ("Login", "Your login name", null)
{
EnablesReturnKeyAutomatically = true,
AlignEntryWithAllSections = true,
},
new EntryElement ("Password", "Your password", null, true)
{
EnablesReturnKeyAutomatically = true,
AlignEntryWithAllSections = true,
},
new DateElement ("Select Date", DateTime.Now),
new TimeElement ("Select Time", DateTime.Now),
},
new Section () {
new EntryElement ("Another Field", "Aligns with above fields", null)
{
AlignEntryWithAllSections = true,
},
},
new Section () {
CreateGeneralSection (),
//new RootElement ("Mail, Contacts, Calendars"),
//new RootElement ("Phone"),
//new RootElement ("Safari"),
//new RootElement ("Messages"),
//new RootElement ("iPod"),
//new RootElement ("Photos"),
//new RootElement ("Store"),
},
new Section () {
new HtmlElement ("About", "http://monotouch.net"),
new MultilineElement ("Remember to eat\nfruits and vegetables\nevery day")
}
};
}
RootElement CreateSoundSection ()
{
return new RootElement ("Sounds"){
new Section ("Silent") {
new BooleanElement ("Vibrate", true),
},
new Section ("Ring") {
new BooleanElement ("Vibrate", true),
#if !XAMCORE_2_0
new FloatElement (null, null, 0.8f),
#endif
new RootElement ("Ringtone", new RadioGroup (0)){
new Section ("Custom"){
new RadioElement ("Circus Music"),
new RadioElement ("True Blood"),
},
new Section ("Standard"){
from n in "Marimba,Alarm,Ascending,Bark,Xylophone".Split (',')
select (Element) new RadioElement (n)
}
},
new RootElement ("New Text Message", new RadioGroup (3)){
new Section (){
from n in "None,Tri-tone,Chime,Glass,Horn,Bell,Eletronic".Split (',')
select (Element) new RadioElement (n)
}
},
new BooleanElement ("New Voice Mail", false),
new BooleanElement ("New Mail", false),
new BooleanElement ("Sent Mail", true),
new BooleanElement ("Calendar Alerts", true),
new BooleanElement ("Lock Sounds", true),
new BooleanElement ("Keyboard Clicks", false)
}
};
}
public RootElement CreateGeneralSection ()
{
return new RootElement ("General") {
new Section (){
new RootElement ("About"){
new Section ("My Phone") {
new RootElement ("Network", new RadioGroup (null, 0)) {
new Section (){
new RadioElement ("My First Network"),
new RadioElement ("Second Network"),
}
},
new StringElement ("Songs", "23"),
new StringElement ("Videos", "3"),
new StringElement ("Photos", "24"),
new StringElement ("Applications", "50"),
new StringElement ("Capacity", "14.6GB"),
new StringElement ("Available", "12.8GB"),
new StringElement ("Version", "3.0 (FOOBAR)"),
new StringElement ("Carrier", "My Carrier"),
new StringElement ("Serial Number", "555-3434"),
new StringElement ("Model", "The"),
new StringElement ("Wi-Fi Address", "11:22:33:44:55:66"),
new StringElement ("Bluetooth", "aa:bb:cc:dd:ee:ff:00"),
},
new Section () {
new HtmlElement ("Monologue", "http://www.go-mono.com/monologue"),
}
},
new RootElement ("Usage"){
new Section ("Time since last full charge"){
new StringElement ("Usage", "0 minutes"),
new StringElement ("Standby", "0 minutes"),
},
new Section ("Call time") {
new StringElement ("Current Period", "4 days, 21 hours"),
new StringElement ("Lifetime", "7 days, 20 hours")
},
new Section ("Celullar Network Data"){
new StringElement ("Sent", "10 bytes"),
new StringElement ("Received", "30 TB"),
},
new Section (null, "Last Reset: 1/1/08 4:44pm"){
new StringElement ("Reset Statistics"){
Alignment = UITextAlignment.Center
}
}
}
},
new Section (){
new RootElement ("Network"){
new Section (null, "Using 3G loads data faster\nand burns the battery"){
new BooleanElement ("Enable 3G", true)
},
new Section (null, "Turn this on if you are Donald Trump"){
new BooleanElement ("Data Roaming", false),
},
new Section (){
new RootElement ("VPN", 0, 0){
new Section (){
new BooleanElement ("VPN", false),
},
new Section ("Choose a configuration"){
new StringElement ("Add VPN Configuration")
}
}
}
},
new RootElement ("Bluetooth", 0, 0){
new Section (){
new BooleanElement ("Bluetooth", false)
}
},
new BooleanElement ("Location Services", true),
},
new Section (){
new RootElement ("Auto-Lock", new RadioGroup (0)){
new Section (){
new RadioElement ("1 Minute"),
new RadioElement ("2 Minutes"),
new RadioElement ("3 Minutes"),
new RadioElement ("4 Minutes"),
new RadioElement ("5 Minutes"),
new RadioElement ("Never"),
}
},
// Can be implemented with StringElement + Tapped, but makes sample larger
// new StringElement ("Passcode lock"),
new BooleanElement ("Restrictions", false),
},
new Section () {
new RootElement ("Home", new RadioGroup (2)){
new Section ("Double-click the Home Button for:"){
new RadioElement ("Home"),
new RadioElement ("Search"),
new RadioElement ("Phone favorites"),
new RadioElement ("Camera"),
new RadioElement ("iPod"),
},
new Section (null, "When playing music, show iPod controls"){
new BooleanElement ("iPod Controls", true),
}
// Missing feature: sortable list of data
// SearchResults
},
new RootElement ("Date & Time"){
new Section (){
new BooleanElement ("24-Hour Time", false),
},
new Section (){
new BooleanElement ("Set Automatically", false),
// TimeZone: Can be implemented with string + tapped event
// SetTime: Can be imeplemeneted with String + Tapped Event
}
},
new RootElement ("Keyboard"){
new Section (null, "Double tapping the space bar will\n" +
"insert a period followed by a space"){
new BooleanElement ("Auto-Correction", true),
new BooleanElement ("Auto-Capitalization", true),
new BooleanElement ("Enable Caps Lock", false),
new BooleanElement ("\".\" Shortcut", true),
},
new Section (){
new RootElement ("International Keyboards", new Group ("kbd")){
new Section ("Using Checkboxes"){
new CheckboxElement ("English", true, "kbd"),
new CheckboxElement ("Spanish", false, "kbd"),
new CheckboxElement ("French", false, "kbd"),
},
new Section ("Using BooleanElement"){
new BooleanElement ("Portuguese", true, "kbd"),
new BooleanElement ("German", false, "kbd"),
},
new Section ("Or mixing them"){
new BooleanElement ("Italian", true, "kbd"),
new CheckboxElement ("Czech", true, "kbd"),
}
}
}
}
}
};
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
namespace Revit.SDK.Samples.CreateBeamSystem.CS
{
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.Collections.ObjectModel;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Structure;
/// <summary>
/// mixed data class save the data to show in UI
/// and the data used to create beam system
/// </summary>
public class BeamSystemData
{
/// <summary>
/// all beam types loaded in current Revit project
/// it is declared as static only because of PropertyGrid
/// </summary>
private static Dictionary<string, FamilySymbol> m_beamTypes = new Dictionary<string, FamilySymbol>();
/// <summary>
/// properties of beam system
/// </summary>
private BeamSystemParam m_param;
/// <summary>
/// buffer of ExternalCommandData
/// </summary>
private ExternalCommandData m_commandData;
/// <summary>
/// the lines compose the profile of beam system
/// </summary>
private List<Line> m_lines = new List<Line>();
/// <summary>
/// a number of beams that intersect end to end
/// so that form a profile used as beam system's profile
/// </summary>
private List<FamilyInstance> m_beams = new List<FamilyInstance>();
/// <summary>
/// properties of beam system
/// </summary>
public BeamSystemParam Param
{
get
{
return m_param;
}
}
/// <summary>
/// lines form the profile of beam system
/// </summary>
public ReadOnlyCollection<Line> Lines
{
get
{
return new ReadOnlyCollection<Line>(m_lines);
}
}
/// <summary>
/// buffer of ExternalCommandData
/// </summary>
public ExternalCommandData CommandData
{
get
{
return m_commandData;
}
}
/// <summary>
/// the data used to show in UI is updated
/// </summary>
public event EventHandler ParamsUpdated;
/// <summary>
/// constructor
/// if precondition in current Revit project isn't enough,
/// ErrorMessageException will be throw out
/// </summary>
/// <param name="commandData">data from Revit</param>
public BeamSystemData(ExternalCommandData commandData)
{
// initialize members
m_commandData = commandData;
PrepareData();
InitializeProfile(m_beams);
m_param = BeamSystemParam.CreateInstance(LayoutMethod.ClearSpacing);
List<FamilySymbol> beamTypes = new List<FamilySymbol>(m_beamTypes.Values);
m_param.BeamType = beamTypes[0];
m_param.LayoutRuleChanged += new LayoutRuleChangedHandler(LayoutRuleChanged);
}
/// <summary>
/// change the direction to the next line in the profile
/// </summary>
public void ChangeProfileDirection()
{
Line tmp = m_lines[0];
m_lines.RemoveAt(0);
m_lines.Add(tmp);
}
/// <summary>
/// all beam types loaded in current Revit project
/// it is declared as static only because of PropertyGrid
/// </summary>
/// <returns></returns>
public static Dictionary<string, FamilySymbol> GetBeamTypes()
{
Dictionary<string, FamilySymbol> beamTypes = new Dictionary<string, FamilySymbol>(m_beamTypes);
return beamTypes;
}
/// <summary>
/// initialize members using data from current Revit project
/// </summary>
private void PrepareData()
{
UIDocument doc = m_commandData.Application.ActiveUIDocument;
m_beamTypes.Clear();
// iterate all selected beams
foreach (object obj in doc.Selection.Elements)
{
FamilyInstance beam = obj as FamilyInstance;
if (null == beam)
{
continue;
}
// add beam to lists according to category name
string categoryName = beam.Category.Name;
if ("Structural Framing" == categoryName
&& beam.StructuralType == StructuralType.Beam)
{
m_beams.Add(beam);
}
}
//iterate all beam types
FilteredElementIterator itor = new FilteredElementCollector(doc.Document).OfClass(typeof(Family)).GetElementIterator();
itor.Reset();
while (itor.MoveNext())
{
// get Family to get FamilySymbols
Family aFamily = itor.Current as Family;
if (null == aFamily)
{
continue;
}
foreach (FamilySymbol symbol in aFamily.Symbols)
{
if (null == symbol.Category)
{
continue;
}
// add symbols to lists according to category name
string categoryName = symbol.Category.Name;
if ("Structural Framing" == categoryName)
{
m_beamTypes.Add(symbol.Family.Name + ":" + symbol.Name, symbol);
}
}
}
if (m_beams.Count == 0)
{
throw new ErrorMessageException("Please select beams.");
}
if (m_beamTypes.Count == 0)
{
throw new ErrorMessageException("There is no Beam families loaded in current project.");
}
}
/// <summary>
/// retrieve the profiles using the selected beams
/// ErrorMessageException will be thrown out if beams can't make a closed profile
/// </summary>
/// <param name="beams">beams which may form a closed profile</param>
private void InitializeProfile(List<FamilyInstance> beams)
{
// retrieve collection of lines in beams
List<Line> lines = new List<Line>();
foreach (FamilyInstance beam in beams)
{
LocationCurve locationLine = beam.Location as LocationCurve;
Line line = locationLine.Curve as Line;
if (null == line)
{
throw new ErrorMessageException("Please don't select any arc beam.");
}
lines.Add(line);
}
// lines should in the same horizontal plane
if (!GeometryUtil.InSameHorizontalPlane(lines))
{
throw new ErrorMessageException("The selected beams can't form a horizontal profile.");
}
// sorted lines so that all lines are intersect end to end
m_lines = GeometryUtil.SortLines(lines);
// lines can't make a closed profile
if (null == m_lines)
{
throw new ErrorMessageException("The selected beams can't form a closed profile.");
}
}
/// <summary>
/// layout rule of beam system has changed
/// </summary>
/// <param name="layoutMethod">changed method</param>
private void LayoutRuleChanged(ref LayoutMethod layoutMethod)
{
// create BeamSystemParams instance according to changed LayoutMethod
m_param = m_param.CloneInstance(layoutMethod);
// raise DataUpdated event
OnParamsUpdated(new EventArgs());
// rebind delegate
m_param.LayoutRuleChanged += new LayoutRuleChangedHandler(LayoutRuleChanged);
}
/// <summary>
/// the data used to show in UI is updated
/// </summary>
/// <param name="e"></param>
protected virtual void OnParamsUpdated(EventArgs e)
{
if (null != ParamsUpdated)
{
ParamsUpdated(this, e);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Linq;
namespace Test
{
public class SumTests
{
//
// Sum
//
[Fact]
public static void RunSumTests()
{
int count1 = 0, count2 = 1024 * 8, count3 = 1024 * 16, count4 = 1024 * 1024;
Action<int>[] testActions = new Action<int>[]
{
(count) => RunSumTest1<int>(count),
(count) => RunSumTest1<int?>(count),
(count) => RunSumTest1<long>(count),
(count) => RunSumTest1<long?>(count),
(count) => RunSumTest1<float>(count),
(count) => RunSumTest1<float?>(count),
(count) => RunSumTest1<double>(count),
(count) => RunSumTest1<double?>(count),
(count) => RunSumTest1<decimal>(count),
(count) => RunSumTest1<decimal?>(count)
};
for (int i = 0; i < testActions.Length; i++)
{
bool isLong = i == 2 || i == 3;
bool isFloat = i == 4 || i == 5;
testActions[i](count1);
testActions[i](count2);
if (!isFloat)
testActions[i](count3);
if (isLong)
testActions[i](count4);
}
}
private static void RunSumTest1<T>(int count)
{
if (typeof(T) == typeof(int))
{
int expectSum = 0;
int[] ints = new int[count];
for (int i = 0; i < ints.Length; i++)
{
ints[i] = i;
expectSum += i;
}
int realSum = ints.AsParallel().Sum();
if (!expectSum.Equals(realSum))
Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}): FAILED. > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
}
else if (typeof(T) == typeof(long))
{
long expectSum = 0;
long[] longs = new long[count];
for (int i = 0; i < longs.Length; i++)
{
longs[i] = i;
expectSum += i;
}
long realSum = longs.AsParallel().Sum();
if (!expectSum.Equals(realSum))
Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}): FAILED. > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
}
else if (typeof(T) == typeof(float))
{
float expectSum = 0;
float[] floats = new float[count];
for (int i = 0; i < floats.Length; i++)
{
float val = (float)i / 10;
floats[i] = val;
expectSum += val;
}
float realSum = floats.AsParallel().Sum();
if (!AreEpsEqual(expectSum, realSum))
Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}): FAILED. > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
}
else if (typeof(T) == typeof(double))
{
double expectSum = 0;
double[] doubles = new double[count];
for (int i = 0; i < doubles.Length; i++)
{
double val = (double)i / 100;
doubles[i] = val;
expectSum += val;
}
double realSum = doubles.AsParallel().Sum();
if (!AreEpsEqual(expectSum, realSum))
Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}): FAILED. > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
}
else if (typeof(T) == typeof(decimal))
{
decimal expectSum = 0;
decimal[] decimals = new decimal[count];
for (int i = 0; i < decimals.Length; i++)
{
decimal val = (decimal)i / 100;
decimals[i] = val;
expectSum += val;
}
decimal realSum = decimals.AsParallel().Sum();
//round the numbers for the comparison
if (!AreEpsEqual(expectSum, realSum))
Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}): FAILED. > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
}
else if (typeof(T) == typeof(int?))
{
int? expectSum = 0;
int?[] ints = new int?[count];
for (int i = 0; i < ints.Length; i++)
{
ints[i] = i;
expectSum += i;
}
int? realSum = ints.AsParallel().Sum();
if (!expectSum.Equals(realSum))
Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}): FAILED. > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
}
else if (typeof(T) == typeof(long?))
{
long? expectSum = 0;
long?[] longs = new long?[count];
for (int i = 0; i < longs.Length; i++)
{
longs[i] = i;
expectSum += i;
}
long? realSum = longs.AsParallel().Sum();
if (!expectSum.Equals(realSum))
Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}): FAILED. > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
}
else if (typeof(T) == typeof(float?))
{
float? expectSum = 0;
float?[] floats = new float?[count];
for (int i = 0; i < floats.Length; i++)
{
float? val = (float)i / 10;
floats[i] = val;
expectSum += val;
}
bool passed = true;
float? realSum = floats.AsParallel().Sum();
if (!expectSum.HasValue || !realSum.HasValue)
passed = expectSum.HasValue.Equals(realSum.HasValue);
else
passed = AreEpsEqual(expectSum.Value, realSum.Value);
if (!passed)
Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}): FAILED. > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
}
else if (typeof(T) == typeof(double?))
{
double? expectSum = 0;
double?[] doubles = new double?[count];
for (int i = 0; i < doubles.Length; i++)
{
double? val = (double)i / 100;
doubles[i] = val;
expectSum += val;
}
double? realSum = doubles.AsParallel().Sum();
bool passed = true;
if (!expectSum.HasValue || !realSum.HasValue)
passed = expectSum.HasValue.Equals(realSum.HasValue);
else
passed = AreEpsEqual(expectSum.Value, realSum.Value);
if (!passed)
Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}): FAILED. > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
}
else if (typeof(T) == typeof(decimal?))
{
decimal? expectSum = 0;
decimal?[] decimals = new decimal?[count];
for (int i = 0; i < decimals.Length; i++)
{
decimal? val = (decimal)i / 100;
decimals[i] = val;
expectSum += val;
}
decimal? realSum = decimals.AsParallel().Sum();
bool passed = true;
if (!expectSum.HasValue || !realSum.HasValue)
passed = expectSum.HasValue.Equals(realSum.HasValue);
else
passed = AreEpsEqual(expectSum.Value, realSum.Value);
if (!passed)
Assert.True(false, string.Format("RunSumTest1<{0}>(count={1}): FAILED. > Expect: {2}, real: {3}", typeof(T), count, expectSum, realSum));
}
}
//
// Tests summing an ordered list.
//
private static void RunSumTestOrderBy1(int count)
{
int expectSum = 0;
int[] ints = new int[count];
for (int i = 0; i < ints.Length; i++)
{
ints[i] = i;
expectSum += i;
}
int realSum = ints.AsParallel().OrderBy(x => x).Sum();
if (realSum != expectSum)
Assert.True(false, string.Format("RunSumTestOrderBy1(count={2}): FAILED. > Expect: {0}, real: {1}", expectSum, realSum, count));
}
#region Helper Methods
/// <summary>
/// Returns whether two float values are approximately equal.
/// The values compare as equal if either the relative or absolute
/// error is less than 1e-4f.
/// </summary>
internal static bool AreEpsEqual(float a, float b)
{
const float eps = 1e-4f;
float absA = a >= 0 ? a : -a;
float absB = b >= 0 ? b : -b;
float maximumAB = absA >= absB ? absA : absB;
const float oneF = 1.0f;
float maxABOneF = oneF >= maximumAB ? oneF : maximumAB;
float absASubB = (a - b) >= 0 ? (a - b) : -(a - b);
bool isEqual = (absASubB / maxABOneF) < eps;
return isEqual;
}
/// <summary>
/// Returns whether two double values are approximately equal.
/// The values compare as equal if either the relative or absolute
/// error is less than 1e-9.
/// </summary>
internal static bool AreEpsEqual(double a, double b)
{
const double eps = 1e-9;
double absA = a >= 0 ? a : -a;
double absB = b >= 0 ? b : -b;
double maximumAB = absA >= absB ? absA : absB;
const double oneD = 1.0;
double maxABOne = oneD >= maximumAB ? oneD : maximumAB;
double absASubB = (a - b) >= 0 ? (a - b) : -(a - b);
bool isEqual = (absASubB / maxABOne) < eps;
return isEqual;
}
/// <summary>
/// Returns whether two decimal values are approximately equal.
/// The values compare as equal if either the relative or absolute
/// error is less than 1e-9m.
/// </summary>
internal static bool AreEpsEqual(decimal a, decimal b)
{
const decimal eps = 1e-9m;
decimal absA = a >= 0 ? a : -a;
decimal absB = b >= 0 ? b : -b;
decimal maximumAB = absA >= absB ? absA : absB;
const decimal oneD = 1.0m;
decimal maxABOne = oneD >= maximumAB ? oneD : maximumAB;
decimal absASubB = (a - b) >= 0 ? (a - b) : -(a - b);
bool isEqual = (absASubB / maxABOne) < eps;
return isEqual;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="BindingSourceRefresh.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>BindingSourceRefresh contains functionality for refreshing the data bound to controls on Host as well as a mechinism for catching data</summary>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
// code from Bill McCarthy
// http://msmvps.com/bill/archive/2005/10/05/69012.aspx
// used with permission
namespace Csla.Windows
{
/// <summary>
/// BindingSourceRefresh contains functionality for refreshing the data bound to controls on Host as well as a mechinism for catching data
/// binding errors that occur in Host.
/// </summary>
/// <remarks>Windows Forms extender control that resolves the
/// data refresh issue with data bound detail controls
/// as discussed in Chapter 5.</remarks>
[DesignerCategory("")]
[ProvideProperty("ReadValuesOnChange", typeof(BindingSource))]
public class BindingSourceRefresh : Component, IExtenderProvider, ISupportInitialize
{
#region Fields
private readonly Dictionary<BindingSource, bool> _sources = new Dictionary<BindingSource, bool>();
#endregion
#region Events
/// <summary>
/// BindingError event is raised when a data binding error occurs due to a exception.
/// </summary>
public event BindingErrorEventHandler BindingError = null;
#endregion
#region Constructors
/// <summary>
/// Constructor creates a new BindingSourceRefresh component then initialises all the different sub components.
/// </summary>
public BindingSourceRefresh()
{
InitializeComponent();
}
/// <summary>
/// Constructor creates a new BindingSourceRefresh component, adds the component to the container supplied before initialising all the different sub components.
/// </summary>
/// <param name="container">The container the component is to be added to.</param>
public BindingSourceRefresh(IContainer container)
{
container.Add(this);
InitializeComponent();
}
#endregion
#region Designer Functionality
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
#endregion
#region Public Methods
/// <summary>
/// CanExtend() returns true if extendee is a binding source.
/// </summary>
/// <param name="extendee">The control to be extended.</param>
/// <returns>True if the control is a binding source, else false.</returns>
public bool CanExtend(object extendee)
{
return (extendee is BindingSource);
}
/// <summary>
/// GetReadValuesOnChange() gets the value of the custom ReadValuesOnChange extender property added to extended controls.
/// property added to extended controls.
/// </summary>
/// <param name="source">Control being extended.</param>
[Category("Csla")]
public bool GetReadValuesOnChange(BindingSource source)
{
bool result;
if (_sources.TryGetValue(source, out result))
return result;
else
return false;
}
/// <summary>
/// SetReadValuesOnChange() sets the value of the custom ReadValuesOnChange extender
/// property added to extended controls.
/// </summary>
/// <param name="source">Control being extended.</param>
/// <param name="value">New value of property.</param>
/// <remarks></remarks>
[Category("Csla")]
public void SetReadValuesOnChange(
BindingSource source, bool value)
{
_sources[source] = value;
if (!_isInitialising)
{
RegisterControlEvents(source, value);
}
}
#endregion
#region Properties
/// <summary>
/// Not in use - kept for backward compatibility
/// </summary>
[Browsable(false)]
[DefaultValue(null)]
#if NETSTANDARD2_0 || NET5_0
[System.ComponentModel.DataAnnotations.ScaffoldColumn(false)]
#endif
public ContainerControl Host { get; set; }
/// <summary>
/// Forces the binding to re-read after an exception is thrown when changing the binding value
/// </summary>
[Browsable(true)]
[DefaultValue(false)]
public bool RefreshOnException { get; set; }
#endregion
#region Private Methods
/// <summary>
/// RegisterControlEvents() registers all the relevant events for the container control supplied and also to all child controls
/// in the oontainer control.
/// </summary>
/// <param name="container">The control (including child controls) to have the refresh events registered.</param>
/// <param name="register">True to register the events, false to unregister them.</param>
private void RegisterControlEvents(ICurrencyManagerProvider container, bool register)
{
var currencyManager = container.CurrencyManager;
// If we are to register the events the do so.
if (register)
{
currencyManager.Bindings.CollectionChanged += Bindings_CollectionChanged;
currencyManager.Bindings.CollectionChanging += Bindings_CollectionChanging;
}
// Else unregister them.
else
{
currencyManager.Bindings.CollectionChanged -= Bindings_CollectionChanged;
currencyManager.Bindings.CollectionChanging -= Bindings_CollectionChanging;
}
// Reigster the binding complete events for the currencymanagers bindings.
RegisterBindingEvents(currencyManager.Bindings, register);
}
/// <summary>
/// Registers the control events.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="register">if set to <c>true</c> [register].</param>
private void RegisterBindingEvents(BindingsCollection source, bool register)
{
foreach (Binding binding in source)
{
RegisterBindingEvent(binding, register);
}
}
/// <summary>
/// Registers the binding event.
/// </summary>
/// <param name="register">if set to <c>true</c> [register].</param>
/// <param name="binding">The binding.</param>
private void RegisterBindingEvent(Binding binding, bool register)
{
if (register)
{
binding.BindingComplete += Control_BindingComplete;
}
else
{
binding.BindingComplete -= Control_BindingComplete;
}
}
#endregion
#region Event Methods
/// <summary>
/// Handles the CollectionChanging event of the Bindings control.
///
/// Remove event hooks for element or entire list depending on CollectionChangeAction.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.CollectionChangeEventArgs"/> instance containing the event data.</param>
private void Bindings_CollectionChanging(object sender, CollectionChangeEventArgs e)
{
switch (e.Action)
{
case CollectionChangeAction.Refresh:
// remove events for entire list
RegisterBindingEvents((BindingsCollection)sender, false);
break;
case CollectionChangeAction.Add:
// adding new element - remove events for element
RegisterBindingEvent((Binding)e.Element, false);
break;
case CollectionChangeAction.Remove:
// removing element - remove events for element
RegisterBindingEvent((Binding)e.Element, false);
break;
}
}
/// <summary>
/// Handles the CollectionChanged event of the Bindings control.
///
/// Add event hooks for element or entire list depending on CollectionChangeAction.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.CollectionChangeEventArgs"/> instance containing the event data.</param>
private void Bindings_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
switch (e.Action)
{
case CollectionChangeAction.Refresh:
// refresh entire list - add event to all items
RegisterBindingEvents((BindingsCollection)sender, true);
break;
case CollectionChangeAction.Add:
// new element added - add event to element
RegisterBindingEvent((Binding)e.Element, true);
break;
case CollectionChangeAction.Remove:
// element has been removed - do nothing
break;
}
}
/// <summary>
/// Control_BindingComplete() is a event driven routine triggered when one of the control's bindings has been completed.
/// Control_BindingComplete() simply validates the result where if the result was a exception then the BindingError
/// event is raised, else if the binding was a successful data source update and we are to re-read the value on changed then
/// the binding value is reread into the control.
/// </summary>
/// <param name="sender">The object that triggered the event.</param>
/// <param name="e">The event arguments.</param>
private void Control_BindingComplete(object sender, BindingCompleteEventArgs e)
{
switch (e.BindingCompleteState)
{
case BindingCompleteState.Exception:
if ((RefreshOnException)
&& e.Binding.DataSource is BindingSource
&& GetReadValuesOnChange((BindingSource)e.Binding.DataSource))
{
e.Binding.ReadValue();
}
if (BindingError != null)
{
BindingError(this, new BindingErrorEventArgs(e.Binding, e.Exception));
}
break;
default:
if ((e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate)
&& e.Binding.DataSource is BindingSource
&& GetReadValuesOnChange((BindingSource)e.Binding.DataSource))
{
e.Binding.ReadValue();
}
break;
}
}
#endregion
#region ISupportInitialize Interface
private bool _isInitialising = false;
/// <summary>
/// BeginInit() is called when the component is starting to be initialised. BeginInit() simply sets the initialisation flag to true.
/// </summary>
void ISupportInitialize.BeginInit()
{
_isInitialising = true;
}
/// <summary>
/// EndInit() is called when the component has finished being initialised. EndInt() sets the initialise flag to false then runs
/// through registering all the different events that the component needs to hook into in Host.
/// </summary>
void ISupportInitialize.EndInit()
{
_isInitialising = false;
foreach (var source in _sources)
{
if (source.Value)
RegisterControlEvents(source.Key, true);
}
}
#endregion
}
#region Delegates
/// <summary>
/// BindingErrorEventHandler delegates is the event handling definition for handling data binding errors that occurred due to exceptions.
/// </summary>
/// <param name="sender">The object that triggered the event.</param>
/// <param name="e">The event arguments.</param>
public delegate void BindingErrorEventHandler(object sender, BindingErrorEventArgs e);
#endregion
#region BindingErrorEventArgs Class
/// <summary>
/// BindingErrorEventArgs defines the event arguments for reporting a data binding error due to a exception.
/// </summary>
public class BindingErrorEventArgs : EventArgs
{
#region Property Fields
private Exception _exception = null;
private Binding _binding = null;
#endregion
#region Properties
/// <summary>
/// Exception gets the exception that caused the binding error.
/// </summary>
public Exception Exception
{
get { return (_exception); }
}
/// <summary>
/// Binding gets the binding that caused the exception.
/// </summary>
public Binding Binding
{
get { return (_binding); }
}
#endregion
#region Constructors
/// <summary>
/// Constructor creates a new BindingErrorEventArgs object instance using the information specified.
/// </summary>
/// <param name="binding">The binding that caused th exception.</param>
/// <param name="exception">The exception that caused the error.</param>
public BindingErrorEventArgs(Binding binding, Exception exception)
{
_binding = binding;
_exception = exception;
}
#endregion
}
#endregion
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Deki.Data {
public class ArchiveBE {
//--- Fields ---
protected uint _id;
protected Title _title = null;
protected string _text;
protected string _comment;
protected uint _userId;
protected DateTime _timestamp;
protected bool _minorEdit;
protected ulong _lastPageId;
protected ulong _oldId;
protected string _contentType;
protected string _language;
protected uint _transactionId;
protected bool _isHidden;
protected string _metaStr;
protected ulong _revision;
protected XDoc _metaTempDoc = null;
//--- Properties ---
public virtual uint Id {
get { return _id; }
set { _id = value; }
}
public virtual ushort _Namespace {
get { return (ushort)Title.Namespace; }
set { Title.Namespace = (NS)value; }
}
public virtual string _Title {
get { return Title.AsUnprefixedDbPath(); }
set { Title.Path = value; }
}
public virtual string _DisplayName {
get { return Title.DisplayName; }
set { Title.DisplayName = value; }
}
public virtual Title Title {
get {
if (null == _title) {
_title = Title.FromDbPath(NS.UNKNOWN, String.Empty, null);
}
return _title;
}
set {
_title = value;
}
}
public virtual string Text {
get { return _text; }
set { _text = value; }
}
public virtual byte[] _Comment {
get { return DbUtils.ToBlob(_comment); }
set { _comment = DbUtils.ToString(value); }
}
public virtual string Comment {
get { return _comment; }
set { _comment = value; }
}
public virtual uint UserID {
get { return _userId; }
set { _userId = value; }
}
public virtual string _TimeStamp {
get { return DbUtils.ToString(_timestamp); }
set { _timestamp = DbUtils.ToDateTime(value); }
}
public virtual DateTime TimeStamp {
get { return _timestamp; }
set { _timestamp = value; }
}
public virtual bool MinorEdit {
get { return _minorEdit; }
set { _minorEdit = value; }
}
public virtual ulong LastPageId {
get { return _lastPageId; }
set { _lastPageId = value; }
}
public virtual ulong OldId {
get { return _oldId; }
set { _oldId = value; }
}
public virtual string ContentType {
get { return _contentType ?? DekiMimeType.DEKI_TEXT; }
set { _contentType = value; }
}
public virtual string Language {
get { return _language; }
set { _language = value; }
}
public virtual uint TransactionId {
get { return _transactionId; }
set { _transactionId = value; }
}
public virtual bool IsHidden {
get { return _isHidden; }
set { _isHidden = value; }
}
public virtual ulong Revision {
get { return _revision; }
set { _revision = value; }
}
public virtual string Meta {
get {
if(_metaTempDoc != null) {
_metaStr = _metaTempDoc.ToString();
}
return _metaStr;
}
set {
_metaStr = value;
_metaTempDoc = null;
}
}
public virtual XDoc MetaXml {
get {
XDoc ret = null;
if(_metaTempDoc != null) {
ret = _metaTempDoc;
} else if(string.IsNullOrEmpty(_metaStr)) {
ret = _metaTempDoc = new XDoc(ResourceBE.ATTRIBUTE_ROOT);
} else {
ret = _metaTempDoc = XDocFactory.From(_metaStr, MimeType.XML);
}
return _metaTempDoc;
}
}
//--- Methods ---
public virtual ArchiveBE Copy() {
ArchiveBE archive = new ArchiveBE();
archive._Comment = _Comment;
archive._DisplayName = _DisplayName;
archive._Namespace = _Namespace;
archive._Title = _Title;
archive._TimeStamp = _TimeStamp;
archive.ContentType = ContentType;
archive.Id = Id;
archive.IsHidden = IsHidden;
archive.Language = Language;
archive.LastPageId = LastPageId;
archive.Meta = Meta;
archive.MinorEdit = MinorEdit;
archive.OldId = OldId;
archive.Text = Text;
archive.TransactionId = TransactionId;
archive.UserID = UserID;
archive.Revision = Revision;
return archive;
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
#pragma warning disable SA1649
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
namespace Irony.Parsing
{
#region notes
//Identifier terminal. Matches alpha-numeric sequences that usually represent identifiers and keywords.
// c#: @ prefix signals to not interpret as a keyword; allows \u escapes
//
#endregion
[Flags]
public enum IdOptions : short
{
None = 0,
AllowsEscapes = 0x01,
CanStartWithEscape = 0x03,
IsNotKeyword = 0x10,
NameIncludesPrefix = 0x20,
}
public enum CaseRestriction
{
None,
FirstUpper,
FirstLower,
AllUpper,
AllLower
}
public class UnicodeCategoryList : List<UnicodeCategory> { }
public class IdentifierTerminal : CompoundTerminalBase
{
//Id flags for internal use
internal enum IdFlagsInternal : short
{
HasEscapes = 0x100,
}
#region constructors and initialization
public IdentifierTerminal(string name)
: this(name, IdOptions.None)
{
}
public IdentifierTerminal(string name, IdOptions options)
: this(name, "_", "_")
{
this.Options = options;
}
public IdentifierTerminal(string name, string extraChars, string extraFirstChars = "")
: base(name)
{
this.AllFirstChars = Strings.AllLatinLetters + extraFirstChars;
this.AllChars = Strings.AllLatinLetters + Strings.DecimalDigits + extraChars;
}
public void AddPrefix(string prefix, IdOptions options)
{
base.AddPrefixFlag(prefix, (short)options);
}
#endregion
#region properties: AllChars, AllFirstChars
public readonly UnicodeCategoryList StartCharCategories = new UnicodeCategoryList(); //categories of first char
public readonly UnicodeCategoryList CharCategories = new UnicodeCategoryList(); //categories of all other chars
public readonly UnicodeCategoryList CharsToRemoveCategories = new UnicodeCategoryList(); //categories of chars to remove from final id, usually formatting category
public string AllFirstChars;
public string AllChars;
public TokenEditorInfo KeywordEditorInfo = new TokenEditorInfo(TokenType.Keyword, TokenColor.Keyword, TokenTriggers.None);
public IdOptions Options; //flags for the case when there are no prefixes
public CaseRestriction CaseRestriction;
private CharHashSet _allCharsSet;
private CharHashSet _allFirstCharsSet;
#endregion
#region overrides
public override void Init(GrammarData grammarData)
{
base.Init(grammarData);
this._allCharsSet = new CharHashSet(this.Grammar.CaseSensitive);
this._allCharsSet.UnionWith(this.AllChars.ToCharArray());
//Adjust case restriction. We adjust only first chars; if first char is ok, we will scan the rest without restriction
// and then check casing for entire identifier
switch (this.CaseRestriction)
{
case CaseRestriction.AllLower:
case CaseRestriction.FirstLower:
this._allFirstCharsSet = new CharHashSet(true);
this._allFirstCharsSet.UnionWith(this.AllFirstChars.ToLowerInvariant().ToCharArray());
break;
case CaseRestriction.AllUpper:
case CaseRestriction.FirstUpper:
this._allFirstCharsSet = new CharHashSet(true);
this._allFirstCharsSet.UnionWith(this.AllFirstChars.ToUpperInvariant().ToCharArray());
break;
default: //None
this._allFirstCharsSet = new CharHashSet(this.Grammar.CaseSensitive);
this._allFirstCharsSet.UnionWith(this.AllFirstChars.ToCharArray());
break;
}
//if there are "first" chars defined by categories, add the terminal to FallbackTerminals
if (this.StartCharCategories.Count > 0)
{
grammarData.NoPrefixTerminals.Add(this);
}
if (this.EditorInfo == null)
{
this.EditorInfo = new TokenEditorInfo(TokenType.Identifier, TokenColor.Identifier, TokenTriggers.None);
}
}
public override IList<string> GetFirsts()
{
// new scanner: identifier has no prefixes
return null;
/*
var list = new StringList();
list.AddRange(Prefixes);
foreach (char ch in _allFirstCharsSet)
list.Add(ch.ToString());
if ((Options & IdOptions.CanStartWithEscape) != 0)
list.Add(this.EscapeChar.ToString());
return list;
*/
}
protected override void InitDetails(ParsingContext context, CompoundTokenDetails details)
{
base.InitDetails(context, details);
details.Flags = (short)this.Options;
}
//Override to assign IsKeyword flag to keyword tokens
protected override Token CreateToken(ParsingContext context, ISourceStream source, CompoundTokenDetails details)
{
Token token = base.CreateToken(context, source, details);
if (details.IsSet((short)IdOptions.IsNotKeyword))
{
return token;
}
//check if it is keyword
this.CheckReservedWord(token);
return token;
}
private void CheckReservedWord(Token token)
{
KeyTerm keyTerm;
if (this.Grammar.KeyTerms.TryGetValue(token.Text, out keyTerm))
{
token.KeyTerm = keyTerm;
//if it is reserved word, then overwrite terminal
if (keyTerm.Flags.IsSet(TermFlags.IsReservedWord))
{
token.SetTerminal(keyTerm);
}
}
}
protected override Token QuickParse(ParsingContext context, ISourceStream source)
{
if (!this._allFirstCharsSet.Contains(source.PreviewChar))
{
return null;
}
source.PreviewPosition++;
while (this._allCharsSet.Contains(source.PreviewChar) && !source.EOF())
{
source.PreviewPosition++;
}
//if it is not a terminator then cancel; we need to go through full algorithm
if (!this.Grammar.IsWhitespaceOrDelimiter(source.PreviewChar))
{
return null;
}
var token = source.CreateToken(this.OutputTerminal);
if (this.CaseRestriction != CaseRestriction.None && !this.CheckCaseRestriction(token.ValueString))
{
return null;
}
//!!! Do not convert to common case (all-lower) for case-insensitive grammar. Let identifiers remain as is,
// it is responsibility of interpreter to provide case-insensitive read/write operations for identifiers
// if (!this.GrammarData.Grammar.CaseSensitive)
// token.Value = token.Text.ToLower(CultureInfo.InvariantCulture);
this.CheckReservedWord(token);
return token;
}
protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details)
{
int start = source.PreviewPosition;
bool allowEscapes = details.IsSet((short)IdOptions.AllowsEscapes);
CharList outputChars = new CharList();
while (!source.EOF())
{
char current = source.PreviewChar;
if (this.Grammar.IsWhitespaceOrDelimiter(current))
{
break;
}
if (allowEscapes && current == this.EscapeChar)
{
current = this.ReadUnicodeEscape(source, details);
//We need to back off the position. ReadUnicodeEscape sets the position to symbol right after escape digits.
//This is the char that we should process in next iteration, so we must backup one char, to pretend the escaped
// char is at position of last digit of escape sequence.
source.PreviewPosition--;
if (details.Error != null)
{
return false;
}
}
//Check if current character is OK
if (!this.CharOk(current, source.PreviewPosition == start))
{
break;
}
//Check if we need to skip this char
UnicodeCategory currCat = char.GetUnicodeCategory(current); //I know, it suxx, we do it twice, fix it later
if (!this.CharsToRemoveCategories.Contains(currCat))
{
outputChars.Add(current); //add it to output (identifier)
}
source.PreviewPosition++;
}//while
if (outputChars.Count == 0)
{
return false;
}
//Convert collected chars to string
details.Body = new string(outputChars.ToArray());
if (!this.CheckCaseRestriction(details.Body))
{
return false;
}
return !string.IsNullOrEmpty(details.Body);
}
private bool CharOk(char ch, bool first)
{
//first check char lists, then categories
var charSet = first ? this._allFirstCharsSet : this._allCharsSet;
if (charSet.Contains(ch))
{
return true;
}
//check categories
if (this.CharCategories.Count > 0)
{
UnicodeCategory chCat = char.GetUnicodeCategory(ch);
UnicodeCategoryList catList = first ? this.StartCharCategories : this.CharCategories;
if (catList.Contains(chCat))
{
return true;
}
}
return false;
}
private bool CheckCaseRestriction(string body)
{
switch (this.CaseRestriction)
{
case CaseRestriction.FirstLower: return Char.IsLower(body, 0);
case CaseRestriction.FirstUpper: return Char.IsUpper(body, 0);
case CaseRestriction.AllLower: return body.ToLower() == body;
case CaseRestriction.AllUpper: return body.ToUpper() == body;
default: return true;
}
}//method
private char ReadUnicodeEscape(ISourceStream source, CompoundTokenDetails details)
{
//Position is currently at "\" symbol
source.PreviewPosition++; //move to U/u char
int len;
switch (source.PreviewChar)
{
case 'u': len = 4; break;
case 'U': len = 8; break;
default:
details.Error = Resources.ErrInvEscSymbol; // "Invalid escape symbol, expected 'u' or 'U' only."
return '\0';
}
if (source.PreviewPosition + len > source.Text.Length)
{
details.Error = Resources.ErrInvEscSeq; // "Invalid escape sequence";
return '\0';
}
source.PreviewPosition++; //move to the first digit
string digits = source.Text.Substring(source.PreviewPosition, len);
char result = (char)Convert.ToUInt32(digits, 16);
source.PreviewPosition += len;
details.Flags |= (int)IdFlagsInternal.HasEscapes;
return result;
}
protected override bool ConvertValue(CompoundTokenDetails details)
{
if (details.IsSet((short)IdOptions.NameIncludesPrefix))
{
details.Value = details.Prefix + details.Body;
}
else
{
details.Value = details.Body;
}
return true;
}
#endregion
}//class
} //namespace
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.AspNet
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Services.Query;
using Microsoft.Owin;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
internal static class TaskExtensions
{
public static ConfiguredTaskAwaitable WithCurrentCulture(this Task task)
{
return task.ConfigureAwait(false);
}
public static ConfiguredTaskAwaitable<T> WithCurrentCulture<T>(this Task<T> task)
{
return task.ConfigureAwait(false);
}
}
public static class Extensions
{
/// <summary>
/// Filter columns based on crm solution version and returns the filtered columns as string array.
/// </summary>
/// <param name="columns">Entity Node columns</param>
/// <param name="solutionVersion">solution version based on which filtering needs to be done.</param>
/// <returns> Returns string array of column names.</returns>
public static string[] ToFilteredColumns(this EntityNodeColumn[] columns, Version solutionVersion)
{
if (columns.Any())
{
return columns
.Where(c => c.IntroducedVersion != null && c.IntroducedVersion.Major <= solutionVersion.Major && c.IntroducedVersion.Minor <= solutionVersion.Minor)
.Select(c => c.Name)
.ToArray();
}
return null;
}
public static string GetRequestBody(this IOwinContext context)
{
if (!string.Equals(context.Request.Method, "POST"))
{
ADXTrace.Instance.TraceWarning(TraceCategory.Application, "Unable to read request body. Invalid request method.");
return null;
}
if (context.Request.CallCancelled.IsCancellationRequested)
{
ADXTrace.Instance.TraceWarning(TraceCategory.Application, "Unable to read request body. The client is disconnected.");
return null;
}
var reader = new StreamReader(context.Request.Body);
var originalPosition = context.Request.Body.Position;
var body = reader.ReadToEnd();
context.Request.Body.Position = originalPosition;
return body;
}
}
public static class OrganizationServiceExtensions
{
public static ExecuteMultipleResponse ExecuteMultiple(this IOrganizationService service, IEnumerable<OrganizationRequest> requests, bool returnResponses = false, bool continueOnError = false)
{
var request = new ExecuteMultipleRequest
{
Settings = new ExecuteMultipleSettings { ContinueOnError = continueOnError, ReturnResponses = returnResponses },
Requests = new OrganizationRequestCollection(),
};
request.Requests.AddRange(requests);
return service.Execute(request) as ExecuteMultipleResponse;
}
}
public static class EntityExtensions
{
internal static readonly Condition ActiveStateCondition = new Condition("statecode", ConditionOperator.Equal, 0);
internal static Guid ToGuid<TKey>(this TKey key)
{
if (Equals(key, default(TKey)) || Equals(key, string.Empty)) return Guid.Empty;
if (typeof(TKey) == typeof(string)) return new Guid((string)(object)key);
return (Guid)(object)key;
}
internal static TKey ToKey<TKey>(this Guid guid)
{
if (typeof(TKey) == typeof(string)) return (TKey)(object)guid.ToString();
return (TKey)(object)guid;
}
/// <summary>
/// Returns an entity graph containing the attributes and relationships that have changed
/// </summary>
public static Entity ToChangedEntity(this Entity entity, Entity snapshot)
{
if (entity == null) return null;
var result = new Entity(entity.LogicalName)
{
Id = entity.Id,
EntityState = entity.Id == Guid.Empty ? EntityState.Created : entity.EntityState,
};
result.Attributes.AddRange(ToChangedAttributes(entity.Attributes, snapshot));
result.RelatedEntities.AddRange(ToChangedRelationships(entity.RelatedEntities, snapshot));
return result.Attributes.Any() || result.RelatedEntities.Any()
? result
: null;
}
private static IEnumerable<KeyValuePair<string, object>> ToChangedAttributes(
IEnumerable<KeyValuePair<string, object>> attributes, Entity snapshot)
{
foreach (var attribute in attributes)
{
object value;
if (snapshot == null)
{
yield return attribute;
}
else if (!snapshot.Attributes.TryGetValue(attribute.Key, out value))
{
if (attribute.Value != null)
{
yield return attribute;
}
}
else if (!Equals(attribute.Value, value))
{
yield return attribute;
}
}
}
private static IEnumerable<KeyValuePair<Relationship, EntityCollection>> ToChangedRelationships(
IEnumerable<KeyValuePair<Relationship, EntityCollection>> relationships, Entity snapshot)
{
foreach (var relationship in relationships)
{
EntityCollection collection;
if (snapshot == null || !snapshot.RelatedEntities.TryGetValue(relationship.Key, out collection))
{
collection = null;
}
var result = new EntityCollection(ToChangedRelationship(relationship.Value.Entities, collection).ToList());
if (result.Entities.Any())
{
yield return new KeyValuePair<Relationship, EntityCollection>(relationship.Key, result);
}
}
}
private static IEnumerable<Entity> ToChangedRelationship(IEnumerable<Entity> entities, EntityCollection collection)
{
foreach (var entity in entities)
{
var snapshot = collection != null
? collection.Entities.SingleOrDefault(e => Equals(e.ToEntityReference(), entity.ToEntityReference()))
: null;
var result = ToChangedEntity(entity, snapshot);
if (result != null)
{
yield return result;
}
}
}
/// <summary>
/// Returns a collection of entities that exist in the snapshot entity graph but are absent in this entity graph.
/// </summary>
public static IEnumerable<Entity> ToRemovedEntities(this Entity entity, Entity snapshot)
{
var removed = ToRemovedEntity(entity, snapshot);
return GetRelatedEntitiesRecursive(removed).Except(new[] { removed }).ToList();
}
private static Entity ToRemovedEntity(Entity entity, Entity snapshot)
{
if (snapshot == null) return null;
var result = new Entity(snapshot.LogicalName)
{
Id = snapshot.Id,
EntityState = snapshot.Id == Guid.Empty ? EntityState.Created : snapshot.EntityState,
};
result.RelatedEntities.AddRange(ToRemovedRelationships(entity, snapshot.RelatedEntities));
return entity == null || result.RelatedEntities.Any()
? result
: null;
}
private static IEnumerable<Entity> GetRelatedEntitiesRecursive(Entity entity)
{
if (entity == null) yield break;
yield return entity;
foreach (
var related in
entity.RelatedEntities.SelectMany(relationship => relationship.Value.Entities)
.SelectMany(GetRelatedEntitiesRecursive))
{
yield return related;
}
}
private static IEnumerable<KeyValuePair<Relationship, EntityCollection>> ToRemovedRelationships(Entity entity,
IEnumerable<KeyValuePair<Relationship, EntityCollection>> relationships)
{
foreach (var relationship in relationships)
{
EntityCollection collection;
if (entity == null || !entity.RelatedEntities.TryGetValue(relationship.Key, out collection))
{
collection = null;
}
var result = new EntityCollection(ToRemovedRelationship(collection, relationship.Value.Entities).ToList());
if (result.Entities.Any())
{
yield return new KeyValuePair<Relationship, EntityCollection>(relationship.Key, result);
}
}
}
private static IEnumerable<Entity> ToRemovedRelationship(EntityCollection collection, IEnumerable<Entity> entities)
{
foreach (var snapshot in entities)
{
var entity = collection != null
? collection.Entities.SingleOrDefault(e => Equals(e.ToEntityReference(), snapshot.ToEntityReference()))
: null;
var result = ToRemovedEntity(entity, snapshot);
if (result != null)
{
yield return result;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Drawing.Design;
using VersionOne.VisualStudio.DataLayer.Entities;
using VersionOne.VisualStudio.VSPackage.Events;
using VersionOne.VisualStudio.VSPackage.PropertyEditors;
using VersionOne.VisualStudio.DataLayer;
using VersionOne.VisualStudio.VSPackage.Settings;
namespace VersionOne.VisualStudio.VSPackage.Descriptors {
public class WorkitemDescriptor : ICustomTypeDescriptor {
private readonly Entity entity;
private readonly PropertyUpdateSource updateSource;
private readonly bool iconless;
private readonly PropertyDescriptorCollection propertyDescriptors = new PropertyDescriptorCollection(new PropertyDescriptor[] {});
private readonly IDataLayer dataLayer;
public WorkitemDescriptor(Entity entity, IEnumerable<ColumnSetting> columns, PropertyUpdateSource updateSource, bool iconless) {
this.entity = entity;
this.updateSource = updateSource;
this.iconless = iconless;
dataLayer = ServiceLocator.Instance.Get<IDataLayer>();
ConfigurePropertyDescriptors(columns);
}
public Entity Entity {
get { return entity; }
}
public Workitem Workitem {
get { return entity as Workitem; }
}
public AttributeCollection GetAttributes() {
return TypeDescriptor.GetAttributes(this, true);
}
// Begin Binding properties in order to show values in treenodes.
public object Title
{
get { return GetProperty("Title"); }
set { SetProperty("Title", value); }
}
public object ID
{
get { return GetProperty("ID"); }
set { SetProperty("ID", value); }
}
public object Owner
{
get { return GetProperty("Owner"); }
set { SetProperty("Owner", value); }
}
public object Icon
{
get { return GetProperty("Icon"); }
set { SetProperty("Icon", value); }
}
public object Status
{
get { return GetProperty("Status"); }
set { SetProperty("Status", value); }
}
public object Estimate
{
get { return GetProperty("Estimate"); }
set { SetProperty("Estimate", value); }
}
public object DetailEstimate
{
get { return GetProperty("DetailEstimate"); }
set { SetProperty("DetailEstimate", value); }
}
public object Done
{
get { return GetProperty("Done"); }
set { SetProperty("Done", value); }
}
public object Effort
{
get { return GetProperty("Effort"); }
set { SetProperty("Effort", value); }
}
public object ToDo
{
get { return GetProperty("ToDo"); }
set { SetProperty("ToDo", value); }
}
// End Binding properties in order to show values in treenodes.
public string GetClassName() {
return "Details";
}
public string GetComponentName() {
return (string) entity.GetProperty("Name");
}
public TypeConverter GetConverter() {
return TypeDescriptor.GetConverter(this, true);
}
public EventDescriptor GetDefaultEvent() {
return TypeDescriptor.GetDefaultEvent(this, false);
}
public PropertyDescriptor GetDefaultProperty() {
return TypeDescriptor.GetDefaultProperty(this, true);
}
public object GetEditor(Type editorBaseType) {
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
public EventDescriptorCollection GetEvents() {
return TypeDescriptor.GetEvents(this, true);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes) {
return TypeDescriptor.GetEvents(this, attributes, true);
}
public object GetProperty(string propertyName)
{
return GetProperties()[propertyName].GetValue(entity);
}
public void SetProperty(string propertyName, object value)
{
GetProperties()[propertyName].SetValue(entity, value);
}
public PropertyDescriptorCollection GetProperties() {
return GetProperties(null);
}
public PropertyDescriptorCollection GetProperties(Attribute[] attributes) {
return propertyDescriptors;
}
public object GetPropertyOwner(PropertyDescriptor pd) {
return entity;
}
public WorkitemDescriptor GetDetailedDescriptor(ColumnSetting[] settings, PropertyUpdateSource requiredUpdateSource) {
return new WorkitemDescriptor(entity, settings, requiredUpdateSource, true);
}
private bool ShouldSkipColumnDueToEffortTracking(ColumnSetting column) {
return column.EffortTracking && !dataLayer.EffortTracking.TrackEffort;
}
private void ConfigurePropertyDescriptors(IEnumerable<ColumnSetting> columns) {
foreach (var column in columns) {
if (ShouldSkipColumnDueToEffortTracking(column)) {
continue;
}
var attrs = new List<Attribute> {new CategoryAttribute(column.Category)};
var name = dataLayer.LocalizerResolve(column.Name).Replace(" ", string.Empty);
switch (column.Type) {
case "String":
case "Effort":
break;
case "List":
attrs.Add(new EditorAttribute(typeof(ListPropertyEditor), typeof(UITypeEditor)));
break;
case "Multi":
attrs.Add(new EditorAttribute(typeof(MultiValueEditor), typeof(UITypeEditor)));
break;
case "RichText":
attrs.Add(new EditorAttribute(typeof(RichTextTypeEditor), typeof(UITypeEditor)));
break;
}
propertyDescriptors.Add(new WorkitemPropertyDescriptor(entity, name, column, attrs.ToArray(), updateSource));
}
if (!iconless) {
propertyDescriptors.Add(new IconDescriptor("Icon"));
}
}
#region Equals(), GetHashCode(), ==, !=
public override bool Equals(object obj) {
if (ReferenceEquals(null, obj)) {
return false;
}
if (ReferenceEquals(this, obj)) {
return true;
}
if (obj.GetType() != typeof(WorkitemDescriptor)) {
return false;
}
var other = (WorkitemDescriptor)obj;
return Equals(other.entity, entity);
}
public override int GetHashCode() {
unchecked {
return entity.GetHashCode();
}
}
public static bool operator ==(WorkitemDescriptor left, WorkitemDescriptor right) {
return Equals(left, right);
}
public static bool operator !=(WorkitemDescriptor left, WorkitemDescriptor right) {
return !Equals(left, right);
}
#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;
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Xml;
using System.Linq;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Security;
// The interface is a perf optimization.
// Only KeyValuePairAdapter should implement the interface.
internal interface IKeyValuePairAdapter { }
//Special Adapter class to serialize KeyValuePair as Dictionary needs it when polymorphism is involved
[DataContract(Namespace = "http://schemas.datacontract.org/2004/07/System.Collections.Generic")]
internal class KeyValuePairAdapter<K, T> : IKeyValuePairAdapter
{
private K _kvpKey;
private T _kvpValue;
public KeyValuePairAdapter(KeyValuePair<K, T> kvPair)
{
_kvpKey = kvPair.Key;
_kvpValue = kvPair.Value;
}
[DataMember(Name = "key")]
public K Key
{
get { return _kvpKey; }
set { _kvpKey = value; }
}
[DataMember(Name = "value")]
public T Value
{
get
{
return _kvpValue;
}
set
{
_kvpValue = value;
}
}
internal KeyValuePair<K, T> GetKeyValuePair()
{
return new KeyValuePair<K, T>(_kvpKey, _kvpValue);
}
internal static KeyValuePairAdapter<K, T> GetKeyValuePairAdapter(KeyValuePair<K, T> kvPair)
{
return new KeyValuePairAdapter<K, T>(kvPair);
}
}
#if USE_REFEMIT
public interface IKeyValue
#else
internal interface IKeyValue
#endif
{
object Key { get; set; }
object Value { get; set; }
}
[DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
#if USE_REFEMIT
public struct KeyValue<K, V> : IKeyValue
#else
internal struct KeyValue<K, V> : IKeyValue
#endif
{
private K _key;
private V _value;
internal KeyValue(K key, V value)
{
_key = key;
_value = value;
}
[DataMember(IsRequired = true)]
public K Key
{
get { return _key; }
set { _key = value; }
}
[DataMember(IsRequired = true)]
public V Value
{
get { return _value; }
set { _value = value; }
}
object IKeyValue.Key
{
get { return _key; }
set { _key = (K)value; }
}
object IKeyValue.Value
{
get { return _value; }
set { _value = (V)value; }
}
}
#if uapaot
public enum CollectionKind : byte
#else
internal enum CollectionKind : byte
#endif
{
None,
GenericDictionary,
Dictionary,
GenericList,
GenericCollection,
List,
GenericEnumerable,
Collection,
Enumerable,
Array,
}
#if USE_REFEMIT || uapaot
public sealed class CollectionDataContract : DataContract
#else
internal sealed class CollectionDataContract : DataContract
#endif
{
private XmlDictionaryString _collectionItemName;
private XmlDictionaryString _childElementNamespace;
private DataContract _itemContract;
private CollectionDataContractCriticalHelper _helper;
public CollectionDataContract(CollectionKind kind) : base(new CollectionDataContractCriticalHelper(kind))
{
InitCollectionDataContract(this);
}
internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type))
{
InitCollectionDataContract(this);
}
private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private CollectionDataContract(Type type, string invalidCollectionInSharedContractMessage) : base(new CollectionDataContractCriticalHelper(type, invalidCollectionInSharedContractMessage))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private void InitCollectionDataContract(DataContract sharedTypeContract)
{
_helper = base.Helper as CollectionDataContractCriticalHelper;
_collectionItemName = _helper.CollectionItemName;
if (_helper.Kind == CollectionKind.Dictionary || _helper.Kind == CollectionKind.GenericDictionary)
{
_itemContract = _helper.ItemContract;
}
_helper.SharedTypeContract = sharedTypeContract;
}
private static Type[] KnownInterfaces
{
get
{ return CollectionDataContractCriticalHelper.KnownInterfaces; }
}
internal CollectionKind Kind
{
get
{ return _helper.Kind; }
}
public Type ItemType
{
get
{ return _helper.ItemType; }
set { _helper.ItemType = value; }
}
public DataContract ItemContract
{
get
{
return _itemContract ?? _helper.ItemContract;
}
set
{
_itemContract = value;
_helper.ItemContract = value;
}
}
internal DataContract SharedTypeContract
{
get
{ return _helper.SharedTypeContract; }
}
public string ItemName
{
get
{ return _helper.ItemName; }
set
{ _helper.ItemName = value; }
}
public XmlDictionaryString CollectionItemName
{
get { return _collectionItemName; }
set { _collectionItemName = value; }
}
public string KeyName
{
get
{ return _helper.KeyName; }
set
{ _helper.KeyName = value; }
}
public string ValueName
{
get
{ return _helper.ValueName; }
set
{ _helper.ValueName = value; }
}
internal bool IsDictionary
{
get { return KeyName != null; }
}
public XmlDictionaryString ChildElementNamespace
{
get
{
if (_childElementNamespace == null)
{
lock (this)
{
if (_childElementNamespace == null)
{
if (_helper.ChildElementNamespace == null && !IsDictionary)
{
XmlDictionaryString tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary());
Interlocked.MemoryBarrier();
_helper.ChildElementNamespace = tempChildElementNamespace;
}
_childElementNamespace = _helper.ChildElementNamespace;
}
}
}
return _childElementNamespace;
}
}
internal bool IsConstructorCheckRequired
{
get
{ return _helper.IsConstructorCheckRequired; }
set
{ _helper.IsConstructorCheckRequired = value; }
}
internal MethodInfo GetEnumeratorMethod
{
get
{ return _helper.GetEnumeratorMethod; }
}
internal MethodInfo AddMethod
{
get
{ return _helper.AddMethod; }
}
internal ConstructorInfo Constructor
{
get
{ return _helper.Constructor; }
}
public override DataContractDictionary KnownDataContracts
{
get
{ return _helper.KnownDataContracts; }
set
{ _helper.KnownDataContracts = value; }
}
internal string InvalidCollectionInSharedContractMessage
{
get
{ return _helper.InvalidCollectionInSharedContractMessage; }
}
#if uapaot
private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate;
public XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
#else
internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
#endif
{
get
{
#if uapaot
if (DataContractSerializer.Option == SerializationOption.CodeGenOnly
|| (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatWriterDelegate != null))
{
return _xmlFormatWriterDelegate;
}
#endif
if (_helper.XmlFormatWriterDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatWriterDelegate == null)
{
XmlFormatCollectionWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateCollectionWriter(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatWriterDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatWriterDelegate;
}
set
{
#if uapaot
_xmlFormatWriterDelegate = value;
#endif
}
}
#if uapaot
private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate;
public XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
#else
internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
#endif
{
get
{
#if uapaot
if (DataContractSerializer.Option == SerializationOption.CodeGenOnly
|| (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatReaderDelegate != null))
{
return _xmlFormatReaderDelegate;
}
#endif
if (_helper.XmlFormatReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatReaderDelegate == null)
{
XmlFormatCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateCollectionReader(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatReaderDelegate;
}
set
{
#if uapaot
_xmlFormatReaderDelegate = value;
#endif
}
}
#if uapaot
private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate;
public XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
#else
internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
#endif
{
get
{
#if uapaot
if (DataContractSerializer.Option == SerializationOption.CodeGenOnly
|| (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatGetOnlyCollectionReaderDelegate != null))
{
return _xmlFormatGetOnlyCollectionReaderDelegate;
}
#endif
if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null)
{
if (UnderlyingType.IsInterface && (Kind == CollectionKind.Enumerable || Kind == CollectionKind.Collection || Kind == CollectionKind.GenericEnumerable))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType))));
}
Debug.Assert(AddMethod != null || Kind == CollectionKind.Array, "Add method cannot be null if the collection is being used as a get-only property");
XmlFormatGetOnlyCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateGetOnlyCollectionReader(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatGetOnlyCollectionReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatGetOnlyCollectionReaderDelegate;
}
set
{
#if uapaot
_xmlFormatGetOnlyCollectionReaderDelegate = value;
#endif
}
}
internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
_helper.IncrementCollectionCount(xmlWriter, obj, context);
}
internal IEnumerator GetEnumeratorForCollection(object obj, out Type enumeratorReturnType)
{
return _helper.GetEnumeratorForCollection(obj, out enumeratorReturnType);
}
private class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private static Type[] s_knownInterfaces;
private Type _itemType;
private CollectionKind _kind;
private readonly MethodInfo _getEnumeratorMethod, _addMethod;
private readonly ConstructorInfo _constructor;
private DataContract _itemContract;
private DataContract _sharedTypeContract;
private DataContractDictionary _knownDataContracts;
private bool _isKnownTypeAttributeChecked;
private string _itemName;
private bool _itemNameSetExplicit;
private XmlDictionaryString _collectionItemName;
private string _keyName;
private string _valueName;
private XmlDictionaryString _childElementNamespace;
private string _invalidCollectionInSharedContractMessage;
private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate;
private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate;
private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate;
private bool _isConstructorCheckRequired = false;
internal static Type[] KnownInterfaces
{
get
{
if (s_knownInterfaces == null)
{
// Listed in priority order
s_knownInterfaces = new Type[]
{
Globals.TypeOfIDictionaryGeneric,
Globals.TypeOfIDictionary,
Globals.TypeOfIListGeneric,
Globals.TypeOfICollectionGeneric,
Globals.TypeOfIList,
Globals.TypeOfIEnumerableGeneric,
Globals.TypeOfICollection,
Globals.TypeOfIEnumerable
};
}
return s_knownInterfaces;
}
}
private void Init(CollectionKind kind, Type itemType, CollectionDataContractAttribute collectionContractAttribute)
{
_kind = kind;
if (itemType != null)
{
_itemType = itemType;
bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary);
string itemName = null, keyName = null, valueName = null;
if (collectionContractAttribute != null)
{
if (collectionContractAttribute.IsItemNameSetExplicitly)
{
if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractItemName, DataContract.GetClrTypeFullName(UnderlyingType))));
itemName = DataContract.EncodeLocalName(collectionContractAttribute.ItemName);
_itemNameSetExplicit = true;
}
if (collectionContractAttribute.IsKeyNameSetExplicitly)
{
if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType))));
if (!isDictionary)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName)));
keyName = DataContract.EncodeLocalName(collectionContractAttribute.KeyName);
}
if (collectionContractAttribute.IsValueNameSetExplicitly)
{
if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType))));
if (!isDictionary)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName)));
valueName = DataContract.EncodeLocalName(collectionContractAttribute.ValueName);
}
}
XmlDictionary dictionary = isDictionary ? new XmlDictionary(5) : new XmlDictionary(3);
this.Name = dictionary.Add(this.StableName.Name);
this.Namespace = dictionary.Add(this.StableName.Namespace);
_itemName = itemName ?? DataContract.GetStableName(DataContract.UnwrapNullableType(itemType)).Name;
_collectionItemName = dictionary.Add(_itemName);
if (isDictionary)
{
_keyName = keyName ?? Globals.KeyLocalName;
_valueName = valueName ?? Globals.ValueLocalName;
}
}
if (collectionContractAttribute != null)
{
this.IsReference = collectionContractAttribute.IsReference;
}
}
internal CollectionDataContractCriticalHelper(CollectionKind kind)
: base()
{
Init(kind, null, null);
}
// array
internal CollectionDataContractCriticalHelper(Type type) : base(type)
{
if (type == Globals.TypeOfArray)
type = Globals.TypeOfObjectArray;
if (type.GetArrayRank() > 1)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SupportForMultidimensionalArraysNotPresent)));
this.StableName = DataContract.GetStableName(type);
Init(CollectionKind.Array, type.GetElementType(), null);
}
// collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(type)
{
if (getEnumeratorMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type))));
if (addMethod == null && !type.IsInterface)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(type))));
if (itemType == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type))));
CollectionDataContractAttribute collectionContractAttribute;
this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute);
Init(kind, itemType, collectionContractAttribute);
_getEnumeratorMethod = getEnumeratorMethod;
_addMethod = addMethod;
_constructor = constructor;
}
// collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
: this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)
{
_isConstructorCheckRequired = isConstructorCheckRequired;
}
internal CollectionDataContractCriticalHelper(Type type, string invalidCollectionInSharedContractMessage) : base(type)
{
Init(CollectionKind.Collection, null /*itemType*/, null);
_invalidCollectionInSharedContractMessage = invalidCollectionInSharedContractMessage;
}
internal CollectionKind Kind
{
get { return _kind; }
}
internal Type ItemType
{
get { return _itemType; }
set { _itemType = value; }
}
internal DataContract ItemContract
{
get
{
if (_itemContract == null && UnderlyingType != null)
{
if (IsDictionary)
{
if (String.CompareOrdinal(KeyName, ValueName) == 0)
{
DataContract.ThrowInvalidDataContractException(
SR.Format(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName),
UnderlyingType);
}
_itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName });
// Ensure that DataContract gets added to the static DataContract cache for dictionary items
DataContract.GetDataContract(ItemType);
}
else
{
_itemContract = DataContract.GetDataContractFromGeneratedAssembly(ItemType);
if (_itemContract == null)
{
_itemContract = DataContract.GetDataContract(ItemType);
}
}
}
return _itemContract;
}
set
{
_itemContract = value;
}
}
internal DataContract SharedTypeContract
{
get { return _sharedTypeContract; }
set { _sharedTypeContract = value; }
}
internal string ItemName
{
get { return _itemName; }
set { _itemName = value; }
}
internal bool IsConstructorCheckRequired
{
get { return _isConstructorCheckRequired; }
set { _isConstructorCheckRequired = value; }
}
public XmlDictionaryString CollectionItemName
{
get { return _collectionItemName; }
}
internal string KeyName
{
get { return _keyName; }
set { _keyName = value; }
}
internal string ValueName
{
get { return _valueName; }
set { _valueName = value; }
}
internal bool IsDictionary => KeyName != null;
public XmlDictionaryString ChildElementNamespace
{
get { return _childElementNamespace; }
set { _childElementNamespace = value; }
}
internal MethodInfo GetEnumeratorMethod => _getEnumeratorMethod;
internal MethodInfo AddMethod => _addMethod;
internal ConstructorInfo Constructor => _constructor;
internal override DataContractDictionary KnownDataContracts
{
get
{
if (!_isKnownTypeAttributeChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isKnownTypeAttributeChecked)
{
_knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);
Interlocked.MemoryBarrier();
_isKnownTypeAttributeChecked = true;
}
}
}
return _knownDataContracts;
}
set
{ _knownDataContracts = value; }
}
internal string InvalidCollectionInSharedContractMessage => _invalidCollectionInSharedContractMessage;
internal bool ItemNameSetExplicit => _itemNameSetExplicit;
internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
{
get { return _xmlFormatWriterDelegate; }
set { _xmlFormatWriterDelegate = value; }
}
internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
{
get { return _xmlFormatReaderDelegate; }
set { _xmlFormatReaderDelegate = value; }
}
internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
{
get { return _xmlFormatGetOnlyCollectionReaderDelegate; }
set { _xmlFormatGetOnlyCollectionReaderDelegate = value; }
}
private delegate void IncrementCollectionCountDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context);
private IncrementCollectionCountDelegate _incrementCollectionCountDelegate = null;
private static void DummyIncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { }
internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
if (_incrementCollectionCountDelegate == null)
{
switch (Kind)
{
case CollectionKind.Collection:
case CollectionKind.List:
case CollectionKind.Dictionary:
{
_incrementCollectionCountDelegate = (x, o, c) =>
{
context.IncrementCollectionCount(x, (ICollection)o);
};
}
break;
case CollectionKind.GenericCollection:
case CollectionKind.GenericList:
{
var buildIncrementCollectionCountDelegate = BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(ItemType);
_incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>());
}
break;
case CollectionKind.GenericDictionary:
{
var buildIncrementCollectionCountDelegate = BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(ItemType.GetGenericArguments()));
_incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>());
}
break;
default:
// Do nothing.
_incrementCollectionCountDelegate = DummyIncrementCollectionCount;
break;
}
}
_incrementCollectionCountDelegate(xmlWriter, obj, context);
}
private static MethodInfo s_buildIncrementCollectionCountDelegateMethod;
private static MethodInfo BuildIncrementCollectionCountDelegateMethod
{
get
{
if (s_buildIncrementCollectionCountDelegateMethod == null)
{
s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers);
}
return s_buildIncrementCollectionCountDelegateMethod;
}
}
private static IncrementCollectionCountDelegate BuildIncrementCollectionCountDelegate<T>()
{
return (xmlwriter, obj, context) =>
{
context.IncrementCollectionCountGeneric<T>(xmlwriter, (ICollection<T>)obj);
};
}
private delegate IEnumerator CreateGenericDictionaryEnumeratorDelegate(IEnumerator enumerator);
private CreateGenericDictionaryEnumeratorDelegate _createGenericDictionaryEnumeratorDelegate;
internal IEnumerator GetEnumeratorForCollection(object obj, out Type enumeratorReturnType)
{
IEnumerator enumerator = ((IEnumerable)obj).GetEnumerator();
if (Kind == CollectionKind.GenericDictionary)
{
if (_createGenericDictionaryEnumeratorDelegate == null)
{
var keyValueTypes = ItemType.GetGenericArguments();
var buildCreateGenericDictionaryEnumerator = BuildCreateGenericDictionaryEnumerato.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]);
_createGenericDictionaryEnumeratorDelegate = (CreateGenericDictionaryEnumeratorDelegate)buildCreateGenericDictionaryEnumerator.Invoke(null, Array.Empty<object>());
}
enumerator = _createGenericDictionaryEnumeratorDelegate(enumerator);
}
else if (Kind == CollectionKind.Dictionary)
{
enumerator = new DictionaryEnumerator(((IDictionary)obj).GetEnumerator());
}
enumeratorReturnType = EnumeratorReturnType;
return enumerator;
}
private Type _enumeratorReturnType;
public Type EnumeratorReturnType
{
get
{
_enumeratorReturnType = _enumeratorReturnType ?? GetCollectionEnumeratorReturnType();
return _enumeratorReturnType;
}
}
private Type GetCollectionEnumeratorReturnType()
{
Type enumeratorReturnType;
if (Kind == CollectionKind.GenericDictionary)
{
var keyValueTypes = ItemType.GetGenericArguments();
enumeratorReturnType = Globals.TypeOfKeyValue.MakeGenericType(keyValueTypes);
}
else if (Kind == CollectionKind.Dictionary)
{
enumeratorReturnType = Globals.TypeOfObject;
}
else if (Kind == CollectionKind.GenericCollection
|| Kind == CollectionKind.GenericList)
{
enumeratorReturnType = ItemType;
}
else
{
var enumeratorType = GetEnumeratorMethod.ReturnType;
if (enumeratorType.IsGenericType)
{
MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
enumeratorReturnType = getCurrentMethod.ReturnType;
}
else
{
enumeratorReturnType = Globals.TypeOfObject;
}
}
return enumeratorReturnType;
}
private static MethodInfo s_buildCreateGenericDictionaryEnumerator;
private static MethodInfo BuildCreateGenericDictionaryEnumerato
{
get
{
if (s_buildCreateGenericDictionaryEnumerator == null)
{
s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers);
}
return s_buildCreateGenericDictionaryEnumerator;
}
}
private static CreateGenericDictionaryEnumeratorDelegate BuildCreateGenericDictionaryEnumerator<K, V>()
{
return (enumerator) =>
{
return new GenericDictionaryEnumerator<K, V>((IEnumerator<KeyValuePair<K, V>>)enumerator);
};
}
}
private DataContract GetSharedTypeContract(Type type)
{
if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
{
return this;
}
if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return new ClassDataContract(type);
}
return null;
}
internal static bool IsCollectionInterface(Type type)
{
if (type.IsGenericType)
type = type.GetGenericTypeDefinition();
return ((IList<Type>)KnownInterfaces).Contains(type);
}
internal static bool IsCollection(Type type)
{
Type itemType;
return IsCollection(type, out itemType);
}
internal static bool IsCollection(Type type, out Type itemType)
{
return IsCollectionHelper(type, out itemType, true /*constructorRequired*/);
}
internal static bool IsCollection(Type type, bool constructorRequired)
{
Type itemType;
return IsCollectionHelper(type, out itemType, constructorRequired);
}
private static bool IsCollectionHelper(Type type, out Type itemType, bool constructorRequired)
{
if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null)
{
itemType = type.GetElementType();
return true;
}
DataContract dataContract;
return IsCollectionOrTryCreate(type, false /*tryCreate*/, out dataContract, out itemType, constructorRequired);
}
internal static bool TryCreate(Type type, out DataContract dataContract)
{
Type itemType;
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, true /*constructorRequired*/);
}
internal static bool CreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
{
Type itemType;
if (type.IsArray)
{
dataContract = new CollectionDataContract(type);
return true;
}
else
{
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
}
}
internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
{
dataContract = DataContract.GetDataContractFromGeneratedAssembly(type);
if (dataContract == null)
{
Type itemType;
if (type.IsArray)
{
dataContract = new CollectionDataContract(type);
return true;
}
else
{
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
}
}
else
{
if (dataContract is CollectionDataContract)
{
return true;
}
else
{
dataContract = null;
return false;
}
}
}
internal static MethodInfo GetTargetMethodWithName(string name, Type type, Type interfaceType)
{
Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
return t?.GetMethod(name);
}
private static bool IsArraySegment(Type t)
{
return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
}
private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract dataContract, out Type itemType, bool constructorRequired)
{
dataContract = null;
itemType = Globals.TypeOfObject;
if (DataContract.GetBuiltInDataContract(type) != null)
{
return HandleIfInvalidCollection(type, tryCreate, false/*hasCollectionDataContract*/, false/*isBaseTypeCollection*/,
SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract);
}
MethodInfo addMethod, getEnumeratorMethod;
bool hasCollectionDataContract = IsCollectionDataContract(type);
Type baseType = type.BaseType;
bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject
&& baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false;
if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection,
SR.CollectionTypeCannotHaveDataContract, null, ref dataContract);
}
if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) || IsArraySegment(type))
{
return false;
}
if (!Globals.TypeOfIEnumerable.IsAssignableFrom(type))
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection,
SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
}
if (type.IsInterface)
{
Type interfaceTypeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
Type[] knownInterfaces = KnownInterfaces;
for (int i = 0; i < knownInterfaces.Length; i++)
{
if (knownInterfaces[i] == interfaceTypeToCheck)
{
addMethod = null;
if (type.IsGenericType)
{
Type[] genericArgs = type.GetGenericArguments();
if (interfaceTypeToCheck == Globals.TypeOfIDictionaryGeneric)
{
itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs);
addMethod = type.GetMethod(Globals.AddMethodName);
getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName);
}
else
{
itemType = genericArgs[0];
// ICollection<T> has AddMethod
var collectionType = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType);
if (collectionType.IsAssignableFrom(type))
{
addMethod = collectionType.GetMethod(Globals.AddMethodName);
}
getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName);
}
}
else
{
if (interfaceTypeToCheck == Globals.TypeOfIDictionary)
{
itemType = typeof(KeyValue<object, object>);
addMethod = type.GetMethod(Globals.AddMethodName);
}
else
{
itemType = Globals.TypeOfObject;
// IList has AddMethod
if (interfaceTypeToCheck == Globals.TypeOfIList)
{
addMethod = type.GetMethod(Globals.AddMethodName);
}
}
getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName);
}
if (tryCreate)
dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/);
return true;
}
}
}
ConstructorInfo defaultCtor = null;
if (!type.IsValueType)
{
defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>());
if (defaultCtor == null && constructorRequired)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/,
SR.CollectionTypeDoesNotHaveDefaultCtor, null, ref dataContract);
}
}
Type knownInterfaceType = null;
CollectionKind kind = CollectionKind.None;
bool multipleDefinitions = false;
Type[] interfaceTypes = type.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
Type interfaceTypeToCheck = interfaceType.IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType;
Type[] knownInterfaces = KnownInterfaces;
for (int i = 0; i < knownInterfaces.Length; i++)
{
if (knownInterfaces[i] == interfaceTypeToCheck)
{
CollectionKind currentKind = (CollectionKind)(i + 1);
if (kind == CollectionKind.None || currentKind < kind)
{
kind = currentKind;
knownInterfaceType = interfaceType;
multipleDefinitions = false;
}
else if ((kind & currentKind) == currentKind)
multipleDefinitions = true;
break;
}
}
}
if (kind == CollectionKind.None)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection,
SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
}
if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable)
{
if (multipleDefinitions)
knownInterfaceType = Globals.TypeOfIEnumerable;
itemType = knownInterfaceType.IsGenericType ? knownInterfaceType.GetGenericArguments()[0] : Globals.TypeOfObject;
GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType },
false /*addMethodOnInterface*/,
out getEnumeratorMethod, out addMethod);
if (addMethod == null)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/,
SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), ref dataContract);
}
if (tryCreate)
dataContract = new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
}
else
{
if (multipleDefinitions)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/,
SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract);
}
Type[] addMethodTypeArray = null;
switch (kind)
{
case CollectionKind.GenericDictionary:
addMethodTypeArray = knownInterfaceType.GetGenericArguments();
bool isOpenGeneric = knownInterfaceType.IsGenericTypeDefinition
|| (addMethodTypeArray[0].IsGenericParameter && addMethodTypeArray[1].IsGenericParameter);
itemType = isOpenGeneric ? Globals.TypeOfKeyValue : Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray);
break;
case CollectionKind.Dictionary:
addMethodTypeArray = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
itemType = Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray);
break;
case CollectionKind.GenericList:
case CollectionKind.GenericCollection:
addMethodTypeArray = knownInterfaceType.GetGenericArguments();
itemType = addMethodTypeArray[0];
break;
case CollectionKind.List:
itemType = Globals.TypeOfObject;
addMethodTypeArray = new Type[] { itemType };
break;
}
if (tryCreate)
{
GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray,
true /*addMethodOnInterface*/,
out getEnumeratorMethod, out addMethod);
dataContract = DataContract.GetDataContractFromGeneratedAssembly(type);
if (dataContract == null)
{
dataContract = new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
}
}
}
return true;
}
internal static bool IsCollectionDataContract(Type type)
{
return type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false);
}
private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string param, ref DataContract dataContract)
{
if (hasCollectionDataContract)
{
if (tryCreate)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionDataContract, DataContract.GetClrTypeFullName(type)), param)));
return true;
}
if (createContractWithException)
{
if (tryCreate)
dataContract = new CollectionDataContract(type, GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param));
return true;
}
return false;
}
private static string GetInvalidCollectionMessage(string message, string nestedMessage, string param)
{
return (param == null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param);
}
private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo addMethod, ref MethodInfo getEnumeratorMethod)
{
Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
if (t != null)
{
addMethod = t.GetMethod(Globals.AddMethodName) ?? addMethod;
getEnumeratorMethod = t.GetMethod(Globals.GetEnumeratorMethodName) ?? getEnumeratorMethod;
}
}
private static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo getEnumeratorMethod, out MethodInfo addMethod)
{
addMethod = getEnumeratorMethod = null;
if (addMethodOnInterface)
{
addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public, addMethodTypeArray);
if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0])
{
FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod);
if (addMethod == null)
{
Type[] parentInterfaceTypes = interfaceType.GetInterfaces();
foreach (Type parentInterfaceType in parentInterfaceTypes)
{
if (IsKnownInterface(parentInterfaceType))
{
FindCollectionMethodsOnInterface(type, parentInterfaceType, ref addMethod, ref getEnumeratorMethod);
if (addMethod == null)
{
break;
}
}
}
}
}
}
else
{
// GetMethod returns Add() method with parameter closest matching T in assignability/inheritance chain
addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, addMethodTypeArray);
if (addMethod == null)
return;
}
if (getEnumeratorMethod == null)
{
getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType))
{
Type ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault();
if (ienumerableInterface == null)
ienumerableInterface = Globals.TypeOfIEnumerable;
getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface);
}
}
}
private static bool IsKnownInterface(Type type)
{
Type typeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
foreach (Type knownInterfaceType in KnownInterfaces)
{
if (typeToCheck == knownInterfaceType)
{
return true;
}
}
return false;
}
internal override DataContract GetValidContract(SerializationMode mode)
{
if (InvalidCollectionInSharedContractMessage != null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage));
return this;
}
internal override DataContract GetValidContract()
{
if (this.IsConstructorCheckRequired)
{
CheckConstructor();
}
return this;
}
private void CheckConstructor()
{
if (this.Constructor == null)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionTypeDoesNotHaveDefaultCtor, DataContract.GetClrTypeFullName(this.UnderlyingType))));
}
else
{
this.IsConstructorCheckRequired = false;
}
}
internal override bool IsValidContract(SerializationMode mode)
{
return (InvalidCollectionInSharedContractMessage == null);
}
/// <SecurityNote>
/// Review - calculates whether this collection requires MemberAccessPermission for deserialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForRead(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ItemType != null && !IsTypeVisible(ItemType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(ItemType)),
securityException));
}
return true;
}
if (ConstructorRequiresMemberAccess(Constructor))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractNoPublicConstructor,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.AddMethod))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractAddMethodNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.AddMethod.Name),
securityException));
}
return true;
}
return false;
}
/// <SecurityNote>
/// Review - calculates whether this collection requires MemberAccessPermission for serialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForWrite(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ItemType != null && !IsTypeVisible(ItemType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(ItemType)),
securityException));
}
return true;
}
return false;
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
XmlFormatWriterDelegate(xmlWriter, obj, context, this);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
xmlReader.Read();
object o = null;
if (context.IsGetOnlyCollection)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
#if uapaot
if (XmlFormatGetOnlyCollectionReaderDelegate == null)
{
throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, UnderlyingType.ToString()));
}
#endif
XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
}
else
{
o = XmlFormatReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
}
xmlReader.ReadEndElement();
return o;
}
internal class DictionaryEnumerator : IEnumerator<KeyValue<object, object>>
{
private IDictionaryEnumerator _enumerator;
public DictionaryEnumerator(IDictionaryEnumerator enumerator)
{
_enumerator = enumerator;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public KeyValue<object, object> Current
{
get { return new KeyValue<object, object>(_enumerator.Key, _enumerator.Value); }
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
_enumerator.Reset();
}
}
internal class GenericDictionaryEnumerator<K, V> : IEnumerator<KeyValue<K, V>>
{
private IEnumerator<KeyValuePair<K, V>> _enumerator;
public GenericDictionaryEnumerator(IEnumerator<KeyValuePair<K, V>> enumerator)
{
_enumerator = enumerator;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public KeyValue<K, V> Current
{
get
{
KeyValuePair<K, V> current = _enumerator.Current;
return new KeyValue<K, V>(current.Key, current.Value);
}
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
_enumerator.Reset();
}
}
}
}
| |
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
namespace WeifenLuo.WinFormsUI.Docking
{
/// <summary>
/// Dock window base class.
/// </summary>
[ToolboxItem(false)]
public partial class DockWindow : Panel, INestedPanesContainer, ISplitterDragSource
{
private DockPanel m_dockPanel;
private DockState m_dockState;
private SplitterBase m_splitter;
private NestedPaneCollection m_nestedPanes;
internal DockWindow(DockPanel dockPanel, DockState dockState)
{
m_nestedPanes = new NestedPaneCollection(this);
m_dockPanel = dockPanel;
m_dockState = dockState;
Visible = false;
SuspendLayout();
if (DockState == DockState.DockLeft || DockState == DockState.DockRight ||
DockState == DockState.DockTop || DockState == DockState.DockBottom)
{
m_splitter = DockPanel.Extender.DockWindowSplitterControlFactory.CreateSplitterControl();
Controls.Add(m_splitter);
}
if (DockState == DockState.DockLeft)
{
Dock = DockStyle.Left;
m_splitter.Dock = DockStyle.Right;
}
else if (DockState == DockState.DockRight)
{
Dock = DockStyle.Right;
m_splitter.Dock = DockStyle.Left;
}
else if (DockState == DockState.DockTop)
{
Dock = DockStyle.Top;
m_splitter.Dock = DockStyle.Bottom;
}
else if (DockState == DockState.DockBottom)
{
Dock = DockStyle.Bottom;
m_splitter.Dock = DockStyle.Top;
}
else if (DockState == DockState.Document)
{
Dock = DockStyle.Fill;
}
ResumeLayout();
}
public VisibleNestedPaneCollection VisibleNestedPanes
{
get { return NestedPanes.VisibleNestedPanes; }
}
public NestedPaneCollection NestedPanes
{
get { return m_nestedPanes; }
}
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
public DockState DockState
{
get { return m_dockState; }
}
public bool IsFloat
{
get { return DockState == DockState.Float; }
}
internal DockPane DefaultPane
{
get { return VisibleNestedPanes.Count == 0 ? null : VisibleNestedPanes[0]; }
}
public virtual Rectangle DisplayingRectangle
{
get
{
Rectangle rect = ClientRectangle;
// if DockWindow is document, exclude the border
if (DockState == DockState.Document)
{
rect.X += 1;
rect.Y += 1;
rect.Width -= 2;
rect.Height -= 2;
}
// exclude the splitter
else if (DockState == DockState.DockLeft)
rect.Width -= Measures.SplitterSize;
else if (DockState == DockState.DockRight)
{
rect.X += Measures.SplitterSize;
rect.Width -= Measures.SplitterSize;
}
else if (DockState == DockState.DockTop)
rect.Height -= Measures.SplitterSize;
else if (DockState == DockState.DockBottom)
{
rect.Y += Measures.SplitterSize;
rect.Height -= Measures.SplitterSize;
}
return rect;
}
}
protected override void OnLayout(LayoutEventArgs levent)
{
VisibleNestedPanes.Refresh();
if (VisibleNestedPanes.Count == 0)
{
if (Visible)
Visible = false;
}
else if (!Visible)
{
Visible = true;
VisibleNestedPanes.Refresh();
}
base.OnLayout (levent);
}
#region ISplitterDragSource Members
void ISplitterDragSource.BeginDrag(Rectangle rectSplitter)
{
}
void ISplitterDragSource.EndDrag()
{
}
bool ISplitterDragSource.IsVertical
{
get { return (DockState == DockState.DockLeft || DockState == DockState.DockRight); }
}
Rectangle ISplitterDragSource.DragLimitBounds
{
get
{
Rectangle rectLimit = DockPanel.DockArea;
Point location;
if ((Control.ModifierKeys & Keys.Shift) == 0)
location = Location;
else
location = DockPanel.DockArea.Location;
if (((ISplitterDragSource)this).IsVertical)
{
rectLimit.X += MeasurePane.MinSize;
rectLimit.Width -= 2 * MeasurePane.MinSize;
rectLimit.Y = location.Y;
if ((Control.ModifierKeys & Keys.Shift) == 0)
rectLimit.Height = Height;
}
else
{
rectLimit.Y += MeasurePane.MinSize;
rectLimit.Height -= 2 * MeasurePane.MinSize;
rectLimit.X = location.X;
if ((Control.ModifierKeys & Keys.Shift) == 0)
rectLimit.Width = Width;
}
return DockPanel.RectangleToScreen(rectLimit);
}
}
void ISplitterDragSource.MoveSplitter(int offset)
{
if ((Control.ModifierKeys & Keys.Shift) != 0)
SendToBack();
Rectangle rectDockArea = DockPanel.DockArea;
if (DockState == DockState.DockLeft && rectDockArea.Width > 0)
{
if (DockPanel.DockLeftPortion > 1)
DockPanel.DockLeftPortion = Width + offset;
else
DockPanel.DockLeftPortion += ((double)offset) / (double)rectDockArea.Width;
}
else if (DockState == DockState.DockRight && rectDockArea.Width > 0)
{
if (DockPanel.DockRightPortion > 1)
DockPanel.DockRightPortion = Width - offset;
else
DockPanel.DockRightPortion -= ((double)offset) / (double)rectDockArea.Width;
}
else if (DockState == DockState.DockBottom && rectDockArea.Height > 0)
{
if (DockPanel.DockBottomPortion > 1)
DockPanel.DockBottomPortion = Height - offset;
else
DockPanel.DockBottomPortion -= ((double)offset) / (double)rectDockArea.Height;
}
else if (DockState == DockState.DockTop && rectDockArea.Height > 0)
{
if (DockPanel.DockTopPortion > 1)
DockPanel.DockTopPortion = Height + offset;
else
DockPanel.DockTopPortion += ((double)offset) / (double)rectDockArea.Height;
}
}
#region IDragSource Members
Control IDragSource.DragControl
{
get { return this; }
}
#endregion
#endregion
}
/// <summary>
/// Dock window of Visual Studio 2003/2005 theme.
/// </summary>
[ToolboxItem(false)]
internal class DefaultDockWindow : DockWindow
{
internal DefaultDockWindow(DockPanel dockPanel, DockState dockState) : base(dockPanel, dockState)
{
}
protected override void OnPaint(PaintEventArgs e)
{
// if DockWindow is document, draw the border
if (DockState == DockState.Document)
e.Graphics.DrawRectangle(SystemPens.ControlDark, ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 1);
base.OnPaint(e);
}
}
}
| |
using System;
using System.Collections;
using Server.Network;
using Server.Items;
using Server.Multis;
namespace Server.Items
{
public enum HolidayTreeType
{
Classic,
Modern
}
public class HolidayTree : Item, IAddon
{
private ArrayList m_Components;
private Mobile m_Placer;
[CommandProperty( AccessLevel.GameMaster )]
public Mobile Placer
{
get{ return m_Placer; }
set{ m_Placer = value; }
}
private class Ornament : Item
{
public override int LabelNumber{ get{ return 1041118; } } // a tree ornament
public Ornament( int itemID ) : base( itemID )
{
Movable = false;
}
public Ornament( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
private class TreeTrunk : Item
{
private HolidayTree m_Tree;
public override int LabelNumber{ get{ return 1041117; } } // a tree for the holidays
public TreeTrunk( HolidayTree tree, int itemID ) : base( itemID )
{
Movable = false;
MoveToWorld( tree.Location, tree.Map );
m_Tree = tree;
}
public TreeTrunk( Serial serial ) : base( serial )
{
}
public override void OnDoubleClick( Mobile from )
{
if ( m_Tree != null && !m_Tree.Deleted )
m_Tree.OnDoubleClick( from );
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
writer.Write( m_Tree );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_Tree = reader.ReadItem() as HolidayTree;
if ( m_Tree == null )
Delete();
break;
}
}
}
}
public override int LabelNumber{ get{ return 1041117; } } // a tree for the holidays
public HolidayTree( Mobile from, HolidayTreeType type, Point3D loc ) : base( 1 )
{
Movable = false;
MoveToWorld( loc, from.Map );
m_Placer = from;
m_Components = new ArrayList();
switch ( type )
{
case HolidayTreeType.Classic:
{
ItemID = 0xCD7;
AddItem( 0, 0, 0, new TreeTrunk( this, 0xCD6 ) );
AddOrnament( 0, 0, 2, 0xF22 );
AddOrnament( 0, 0, 9, 0xF18 );
AddOrnament( 0, 0, 15, 0xF20 );
AddOrnament( 0, 0, 19, 0xF17 );
AddOrnament( 0, 0, 20, 0xF24 );
AddOrnament( 0, 0, 20, 0xF1F );
AddOrnament( 0, 0, 20, 0xF19 );
AddOrnament( 0, 0, 21, 0xF1B );
AddOrnament( 0, 0, 28, 0xF2F );
AddOrnament( 0, 0, 30, 0xF23 );
AddOrnament( 0, 0, 32, 0xF2A );
AddOrnament( 0, 0, 33, 0xF30 );
AddOrnament( 0, 0, 34, 0xF29 );
AddOrnament( 0, 1, 7, 0xF16 );
AddOrnament( 0, 1, 7, 0xF1E );
AddOrnament( 0, 1, 12, 0xF0F );
AddOrnament( 0, 1, 13, 0xF13 );
AddOrnament( 0, 1, 18, 0xF12 );
AddOrnament( 0, 1, 19, 0xF15 );
AddOrnament( 0, 1, 25, 0xF28 );
AddOrnament( 0, 1, 29, 0xF1A );
AddOrnament( 0, 1, 37, 0xF2B );
AddOrnament( 1, 0, 13, 0xF10 );
AddOrnament( 1, 0, 14, 0xF1C );
AddOrnament( 1, 0, 16, 0xF14 );
AddOrnament( 1, 0, 17, 0xF26 );
AddOrnament( 1, 0, 22, 0xF27 );
break;
}
case HolidayTreeType.Modern:
{
ItemID = 0x1B7E;
AddOrnament( 0, 0, 2, 0xF2F );
AddOrnament( 0, 0, 2, 0xF20 );
AddOrnament( 0, 0, 2, 0xF22 );
AddOrnament( 0, 0, 5, 0xF30 );
AddOrnament( 0, 0, 5, 0xF15 );
AddOrnament( 0, 0, 5, 0xF1F );
AddOrnament( 0, 0, 5, 0xF2B );
AddOrnament( 0, 0, 6, 0xF0F );
AddOrnament( 0, 0, 7, 0xF1E );
AddOrnament( 0, 0, 7, 0xF24 );
AddOrnament( 0, 0, 8, 0xF29 );
AddOrnament( 0, 0, 9, 0xF18 );
AddOrnament( 0, 0, 14, 0xF1C );
AddOrnament( 0, 0, 15, 0xF13 );
AddOrnament( 0, 0, 15, 0xF20 );
AddOrnament( 0, 0, 16, 0xF26 );
AddOrnament( 0, 0, 17, 0xF12 );
AddOrnament( 0, 0, 18, 0xF17 );
AddOrnament( 0, 0, 20, 0xF1B );
AddOrnament( 0, 0, 23, 0xF28 );
AddOrnament( 0, 0, 25, 0xF18 );
AddOrnament( 0, 0, 25, 0xF2A );
AddOrnament( 0, 1, 7, 0xF16 );
break;
}
}
}
public override void OnAfterDelete()
{
for ( int i = 0; i < m_Components.Count; ++i )
((Item)m_Components[i]).Delete();
}
private void AddOrnament( int x, int y, int z, int itemID )
{
AddItem( x + 1, y + 1, z + 11, new Ornament( itemID ) );
}
private void AddItem( int x, int y, int z, Item item )
{
item.MoveToWorld( new Point3D( this.Location.X + x, this.Location.Y + y, this.Location.Z + z ), this.Map );
m_Components.Add( item );
}
public HolidayTree( Serial serial ) : base( serial )
{
}
public bool CouldFit( IPoint3D p, Map map )
{
return map.CanFit( (Point3D)p, 20 );
}
Item IAddon.Deed
{
get{ return new HolidayTreeDeed(); }
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 1 ); // version
writer.Write( m_Placer );
writer.Write( (int) m_Components.Count );
for ( int i = 0; i < m_Components.Count; ++i )
writer.Write( (Item)m_Components[i] );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 1:
{
m_Placer = reader.ReadMobile();
goto case 0;
}
case 0:
{
int count = reader.ReadInt();
m_Components = new ArrayList( count );
for ( int i = 0; i < count; ++i )
{
Item item = reader.ReadItem();
if ( item != null )
m_Components.Add( item );
}
break;
}
}
Timer.DelayCall( TimeSpan.Zero, ValidatePlacement );
}
public void ValidatePlacement()
{
BaseHouse house = BaseHouse.FindHouseAt( this );
if ( house == null )
{
HolidayTreeDeed deed = new HolidayTreeDeed();
deed.MoveToWorld( Location, Map );
Delete();
}
}
public override void OnDoubleClick( Mobile from )
{
if ( from.InRange( this.GetWorldLocation(), 1 ) )
{
if ( m_Placer == null || from == m_Placer || from.AccessLevel >= AccessLevel.GameMaster )
{
from.AddToBackpack( new HolidayTreeDeed() );
this.Delete();
BaseHouse house = BaseHouse.FindHouseAt( this );
if ( house != null && house.Addons.Contains( this ) )
{
house.Addons.Remove( this );
}
from.SendLocalizedMessage( 503393 ); // A deed for the tree has been placed in your backpack.
}
else
{
from.SendLocalizedMessage( 503396 ); // You cannot take this tree down.
}
}
else
{
from.SendLocalizedMessage( 500446 ); // That is too far away.
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BasicOperations operations.
/// </summary>
internal partial class BasicOperations : IServiceOperations<AzureCompositeModelClient>, IBasicOperations
{
/// <summary>
/// Initializes a new instance of the BasicOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BasicOperations(AzureCompositeModelClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModelClient
/// </summary>
public AzureCompositeModelClient Client { get; private set; }
/// <summary>
/// Get complex type {id: 2, name: 'abc', color: 'YELLOW'}
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Basic>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Please put {id: 2, name: 'abc', color: 'Magenta'}
/// </summary>
/// <param name='complexBody'>
/// Please put {id: 2, name: 'abc', color: 'Magenta'}
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(Basic complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
string apiVersion = "2016-02-29";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type that is invalid for the local strong type
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Basic>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/invalid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type that is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Basic>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/empty").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type whose properties are null
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Basic>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/null").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type while the server doesn't provide a response
/// payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Basic>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/notprovided").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
namespace IO.Swagger.Client {
/// <summary>
/// API client is mainly responible for making the HTTP call to the API backend
/// </summary>
public class ApiClient {
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient"/> class.
/// </summary>
/// <param name="basePath">The base path.</param>
public ApiClient(String basePath="http://api2.online-convert.com/") {
this.basePath = basePath;
this.restClient = new RestClient(this.basePath);
}
/// <summary>
/// Gets or sets the base path.
/// </summary>
/// <value>The base path.</value>
public string basePath { get; set; }
/// <summary>
/// Gets or sets the RestClient
/// </summary>
/// <value>The RestClient.</value>
public RestClient restClient { get; set; }
private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
public Object CallApi(String Path, RestSharp.Method Method, Dictionary<String, String> QueryParams, String PostBody,
Dictionary<String, String> HeaderParams, Dictionary<String, String> FormParams, Dictionary<String, String> FileParams, String[] AuthSettings) {
var response = Task.Run(async () => {
var resp = await CallApiAsync(Path, Method, QueryParams, PostBody, HeaderParams, FormParams, FileParams, AuthSettings);
return resp;
});
return response.Result;
}
public async Task<Object> CallApiAsync(String Path, RestSharp.Method Method, Dictionary<String, String> QueryParams, String PostBody,
Dictionary<String, String> HeaderParams, Dictionary<String, String> FormParams, Dictionary<String, String> FileParams, String[] AuthSettings) {
var request = new RestRequest(Path, Method);
UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in this.defaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any
foreach(KeyValuePair<string, string> param in HeaderParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(KeyValuePair<string, string> param in QueryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(KeyValuePair<string, string> param in FormParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(KeyValuePair<string, string> param in FileParams)
request.AddFile(param.Key, param.Value);
if (PostBody != null) {
request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter
}
return (Object) await restClient.ExecuteTaskAsync(request);
}
/// <summary>
/// Add default header
/// </summary>
/// <param name="key"> Header field name
/// <param name="value"> Header field value
/// <returns></returns>
public void AddDefaultHeader(string key, string value) {
defaultHeaderMap.Add(key, value);
}
/// <summary>
/// Get default header
/// </summary>
/// <returns>Dictionary of default header</returns>
public Dictionary<String, String> GetDefaultHeader() {
return defaultHeaderMap;
}
/// <summary>
/// escape string (url-encoded)
/// </summary>
/// <param name="str"> String to be escaped
/// <returns>Escaped string</returns>
public string EscapeString(string str) {
return str;
}
/// <summary>
/// if parameter is DateTime, output in ISO8601 format
/// if parameter is a list of string, join the list with ","
/// otherwise just return the string
/// </summary>
/// <param name="obj"> The parameter (header, path, query, form)
/// <returns>Formatted string</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime) {
return ((DateTime)obj).ToString ("u");
} else if (obj is List<string>) {
return String.Join(",", obj as List<string>);
} else {
return Convert.ToString (obj);
}
}
/// <summary>
/// Deserialize the JSON string into a proper object
/// </summary>
/// <param name="json"> JSON string
/// <param name="type"> Object type
/// <returns>Object representation of the JSON string</returns>
public object Deserialize(string content, Type type) {
if (type.GetType() == typeof(Object))
return (Object)content;
try
{
return JsonConvert.DeserializeObject(content, type);
}
catch (IOException e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an object into JSON string
/// </summary>
/// <param name="obj"> Object
/// <returns>JSON string</returns>
public string Serialize(object obj) {
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Get the API key with prefix
/// </summary>
/// <param name="obj"> Object
/// <returns>API key with prefix</returns>
public string GetApiKeyWithPrefix (string apiKey)
{
var apiKeyValue = "";
Configuration.apiKey.TryGetValue (apiKey, out apiKeyValue);
var apiKeyPrefix = "";
if (Configuration.apiKeyPrefix.TryGetValue (apiKey, out apiKeyPrefix)) {
return apiKeyPrefix + " " + apiKeyValue;
} else {
return apiKeyValue;
}
}
/// <summary>
/// Update parameters based on authentication
/// </summary>
/// <param name="QueryParams">Query parameters</param>
/// <param name="HeaderParams">Header parameters</param>
/// <param name="AuthSettings">Authentication settings</param>
public void UpdateParamsForAuth(Dictionary<String, String> QueryParams, Dictionary<String, String> HeaderParams, string[] AuthSettings) {
if (AuthSettings == null || AuthSettings.Length == 0)
return;
foreach (string auth in AuthSettings) {
// determine which one to use
switch(auth) {
default:
//TODO show warning about security definition not found
break;
}
}
}
/// <summary>
/// Encode string in base64 format
/// </summary>
/// <param name="text">String to be encoded</param>
public static string Base64Encode(string text) {
var textByte = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(textByte);
}
}
}
| |
// GZipStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-August-08 18:14:39>
//
// ------------------------------------------------------------------
//
// This module defines the GZipStream class, which can be used as a replacement for
// the System.IO.Compression.GZipStream class in the .NET BCL. NB: The design is not
// completely OO clean: there is some intelligence in the ZlibBaseStream that reads the
// GZip header.
//
// ------------------------------------------------------------------
using System;
using System.IO;
namespace Ionic.Zlib
{
/// <summary>
/// A class for compressing and decompressing GZIP streams.
/// </summary>
/// <remarks>
///
/// <para>
/// The <c>GZipStream</c> is a <see
/// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a
/// <see cref="Stream"/>. It adds GZIP compression or decompression to any
/// stream.
/// </para>
///
/// <para>
/// Like the <c>System.IO.Compression.GZipStream</c> in the .NET Base Class Library, the
/// <c>Ionic.Zlib.GZipStream</c> can compress while writing, or decompress while
/// reading, but not vice versa. The compression method used is GZIP, which is
/// documented in <see href="http://www.ietf.org/rfc/rfc1952.txt">IETF RFC
/// 1952</see>, "GZIP file format specification version 4.3".</para>
///
/// <para>
/// A <c>GZipStream</c> can be used to decompress data (through <c>Read()</c>) or
/// to compress data (through <c>Write()</c>), but not both.
/// </para>
///
/// <para>
/// If you wish to use the <c>GZipStream</c> to compress data, you must wrap it
/// around a write-able stream. As you call <c>Write()</c> on the <c>GZipStream</c>, the
/// data will be compressed into the GZIP format. If you want to decompress data,
/// you must wrap the <c>GZipStream</c> around a readable stream that contains an
/// IETF RFC 1952-compliant stream. The data will be decompressed as you call
/// <c>Read()</c> on the <c>GZipStream</c>.
/// </para>
///
/// <para>
/// Though the GZIP format allows data from multiple files to be concatenated
/// together, this stream handles only a single segment of GZIP format, typically
/// representing a single file.
/// </para>
///
/// <para>
/// This class is similar to <see cref="ZlibStream"/> and <see cref="DeflateStream"/>.
/// <c>ZlibStream</c> handles RFC1950-compliant streams. <see cref="DeflateStream"/>
/// handles RFC1951-compliant streams. This class handles RFC1952-compliant streams.
/// </para>
///
/// </remarks>
///
/// <seealso cref="DeflateStream" />
/// <seealso cref="ZlibStream" />
public class GZipStream : System.IO.Stream
{
// GZip format
// source: http://tools.ietf.org/html/rfc1952
//
// header id: 2 bytes 1F 8B
// compress method 1 byte 8= DEFLATE (none other supported)
// flag 1 byte bitfield (See below)
// mtime 4 bytes time_t (seconds since jan 1, 1970 UTC of the file.
// xflg 1 byte 2 = max compress used , 4 = max speed (can be ignored)
// OS 1 byte OS for originating archive. set to 0xFF in compression.
// extra field length 2 bytes optional - only if FEXTRA is set.
// extra field varies
// filename varies optional - if FNAME is set. zero terminated. ISO-8859-1.
// file comment varies optional - if FCOMMENT is set. zero terminated. ISO-8859-1.
// crc16 1 byte optional - present only if FHCRC bit is set
// compressed data varies
// CRC32 4 bytes
// isize 4 bytes data size modulo 2^32
//
// FLG (FLaGs)
// bit 0 FTEXT - indicates file is ASCII text (can be safely ignored)
// bit 1 FHCRC - there is a CRC16 for the header immediately following the header
// bit 2 FEXTRA - extra fields are present
// bit 3 FNAME - the zero-terminated filename is present. encoding; ISO-8859-1.
// bit 4 FCOMMENT - a zero-terminated file comment is present. encoding: ISO-8859-1
// bit 5 reserved
// bit 6 reserved
// bit 7 reserved
//
// On consumption:
// Extra field is a bunch of nonsense and can be safely ignored.
// Header CRC and OS, likewise.
//
// on generation:
// all optional fields get 0, except for the OS, which gets 255.
//
/// <summary>
/// The comment on the GZIP stream.
/// </summary>
///
/// <remarks>
/// <para>
/// The GZIP format allows for each file to optionally have an associated
/// comment stored with the file. The comment is encoded with the ISO-8859-1
/// code page. To include a comment in a GZIP stream you create, set this
/// property before calling <c>Write()</c> for the first time on the
/// <c>GZipStream</c>.
/// </para>
///
/// <para>
/// When using <c>GZipStream</c> to decompress, you can retrieve this property
/// after the first call to <c>Read()</c>. If no comment has been set in the
/// GZIP bytestream, the Comment property will return <c>null</c>
/// (<c>Nothing</c> in VB).
/// </para>
/// </remarks>
public String Comment
{
get
{
return _Comment;
}
set
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
_Comment = value;
}
}
/// <summary>
/// The FileName for the GZIP stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// The GZIP format optionally allows each file to have an associated
/// filename. When compressing data (through <c>Write()</c>), set this
/// FileName before calling <c>Write()</c> the first time on the <c>GZipStream</c>.
/// The actual filename is encoded into the GZIP bytestream with the
/// ISO-8859-1 code page, according to RFC 1952. It is the application's
/// responsibility to insure that the FileName can be encoded and decoded
/// correctly with this code page.
/// </para>
///
/// <para>
/// When decompressing (through <c>Read()</c>), you can retrieve this value
/// any time after the first <c>Read()</c>. In the case where there was no filename
/// encoded into the GZIP bytestream, the property will return <c>null</c> (<c>Nothing</c>
/// in VB).
/// </para>
/// </remarks>
public String FileName
{
get { return _FileName; }
set
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
_FileName = value;
if (_FileName == null) return;
if (_FileName.IndexOf("/") != -1)
{
_FileName = _FileName.Replace("/", "\\");
}
if (_FileName.EndsWith("\\"))
throw new Exception("Illegal filename");
if (_FileName.IndexOf("\\") != -1)
{
// trim any leading path
_FileName = Path2.GetFileName(_FileName);
}
}
}
/// <summary>
/// The last modified time for the GZIP stream.
/// </summary>
///
/// <remarks>
/// GZIP allows the storage of a last modified time with each GZIP entry.
/// When compressing data, you can set this before the first call to
/// <c>Write()</c>. When decompressing, you can retrieve this value any time
/// after the first call to <c>Read()</c>.
/// </remarks>
public DateTime? LastModified;
/// <summary>
/// The CRC on the GZIP stream.
/// </summary>
/// <remarks>
/// This is used for internal error checking. You probably don't need to look at this property.
/// </remarks>
public int Crc32 { get { return _Crc32; } }
private int _headerByteCount;
internal ZlibBaseStream _baseStream;
bool _disposed;
bool _firstReadDone;
string _FileName;
string _Comment;
int _Crc32;
/// <summary>
/// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c>.
/// </summary>
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Compress</c>, the <c>GZipStream</c> will use the
/// default compression level.
/// </para>
///
/// <para>
/// As noted in the class documentation, the <c>CompressionMode</c> (Compress
/// or Decompress) also establishes the "direction" of the stream. A
/// <c>GZipStream</c> with <c>CompressionMode.Compress</c> works only through
/// <c>Write()</c>. A <c>GZipStream</c> with
/// <c>CompressionMode.Decompress</c> works only through <c>Read()</c>.
/// </para>
///
/// </remarks>
///
/// <example>
/// This example shows how to use a GZipStream to compress data.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(outputFile))
/// {
/// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Dim outputFile As String = (fileToCompress & ".compressed")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(outputFile)
/// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
///
/// <example>
/// This example shows how to use a GZipStream to uncompress a file.
/// <code>
/// private void GunZipFile(string filename)
/// {
/// if (!filename.EndsWith(".gz))
/// throw new ArgumentException("filename");
/// var DecompressedFile = filename.Substring(0,filename.Length-3);
/// byte[] working = new byte[WORKING_BUFFER_SIZE];
/// int n= 1;
/// using (System.IO.Stream input = System.IO.File.OpenRead(filename))
/// {
/// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
/// {
/// using (var output = System.IO.File.Create(DecompressedFile))
/// {
/// while (n !=0)
/// {
/// n= decompressor.Read(working, 0, working.Length);
/// if (n > 0)
/// {
/// output.Write(working, 0, n);
/// }
/// }
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Private Sub GunZipFile(ByVal filename as String)
/// If Not (filename.EndsWith(".gz)) Then
/// Throw New ArgumentException("filename")
/// End If
/// Dim DecompressedFile as String = filename.Substring(0,filename.Length-3)
/// Dim working(WORKING_BUFFER_SIZE) as Byte
/// Dim n As Integer = 1
/// Using input As Stream = File.OpenRead(filename)
/// Using decompressor As Stream = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, True)
/// Using output As Stream = File.Create(UncompressedFile)
/// Do
/// n= decompressor.Read(working, 0, working.Length)
/// If n > 0 Then
/// output.Write(working, 0, n)
/// End IF
/// Loop While (n > 0)
/// End Using
/// End Using
/// End Using
/// End Sub
/// </code>
/// </example>
///
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param>
public GZipStream(Stream stream, CompressionMode mode)
: this(stream, mode, CompressionLevel.Default, false)
{
}
/// <summary>
/// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c> and
/// the specified <c>CompressionLevel</c>.
/// </summary>
/// <remarks>
///
/// <para>
/// The <c>CompressionMode</c> (Compress or Decompress) also establishes the
/// "direction" of the stream. A <c>GZipStream</c> with
/// <c>CompressionMode.Compress</c> works only through <c>Write()</c>. A
/// <c>GZipStream</c> with <c>CompressionMode.Decompress</c> works only
/// through <c>Read()</c>.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example shows how to use a <c>GZipStream</c> to compress a file into a .gz file.
///
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".gz"))
/// {
/// using (Stream compressor = new GZipStream(raw,
/// CompressionMode.Compress,
/// CompressionLevel.BestCompression))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".gz")
/// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream to be read or written while deflating or inflating.</param>
/// <param name="mode">Indicates whether the <c>GZipStream</c> will compress or decompress.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level)
: this(stream, mode, level, false)
{
}
/// <summary>
/// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c>, and
/// explicitly specify whether the stream should be left open after Deflation
/// or Inflation.
/// </summary>
///
/// <remarks>
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// memory stream that will be re-read after compressed data has been written
/// to it. Specify true for the <paramref name="leaveOpen"/> parameter to leave
/// the stream open.
/// </para>
///
/// <para>
/// The <see cref="CompressionMode"/> (Compress or Decompress) also
/// establishes the "direction" of the stream. A <c>GZipStream</c> with
/// <c>CompressionMode.Compress</c> works only through <c>Write()</c>. A <c>GZipStream</c>
/// with <c>CompressionMode.Decompress</c> works only through <c>Read()</c>.
/// </para>
///
/// <para>
/// The <c>GZipStream</c> will use the default compression level. If you want
/// to specify the compression level, see <see cref="GZipStream(Stream,
/// CompressionMode, CompressionLevel, bool)"/>.
/// </para>
///
/// <para>
/// See the other overloads of this constructor for example code.
/// </para>
///
/// </remarks>
///
/// <param name="stream">
/// The stream which will be read or written. This is called the "captive"
/// stream in other places in this documentation.
/// </param>
///
/// <param name="mode">Indicates whether the GZipStream will compress or decompress.
/// </param>
///
/// <param name="leaveOpen">
/// true if the application would like the base stream to remain open after
/// inflation/deflation.
/// </param>
public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen)
: this(stream, mode, CompressionLevel.Default, leaveOpen)
{
}
/// <summary>
/// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c> and the
/// specified <c>CompressionLevel</c>, and explicitly specify whether the
/// stream should be left open after Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// memory stream that will be re-read after compressed data has been written
/// to it. Specify true for the <paramref name="leaveOpen"/> parameter to
/// leave the stream open.
/// </para>
///
/// <para>
/// As noted in the class documentation, the <c>CompressionMode</c> (Compress
/// or Decompress) also establishes the "direction" of the stream. A
/// <c>GZipStream</c> with <c>CompressionMode.Compress</c> works only through
/// <c>Write()</c>. A <c>GZipStream</c> with <c>CompressionMode.Decompress</c> works only
/// through <c>Read()</c>.
/// </para>
///
/// </remarks>
///
/// <example>
/// This example shows how to use a <c>GZipStream</c> to compress data.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(outputFile))
/// {
/// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Dim outputFile As String = (fileToCompress & ".compressed")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(outputFile)
/// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, True)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param>
/// <param name="leaveOpen">true if the application would like the stream to remain open after inflation/deflation.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen)
{
_baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.GZIP, leaveOpen);
}
#region Zlib properties
/// <summary>
/// This property sets the flush behavior on the stream.
/// </summary>
virtual public FlushType FlushMode
{
get { return (this._baseStream._flushMode); }
set {
if (_disposed) throw new ObjectDisposedException("GZipStream");
this._baseStream._flushMode = value;
}
}
/// <summary>
/// The size of the working buffer for the compression codec.
/// </summary>
///
/// <remarks>
/// <para>
/// The working buffer is used for all stream operations. The default size is
/// 1024 bytes. The minimum size is 128 bytes. You may get better performance
/// with a larger buffer. Then again, you might not. You would have to test
/// it.
/// </para>
///
/// <para>
/// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the
/// stream. If you try to set it afterwards, it will throw.
/// </para>
/// </remarks>
public int BufferSize
{
get
{
return this._baseStream._bufferSize;
}
set
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
if (this._baseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < ZlibConstants.WorkingBufferSizeMin)
throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin));
this._baseStream._bufferSize = value;
}
}
/// <summary> Returns the total number of bytes input so far.</summary>
virtual public long TotalIn
{
get
{
return this._baseStream._z.TotalBytesIn;
}
}
/// <summary> Returns the total number of bytes output so far.</summary>
virtual public long TotalOut
{
get
{
return this._baseStream._z.TotalBytesOut;
}
}
#endregion
#region Stream methods
/// <summary>
/// Dispose the stream.
/// </summary>
/// <remarks>
/// <para>
/// This may or may not result in a <c>Close()</c> call on the captive
/// stream. See the constructors that have a <c>leaveOpen</c> parameter
/// for more information.
/// </para>
/// <para>
/// This method may be invoked in two distinct scenarios. If disposing
/// == true, the method has been called directly or indirectly by a
/// user's code, for example via the public Dispose() method. In this
/// case, both managed and unmanaged resources can be referenced and
/// disposed. If disposing == false, the method has been called by the
/// runtime from inside the object finalizer and this method should not
/// reference other objects; in that case only unmanaged resources must
/// be referenced or disposed.
/// </para>
/// </remarks>
/// <param name="disposing">
/// indicates whether the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing && (this._baseStream != null))
{
this._baseStream.Close();
this._Crc32 = _baseStream.Crc32;
}
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
return _baseStream._stream.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
return _baseStream._stream.CanWrite;
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
_baseStream.Flush();
}
/// <summary>
/// Reading this property always throws a <see cref="NotImplementedException"/>.
/// </summary>
public override long Length
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotImplementedException"/>. Reading will return the total bytes
/// written out, if used in writing, or the total bytes read in, if used in
/// reading. The count may refer to compressed bytes or uncompressed bytes,
/// depending on how you've used the stream.
/// </remarks>
public override long Position
{
get
{
if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Writer)
return this._baseStream._z.TotalBytesOut + _headerByteCount;
if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Reader)
return this._baseStream._z.TotalBytesIn + this._baseStream._gzipHeaderByteCount;
return 0;
}
set { throw new NotImplementedException(); }
}
/// <summary>
/// Read and decompress data from the source stream.
/// </summary>
///
/// <remarks>
/// With a <c>GZipStream</c>, decompression is done through reading.
/// </remarks>
///
/// <example>
/// <code>
/// byte[] working = new byte[WORKING_BUFFER_SIZE];
/// using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile))
/// {
/// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
/// {
/// using (var output = System.IO.File.Create(_DecompressedFile))
/// {
/// int n;
/// while ((n= decompressor.Read(working, 0, working.Length)) !=0)
/// {
/// output.Write(working, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
/// <param name="buffer">The buffer into which the decompressed data should be placed.</param>
/// <param name="offset">the offset within that data array to put the first byte read.</param>
/// <param name="count">the number of bytes to read.</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
int n = _baseStream.Read(buffer, offset, count);
// Console.WriteLine("GZipStream::Read(buffer, off({0}), c({1}) = {2}", offset, count, n);
// Console.WriteLine( Util.FormatByteArray(buffer, offset, n) );
if (!_firstReadDone)
{
_firstReadDone = true;
FileName = _baseStream._GzipFileName;
Comment = _baseStream._GzipComment;
}
return n;
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">irrelevant; it will always throw!</param>
/// <param name="origin">irrelevant; it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="value">irrelevant; this method will always throw!</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
/// <summary>
/// Write data to the stream.
/// </summary>
///
/// <remarks>
/// <para>
/// If you wish to use the <c>GZipStream</c> to compress data while writing,
/// you can create a <c>GZipStream</c> with <c>CompressionMode.Compress</c>, and a
/// writable output stream. Then call <c>Write()</c> on that <c>GZipStream</c>,
/// providing uncompressed data as input. The data sent to the output stream
/// will be the compressed form of the data written.
/// </para>
///
/// <para>
/// A <c>GZipStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not
/// both. Writing implies compression. Reading implies decompression.
/// </para>
///
/// </remarks>
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
if (_baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Undefined)
{
//Console.WriteLine("GZipStream: First write");
if (_baseStream._wantCompress)
{
// first write in compression, therefore, emit the GZIP header
_headerByteCount = EmitHeader();
}
else
{
throw new InvalidOperationException();
}
}
_baseStream.Write(buffer, offset, count);
}
#endregion
internal static readonly System.DateTime _unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
internal static readonly System.Text.Encoding iso8859dash1 = new Ionic.Encoding.Iso8859Dash1Encoding();
private int EmitHeader()
{
byte[] commentBytes = (Comment == null) ? null : iso8859dash1.GetBytes(Comment);
byte[] filenameBytes = (FileName == null) ? null : iso8859dash1.GetBytes(FileName);
int cbLength = (Comment == null) ? 0 : commentBytes.Length + 1;
int fnLength = (FileName == null) ? 0 : filenameBytes.Length + 1;
int bufferLength = 10 + cbLength + fnLength;
byte[] header = new byte[bufferLength];
int i = 0;
// ID
header[i++] = 0x1F;
header[i++] = 0x8B;
// compression method
header[i++] = 8;
byte flag = 0;
if (Comment != null)
flag ^= 0x10;
if (FileName != null)
flag ^= 0x8;
// flag
header[i++] = flag;
// mtime
if (!LastModified.HasValue) LastModified = DateTime.Now;
System.TimeSpan delta = LastModified.Value - _unixEpoch;
Int32 timet = (Int32)delta.TotalSeconds;
Array.Copy(BitConverter.GetBytes(timet), 0, header, i, 4);
i += 4;
// xflg
header[i++] = 0; // this field is totally useless
// OS
header[i++] = 0xFF; // 0xFF == unspecified
// extra field length - only if FEXTRA is set, which it is not.
//header[i++]= 0;
//header[i++]= 0;
// filename
if (fnLength != 0)
{
Array.Copy(filenameBytes, 0, header, i, fnLength - 1);
i += fnLength - 1;
header[i++] = 0; // terminate
}
// comment
if (cbLength != 0)
{
Array.Copy(commentBytes, 0, header, i, cbLength - 1);
i += cbLength - 1;
header[i++] = 0; // terminate
}
_baseStream._stream.Write(header, 0, header.Length);
return header.Length; // bytes written
}
/// <summary>
/// Compress a string into a byte array using GZip.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="GZipStream.UncompressString(byte[])"/>.
/// </remarks>
///
/// <seealso cref="GZipStream.UncompressString(byte[])"/>
/// <seealso cref="GZipStream.CompressBuffer(byte[])"/>
///
/// <param name="s">
/// A string to compress. The string will first be encoded
/// using UTF8, then compressed.
/// </param>
///
/// <returns>The string in compressed form</returns>
public static byte[] CompressString(String s)
{
using (var ms = new MemoryStream())
{
System.IO.Stream compressor =
new GZipStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);
ZlibBaseStream.CompressString(s, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Compress a byte array into a new byte array using GZip.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="GZipStream.UncompressBuffer(byte[])"/>.
/// </remarks>
///
/// <seealso cref="GZipStream.CompressString(string)"/>
/// <seealso cref="GZipStream.UncompressBuffer(byte[])"/>
///
/// <param name="b">
/// A buffer to compress.
/// </param>
///
/// <returns>The data in compressed form</returns>
public static byte[] CompressBuffer(byte[] b)
{
using (var ms = new MemoryStream())
{
System.IO.Stream compressor =
new GZipStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression );
ZlibBaseStream.CompressBuffer(b, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Uncompress a GZip'ed byte array into a single string.
/// </summary>
///
/// <seealso cref="GZipStream.CompressString(String)"/>
/// <seealso cref="GZipStream.UncompressBuffer(byte[])"/>
///
/// <param name="compressed">
/// A buffer containing GZIP-compressed data.
/// </param>
///
/// <returns>The uncompressed string</returns>
public static String UncompressString(byte[] compressed)
{
using (var input = new MemoryStream(compressed))
{
Stream decompressor = new GZipStream(input, CompressionMode.Decompress);
return ZlibBaseStream.UncompressString(compressed, decompressor);
}
}
/// <summary>
/// Uncompress a GZip'ed byte array into a byte array.
/// </summary>
///
/// <seealso cref="GZipStream.CompressBuffer(byte[])"/>
/// <seealso cref="GZipStream.UncompressString(byte[])"/>
///
/// <param name="compressed">
/// A buffer containing data that has been compressed with GZip.
/// </param>
///
/// <returns>The data in uncompressed form</returns>
public static byte[] UncompressBuffer(byte[] compressed)
{
using (var input = new System.IO.MemoryStream(compressed))
{
System.IO.Stream decompressor =
new GZipStream( input, CompressionMode.Decompress );
return ZlibBaseStream.UncompressBuffer(compressed, decompressor);
}
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
namespace Ctrip.Log4.Core
{
/// <summary>
/// A strongly-typed collection of <see cref="Level"/> objects.
/// </summary>
/// <author>Nicko Cadell</author>
public class LevelCollection : ICollection, IList, IEnumerable, ICloneable
{
#region Interfaces
/// <summary>
/// Supports type-safe iteration over a <see cref="LevelCollection"/>.
/// </summary>
public interface ILevelCollectionEnumerator
{
/// <summary>
/// Gets the current element in the collection.
/// </summary>
Level Current { get; }
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
bool MoveNext();
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
void Reset();
}
#endregion
private const int DEFAULT_CAPACITY = 16;
#region Implementation (data)
private Level[] m_array;
private int m_count = 0;
private int m_version = 0;
#endregion
#region Static Wrappers
/// <summary>
/// Creates a read-only wrapper for a <c>LevelCollection</c> instance.
/// </summary>
/// <param name="list">list to create a readonly wrapper arround</param>
/// <returns>
/// A <c>LevelCollection</c> wrapper that is read-only.
/// </returns>
public static LevelCollection ReadOnly(LevelCollection list)
{
if(list==null) throw new ArgumentNullException("list");
return new ReadOnlyLevelCollection(list);
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that is empty and has the default initial capacity.
/// </summary>
public LevelCollection()
{
m_array = new Level[DEFAULT_CAPACITY];
}
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that has the specified initial capacity.
/// </summary>
/// <param name="capacity">
/// The number of elements that the new <c>LevelCollection</c> is initially capable of storing.
/// </param>
public LevelCollection(int capacity)
{
m_array = new Level[capacity];
}
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that contains elements copied from the specified <c>LevelCollection</c>.
/// </summary>
/// <param name="c">The <c>LevelCollection</c> whose elements are copied to the new collection.</param>
public LevelCollection(LevelCollection c)
{
m_array = new Level[c.Count];
AddRange(c);
}
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that contains elements copied from the specified <see cref="Level"/> array.
/// </summary>
/// <param name="a">The <see cref="Level"/> array whose elements are copied to the new list.</param>
public LevelCollection(Level[] a)
{
m_array = new Level[a.Length];
AddRange(a);
}
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that contains elements copied from the specified <see cref="Level"/> collection.
/// </summary>
/// <param name="col">The <see cref="Level"/> collection whose elements are copied to the new list.</param>
public LevelCollection(ICollection col)
{
m_array = new Level[col.Count];
AddRange(col);
}
/// <summary>
/// Type visible only to our subclasses
/// Used to access protected constructor
/// </summary>
protected internal enum Tag
{
/// <summary>
/// A value
/// </summary>
Default
}
/// <summary>
/// Allow subclasses to avoid our default constructors
/// </summary>
/// <param name="tag"></param>
protected internal LevelCollection(Tag tag)
{
m_array = null;
}
#endregion
#region Operations (type-safe ICollection)
/// <summary>
/// Gets the number of elements actually contained in the <c>LevelCollection</c>.
/// </summary>
public virtual int Count
{
get { return m_count; }
}
/// <summary>
/// Copies the entire <c>LevelCollection</c> to a one-dimensional
/// <see cref="Level"/> array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Level"/> array to copy to.</param>
public virtual void CopyTo(Level[] array)
{
this.CopyTo(array, 0);
}
/// <summary>
/// Copies the entire <c>LevelCollection</c> to a one-dimensional
/// <see cref="Level"/> array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Level"/> array to copy to.</param>
/// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param>
public virtual void CopyTo(Level[] array, int start)
{
if (m_count > array.GetUpperBound(0) + 1 - start)
{
throw new System.ArgumentException("Destination array was not long enough.");
}
Array.Copy(m_array, 0, array, start, m_count);
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <value>true if access to the ICollection is synchronized (thread-safe); otherwise, false.</value>
public virtual bool IsSynchronized
{
get { return m_array.IsSynchronized; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
public virtual object SyncRoot
{
get { return m_array.SyncRoot; }
}
#endregion
#region Operations (type-safe IList)
/// <summary>
/// Gets or sets the <see cref="Level"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
public virtual Level this[int index]
{
get
{
ValidateIndex(index); // throws
return m_array[index];
}
set
{
ValidateIndex(index); // throws
++m_version;
m_array[index] = value;
}
}
/// <summary>
/// Adds a <see cref="Level"/> to the end of the <c>LevelCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Level"/> to be added to the end of the <c>LevelCollection</c>.</param>
/// <returns>The index at which the value has been added.</returns>
public virtual int Add(Level item)
{
if (m_count == m_array.Length)
{
EnsureCapacity(m_count + 1);
}
m_array[m_count] = item;
m_version++;
return m_count++;
}
/// <summary>
/// Removes all elements from the <c>LevelCollection</c>.
/// </summary>
public virtual void Clear()
{
++m_version;
m_array = new Level[DEFAULT_CAPACITY];
m_count = 0;
}
/// <summary>
/// Creates a shallow copy of the <see cref="LevelCollection"/>.
/// </summary>
/// <returns>A new <see cref="LevelCollection"/> with a shallow copy of the collection data.</returns>
public virtual object Clone()
{
LevelCollection newCol = new LevelCollection(m_count);
Array.Copy(m_array, 0, newCol.m_array, 0, m_count);
newCol.m_count = m_count;
newCol.m_version = m_version;
return newCol;
}
/// <summary>
/// Determines whether a given <see cref="Level"/> is in the <c>LevelCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Level"/> to check for.</param>
/// <returns><c>true</c> if <paramref name="item"/> is found in the <c>LevelCollection</c>; otherwise, <c>false</c>.</returns>
public virtual bool Contains(Level item)
{
for (int i=0; i != m_count; ++i)
{
if (m_array[i].Equals(item))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns the zero-based index of the first occurrence of a <see cref="Level"/>
/// in the <c>LevelCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Level"/> to locate in the <c>LevelCollection</c>.</param>
/// <returns>
/// The zero-based index of the first occurrence of <paramref name="item"/>
/// in the entire <c>LevelCollection</c>, if found; otherwise, -1.
/// </returns>
public virtual int IndexOf(Level item)
{
for (int i=0; i != m_count; ++i)
{
if (m_array[i].Equals(item))
{
return i;
}
}
return -1;
}
/// <summary>
/// Inserts an element into the <c>LevelCollection</c> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The <see cref="Level"/> to insert.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
public virtual void Insert(int index, Level item)
{
ValidateIndex(index, true); // throws
if (m_count == m_array.Length)
{
EnsureCapacity(m_count + 1);
}
if (index < m_count)
{
Array.Copy(m_array, index, m_array, index + 1, m_count - index);
}
m_array[index] = item;
m_count++;
m_version++;
}
/// <summary>
/// Removes the first occurrence of a specific <see cref="Level"/> from the <c>LevelCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Level"/> to remove from the <c>LevelCollection</c>.</param>
/// <exception cref="ArgumentException">
/// The specified <see cref="Level"/> was not found in the <c>LevelCollection</c>.
/// </exception>
public virtual void Remove(Level item)
{
int i = IndexOf(item);
if (i < 0)
{
throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection.");
}
++m_version;
RemoveAt(i);
}
/// <summary>
/// Removes the element at the specified index of the <c>LevelCollection</c>.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
public virtual void RemoveAt(int index)
{
ValidateIndex(index); // throws
m_count--;
if (index < m_count)
{
Array.Copy(m_array, index + 1, m_array, index, m_count - index);
}
// We can't set the deleted entry equal to null, because it might be a value type.
// Instead, we'll create an empty single-element array of the right type and copy it
// over the entry we want to erase.
Level[] temp = new Level[1];
Array.Copy(temp, 0, m_array, m_count, 1);
m_version++;
}
/// <summary>
/// Gets a value indicating whether the collection has a fixed size.
/// </summary>
/// <value>true if the collection has a fixed size; otherwise, false. The default is false</value>
public virtual bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the IList is read-only.
/// </summary>
/// <value>true if the collection is read-only; otherwise, false. The default is false</value>
public virtual bool IsReadOnly
{
get { return false; }
}
#endregion
#region Operations (type-safe IEnumerable)
/// <summary>
/// Returns an enumerator that can iterate through the <c>LevelCollection</c>.
/// </summary>
/// <returns>An <see cref="Enumerator"/> for the entire <c>LevelCollection</c>.</returns>
public virtual ILevelCollectionEnumerator GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region Public helpers (just to mimic some nice features of ArrayList)
/// <summary>
/// Gets or sets the number of elements the <c>LevelCollection</c> can contain.
/// </summary>
public virtual int Capacity
{
get
{
return m_array.Length;
}
set
{
if (value < m_count)
{
value = m_count;
}
if (value != m_array.Length)
{
if (value > 0)
{
Level[] temp = new Level[value];
Array.Copy(m_array, 0, temp, 0, m_count);
m_array = temp;
}
else
{
m_array = new Level[DEFAULT_CAPACITY];
}
}
}
}
/// <summary>
/// Adds the elements of another <c>LevelCollection</c> to the current <c>LevelCollection</c>.
/// </summary>
/// <param name="x">The <c>LevelCollection</c> whose elements should be added to the end of the current <c>LevelCollection</c>.</param>
/// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns>
public virtual int AddRange(LevelCollection x)
{
if (m_count + x.Count >= m_array.Length)
{
EnsureCapacity(m_count + x.Count);
}
Array.Copy(x.m_array, 0, m_array, m_count, x.Count);
m_count += x.Count;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="Level"/> array to the current <c>LevelCollection</c>.
/// </summary>
/// <param name="x">The <see cref="Level"/> array whose elements should be added to the end of the <c>LevelCollection</c>.</param>
/// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns>
public virtual int AddRange(Level[] x)
{
if (m_count + x.Length >= m_array.Length)
{
EnsureCapacity(m_count + x.Length);
}
Array.Copy(x, 0, m_array, m_count, x.Length);
m_count += x.Length;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="Level"/> collection to the current <c>LevelCollection</c>.
/// </summary>
/// <param name="col">The <see cref="Level"/> collection whose elements should be added to the end of the <c>LevelCollection</c>.</param>
/// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns>
public virtual int AddRange(ICollection col)
{
if (m_count + col.Count >= m_array.Length)
{
EnsureCapacity(m_count + col.Count);
}
foreach(object item in col)
{
Add((Level)item);
}
return m_count;
}
/// <summary>
/// Sets the capacity to the actual number of elements.
/// </summary>
public virtual void TrimToSize()
{
this.Capacity = m_count;
}
#endregion
#region Implementation (helpers)
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="i"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="i"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i)
{
ValidateIndex(i, false);
}
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="i"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="i"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i, bool allowEqualEnd)
{
int max = (allowEqualEnd) ? (m_count) : (m_count-1);
if (i < 0 || i > max)
{
throw Ctrip.Log4.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values.");
}
}
private void EnsureCapacity(int min)
{
int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2);
if (newCapacity < min)
{
newCapacity = min;
}
this.Capacity = newCapacity;
}
#endregion
#region Implementation (ICollection)
void ICollection.CopyTo(Array array, int start)
{
Array.Copy(m_array, 0, array, start, m_count);
}
#endregion
#region Implementation (IList)
object IList.this[int i]
{
get { return (object)this[i]; }
set { this[i] = (Level)value; }
}
int IList.Add(object x)
{
return this.Add((Level)x);
}
bool IList.Contains(object x)
{
return this.Contains((Level)x);
}
int IList.IndexOf(object x)
{
return this.IndexOf((Level)x);
}
void IList.Insert(int pos, object x)
{
this.Insert(pos, (Level)x);
}
void IList.Remove(object x)
{
this.Remove((Level)x);
}
void IList.RemoveAt(int pos)
{
this.RemoveAt(pos);
}
#endregion
#region Implementation (IEnumerable)
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)(this.GetEnumerator());
}
#endregion
#region Nested enumerator class
/// <summary>
/// Supports simple iteration over a <see cref="LevelCollection"/>.
/// </summary>
private sealed class Enumerator : IEnumerator, ILevelCollectionEnumerator
{
#region Implementation (data)
private readonly LevelCollection m_collection;
private int m_index;
private int m_version;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <c>Enumerator</c> class.
/// </summary>
/// <param name="tc"></param>
internal Enumerator(LevelCollection tc)
{
m_collection = tc;
m_index = -1;
m_version = tc.m_version;
}
#endregion
#region Operations (type-safe IEnumerator)
/// <summary>
/// Gets the current element in the collection.
/// </summary>
public Level Current
{
get { return m_collection[m_index]; }
}
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public bool MoveNext()
{
if (m_version != m_collection.m_version)
{
throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute.");
}
++m_index;
return (m_index < m_collection.Count);
}
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
public void Reset()
{
m_index = -1;
}
#endregion
#region Implementation (IEnumerator)
object IEnumerator.Current
{
get { return this.Current; }
}
#endregion
}
#endregion
#region Nested Read Only Wrapper class
private sealed class ReadOnlyLevelCollection : LevelCollection
{
#region Implementation (data)
private readonly LevelCollection m_collection;
#endregion
#region Construction
internal ReadOnlyLevelCollection(LevelCollection list) : base(Tag.Default)
{
m_collection = list;
}
#endregion
#region Type-safe ICollection
public override void CopyTo(Level[] array)
{
m_collection.CopyTo(array);
}
public override void CopyTo(Level[] array, int start)
{
m_collection.CopyTo(array,start);
}
public override int Count
{
get { return m_collection.Count; }
}
public override bool IsSynchronized
{
get { return m_collection.IsSynchronized; }
}
public override object SyncRoot
{
get { return this.m_collection.SyncRoot; }
}
#endregion
#region Type-safe IList
public override Level this[int i]
{
get { return m_collection[i]; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int Add(Level x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Clear()
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool Contains(Level x)
{
return m_collection.Contains(x);
}
public override int IndexOf(Level x)
{
return m_collection.IndexOf(x);
}
public override void Insert(int pos, Level x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Remove(Level x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void RemoveAt(int pos)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool IsFixedSize
{
get { return true; }
}
public override bool IsReadOnly
{
get { return true; }
}
#endregion
#region Type-safe IEnumerable
public override ILevelCollectionEnumerator GetEnumerator()
{
return m_collection.GetEnumerator();
}
#endregion
#region Public Helpers
// (just to mimic some nice features of ArrayList)
public override int Capacity
{
get { return m_collection.Capacity; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int AddRange(LevelCollection x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override int AddRange(Level[] x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
#endregion
}
#endregion
}
}
| |
// AttachmentModify
// ----------------------------------------------------------
// Example for intercepting email messages in an Exchange 2010 transport queue
//
// The example intercepts messages sent from a configurable email address(es)
// and checks the mail message for attachments have filename in to format
//
// WORKBOOK_{GUID}
//
// Changing the filename of the attachments makes it easier for the information worker
// to identify the reports in the emails and in the file system as well.
// Copyright (c) Thomas Stensitzki
// ----------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
// the lovely Exchange
using Microsoft.Exchange.Data.Transport;
using Microsoft.Exchange.Data.Transport.Smtp;
using Microsoft.Exchange.Data.Transport.Email;
using Microsoft.Exchange.Data.Transport.Routing;
namespace SFTools.Messaging.AttachmentModify
{
#region Message Modifier Factory
/// <summary>
/// Message Modifier Factory
/// </summary>
public class MessageModifierFactory : RoutingAgentFactory
{
/// <summary>
/// Instance of our transport agent configuration
/// This is for a later implementation
/// </summary>
private MessageModifierConfig messageModifierConfig = new MessageModifierConfig();
/// <summary>
/// Returns an instance of the agent
/// </summary>
/// <param name="server">The SMTP Server</param>
/// <returns>The Transport Agent</returns>
public override RoutingAgent CreateAgent(SmtpServer server)
{
return new MessageModifier(messageModifierConfig);
}
}
#endregion
#region Message Modifier Routing Agent
/// <summary>
/// The Message Modifier Routing Agent for modifying an email message
/// </summary>
public class MessageModifier : RoutingAgent
{
// The agent uses the fileLock object to synchronize access to the log file
private object fileLock = new object();
/// <summary>
/// The current MailItem the transport agent is handling
/// </summary>
private MailItem mailItem;
/// <summary>
/// This context to allow Exchange to continue processing a message
/// </summary>
private AgentAsyncContext agentAsyncContext;
/// <summary>
/// Transport agent configuration
/// </summary>
private MessageModifierConfig messageModifierConfig;
/// <summary>
/// Constructor for the MessageModifier class
/// </summary>
/// <param name="messageModifierConfig">Transport Agent configuration</param>
public MessageModifier(MessageModifierConfig messageModifierConfig)
{
// Set configuration
this.messageModifierConfig = messageModifierConfig;
// Register an OnRoutedMessage event handler
this.OnRoutedMessage += OnRoutedMessageHandler;
}
/// <summary>
/// Event handler for OnRoutedMessage event
/// </summary>
/// <param name="source">Routed Message Event Source</param>
/// <param name="args">Queued Message Event Arguments</param>
void OnRoutedMessageHandler(RoutedMessageEventSource source, QueuedMessageEventArgs args)
{
lock (fileLock) {
try {
this.mailItem = args.MailItem;
this.agentAsyncContext = this.GetAgentAsyncContext();
// Get the folder for accessing the config file
string dllDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// Fetch the from address from the current mail item
RoutingAddress fromAddress = this.mailItem.FromAddress;
Boolean boWorkbookFound = false; // We just want to modifiy subjects when we modified an attachement first
#region External Receive Connector Example
// CHeck first, if the mail item does have a ReceiveConnectorName property first to prevent ugly things to happen
if (mailItem.Properties.ContainsKey("Microsoft.Exchange.Transport.ReceiveConnectorName")) {
// This is just an example, if you want to do something with a mail item which has been received via a named external receive connector
if (mailItem.Properties["Microsoft.Exchange.Transport.ReceiveConnectorName"].ToString().ToLower() == "externalreceiveconnectorname")
{
// do something fancy with the email
}
}
#endregion
RoutingAddress catchAddress;
// Check, if we have any email addresses configured to look for
if (this.messageModifierConfig.AddressMap.Count > 0) {
// Now lets check, if the sender address can be found in the dictionary
if (this.messageModifierConfig.AddressMap.TryGetValue(fromAddress.ToString().ToLower(), out catchAddress)) {
// Sender address found, now check if we have attachments to handle
if (this.mailItem.Message.Attachments.Count != 0) {
// Get all attachments
AttachmentCollection attachments = this.mailItem.Message.Attachments;
// Modify each attachment
for (int count = 0; count < this.mailItem.Message.Attachments.Count; count++) {
// Get attachment
Attachment attachment = this.mailItem.Message.Attachments[count];
// We will only transform attachments which start with "WORKBOOK_"
if (attachment.FileName.StartsWith("WORKBOOK_")) {
// Create a new filename for the attachment
// [MODIFIED SUBJECT]-[NUMBER].[FILEEXTENSION]
String newFileName = MakeValidFileName(string.Format("{0}-{1}{2}", ModifiySubject(this.mailItem.Message.Subject.Trim()), count + 1, Path.GetExtension(attachment.FileName)));
// Change the filename of the attachment
this.mailItem.Message.Attachments[count].FileName = newFileName;
// Yes we have changed the attachment. Therefore we want to change the subject as well.
boWorkbookFound = true;
}
}
// Have changed any attachments?
if (boWorkbookFound) {
// Then let's change the subject as well
this.mailItem.Message.Subject = ModifiySubject(this.mailItem.Message.Subject);
}
}
}
}
}
catch (System.IO.IOException ex) {
// oops
Debug.WriteLine(ex.ToString());
this.agentAsyncContext.Complete();
}
finally {
// We are done
this.agentAsyncContext.Complete();
}
}
// Return to pipeline
return;
}
/// <summary>
/// Build a new subject, if the first 10 chars of the original subject are a valid date.
/// We muste transform the de-DE format dd.MM.yyyy to yyyyMMdd for better sortability in the email client.
/// </summary>
/// <param name="MessageSubject">The original subject string</param>
/// <returns>The modified subject string, if modification was possible</returns>
private static string ModifiySubject(string MessageSubject)
{
string newSubject = String.Empty;
if (MessageSubject.Length >= 10) {
string dateCheck = MessageSubject.Substring(0, 10);
DateTime dt = new DateTime();
try {
// Check if we can parse the datetime
if (DateTime.TryParse(dateCheck, out dt)) {
// lets fetch the subject starting at the 10th character
string subjectRight = MessageSubject.Substring(10).Trim();
// build a new subject
newSubject = string.Format("{0:yyyyMMdd} {1}", dt, subjectRight);
}
}
finally {
// do nothing
}
}
return newSubject;
}
/// <summary>
/// Replace invalid filename chars with an underscore
/// </summary>
/// <param name="name">The filename to be checked</param>
/// <returns>The sanitized filename</returns>
private static string MakeValidFileName(string name)
{
string invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
string invalidRegExStr = string.Format(@"[{0}]+", invalidChars);
return Regex.Replace(name, invalidRegExStr, "_");
}
}
#endregion
#region Message Modifier Configuration
/// <summary>
/// Message Modifier Configuration class
/// </summary>
public class MessageModifierConfig
{
/// <summary>
/// The name of the configuration file.
/// </summary>
private static readonly string configFileName = "SFTools.MessageModify.Config.xml";
/// <summary>
/// Point out the directory with the configuration file (= assembly location)
/// </summary>
private string configDirectory;
/// <summary>
/// The filesystem watcher to monitor configuration file updates.
/// </summary>
private FileSystemWatcher configFileWatcher;
/// <summary>
/// The from address
/// </summary>
private Dictionary<string, RoutingAddress> addressMap;
/// <summary>
/// Whether reloading is ongoing
/// </summary>
private int reLoading = 0;
/// <summary>
/// The mapping between domain to catchall address.
/// </summary>
public Dictionary<string, RoutingAddress> AddressMap
{
get { return this.addressMap; }
}
/// <summary>
/// Constructor
/// </summary>
public MessageModifierConfig()
{
// Setup a file system watcher to monitor the configuration file
this.configDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
this.configFileWatcher = new FileSystemWatcher(this.configDirectory);
this.configFileWatcher.NotifyFilter = NotifyFilters.LastWrite;
this.configFileWatcher.Filter = configFileName;
this.configFileWatcher.Changed += new FileSystemEventHandler(this.OnChanged);
// Create an initially empty map
this.addressMap = new Dictionary<string, RoutingAddress>();
// Load the configuration
this.Load();
// Now start monitoring
this.configFileWatcher.EnableRaisingEvents = true;
}
/// <summary>
/// Configuration changed handler.
/// </summary>
/// <param name="source">Event source.</param>
/// <param name="e">Event arguments.</param>
private void OnChanged(object source, FileSystemEventArgs e)
{
// Ignore if load ongoing
if (Interlocked.CompareExchange(ref this.reLoading, 1, 0) != 0) {
Trace.WriteLine("load ongoing: ignore");
return;
}
// (Re) Load the configuration
this.Load();
// Reset the reload indicator
this.reLoading = 0;
}
/// <summary>
/// Load the configuration file. If any errors occur, does nothing.
/// </summary>
private void Load()
{
// Load the configuration
XmlDocument doc = new XmlDocument();
bool docLoaded = false;
string fileName = Path.Combine(this.configDirectory, MessageModifierConfig.configFileName);
try {
doc.Load(fileName);
docLoaded = true;
}
catch (FileNotFoundException) {
Trace.WriteLine("Configuration file not found: {0}", fileName);
}
catch (XmlException e) {
Trace.WriteLine("XML error: {0}", e.Message);
}
catch (IOException e) {
Trace.WriteLine("IO error: {0}", e.Message);
}
// If a failure occured, ignore and simply return
if (!docLoaded || doc.FirstChild == null) {
Trace.WriteLine("Configuration error: either no file or an XML error");
return;
}
// Create a dictionary to hold the mappings
Dictionary<string, RoutingAddress> map = new Dictionary<string, RoutingAddress>(100);
// Track whether there are invalid entries
bool invalidEntries = false;
// Validate all entries and load into a dictionary
foreach (XmlNode node in doc.FirstChild.ChildNodes) {
if (string.Compare(node.Name, "domain", true, CultureInfo.InvariantCulture) != 0) {
continue;
}
XmlAttribute domain = node.Attributes["name"];
XmlAttribute address = node.Attributes["address"];
// Validate the data
if (domain == null || address == null) {
invalidEntries = true;
Trace.WriteLine("Reject configuration due to an incomplete entry. (Either or both domain and address missing.)");
break;
}
if (!RoutingAddress.IsValidAddress(address.Value)) {
invalidEntries = true;
Trace.WriteLine(String.Format("Reject configuration due to an invalid address ({0}).", address));
break;
}
// Add the new entry
string lowerDomain = domain.Value.ToLower();
map[lowerDomain] = new RoutingAddress(address.Value);
Trace.WriteLine(String.Format("Added entry ({0} -> {1})", lowerDomain, address.Value));
}
// If there are no invalid entries, swap in the map
if (!invalidEntries) {
Interlocked.Exchange<Dictionary<string, RoutingAddress>>(ref this.addressMap, map);
Trace.WriteLine("Accepted configuration");
}
}
}
#endregion
}
| |
using System;
using AngleSharp.Dom;
using NUnit.Framework;
namespace AngleSharp.Core.Tests
{
/// <summary>
/// Tests from https://github.com/html5lib/html5lib-tests:
/// tree-construction/ruby.dat
/// </summary>
[TestFixture]
public class RubyElementTests
{
static IDocument Html(String code)
{
return code.ToHtmlDocument();
}
[Test]
public void RubyElementImpliedEndForRbWithRb()
{
var doc = Html(@"<html><ruby>a<rb>b<rb></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rb1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rb1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rb1).Attributes.Length);
Assert.AreEqual("rb", dochtml0body1ruby0rb1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rb1.NodeType);
var dochtml0body1ruby0rb1Text0 = dochtml0body1ruby0rb1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rb1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rb1Text0.TextContent);
var dochtml0body1ruby0rb2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rb2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rb2).Attributes.Length);
Assert.AreEqual("rb", dochtml0body1ruby0rb2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rb2.NodeType);
}
[Test]
public void RubyElementImpliedEndForRbWithRt()
{
var doc = Html(@"<html><ruby>a<rb>b<rt></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rb1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rb1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rb1).Attributes.Length);
Assert.AreEqual("rb", dochtml0body1ruby0rb1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rb1.NodeType);
var dochtml0body1ruby0rb1Text0 = dochtml0body1ruby0rb1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rb1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rb1Text0.TextContent);
var dochtml0body1ruby0rt2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rt2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rt2).Attributes.Length);
Assert.AreEqual("rt", dochtml0body1ruby0rt2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rt2.NodeType);
}
[Test]
public void RubyElementImpliedEndForRbWithRtc()
{
var doc = Html(@"<html><ruby>a<rb>b<rtc></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rb1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rb1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rb1).Attributes.Length);
Assert.AreEqual("rb", dochtml0body1ruby0rb1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rb1.NodeType);
var dochtml0body1ruby0rb1Text0 = dochtml0body1ruby0rb1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rb1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rb1Text0.TextContent);
var dochtml0body1ruby0rtc2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rtc2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc2).Attributes.Length);
Assert.AreEqual("rtc", dochtml0body1ruby0rtc2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc2.NodeType);
}
[Test]
public void RubyElementImpliedEndForRbWithRp()
{
var doc = Html(@"<html><ruby>a<rb>b<rp></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rb1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rb1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rb1).Attributes.Length);
Assert.AreEqual("rb", dochtml0body1ruby0rb1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rb1.NodeType);
var dochtml0body1ruby0rb1Text0 = dochtml0body1ruby0rb1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rb1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rb1Text0.TextContent);
var dochtml0body1ruby0rp2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rp2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rp2).Attributes.Length);
Assert.AreEqual("rp", dochtml0body1ruby0rp2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rp2.NodeType);
}
[Test]
public void RubyElementNoImpliedEndForRbWithSpan()
{
var doc = Html(@"<html><ruby>a<rb>b<span></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(2, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rb1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(2, dochtml0body1ruby0rb1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rb1).Attributes.Length);
Assert.AreEqual("rb", dochtml0body1ruby0rb1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rb1.NodeType);
var dochtml0body1ruby0rb1Text0 = dochtml0body1ruby0rb1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rb1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rb1Text0.TextContent);
var dochtml0body1ruby0rb1span1 = dochtml0body1ruby0rb1.ChildNodes[1];
Assert.AreEqual(0, dochtml0body1ruby0rb1span1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rb1span1).Attributes.Length);
Assert.AreEqual("span", dochtml0body1ruby0rb1span1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rb1span1.NodeType);
}
[Test]
public void RubyElementImpliedEndForRtWithRb()
{
var doc = Html(@"<html><ruby>a<rt>b<rb></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rt1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rt1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rt1).Attributes.Length);
Assert.AreEqual("rt", dochtml0body1ruby0rt1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rt1.NodeType);
var dochtml0body1ruby0rt1Text0 = dochtml0body1ruby0rt1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rt1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rt1Text0.TextContent);
var dochtml0body1ruby0rb2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rb2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rb2).Attributes.Length);
Assert.AreEqual("rb", dochtml0body1ruby0rb2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rb2.NodeType);
}
[Test]
public void RubyElementImpliedEndForRtWithRt()
{
var doc = Html(@"<html><ruby>a<rt>b<rt></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rt1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rt1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rt1).Attributes.Length);
Assert.AreEqual("rt", dochtml0body1ruby0rt1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rt1.NodeType);
var dochtml0body1ruby0rt1Text0 = dochtml0body1ruby0rt1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rt1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rt1Text0.TextContent);
var dochtml0body1ruby0rt2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rt2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rt2).Attributes.Length);
Assert.AreEqual("rt", dochtml0body1ruby0rt2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rt2.NodeType);
}
[Test]
public void RubyElementImpliedEndForRtWithRtc()
{
var doc = Html(@"<html><ruby>a<rt>b<rtc></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rt1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rt1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rt1).Attributes.Length);
Assert.AreEqual("rt", dochtml0body1ruby0rt1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rt1.NodeType);
var dochtml0body1ruby0rt1Text0 = dochtml0body1ruby0rt1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rt1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rt1Text0.TextContent);
var dochtml0body1ruby0rtc2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rtc2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc2).Attributes.Length);
Assert.AreEqual("rtc", dochtml0body1ruby0rtc2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc2.NodeType);
}
[Test]
public void RubyElementImpliedEndForRtWithRp()
{
var doc = Html(@"<html><ruby>a<rt>b<rp></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rt1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rt1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rt1).Attributes.Length);
Assert.AreEqual("rt", dochtml0body1ruby0rt1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rt1.NodeType);
var dochtml0body1ruby0rt1Text0 = dochtml0body1ruby0rt1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rt1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rt1Text0.TextContent);
var dochtml0body1ruby0rp2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rp2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rp2).Attributes.Length);
Assert.AreEqual("rp", dochtml0body1ruby0rp2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rp2.NodeType);
}
[Test]
public void RubyElementNoImpliedEndForRtWithSpan()
{
var doc = Html(@"<html><ruby>a<rt>b<span></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(2, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rt1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(2, dochtml0body1ruby0rt1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rt1).Attributes.Length);
Assert.AreEqual("rt", dochtml0body1ruby0rt1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rt1.NodeType);
var dochtml0body1ruby0rt1Text0 = dochtml0body1ruby0rt1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rt1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rt1Text0.TextContent);
var dochtml0body1ruby0rt1span1 = dochtml0body1ruby0rt1.ChildNodes[1];
Assert.AreEqual(0, dochtml0body1ruby0rt1span1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rt1span1).Attributes.Length);
Assert.AreEqual("span", dochtml0body1ruby0rt1span1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rt1span1.NodeType);
}
[Test]
public void RubyElementImpliedEndForRtcWithRb()
{
var doc = Html(@"<html><ruby>a<rtc>b<rb></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rtc1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rtc1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc1).Attributes.Length);
Assert.AreEqual("rtc", dochtml0body1ruby0rtc1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc1.NodeType);
var dochtml0body1ruby0rtc1Text0 = dochtml0body1ruby0rtc1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rtc1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rtc1Text0.TextContent);
var dochtml0body1ruby0rb2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rb2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rb2).Attributes.Length);
Assert.AreEqual("rb", dochtml0body1ruby0rb2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rb2.NodeType);
}
[Test]
public void RubyElementNoImpliedEndForRtcWithRt()
{
var doc = Html(@"<html><ruby>a<rtc>b<rt>c<rt>d</ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(2, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rtc1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(3, dochtml0body1ruby0rtc1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc1).Attributes.Length);
Assert.AreEqual("rtc", dochtml0body1ruby0rtc1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc1.NodeType);
var dochtml0body1ruby0rtc1Text0 = dochtml0body1ruby0rtc1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rtc1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rtc1Text0.TextContent);
var dochtml0body1ruby0rtc1rt1 = dochtml0body1ruby0rtc1.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rtc1rt1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc1rt1).Attributes.Length);
Assert.AreEqual("rt", dochtml0body1ruby0rtc1rt1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc1rt1.NodeType);
var dochtml0body1ruby0rtc1rt1Text0 = dochtml0body1ruby0rtc1rt1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rtc1rt1Text0.NodeType);
Assert.AreEqual("c", dochtml0body1ruby0rtc1rt1Text0.TextContent);
var dochtml0body1ruby0rtc1rt2 = dochtml0body1ruby0rtc1.ChildNodes[2];
Assert.AreEqual(1, dochtml0body1ruby0rtc1rt2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc1rt2).Attributes.Length);
Assert.AreEqual("rt", dochtml0body1ruby0rtc1rt2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc1rt2.NodeType);
var dochtml0body1ruby0rtc1rt2Text0 = dochtml0body1ruby0rtc1rt2.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rtc1rt2Text0.NodeType);
Assert.AreEqual("d", dochtml0body1ruby0rtc1rt2Text0.TextContent);
}
[Test]
public void RubyElementImpliedEndForRtcWithRtc()
{
var doc = Html(@"<html><ruby>a<rtc>b<rtc></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rtc1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rtc1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc1).Attributes.Length);
Assert.AreEqual("rtc", dochtml0body1ruby0rtc1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc1.NodeType);
var dochtml0body1ruby0rtc1Text0 = dochtml0body1ruby0rtc1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rtc1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rtc1Text0.TextContent);
var dochtml0body1ruby0rtc2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rtc2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc2).Attributes.Length);
Assert.AreEqual("rtc", dochtml0body1ruby0rtc2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc2.NodeType);
}
[Test]
public void RubyElementImpliedEndForRtcWithRp()
{
var doc = Html(@"<html><ruby>a<rtc>b<rp></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(2, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rtc1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(2, dochtml0body1ruby0rtc1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc1).Attributes.Length);
Assert.AreEqual("rtc", dochtml0body1ruby0rtc1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc1.NodeType);
var dochtml0body1ruby0rtc1Text0 = dochtml0body1ruby0rtc1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rtc1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rtc1Text0.TextContent);
var dochtml0body1ruby0rtc1rp1 = dochtml0body1ruby0rtc1.ChildNodes[1];
Assert.AreEqual(0, dochtml0body1ruby0rtc1rp1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc1rp1).Attributes.Length);
Assert.AreEqual("rp", dochtml0body1ruby0rtc1rp1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc1rp1.NodeType);
}
[Test]
public void RubyElementNoImpliedEndForRtcWithSpan()
{
var doc = Html(@"<html><ruby>a<rtc>b<span></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(2, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rtc1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(2, dochtml0body1ruby0rtc1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc1).Attributes.Length);
Assert.AreEqual("rtc", dochtml0body1ruby0rtc1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc1.NodeType);
var dochtml0body1ruby0rtc1Text0 = dochtml0body1ruby0rtc1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rtc1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rtc1Text0.TextContent);
var dochtml0body1ruby0rtc1span1 = dochtml0body1ruby0rtc1.ChildNodes[1];
Assert.AreEqual(0, dochtml0body1ruby0rtc1span1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc1span1).Attributes.Length);
Assert.AreEqual("span", dochtml0body1ruby0rtc1span1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc1span1.NodeType);
}
[Test]
public void RubyElementImpliedEndForRpWithRb()
{
var doc = Html(@"<html><ruby>a<rp>b<rb></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rp1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rp1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rp1).Attributes.Length);
Assert.AreEqual("rp", dochtml0body1ruby0rp1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rp1.NodeType);
var dochtml0body1ruby0rp1Text0 = dochtml0body1ruby0rp1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rp1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rp1Text0.TextContent);
var dochtml0body1ruby0rb2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rb2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rb2).Attributes.Length);
Assert.AreEqual("rb", dochtml0body1ruby0rb2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rb2.NodeType);
}
[Test]
public void RubyElementImpliedEndForRpWithRt()
{
var doc = Html(@"<html><ruby>a<rp>b<rt></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rp1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rp1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rp1).Attributes.Length);
Assert.AreEqual("rp", dochtml0body1ruby0rp1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rp1.NodeType);
var dochtml0body1ruby0rp1Text0 = dochtml0body1ruby0rp1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rp1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rp1Text0.TextContent);
var dochtml0body1ruby0rt2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rt2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rt2).Attributes.Length);
Assert.AreEqual("rt", dochtml0body1ruby0rt2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rt2.NodeType);
}
[Test]
public void RubyElementImpliedEndForRpWithRtc()
{
var doc = Html(@"<html><ruby>a<rp>b<rtc></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rp1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rp1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rp1).Attributes.Length);
Assert.AreEqual("rp", dochtml0body1ruby0rp1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rp1.NodeType);
var dochtml0body1ruby0rp1Text0 = dochtml0body1ruby0rp1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rp1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rp1Text0.TextContent);
var dochtml0body1ruby0rtc2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rtc2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc2).Attributes.Length);
Assert.AreEqual("rtc", dochtml0body1ruby0rtc2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc2.NodeType);
}
[Test]
public void RubyElementImpliedEndForRpWithRp()
{
var doc = Html(@"<html><ruby>a<rp>b<rp></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rp1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rp1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rp1).Attributes.Length);
Assert.AreEqual("rp", dochtml0body1ruby0rp1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rp1.NodeType);
var dochtml0body1ruby0rp1Text0 = dochtml0body1ruby0rp1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rp1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rp1Text0.TextContent);
var dochtml0body1ruby0rp2 = dochtml0body1ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rp2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rp2).Attributes.Length);
Assert.AreEqual("rp", dochtml0body1ruby0rp2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rp2.NodeType);
}
[Test]
public void RubyElementNoImpliedEndForRpWithSpan()
{
var doc = Html(@"<html><ruby>a<rp>b<span></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(2, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0Text0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0Text0.TextContent);
var dochtml0body1ruby0rp1 = dochtml0body1ruby0.ChildNodes[1];
Assert.AreEqual(2, dochtml0body1ruby0rp1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rp1).Attributes.Length);
Assert.AreEqual("rp", dochtml0body1ruby0rp1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rp1.NodeType);
var dochtml0body1ruby0rp1Text0 = dochtml0body1ruby0rp1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rp1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rp1Text0.TextContent);
var dochtml0body1ruby0rp1span1 = dochtml0body1ruby0rp1.ChildNodes[1];
Assert.AreEqual(0, dochtml0body1ruby0rp1span1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rp1span1).Attributes.Length);
Assert.AreEqual("span", dochtml0body1ruby0rp1span1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rp1span1.NodeType);
}
[Test]
public void RubyElementImpliedEndWithRuby()
{
var doc = Html(@"<html><ruby><rtc><ruby>a<rb>b<rt></ruby></ruby></html>");
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1ruby0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0.NodeType);
var dochtml0body1ruby0rtc0 = dochtml0body1ruby0.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1ruby0rtc0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc0).Attributes.Length);
Assert.AreEqual("rtc", dochtml0body1ruby0rtc0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc0.NodeType);
var dochtml0body1ruby0rtc0ruby0 = dochtml0body1ruby0rtc0.ChildNodes[0];
Assert.AreEqual(3, dochtml0body1ruby0rtc0ruby0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc0ruby0).Attributes.Length);
Assert.AreEqual("ruby", dochtml0body1ruby0rtc0ruby0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc0ruby0.NodeType);
var dochtml0body1ruby0rtc0ruby0Text0 = dochtml0body1ruby0rtc0ruby0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rtc0ruby0Text0.NodeType);
Assert.AreEqual("a", dochtml0body1ruby0rtc0ruby0Text0.TextContent);
var dochtml0body1ruby0rtc0ruby0rb1 = dochtml0body1ruby0rtc0ruby0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1ruby0rtc0ruby0rb1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc0ruby0rb1).Attributes.Length);
Assert.AreEqual("rb", dochtml0body1ruby0rtc0ruby0rb1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc0ruby0rb1.NodeType);
var dochtml0body1ruby0rtc0ruby0rb1Text0 = dochtml0body1ruby0rtc0ruby0rb1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1ruby0rtc0ruby0rb1Text0.NodeType);
Assert.AreEqual("b", dochtml0body1ruby0rtc0ruby0rb1Text0.TextContent);
var dochtml0body1ruby0rtc0ruby0rt2 = dochtml0body1ruby0rtc0ruby0.ChildNodes[2];
Assert.AreEqual(0, dochtml0body1ruby0rtc0ruby0rt2.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1ruby0rtc0ruby0rt2).Attributes.Length);
Assert.AreEqual("rt", dochtml0body1ruby0rtc0ruby0rt2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1ruby0rtc0ruby0rt2.NodeType);
}
}
}
| |
// Copyright (c) 2013, SIL International.
// Distributable under the terms of the MIT license (http://opensource.org/licenses/MIT).
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using IBusDotNet;
namespace SIL.Windows.Forms.Keyboarding.Linux
{
/// <summary>
/// Default event handler for IBUS events that works with a WinForms text box.
/// </summary>
public class IbusDefaultEventHandler : IIbusEventHandler
{
private TextBox m_TextBox;
/// <summary>
/// The start of the selection in the textbox before we insert a temporary composition string.
/// </summary>
private int m_SelectionStart;
/// <summary>
/// The initial length of the selection in the textbox.
/// </summary>
private int m_SelectionLength;
/// <summary>
/// Number of characters that got inserted temporarily as composition string.
/// </summary>
private int m_PreeditLength;
/// <summary>
/// <c>true</c> while we're inside of Reset(bool).
/// </summary>
private bool m_InReset;
public IbusDefaultEventHandler(TextBox textBox)
{
m_TextBox = textBox;
m_SelectionStart = -1;
m_SelectionLength = -1;
}
/// <summary>
/// Reset the selection and optionally cancel any open compositions.
/// </summary>
/// <param name="cancel">Set to <c>true</c> to also cancel the open composition.</param>
/// <returns><c>true</c> if there was an open composition that we cancelled, otherwise
/// <c>false</c>.</returns>
private bool Reset(bool cancel)
{
if (m_InReset)
return false;
var retVal = false;
m_InReset = true;
if (cancel && m_SelectionStart > -1)
{
var preeditStart = m_SelectionStart + m_SelectionLength;
m_TextBox.Text = RemoveChars(m_TextBox.Text, preeditStart, m_PreeditLength);
m_TextBox.SelectionStart = m_SelectionStart;
m_TextBox.SelectionLength = m_SelectionLength;
retVal = true;
}
m_SelectionStart = -1;
m_SelectionLength = -1;
m_PreeditLength = 0;
m_InReset = false;
return retVal;
}
/// <summary>
/// Removes the characters from the preedit part of <paramref name="text"/>.
/// </summary>
/// <returns>The new string.</returns>
/// <param name="text">Text.</param>
/// <param name="removePos">Position inside of <paramref name="text"/> where the
/// temporary preedit characters start and where we should start to remove the
/// characters.</param>
/// <param name="preeditTextLen">Length of the preedit text part.</param>
private static string RemoveChars(string text, int removePos, int preeditTextLen)
{
var toRemove = preeditTextLen;
if (removePos + toRemove > text.Length)
toRemove = Math.Max(text.Length - removePos, 0);
if (toRemove > 0)
return text.Remove(removePos, toRemove);
return text;
}
/// <summary>
/// Trim beginning backspaces, if any. Return number trimmed.
/// </summary>
private static int TrimBeginningBackspaces(ref string text)
{
const char backSpace = '\b'; // 0x0008
if (!text.StartsWith(backSpace.ToString()))
return 0;
var count = text.Length - text.TrimStart(backSpace).Length;
text = text.TrimStart(backSpace);
return count;
}
private void OnCommitText(string text)
{
// Replace 'toRemove' characters starting at 'insertPos' with 'text'.
int insertPos, toRemove;
if (m_SelectionStart > -1)
{
insertPos = m_SelectionStart;
toRemove = m_SelectionLength + m_PreeditLength;
}
else
{
// IPA Unicode 6.2 ibus keyboard doesn't call OnUpdatePreeditText,
// only OnCommitText, so we don't have a m_SelectionStart stored.
insertPos = m_TextBox.SelectionStart;
toRemove = m_TextBox.SelectionLength;
}
var countBackspace = TrimBeginningBackspaces(ref text);
insertPos -= countBackspace;
if (insertPos < 0)
insertPos = 0;
toRemove += countBackspace;
var boxText = RemoveChars(m_TextBox.Text, insertPos, toRemove);
m_TextBox.Text = boxText.Insert(insertPos, text);
m_TextBox.SelectionStart = insertPos + text.Length;
m_TextBox.SelectionLength = 0;
Reset(false);
}
// When the application loses focus the user expects different behavior for different
// ibus keyboards: for some keyboards (those that do the editing in-place and don't display
// a selection window, e.g. "Danish - post (m17n)") the user expects that what he
// typed remains, i.e. gets committed. Otherwise (e.g. with the Danish keyboard) it's not
// possible to type an "a" and then click in a different field or switch applications.
//
// For other keyboards (e.g. Chinese Pinyin) the commit is made when the user selects
// one of the possible characters in the pop-up window. If he clicks in a different
// field while the pop-up window is open the composition should be deleted.
//
// There doesn't seem to be a way to ask an IME keyboard if it shows a pop-up window or
// if we should commit or reset the composition. One indirect way however seems to be to
// check the attributes: it seems that keyboards where we can/should commit set the
// underline attribute to IBusAttrUnderline.None.
private bool IsCommittingKeyboard { get; set; }
private void CheckAttributesForCommittingKeyboard(IBusText text)
{
IsCommittingKeyboard = false;
foreach (var attribute in text.Attributes)
{
var iBusUnderlineAttribute = attribute as IBusUnderlineAttribute;
if (iBusUnderlineAttribute != null && iBusUnderlineAttribute.Underline == IBusAttrUnderline.None)
IsCommittingKeyboard = true;
}
}
#region IIbusEventHandler implementation
/// <summary>
/// This method gets called when the IBus CommitText event is raised and indicates that
/// the composition is ending. The temporarily inserted composition string will be
/// replaced with <paramref name="ibusText"/>.
/// </summary>
/// <seealso cref="IbusKeyboardSwitchingAdaptor.HandleKeyPress"/>
public void OnCommitText(object ibusText)
{
// Note: when we try to pass IBusText as ibusText parameter we get a compiler crash
// in FW.
if (m_TextBox.InvokeRequired)
{
m_TextBox.BeginInvoke((Action) (() => OnCommitText(ibusText)));
return;
}
if (!m_TextBox.Focused)
return;
OnCommitText(((IBusText)ibusText).Text);
}
/// <summary>
/// Called when the IBus UpdatePreeditText event is raised to update the composition.
/// </summary>
/// <param name="obj">New composition string that will replace the existing
/// composition string.</param>
/// <param name="cursorPos">0-based position where the cursor should be put after
/// updating the composition (pre-edit window). This position is relative to the
/// composition/preedit text.</param>
/// <seealso cref="IbusKeyboardSwitchingAdaptor.HandleKeyPress"/>
public void OnUpdatePreeditText(object obj, int cursorPos)
{
if (m_TextBox.InvokeRequired)
{
m_TextBox.BeginInvoke((Action) (() => OnUpdatePreeditText(obj, cursorPos)));
return;
}
if (!m_TextBox.Focused)
return;
var text = obj as IBusText;
CheckAttributesForCommittingKeyboard(text);
var compositionText = text.Text;
if (m_SelectionStart == -1 || m_SelectionStart + m_SelectionLength > m_TextBox.Text.Length)
{
// Remember selection in textbox prior to inserting composition text.
m_SelectionStart = m_TextBox.SelectionStart;
m_SelectionLength = m_TextBox.SelectionLength;
}
var preeditStart = m_SelectionStart + m_SelectionLength;
m_TextBox.SelectionStart = preeditStart;
m_TextBox.SelectionLength = 0;
// Remove the previous composition text starting at preeditStart
m_TextBox.Text = RemoveChars(m_TextBox.Text, preeditStart, m_PreeditLength);
if (preeditStart >= m_TextBox.Text.Length)
{
preeditStart = m_TextBox.Text.Length;
m_TextBox.AppendText(compositionText);
}
else
m_TextBox.Text = m_TextBox.Text.Insert(preeditStart, compositionText);
m_PreeditLength = compositionText.Length;
if (m_SelectionLength > 0)
{
// We want to keep the range selection. It gets deleted in the CommitTextHandler.
// This mimics the behavior in gedit.
m_TextBox.SelectionStart = m_SelectionStart;
m_TextBox.SelectionLength = m_SelectionLength;
}
else
{
m_TextBox.SelectionStart = m_SelectionStart + cursorPos;
m_TextBox.SelectionLength = 0;
}
}
/// <summary>
/// Called when the IBus DeleteSurroundingText is raised to delete surrounding
/// characters.
/// </summary>
/// <param name="offset">The character offset from the cursor position of the text to be
/// deleted. A negative value indicates a position before the cursor.</param>
/// <param name="nChars">The number of characters to be deleted.</param>
public void OnDeleteSurroundingText(int offset, int nChars)
{
if (m_TextBox.InvokeRequired)
{
m_TextBox.BeginInvoke((Action) (() => OnDeleteSurroundingText(offset, nChars)));
return;
}
if (!m_TextBox.Focused || nChars <= 0)
return;
var selectionStart = m_TextBox.SelectionStart;
var startIndex = selectionStart + offset;
if (startIndex + nChars <= 0)
return;
startIndex = Math.Max(startIndex, 0);
startIndex = Math.Min(startIndex, m_TextBox.Text.Length);
if (startIndex + nChars > m_TextBox.Text.Length)
nChars = m_TextBox.Text.Length - startIndex;
if (startIndex < selectionStart)
selectionStart = Math.Max(selectionStart - nChars, 0);
m_TextBox.Text = m_TextBox.Text.Remove(startIndex, nChars);
m_TextBox.SelectionStart = selectionStart;
m_TextBox.SelectionLength = 0;
}
/// <summary>
/// Called when the IBus HidePreeditText event is raised to cancel/remove the composition.
/// </summary>
public void OnHidePreeditText()
{
if (m_TextBox.InvokeRequired)
{
m_TextBox.BeginInvoke((Action) OnHidePreeditText);
return;
}
if (!m_TextBox.Focused)
return;
Reset(true);
}
/// <summary>
/// Called when the IBus ForwardKeyEvent (as in: forwarding key event) is raised.
/// </summary>
/// <param name="keySym">Key symbol.</param>
/// <param name="scanCode">Scan code.</param>
/// <param name="index">Index into a vector of keycodes associated with a given key
/// depending on which modifier keys are pressed. 0 is always unmodified, and 1 is with
/// shift alone.
/// </param>
/// <seealso cref="IbusKeyboardSwitchingAdaptor.HandleKeyPress"/>
public void OnIbusKeyPress(int keySym, int scanCode, int index)
{
if (m_TextBox.InvokeRequired)
{
m_TextBox.BeginInvoke((Action) (() => OnIbusKeyPress(keySym, scanCode, index)));
return;
}
if (!m_TextBox.Focused)
return;
var inChar = (char)(0x00FF & keySym);
OnCommitText(inChar.ToString());
}
/// <summary>
/// Called by the IBusKeyboardAdapter to cancel any open compositions.
/// </summary>
/// <returns><c>true</c> if there was an open composition that got cancelled, otherwise
/// <c>false</c>.</returns>
public bool Reset()
{
Debug.Assert(!m_TextBox.InvokeRequired);
return Reset(true);
}
/// <summary>
/// Called by the IbusKeyboardAdapter to commit or cancel any open compositions, e.g.
/// after the application loses focus.
/// </summary>
/// <returns><c>true</c> if there was an open composition that got cancelled, otherwise
/// <c>false</c>.</returns>
public bool CommitOrReset()
{
// don't check if we have focus - we won't if this gets called from OnLostFocus.
// However, the IbusKeyboardAdapter calls this method only for the control that just
// lost focus, so it's ok not to check :-)
if (IsCommittingKeyboard)
{
m_SelectionStart = -1;
m_SelectionLength = -1;
m_PreeditLength = 0;
return false;
}
return Reset(true);
}
/// <summary>
/// Called by the IBusKeyboardAdapter to get the position (in pixels) and line height of
/// the end of the selection. The position is relative to the screen in the
/// PointToScreen sense, that is (0,0) is the top left of the primary monitor.
/// IBus will use this information when it opens a pop-up window to present a list of
/// composition choices.
/// </summary>
public Rectangle SelectionLocationAndHeight
{
get
{
Debug.Assert(!m_TextBox.InvokeRequired);
var posInTextBox = m_TextBox.GetPositionFromCharIndex(m_TextBox.SelectionStart + m_TextBox.SelectionLength);
var posScreen = m_TextBox.PointToScreen(posInTextBox);
return new Rectangle(posScreen, new Size(0, m_TextBox.Font.Height));
}
}
/// <summary>
/// Called by the IbusKeyboardAdapter to find out if a preedit is active.
/// </summary>
public bool IsPreeditActive => m_SelectionStart > -1;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using DataTool.Flag;
using DataTool.SaveLogic;
using DataTool.ToolLogic.Extract;
using Microsoft.WindowsAPICodePack.Dialogs;
using TankView.Helper;
using TankView.Properties;
using TankView.ViewModel;
using TACTLib.Client;
using TACTLib.Client.HandlerArgs;
using TACTLib.Core.Product.Tank;
using TankLib;
using TankLib.TACT;
// ReSharper disable MemberCanBeMadeStatic.Local
namespace TankView {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : INotifyPropertyChanged {
public SynchronizationContext ViewContext { get; }
public NGDPPatchHosts NGDPPatchHosts { get; set; }
public RecentLocations RecentLocations { get; set; }
public ProgressInfo ProgressInfo { get; set; }
public CASCSettings CASCSettings { get; set; }
public AppSettings AppSettings { get; set; }
public GUIDCollection GUIDTree { get; set; } = new GUIDCollection();
public ProductLocations ProductAgent { get; set; }
public ExtractionSettings ExtractionSettings { get; set; }
public ImageExtractionFormats ImageExtractionFormats { get; set; }
public static ClientCreateArgs ClientArgs = new ClientCreateArgs();
private bool ready = true;
public bool IsReady {
get => ready;
set {
ready = value;
if (value) {
_progressWorker.ReportProgress(0, "Idle");
}
NotifyPropertyChanged(nameof(IsReady));
NotifyPropertyChanged(nameof(IsDataReady));
NotifyPropertyChanged(nameof(IsDataToolSafe));
}
}
public string SearchQuery {
get {
return GUIDTree.Search;
}
set {
if (GUIDTree == null) return;
GUIDTree.Search = value;
}
}
public bool IsDataReady => IsReady && GUIDTree?.Data?.Folders.Count > 1;
public bool IsDataToolSafe => IsDataReady && DataTool.Program.TankHandler?.m_rootContentManifest?.m_hashList != null; // todo
private ProgressWorker _progressWorker = new ProgressWorker();
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string name) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public MainWindow() {
ClientArgs.HandlerArgs = new ClientCreateArgs_Tank();
ViewContext = SynchronizationContext.Current;
NGDPPatchHosts = new NGDPPatchHosts();
RecentLocations = new RecentLocations();
ProgressInfo = new ProgressInfo();
CASCSettings = new CASCSettings();
AppSettings = new AppSettings();
ProductAgent = new ProductLocations();
ExtractionSettings = new ExtractionSettings();
ImageExtractionFormats = new ImageExtractionFormats();
_progressWorker.OnProgress += UpdateProgress;
if (!NGDPPatchHosts.Any(x => x.Active)) {
NGDPPatchHosts[0].Active = true;
}
if (!ImageExtractionFormats.Any(x => x.Active)) {
ImageExtractionFormats[0].Active = true;
}
InitializeComponent();
DataContext = this;
// FolderView.ItemsSource = ;
// FolderItemList.ItemsSource = ;
}
GridViewColumnHeader _lastHeaderClicked = null;
private ListSortDirection _lastDirection = ListSortDirection.Descending;
void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e) {
var headerClicked = e.OriginalSource as GridViewColumnHeader;
if (headerClicked == null) return;
if (headerClicked.Role == GridViewColumnHeaderRole.Padding) return;
ListSortDirection direction;
if (headerClicked != _lastHeaderClicked) {
direction = ListSortDirection.Descending;
} else {
direction = _lastDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
}
var columnBinding = headerClicked.Column.DisplayMemberBinding as Binding;
var sortBy = columnBinding?.Path.Path ?? headerClicked.Column.Header as string;
GUIDTree.OrderBy(sortBy, direction);
if (direction == ListSortDirection.Ascending) {
headerClicked.Column.HeaderTemplate = Resources["HeaderTemplateArrowUp"] as DataTemplate;
} else {
headerClicked.Column.HeaderTemplate = Resources["HeaderTemplateArrowDown"] as DataTemplate;
}
if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked) {
_lastHeaderClicked.Column.HeaderTemplate = null;
}
_lastHeaderClicked = headerClicked;
_lastDirection = direction;
}
private void UpdateProgress(object sender, ProgressChangedEventArgs @event) {
ViewContext.Send(x => {
if (!(x is ProgressChangedEventArgs evt)) return;
if (evt.UserState != null && evt.UserState is string state) {
ProgressInfo.State = state;
}
ProgressInfo.Percentage = evt.ProgressPercentage;
}, @event);
}
public string ModuloTitle => "TankView";
private void Exit(object sender, RoutedEventArgs e) {
Environment.Exit(0);
}
private void NGDPHostChange(object sender, RoutedEventArgs e) {
if (!(sender is MenuItem menuItem)) return;
foreach (PatchHost node in NGDPPatchHosts.Where(x => x.Active && x.GetHashCode() != ((PatchHost) menuItem.DataContext).GetHashCode())) {
node.Active = false;
}
CollectionViewSource.GetDefaultView(NGDPPatchHosts).Refresh();
}
private void ImageExtractionFormatChange(object sender, RoutedEventArgs e) {
if (!(sender is MenuItem menuItem)) return;
foreach (ImageFormat node in ImageExtractionFormats.Where(x => x.Active && x.GetHashCode() != ((ImageFormat) menuItem.DataContext).GetHashCode())) {
node.Active = false;
}
CollectionViewSource.GetDefaultView(ImageExtractionFormats).Refresh();
}
private void OpenNGDP(object sender, RoutedEventArgs e) {
throw new NotImplementedException(nameof(OpenNGDP));
}
private void OpenCASC(object sender, RoutedEventArgs e) {
CommonOpenFileDialog dialog = new CommonOpenFileDialog {
IsFolderPicker = true,
EnsurePathExists = true
};
if (dialog.ShowDialog() == CommonFileDialogResult.Ok) {
OpenCASC(dialog.FileName);
}
}
private void OpenRecent(object sender, RoutedEventArgs e) {
if (!(sender is MenuItem menuItem)) return;
string path = menuItem.DataContext as string;
RecentLocations.Add(path);
CollectionViewSource.GetDefaultView(RecentLocations).Refresh();
if (path?.StartsWith("ngdp://") == true) {
OpenNGDP(path);
} else {
OpenCASC(path);
}
}
private void OpenAgent(object sender, RoutedEventArgs e) {
if (sender is MenuItem menuItem) {
OpenCASC(menuItem.Tag as string);
}
}
private void OpenNGDP(string path) {
throw new NotImplementedException(nameof(OpenNGDP));
// todo: can be supported again
#pragma warning disable 162
// ReSharper disable once HeuristicUnreachableCode
PrepareTank(path);
Task.Run(delegate {
try {
DataTool.Program.Client = new ClientHandler(null, ClientArgs);
DataTool.Program.TankHandler = DataTool.Program.Client.ProductHandler as ProductHandler_Tank;
} catch (Exception e) {
MessageBox.Show(e.Message, "Error while loading CASC", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
IsReady = true;
if (Debugger.IsAttached) {
throw;
}
} finally {
GCSettings.LatencyMode = GCLatencyMode.Interactive;
GC.Collect();
DataTool.Program.InitTrackedFiles();
}
});
#pragma warning restore 162
}
private void OpenCASC(string path) {
PrepareTank(path);
Task.Run(delegate {
try {
var flags = FlagParser.Parse<ToolFlags>();
if (flags != null) {
ClientArgs.TextLanguage = flags.Language;
ClientArgs.SpeechLanguage = flags.SpeechLanguage;
ClientArgs.Online = flags.Online;
} else {
ClientArgs.Online = false;
}
DataTool.Program.Client = new ClientHandler(path, ClientArgs);
LoadHelper.PostLoad(DataTool.Program.Client);
DataTool.Helper.IO.LoadGUIDTable(false);
DataTool.Program.TankHandler = DataTool.Program.Client.ProductHandler as ProductHandler_Tank;
BuildTree();
} catch (Exception e) {
MessageBox.Show(e.Message, "Error while loading CASC", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
if (Debugger.IsAttached) {
throw;
}
} finally {
GCSettings.LatencyMode = GCLatencyMode.Interactive;
GC.Collect();
if (Settings.Default.LoadManifest) {
DataTool.Program.InitTrackedFiles();
}
ViewContext.Send(delegate { IsReady = true; NotifyPropertyChanged(nameof(IsReady)); }, null);
}
var productCode = DataTool.Program.Client.AgentProduct.ProductCode;
if (productCode != null && productCode != "pro") {
MessageBox.Show($"The branch \"{productCode}\" is not supported!\nThis might result in failure to load.\nProceed with caution.", "Unsupported Branch", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
}
});
}
private void PrepareTank(string path) {
RecentLocations.Add(path);
CollectionViewSource.GetDefaultView(RecentLocations).Refresh();
_progressWorker.ReportProgress(0, $"Preparing to load {path}");
IsReady = false;
DataTool.Program.Client = null;
DataTool.Program.TankHandler = null;
GUIDTree?.Dispose();
GUIDTree = new GUIDCollection();
NotifyPropertyChanged(nameof(GUIDTree));
GCSettings.LatencyMode = GCLatencyMode.Batch;
}
private void BuildTree() {
GUIDTree?.Dispose();
GUIDTree = new GUIDCollection(DataTool.Program.Client, DataTool.Program.TankHandler, _progressWorker);
NotifyPropertyChanged(nameof(GUIDTree));
}
private void ChangeActiveNode(object sender, RoutedEventArgs e) {
if (e.Handled) {
return;
}
if (!(sender is TreeViewItem item)) return;
if (item.DataContext is Folder folder) GUIDTree.SelectedEntries = folder.Files.ToArray();
NotifyPropertyChanged(nameof(GUIDTree));
e.Handled = true;
}
private void ExtractFiles(object sender, RoutedEventArgs e) {
GUIDEntry[] files = {};
switch (Tabs.SelectedIndex) {
case 0: {
files = FolderItemList.SelectedItems.OfType<GUIDEntry>().ToArray();
if (files.Length == 0) {
files = FolderItemList.Items.OfType<GUIDEntry>().ToArray();
}
break;
}
case 1: {
files = FolderImageList.SelectedItems.OfType<GUIDEntry>().ToArray();
break;
}
}
if (files.Length == 0) {
return;
}
CommonOpenFileDialog dialog = new CommonOpenFileDialog {
IsFolderPicker = true,
EnsurePathExists = true
};
if (dialog.ShowDialog() == CommonFileDialogResult.Ok) {
ExtractFiles(dialog.FileName, files);
}
}
private void ExtractFiles(string outPath, IEnumerable<GUIDEntry> files) {
IsReady = false;
IEnumerable<GUIDEntry> guidEntries = files as GUIDEntry[] ?? files.ToArray();
HashSet<string> directories = new HashSet<string>(guidEntries.Select(x => Path.Combine(outPath, Path.GetDirectoryName(x.FullPath.Substring(1)) ?? string.Empty)));
foreach (string directory in directories) {
if (!Directory.Exists(directory)) {
Directory.CreateDirectory(directory);
}
}
var imageExtractFlags = new ExtractFlags {
ConvertTexturesType = Settings.Default.ImageExtractionFormat
};
Task.Run(delegate {
int c = 0;
int t = guidEntries.Count();
_progressWorker?.ReportProgress(0, "Saving files...");
Parallel.ForEach(guidEntries, new ParallelOptions {
MaxDegreeOfParallelism = 4
}, (entry) => {
c++;
if (c % ((int) (t * 0.005) + 1) == 0) {
var progress = (int) ((c / (float) t) * 100);
_progressWorker?.ReportProgress(progress, $"Saving files... {progress}% ({c}/{t})");
}
var dataType = DataHelper.GetDataType(teResourceGUID.Type(entry.GUID));
var fileType = Path.GetExtension(entry.FullPath)?.Substring(1);
var filePath = Path.ChangeExtension(entry.FullPath.Substring(1), null);
var fileOutput = $"{filePath}.{GetFileType(dataType) ?? fileType}";
try {
if (dataType == DataHelper.DataType.Image && ExtractionSettings.EnableConvertImages) {
DataTool.FindLogic.Combo.ComboInfo info = new DataTool.FindLogic.Combo.ComboInfo();
DataTool.FindLogic.Combo.Find(info, entry.GUID);
var newPath = Path.GetFullPath(Path.Combine(outPath, filePath, @"..\")); // filepath includes the filename which we don't want here as combo already does that
var context = new Combo.SaveContext(info);
Combo.SaveLooseTextures(imageExtractFlags, newPath, context);
context.Wait();
return;
}
using (Stream i = IOHelper.OpenFile(entry))
using (Stream o = File.OpenWrite(Path.Combine(outPath, fileOutput))) {
switch (dataType) {
case DataHelper.DataType.Sound when ExtractionSettings.EnableConvertSounds:
o.SetLength(0);
Combo.ConvertSoundFile(i, o);
break;
// not used, image extraction is handled above
case DataHelper.DataType.Image when ExtractionSettings.EnableConvertImages:
DataHelper.SaveImage(entry, i, o);
break;
default:
i.CopyTo(o);
break;
}
}
} catch {
// ignored
}
});
ViewContext.Send(delegate { IsReady = true; }, null);
});
}
private string GetFileType(DataHelper.DataType dataType) {
switch (dataType) {
case DataHelper.DataType.Sound when ExtractionSettings.EnableConvertSounds:
return "ogg";
case DataHelper.DataType.Image when ExtractionSettings.EnableConvertImages:
return "dds"; // todo, support other formats??
default:
return null;
}
}
private void ExtractFolder(Folder folder, ref List<GUIDEntry> files) {
files.AddRange(folder.Files);
foreach (Folder f in folder.Folders) {
ExtractFolder(f, ref files);
}
}
private void ExtractFolder(string outPath, Folder folder) {
List<GUIDEntry> files = new List<GUIDEntry>();
ExtractFolder(folder, ref files);
ExtractFiles(outPath, files);
}
private void ExtractFolder(object sender, RoutedEventArgs e) {
CommonOpenFileDialog dialog = new CommonOpenFileDialog {
IsFolderPicker = true,
EnsurePathExists = true
};
if (dialog.ShowDialog() == CommonFileDialogResult.Ok) {
ExtractFolder(dialog.FileName, (sender as FrameworkElement)?.DataContext as Folder);
}
}
/// <summary>
/// Adds a small delay when holding the arrow key down so it doesn't go through like a million rows a second
/// </summary>
private bool _filJustPressedKeyDown;
private void FolderItemList_OnKeyDown(object sender, KeyEventArgs e) {
if (_filJustPressedKeyDown) {
e.Handled = true;
return;
}
_filJustPressedKeyDown = true;
Task.Delay(90).ContinueWith(t => _filJustPressedKeyDown = false);
}
private void FolderItemList_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) {
if (e.Source is ListView listView && listView.SelectedItem is GUIDEntry guidEntry) {
Clipboard.SetText(guidEntry.Filename);
}
}
}
}
| |
/// Credit BinaryX
/// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/page-2#post-1945602
/// Updated by ddreaper - removed dependency on a custom ScrollRect script. Now implements drag interfaces and standard Scroll Rect.
using System;
using UnityEngine.EventSystems;
namespace UnityEngine.UI.Extensions
{
[RequireComponent(typeof(ScrollRect))]
[AddComponentMenu("Layout/Extensions/Horizontal Scroll Snap")]
public class HorizontalScrollSnap : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
{
private Transform _screensContainer;
private int _screens = 1;
private bool _fastSwipeTimer = false;
private int _fastSwipeCounter = 0;
private int _fastSwipeTarget = 30;
private System.Collections.Generic.List<Vector3> _positions;
private ScrollRect _scroll_rect;
private Vector3 _lerp_target;
private bool _lerp;
[Tooltip("The gameobject that contains toggles which suggest pagination. (optional)")]
public GameObject Pagination;
[Tooltip("Button to go to the next page. (optional)")]
public GameObject NextButton;
[Tooltip("Button to go to the previous page. (optional)")]
public GameObject PrevButton;
[Tooltip("Transition speed between pages. (optional)")]
public float transitionSpeed = 7.5f;
public Boolean UseFastSwipe = true;
public int FastSwipeThreshold = 100;
private bool _startDrag = true;
private Vector3 _startPosition = new Vector3();
[Tooltip("The currently active page")]
[SerializeField]
private int _currentScreen;
[Tooltip("The screen / page to start the control on")]
public int StartingScreen = 1;
[Tooltip("The distance between two pages, by default 3 times the height of the control")]
public int PageStep = 0;
public int CurrentPage
{
get
{
return _currentScreen;
}
}
// Use this for initialization
void Start()
{
_scroll_rect = gameObject.GetComponent<ScrollRect>();
if (_scroll_rect.horizontalScrollbar || _scroll_rect.verticalScrollbar)
{
Debug.LogWarning("Warning, using scrollbors with the Scroll Snap controls is not advised as it causes unpredictable results");
}
_screensContainer = _scroll_rect.content;
if (PageStep == 0)
{
PageStep = (int)_scroll_rect.GetComponent<RectTransform>().rect.width * 3;
}
DistributePages();
_lerp = false;
_currentScreen = StartingScreen;
_scroll_rect.horizontalNormalizedPosition = (float)(_currentScreen - 1) / (_screens - 1);
ChangeBulletsInfo(_currentScreen);
if (NextButton)
NextButton.GetComponent<Button>().onClick.AddListener(() => { NextScreen(); });
if (PrevButton)
PrevButton.GetComponent<Button>().onClick.AddListener(() => { PreviousScreen(); });
}
void Update()
{
if (_lerp)
{
_screensContainer.localPosition = Vector3.Lerp(_screensContainer.localPosition, _lerp_target, transitionSpeed * Time.deltaTime);
if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 0.005f)
{
_lerp = false;
}
//change the info bullets at the bottom of the screen. Just for visual effect
if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 10f)
{
ChangeBulletsInfo(CurrentScreen());
}
}
if (_fastSwipeTimer)
{
_fastSwipeCounter++;
}
}
private bool fastSwipe = false; //to determine if a fast swipe was performed
//Function for switching screens with buttons
public void NextScreen()
{
if (_currentScreen < _screens - 1)
{
_currentScreen++;
_lerp = true;
_lerp_target = _positions[_currentScreen];
ChangeBulletsInfo(_currentScreen);
}
}
//Function for switching screens with buttons
public void PreviousScreen()
{
if (_currentScreen > 0)
{
_currentScreen--;
_lerp = true;
_lerp_target = _positions[_currentScreen];
ChangeBulletsInfo(_currentScreen);
}
}
//Function for switching to a specific screen
public void GoToScreen(int screenIndex)
{
if (screenIndex <= _screens && screenIndex >= 0)
{
_lerp = true;
_lerp_target = _positions[screenIndex];
ChangeBulletsInfo(screenIndex);
}
}
//Because the CurrentScreen function is not so reliable, these are the functions used for swipes
private void NextScreenCommand()
{
if (_currentScreen < _screens - 1)
{
_lerp = true;
_lerp_target = _positions[_currentScreen + 1];
ChangeBulletsInfo(_currentScreen + 1);
}
}
//Because the CurrentScreen function is not so reliable, these are the functions used for swipes
private void PrevScreenCommand()
{
if (_currentScreen > 0)
{
_lerp = true;
_lerp_target = _positions[_currentScreen - 1];
ChangeBulletsInfo(_currentScreen - 1);
}
}
//find the closest registered point to the releasing point
private Vector3 FindClosestFrom(Vector3 start, System.Collections.Generic.List<Vector3> positions)
{
Vector3 closest = Vector3.zero;
float distance = Mathf.Infinity;
foreach (Vector3 position in _positions)
{
if (Vector3.Distance(start, position) < distance)
{
distance = Vector3.Distance(start, position);
closest = position;
}
}
return closest;
}
//returns the current screen that the is seeing
public int CurrentScreen()
{
var pos = FindClosestFrom(_screensContainer.localPosition, _positions);
return _currentScreen = GetPageforPosition(pos);
}
//changes the bullets on the bottom of the page - pagination
private void ChangeBulletsInfo(int currentScreen)
{
if (Pagination)
for (int i = 0; i < Pagination.transform.childCount; i++)
{
Pagination.transform.GetChild(i).GetComponent<Toggle>().isOn = (currentScreen == i)
? true
: false;
}
}
//used for changing between screen resolutions
private void DistributePages()
{
int _offset = 0;
int _dimension = 0;
Vector2 panelDimensions = gameObject.GetComponent<RectTransform>().sizeDelta;
int currentXPosition = 0;
for (int i = 0; i < _screensContainer.transform.childCount; i++)
{
RectTransform child = _screensContainer.transform.GetChild(i).gameObject.GetComponent<RectTransform>();
currentXPosition = _offset + i * PageStep;
child.sizeDelta = new Vector2(panelDimensions.x, panelDimensions.y);
child.anchoredPosition = new Vector2(currentXPosition, 0f);
}
_dimension = currentXPosition + _offset * -1;
_screensContainer.GetComponent<RectTransform>().offsetMax = new Vector2(_dimension, 0f);
_screens = _screensContainer.childCount;
_positions = new System.Collections.Generic.List<Vector3>();
if (_screens > 0)
{
for (float i = 0; i < _screens; ++i)
{
_scroll_rect.horizontalNormalizedPosition = i / (_screens - 1);
_positions.Add(_screensContainer.localPosition);
}
}
}
int GetPageforPosition(Vector3 pos)
{
for (int i = 0; i < _positions.Count; i++)
{
if (_positions[i] == pos)
{
return i;
}
}
return 0;
}
void OnValidate()
{
var childCount = gameObject.GetComponent<ScrollRect>().content.childCount;
if (StartingScreen > childCount)
{
StartingScreen = childCount;
}
if (StartingScreen < 1)
{
StartingScreen = 1;
}
}
/// <summary>
/// Add a new child to this Scroll Snap and recalculate it's children
/// </summary>
/// <param name="GO">GameObject to add to the ScrollSnap</param>
public void AddChild(GameObject GO)
{
_scroll_rect.horizontalNormalizedPosition = 0;
GO.transform.SetParent(_screensContainer);
DistributePages();
_scroll_rect.horizontalNormalizedPosition = (float)(_currentScreen) / (_screens - 1);
}
/// <summary>
/// Remove a new child to this Scroll Snap and recalculate it's children
/// *Note, this is an index address (0-x)
/// </summary>
/// <param name="index"></param>
/// <param name="ChildRemoved"></param>
public void RemoveChild(int index, out GameObject ChildRemoved)
{
ChildRemoved = null;
if (index < 0 || index > _screensContainer.childCount)
{
return;
}
_scroll_rect.horizontalNormalizedPosition = 0;
var children = _screensContainer.transform;
int i = 0;
foreach (Transform child in children)
{
if (i == index)
{
child.SetParent(null);
ChildRemoved = child.gameObject;
break;
}
i++;
}
DistributePages();
if (_currentScreen > _screens - 1)
{
_currentScreen = _screens - 1;
}
_scroll_rect.horizontalNormalizedPosition = (float)(_currentScreen) / (_screens - 1);
}
#region Interfaces
public void OnBeginDrag(PointerEventData eventData)
{
_startPosition = _screensContainer.localPosition;
_fastSwipeCounter = 0;
_fastSwipeTimer = true;
_currentScreen = CurrentScreen();
}
public void OnEndDrag(PointerEventData eventData)
{
_startDrag = true;
if (_scroll_rect.horizontal)
{
if (UseFastSwipe)
{
fastSwipe = false;
_fastSwipeTimer = false;
if (_fastSwipeCounter <= _fastSwipeTarget)
{
if (Math.Abs(_startPosition.x - _screensContainer.localPosition.x) > FastSwipeThreshold)
{
fastSwipe = true;
}
}
if (fastSwipe)
{
if (_startPosition.x - _screensContainer.localPosition.x > 0)
{
NextScreenCommand();
}
else
{
PrevScreenCommand();
}
}
else
{
_lerp = true;
_lerp_target = FindClosestFrom(_screensContainer.localPosition, _positions);
_currentScreen = GetPageforPosition(_lerp_target);
}
}
else
{
_lerp = true;
_lerp_target = FindClosestFrom(_screensContainer.localPosition, _positions);
_currentScreen = GetPageforPosition(_lerp_target);
}
}
}
public void OnDrag(PointerEventData eventData)
{
_lerp = false;
if (_startDrag)
{
OnBeginDrag(eventData);
_startDrag = false;
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MessageTransferModule")]
public class MessageTransferModule : ISharedRegionModule, IMessageTransferModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
protected string m_MessageKey = String.Empty;
protected List<Scene> m_Scenes = new List<Scene>();
protected Dictionary<UUID, UUID> m_UserRegionMap = new Dictionary<UUID, UUID>();
public event UndeliveredMessage OnUndeliveredMessage;
private IPresenceService m_PresenceService;
protected IPresenceService PresenceService
{
get
{
if (m_PresenceService == null)
m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
return m_PresenceService;
}
}
public virtual void Initialise(IConfigSource config)
{
IConfig cnf = config.Configs["Messaging"];
if (cnf != null)
{
if (cnf.GetString("MessageTransferModule",
"MessageTransferModule") != "MessageTransferModule")
{
return;
}
m_MessageKey = cnf.GetString("MessageKey", String.Empty);
}
m_log.Debug("[MESSAGE TRANSFER]: Module enabled");
m_Enabled = true;
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_log.Debug("[MESSAGE TRANSFER]: Message transfer module active");
scene.RegisterModuleInterface<IMessageTransferModule>(this);
m_Scenes.Add(scene);
}
}
public virtual void PostInitialise()
{
if (!m_Enabled)
return;
MainServer.Instance.AddXmlRPCHandler(
"grid_instant_message", processXMLRPCGridInstantMessage);
}
public virtual void RegionLoaded(Scene scene)
{
}
public virtual void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_Scenes.Remove(scene);
}
}
public virtual void Close()
{
}
public virtual string Name
{
get { return "MessageTransferModule"; }
}
public virtual Type ReplaceableInterface
{
get { return null; }
}
public virtual void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
{
UUID toAgentID = new UUID(im.toAgentID);
if (toAgentID == UUID.Zero)
return;
// Try root avatar only first
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[INSTANT MESSAGE]: Looking for root agent {0} in {1}",
// toAgentID.ToString(), scene.RegionInfo.RegionName);
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null && !sp.IsChildAgent)
{
// Local message
// m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to root agent {0} {1}", sp.Name, toAgentID);
sp.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
// try child avatar second
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[INSTANT MESSAGE]: Looking for child of {0} in {1}", toAgentID, scene.RegionInfo.RegionName);
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null)
{
// Local message
// m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to child agent {0} {1}", sp.Name, toAgentID);
sp.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
// m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to {0} via XMLRPC", im.toAgentID);
SendGridInstantMessageViaXMLRPC(im, result);
}
public virtual void HandleUndeliverableMessage(GridInstantMessage im, MessageResultNotification result)
{
UndeliveredMessage handlerUndeliveredMessage = OnUndeliveredMessage;
// If this event has handlers, then an IM from an agent will be
// considered delivered. This will suppress the error message.
//
if (handlerUndeliveredMessage != null)
{
handlerUndeliveredMessage(im);
if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
result(true);
else
result(false);
return;
}
//m_log.DebugFormat("[INSTANT MESSAGE]: Undeliverable");
result(false);
}
/// <summary>
/// Process a XMLRPC Grid Instant Message
/// </summary>
/// <param name="request">XMLRPC parameters
/// </param>
/// <returns>Nothing much</returns>
protected virtual XmlRpcResponse processXMLRPCGridInstantMessage(XmlRpcRequest request, IPEndPoint remoteClient)
{
bool successful = false;
// TODO: For now, as IMs seem to be a bit unreliable on OSGrid, catch all exception that
// happen here and aren't caught and log them.
try
{
// various rational defaults
UUID fromAgentID = UUID.Zero;
UUID toAgentID = UUID.Zero;
UUID imSessionID = UUID.Zero;
uint timestamp = 0;
string fromAgentName = "";
string message = "";
byte dialog = (byte)0;
bool fromGroup = false;
byte offline = (byte)0;
uint ParentEstateID=0;
Vector3 Position = Vector3.Zero;
UUID RegionID = UUID.Zero ;
byte[] binaryBucket = new byte[0];
float pos_x = 0;
float pos_y = 0;
float pos_z = 0;
//m_log.Info("Processing IM");
Hashtable requestData = (Hashtable)request.Params[0];
// Check if it's got all the data
if (requestData.ContainsKey("from_agent_id")
&& requestData.ContainsKey("to_agent_id") && requestData.ContainsKey("im_session_id")
&& requestData.ContainsKey("timestamp") && requestData.ContainsKey("from_agent_name")
&& requestData.ContainsKey("message") && requestData.ContainsKey("dialog")
&& requestData.ContainsKey("from_group")
&& requestData.ContainsKey("offline") && requestData.ContainsKey("parent_estate_id")
&& requestData.ContainsKey("position_x") && requestData.ContainsKey("position_y")
&& requestData.ContainsKey("position_z") && requestData.ContainsKey("region_id")
&& requestData.ContainsKey("binary_bucket"))
{
if (m_MessageKey != String.Empty)
{
XmlRpcResponse error_resp = new XmlRpcResponse();
Hashtable error_respdata = new Hashtable();
error_respdata["success"] = "FALSE";
error_resp.Value = error_respdata;
if (!requestData.Contains("message_key"))
return error_resp;
if (m_MessageKey != (string)requestData["message_key"])
return error_resp;
}
// Do the easy way of validating the UUIDs
UUID.TryParse((string)requestData["from_agent_id"], out fromAgentID);
UUID.TryParse((string)requestData["to_agent_id"], out toAgentID);
UUID.TryParse((string)requestData["im_session_id"], out imSessionID);
UUID.TryParse((string)requestData["region_id"], out RegionID);
try
{
timestamp = (uint)Convert.ToInt32((string)requestData["timestamp"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
fromAgentName = (string)requestData["from_agent_name"];
message = (string)requestData["message"];
if (message == null)
message = string.Empty;
// Bytes don't transfer well over XMLRPC, so, we Base64 Encode them.
string requestData1 = (string)requestData["dialog"];
if (string.IsNullOrEmpty(requestData1))
{
dialog = 0;
}
else
{
byte[] dialogdata = Convert.FromBase64String(requestData1);
dialog = dialogdata[0];
}
if ((string)requestData["from_group"] == "TRUE")
fromGroup = true;
string requestData2 = (string)requestData["offline"];
if (String.IsNullOrEmpty(requestData2))
{
offline = 0;
}
else
{
byte[] offlinedata = Convert.FromBase64String(requestData2);
offline = offlinedata[0];
}
try
{
ParentEstateID = (uint)Convert.ToInt32((string)requestData["parent_estate_id"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_x = (uint)Convert.ToInt32((string)requestData["position_x"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_y = (uint)Convert.ToInt32((string)requestData["position_y"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_z = (uint)Convert.ToInt32((string)requestData["position_z"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
Position = new Vector3(pos_x, pos_y, pos_z);
string requestData3 = (string)requestData["binary_bucket"];
if (string.IsNullOrEmpty(requestData3))
{
binaryBucket = new byte[0];
}
else
{
binaryBucket = Convert.FromBase64String(requestData3);
}
// Create a New GridInstantMessageObject the the data
GridInstantMessage gim = new GridInstantMessage();
gim.fromAgentID = fromAgentID.Guid;
gim.fromAgentName = fromAgentName;
gim.fromGroup = fromGroup;
gim.imSessionID = imSessionID.Guid;
gim.RegionID = RegionID.Guid;
gim.timestamp = timestamp;
gim.toAgentID = toAgentID.Guid;
gim.message = message;
gim.dialog = dialog;
gim.offline = offline;
gim.ParentEstateID = ParentEstateID;
gim.Position = Position;
gim.binaryBucket = binaryBucket;
// Trigger the Instant message in the scene.
foreach (Scene scene in m_Scenes)
{
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null && !sp.IsChildAgent)
{
scene.EventManager.TriggerIncomingInstantMessage(gim);
successful = true;
}
}
if (!successful)
{
// If the message can't be delivered to an agent, it
// is likely to be a group IM. On a group IM, the
// imSessionID = toAgentID = group id. Raise the
// unhandled IM event to give the groups module
// a chance to pick it up. We raise that in a random
// scene, since the groups module is shared.
//
m_Scenes[0].EventManager.TriggerUnhandledInstantMessage(gim);
}
}
}
catch (Exception e)
{
m_log.Error("[INSTANT MESSAGE]: Caught unexpected exception:", e);
successful = false;
}
//Send response back to region calling if it was successful
// calling region uses this to know when to look up a user's location again.
XmlRpcResponse resp = new XmlRpcResponse();
Hashtable respdata = new Hashtable();
if (successful)
respdata["success"] = "TRUE";
else
respdata["success"] = "FALSE";
resp.Value = respdata;
return resp;
}
/// <summary>
/// delegate for sending a grid instant message asynchronously
/// </summary>
private delegate void GridInstantMessageDelegate(GridInstantMessage im, MessageResultNotification result);
private class GIM {
public GridInstantMessage im;
public MessageResultNotification result;
};
private Queue<GIM> pendingInstantMessages = new Queue<GIM>();
private int numInstantMessageThreads = 0;
private void SendGridInstantMessageViaXMLRPC(GridInstantMessage im, MessageResultNotification result)
{
lock (pendingInstantMessages) {
if (numInstantMessageThreads >= 4) {
GIM gim = new GIM();
gim.im = im;
gim.result = result;
pendingInstantMessages.Enqueue(gim);
} else {
++ numInstantMessageThreads;
//m_log.DebugFormat("[SendGridInstantMessageViaXMLRPC]: ++numInstantMessageThreads={0}", numInstantMessageThreads);
GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsyncMain;
d.BeginInvoke(im, result, GridInstantMessageCompleted, d);
}
}
}
private void GridInstantMessageCompleted(IAsyncResult iar)
{
GridInstantMessageDelegate d = (GridInstantMessageDelegate)iar.AsyncState;
d.EndInvoke(iar);
}
/// <summary>
/// Internal SendGridInstantMessage over XMLRPC method.
/// </summary>
/// <param name="prevRegionHandle">
/// Pass in 0 the first time this method is called. It will be called recursively with the last
/// regionhandle tried
/// </param>
private void SendGridInstantMessageViaXMLRPCAsyncMain(GridInstantMessage im, MessageResultNotification result)
{
GIM gim;
do {
try {
SendGridInstantMessageViaXMLRPCAsync(im, result, UUID.Zero);
} catch (Exception e) {
m_log.Error("[SendGridInstantMessageViaXMLRPC]: exception " + e.Message);
}
lock (pendingInstantMessages) {
if (pendingInstantMessages.Count > 0) {
gim = pendingInstantMessages.Dequeue();
im = gim.im;
result = gim.result;
} else {
gim = null;
-- numInstantMessageThreads;
//m_log.DebugFormat("[SendGridInstantMessageViaXMLRPC]: --numInstantMessageThreads={0}", numInstantMessageThreads);
}
}
} while (gim != null);
}
private void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, MessageResultNotification result, UUID prevRegionID)
{
UUID toAgentID = new UUID(im.toAgentID);
PresenceInfo upd = null;
UUID regionID;
bool lookupAgent = false;
lock (m_UserRegionMap)
{
if (m_UserRegionMap.ContainsKey(toAgentID))
{
upd = new PresenceInfo();
upd.RegionID = m_UserRegionMap[toAgentID];
// We need to compare the current regionhandle with the previous region handle
// or the recursive loop will never end because it will never try to lookup the agent again
if (prevRegionID == upd.RegionID)
{
lookupAgent = true;
}
}
else
{
lookupAgent = true;
}
}
// Are we needing to look-up an agent?
if (lookupAgent)
{
// Non-cached user agent lookup.
PresenceInfo[] presences = PresenceService.GetAgents(new string[] { toAgentID.ToString() });
if (presences != null && presences.Length > 0)
{
foreach (PresenceInfo p in presences)
{
if (p.RegionID != UUID.Zero)
{
upd = p;
break;
}
}
}
if (upd != null)
{
// check if we've tried this before..
// This is one way to end the recursive loop
//
if (upd.RegionID == prevRegionID)
{
// m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
HandleUndeliverableMessage(im, result);
return;
}
}
else
{
// m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
HandleUndeliverableMessage(im, result);
return;
}
}
if (upd != null)
{
GridRegion reginfo = m_Scenes[0].GridService.GetRegionByUUID(UUID.Zero,
upd.RegionID);
if (reginfo != null)
{
Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im);
// Not actually used anymore, left in for compatibility
// Remove at next interface change
//
msgdata["region_handle"] = 0;
bool imresult = doIMSending(reginfo, msgdata);
if (imresult)
{
// IM delivery successful, so store the Agent's location in our local cache.
lock (m_UserRegionMap)
{
if (m_UserRegionMap.ContainsKey(toAgentID))
{
m_UserRegionMap[toAgentID] = upd.RegionID;
}
else
{
m_UserRegionMap.Add(toAgentID, upd.RegionID);
}
}
result(true);
}
else
{
// try again, but lookup user this time.
// Warning, this must call the Async version
// of this method or we'll be making thousands of threads
// The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync
// The version that spawns the thread is SendGridInstantMessageViaXMLRPC
// This is recursive!!!!!
SendGridInstantMessageViaXMLRPCAsync(im, result,
upd.RegionID);
}
}
else
{
m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find region {0}", upd.RegionID);
HandleUndeliverableMessage(im, result);
}
}
else
{
HandleUndeliverableMessage(im, result);
}
}
/// <summary>
/// This actually does the XMLRPC Request
/// </summary>
/// <param name="reginfo">RegionInfo we pull the data out of to send the request to</param>
/// <param name="xmlrpcdata">The Instant Message data Hashtable</param>
/// <returns>Bool if the message was successfully delivered at the other side.</returns>
protected virtual bool doIMSending(GridRegion reginfo, Hashtable xmlrpcdata)
{
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
XmlRpcRequest GridReq = new XmlRpcRequest("grid_instant_message", SendParams);
try
{
XmlRpcResponse GridResp = GridReq.Send(reginfo.ServerURI, 3000);
Hashtable responseData = (Hashtable)GridResp.Value;
if (responseData.ContainsKey("success"))
{
if ((string)responseData["success"] == "TRUE")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
catch (WebException e)
{
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: Error sending message to {0} the host didn't respond " + e.ToString(), reginfo.ServerURI.ToString());
}
return false;
}
/// <summary>
/// Get ulong region handle for region by it's Region UUID.
/// We use region handles over grid comms because there's all sorts of free and cool caching.
/// </summary>
/// <param name="regionID">UUID of region to get the region handle for</param>
/// <returns></returns>
// private virtual ulong getLocalRegionHandleFromUUID(UUID regionID)
// {
// ulong returnhandle = 0;
//
// lock (m_Scenes)
// {
// foreach (Scene sn in m_Scenes)
// {
// if (sn.RegionInfo.RegionID == regionID)
// {
// returnhandle = sn.RegionInfo.RegionHandle;
// break;
// }
// }
// }
// return returnhandle;
// }
/// <summary>
/// Takes a GridInstantMessage and converts it into a Hashtable for XMLRPC
/// </summary>
/// <param name="msg">The GridInstantMessage object</param>
/// <returns>Hashtable containing the XMLRPC request</returns>
protected virtual Hashtable ConvertGridInstantMessageToXMLRPC(GridInstantMessage msg)
{
Hashtable gim = new Hashtable();
gim["from_agent_id"] = msg.fromAgentID.ToString();
// Kept for compatibility
gim["from_agent_session"] = UUID.Zero.ToString();
gim["to_agent_id"] = msg.toAgentID.ToString();
gim["im_session_id"] = msg.imSessionID.ToString();
gim["timestamp"] = msg.timestamp.ToString();
gim["from_agent_name"] = msg.fromAgentName;
gim["message"] = msg.message;
byte[] dialogdata = new byte[1];dialogdata[0] = msg.dialog;
gim["dialog"] = Convert.ToBase64String(dialogdata,Base64FormattingOptions.None);
if (msg.fromGroup)
gim["from_group"] = "TRUE";
else
gim["from_group"] = "FALSE";
byte[] offlinedata = new byte[1]; offlinedata[0] = msg.offline;
gim["offline"] = Convert.ToBase64String(offlinedata, Base64FormattingOptions.None);
gim["parent_estate_id"] = msg.ParentEstateID.ToString();
gim["position_x"] = msg.Position.X.ToString();
gim["position_y"] = msg.Position.Y.ToString();
gim["position_z"] = msg.Position.Z.ToString();
gim["region_id"] = new UUID(msg.RegionID).ToString();
gim["binary_bucket"] = Convert.ToBase64String(msg.binaryBucket,Base64FormattingOptions.None);
if (m_MessageKey != String.Empty)
gim["message_key"] = m_MessageKey;
return gim;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.ComponentModel.Design.Serialization;
using System.Workflow.Runtime;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime.Hosting;
namespace System.Workflow.Runtime.Tracking
{
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class SqlTrackingWorkflowInstance
{
#region Private Members
private delegate void LoadFromReader(SqlDataReader reader, object parameter);
private static int _deadlock = 1205;
private static short _retries = 5;
private string _connectionString = null;
private bool _autoRefresh = false;
DateTime _currDT = DateTime.UtcNow,
_actMinDT = SqlDateTime.MinValue.Value,
_userMinDT = SqlDateTime.MinValue.Value,
_instMinDT = SqlDateTime.MinValue.Value,
_childMinDT = SqlDateTime.MinValue.Value,
_changesMinDT = SqlDateTime.MinValue.Value,
_invMinDT = SqlDateTime.MinValue.Value;
long _internalId = -1;
Guid _id;
DateTime _initialized;
Guid _invoker = Guid.Empty;
WorkflowStatus _status;
Type _workflowType = null;
bool _changed = false;
List<ActivityTrackingRecord> _activityEvents = new List<ActivityTrackingRecord>();
List<UserTrackingRecord> _userEvents = new List<UserTrackingRecord>();
List<WorkflowTrackingRecord> _workflowEvents = new List<WorkflowTrackingRecord>();
List<SqlTrackingWorkflowInstance> _invoked = new List<SqlTrackingWorkflowInstance>();
Activity _def = null;
#endregion Private Members
#region Constructors
private SqlTrackingWorkflowInstance() { }
internal SqlTrackingWorkflowInstance(string connectionString)
{
if (null == connectionString)
throw new ArgumentNullException("connectionString");
_connectionString = connectionString;
}
#endregion Constructors
#region Properties
public bool AutoRefresh
{
get { return _autoRefresh; }
set { _autoRefresh = value; }
}
public Guid WorkflowInstanceId
{
get { return _id; }
set { _id = value; }
}
public long WorkflowInstanceInternalId
{
get { return _internalId; }
set { _internalId = value; }
}
public DateTime Initialized
{
get { return _initialized; }
set { _initialized = value; }
}
public Guid InvokingWorkflowInstanceId
{
get { return _invoker; }
set { _invoker = value; }
}
public WorkflowStatus Status
{
get { return _status; }
set { _status = value; }
}
public Type WorkflowType
{
get { return _workflowType; }
set { _workflowType = value; }
}
public bool WorkflowDefinitionUpdated
{
get
{
if (_autoRefresh)
Refresh();
LoadDef();
return _changed;
}
}
public IList<ActivityTrackingRecord> ActivityEvents
{
get
{
if (_autoRefresh)
Refresh();
LoadActivityEvents();
return _activityEvents;
}
}
public IList<UserTrackingRecord> UserEvents
{
get
{
if (_autoRefresh)
Refresh();
LoadUserEvents();
return _userEvents;
}
}
public IList<WorkflowTrackingRecord> WorkflowEvents
{
get
{
if (_autoRefresh)
Refresh();
LoadWorkflowEvents();
return _workflowEvents;
}
}
public Activity WorkflowDefinition
{
get
{
if (_autoRefresh)
Refresh();
LoadDef();
return _def;
}
}
public IList<SqlTrackingWorkflowInstance> InvokedWorkflows
{
get
{
if (_autoRefresh)
Refresh();
LoadInvokedWorkflows();
return _invoked;
}
}
#endregion Properties
public void Refresh()
{
_currDT = DateTime.UtcNow;
}
private void LoadActivityEvents()
{
SqlCommand cmd = CreateInternalIdDateTimeCommand("[dbo].[GetActivityEventsWithDetails]", _actMinDT);
ExecuteRetried(cmd, LoadActivityEventsFromReader);
}
private void LoadActivityEventsFromReader(SqlDataReader reader, object parameter)
{
if (null == reader)
throw new ArgumentNullException("reader");
//
// There should always be 4 recordsets in this reader!
//
Dictionary<long, ActivityTrackingRecord> activities = new Dictionary<long, ActivityTrackingRecord>();
//
// Build a dictionary of activity records so that we can match
// annotation and artifact records from subsequent recordsets
DateTime tmpMin = SqlDateTime.MinValue.Value;
while (reader.Read())
{
string qId = reader.GetString(0);
ActivityExecutionStatus status = (ActivityExecutionStatus)reader[1];
DateTime dt = reader.GetDateTime(2);
Guid context = reader.GetGuid(3), parentContext = reader.GetGuid(4);
int order = reader.GetInt32(5);
if (reader.IsDBNull(6) || reader.IsDBNull(7))
throw new InvalidOperationException(String.Format(System.Globalization.CultureInfo.CurrentCulture, ExecutionStringManager.SqlTrackingTypeNotFound, qId));
Type type = Type.GetType(reader.GetString(6) + ", " + reader.GetString(7), true, false);
long eventId = reader.GetInt64(8);
DateTime dbDt = reader.GetDateTime(9);
activities.Add(eventId, new ActivityTrackingRecord(type, qId, context, parentContext, status, dt, order, null));
if (dbDt > tmpMin)
tmpMin = dbDt;
}
if (!reader.NextResult())
throw new ArgumentException(ExecutionStringManager.InvalidActivityEventReader);
//
// If we have annotations on the event itself, add them
while (reader.Read())
{
long eventId = reader.GetInt64(0);
string annotation = null;
if (!reader.IsDBNull(1))
annotation = reader.GetString(1);
ActivityTrackingRecord activity = null;
if (activities.TryGetValue(eventId, out activity))
{
if (null != activity)
activity.Annotations.Add(annotation);
}
}
if (!reader.NextResult())
throw new ArgumentException(ExecutionStringManager.InvalidActivityEventReader);
//
// Build a dictionary of artifact records so that we can match
// annotation records from subsequent recordsets
BinaryFormatter formatter = new BinaryFormatter();
Dictionary<long, TrackingDataItem> artifacts = new Dictionary<long, TrackingDataItem>();
while (reader.Read())
{
long eventId = reader.GetInt64(0);
long artId = reader.GetInt64(1);
string name = reader.GetString(2), strData = null;
object data = null;
//
// These may both be null
if (!reader.IsDBNull(3))
strData = reader.GetString(3);
if (!reader.IsDBNull(4))
data = formatter.Deserialize(new MemoryStream((Byte[])reader[4]));
TrackingDataItem item = new TrackingDataItem();
item.FieldName = name;
if (null != data)
item.Data = data;
else
item.Data = strData;
artifacts.Add(artId, item);
//
// Find the event to which this artifact belongs and add it to the record
ActivityTrackingRecord activity = null;
if (activities.TryGetValue(eventId, out activity))
{
if (null != activity)
activity.Body.Add(item);
}
}
if (!reader.NextResult())
throw new ArgumentException(ExecutionStringManager.InvalidActivityEventReader);
//
// If we have annotations add them to the appropriate artifact
while (reader.Read())
{
long artId = reader.GetInt64(0);
string annotation = null;
if (!reader.IsDBNull(1))
annotation = reader.GetString(1);
//
// Find the right artifact and give it the annotation
TrackingDataItem item = null;
if (artifacts.TryGetValue(artId, out item))
{
if (null != item)
item.Annotations.Add(annotation);
}
}
_activityEvents.AddRange(activities.Values);
//
// Set the min value to the most recent event that we got with this query
// Don't overwrite the previous min if nothing came back for this query
if (tmpMin > SqlDateTime.MinValue.Value)
_actMinDT = tmpMin;
return;
}
private void LoadUserEvents()
{
SqlCommand cmd = CreateInternalIdDateTimeCommand("[dbo].[GetUserEventsWithDetails]", _userMinDT);
ExecuteRetried(cmd, LoadUserEventsFromReader);
}
private void LoadUserEventsFromReader(SqlDataReader reader, object parameter)
{
if (null == reader)
throw new ArgumentNullException("reader");
//
// There should always be 4 recordsets in this reader!
//
BinaryFormatter formatter = new BinaryFormatter();
Dictionary<long, UserTrackingRecord> userEvents = new Dictionary<long, UserTrackingRecord>();
//
// Build a dictionary of activity records so that we can match
// annotation and artifact records from subsequent recordsets
DateTime tmpMin = SqlDateTime.MinValue.Value;
while (reader.Read())
{
string qId = reader.GetString(0);
DateTime dt = reader.GetDateTime(1);
Guid context = reader.GetGuid(2), parentContext = reader.GetGuid(3);
int order = reader.GetInt32(4);
string key = null;
if (!reader.IsDBNull(5))
key = reader.GetString(5);
//
// Get the user data from the serialized column if we can
// Try the string column if serialized column is null
// If both are null the user data was null originally
object userData = null;
if (!reader.IsDBNull(7))
userData = formatter.Deserialize(new MemoryStream((Byte[])reader[7]));
else if (!reader.IsDBNull(6))
userData = reader.GetString(6);
if (reader.IsDBNull(8) || reader.IsDBNull(9))
throw new InvalidOperationException(String.Format(System.Globalization.CultureInfo.CurrentCulture, ExecutionStringManager.SqlTrackingTypeNotFound, qId));
Type type = Type.GetType(reader.GetString(8) + ", " + reader.GetString(9), true, false);
long eventId = reader.GetInt64(10);
DateTime dbDt = reader.GetDateTime(11);
userEvents.Add(eventId, new UserTrackingRecord(type, qId, context, parentContext, dt, order, key, userData));
if (dbDt > tmpMin)
tmpMin = dbDt;
}
if (!reader.NextResult())
throw new ArgumentException(ExecutionStringManager.InvalidUserEventReader);
//
// If we have annotations on the event itself, add them
while (reader.Read())
{
long eventId = reader.GetInt64(0);
string annotation = null;
if (!reader.IsDBNull(1))
annotation = reader.GetString(1);
UserTrackingRecord user = null;
if (userEvents.TryGetValue(eventId, out user))
{
if (null != user)
user.Annotations.Add(annotation);
}
}
if (!reader.NextResult())
throw new ArgumentException(ExecutionStringManager.InvalidUserEventReader);
//
// Build a dictionary of artifact records so that we can match
// annotation records from subsequent recordsets
Dictionary<long, TrackingDataItem> artifacts = new Dictionary<long, TrackingDataItem>();
while (reader.Read())
{
long eventId = reader.GetInt64(0);
long artId = reader.GetInt64(1);
string name = reader.GetString(2), strData = null;
object data = null;
//
// These may both be null
if (!reader.IsDBNull(3))
strData = reader.GetString(3);
if (!reader.IsDBNull(4))
data = formatter.Deserialize(new MemoryStream((Byte[])reader[4]));
TrackingDataItem item = new TrackingDataItem();
item.FieldName = name;
if (null != data)
item.Data = data;
else
item.Data = strData;
artifacts.Add(artId, item);
//
// Find the event to which this artifact belongs and add it to the record
UserTrackingRecord user = null;
if (userEvents.TryGetValue(eventId, out user))
{
if (null != user)
user.Body.Add(item);
}
}
if (!reader.NextResult())
throw new ArgumentException(ExecutionStringManager.InvalidUserEventReader);
//
// If we have annotations add them to the appropriate artifact
while (reader.Read())
{
long artId = reader.GetInt64(0);
string annotation = null;
if (!reader.IsDBNull(1))
annotation = reader.GetString(1);
//
// Find the right artifact and give it the annotation
TrackingDataItem item = null;
if (artifacts.TryGetValue(artId, out item))
{
if (null != item)
item.Annotations.Add(annotation);
}
}
_userEvents.AddRange(userEvents.Values);
//
// Set the min dt to query for next time to the most recent event we got for this query.
// Don't overwrite the previous min if nothing came back for this query
if (tmpMin > SqlDateTime.MinValue.Value)
_userMinDT = tmpMin;
return;
}
private void LoadWorkflowEvents()
{
SqlCommand cmd = CreateInternalIdDateTimeCommand("[dbo].[GetWorkflowInstanceEventsWithDetails]", _instMinDT);
ExecuteRetried(cmd, LoadWorkflowEventsFromReader);
}
private void LoadWorkflowEventsFromReader(SqlDataReader reader, object parameter)
{
if (null == reader)
throw new ArgumentNullException("reader");
//
// There should always be 2 recordsets in this reader!
//
DateTime tmpMin = SqlDateTime.MinValue.Value;
Dictionary<long, WorkflowTrackingRecord> inst = new Dictionary<long, WorkflowTrackingRecord>();
while (reader.Read())
{
TrackingWorkflowEvent evt = (TrackingWorkflowEvent)reader[0];
DateTime dt = reader.GetDateTime(1);
int order = reader.GetInt32(2);
object tmp = null;
EventArgs args = null;
if (!reader.IsDBNull(3))
{
BinaryFormatter formatter = new BinaryFormatter();
tmp = formatter.Deserialize(new MemoryStream((Byte[])reader[3]));
if (tmp is EventArgs)
args = (EventArgs)tmp;
}
long eventId = reader.GetInt64(4);
DateTime dbDt = reader.GetDateTime(5);
inst.Add(eventId, new WorkflowTrackingRecord(evt, dt, order, args));
if (dbDt > tmpMin)
tmpMin = dbDt;
}
if (!reader.NextResult())
throw new ArgumentException(ExecutionStringManager.InvalidWorkflowInstanceEventReader);
//
// Add any annotations
while (reader.Read())
{
long eventId = reader.GetInt64(0);
string annotation = null;
if (!reader.IsDBNull(1))
annotation = reader.GetString(1);
WorkflowTrackingRecord rec = null;
if (inst.TryGetValue(eventId, out rec))
{
if (null != rec)
rec.Annotations.Add(annotation);
}
}
if (!reader.IsClosed)
reader.Close();
//
// Check if we have any WorkflowChange events in this list
// If so pull back the change actions and reconstruct the args property
foreach (KeyValuePair<long, WorkflowTrackingRecord> kvp in inst)
{
WorkflowTrackingRecord rec = kvp.Value;
if (TrackingWorkflowEvent.Changed != rec.TrackingWorkflowEvent)
continue;
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[dbo].[GetWorkflowChangeEventArgs]";
cmd.Parameters.Add(new SqlParameter("@WorkflowInstanceInternalId", _internalId));
cmd.Parameters.Add(new SqlParameter("@BeginDateTime", SqlDateTime.MinValue.Value));
cmd.Parameters.Add(new SqlParameter("@WorkflowInstanceEventId", kvp.Key));
ExecuteRetried(cmd, LoadWorkflowChangeEventArgsFromReader, rec);
}
_workflowEvents.AddRange(inst.Values);
//
// set the min for the next query to the most recent event from this query
// Don't overwrite the previous min if nothing came back for this query
if (tmpMin > SqlDateTime.MinValue.Value)
_instMinDT = tmpMin;
}
private void LoadWorkflowChangeEventArgsFromReader(SqlDataReader reader, object parameter)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == parameter)
throw new ArgumentNullException("parameter");
WorkflowTrackingRecord record = parameter as WorkflowTrackingRecord;
if (null == record)
throw new ArgumentException(ExecutionStringManager.InvalidWorkflowChangeEventArgsParameter, "parameter");
if (!reader.Read())
throw new ArgumentException(ExecutionStringManager.InvalidWorkflowChangeEventArgsReader);
StringReader sr = new StringReader(reader.GetString(0));
//Deserialize the xoml and set the root activity
Activity def = null;
WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
DesignerSerializationManager serializationManager = new DesignerSerializationManager();
IList errors = null;
try
{
using (serializationManager.CreateSession())
{
using (XmlReader xmlReader = XmlReader.Create(sr))
{
def = serializer.Deserialize(serializationManager, xmlReader) as Activity;
errors = serializationManager.Errors;
}
}
}
finally
{
sr.Close();
}
if ((null == def) || ((null != errors) && (errors.Count > 0)))
throw new WorkflowMarkupSerializationException(ExecutionStringManager.WorkflowMarkupDeserializationError);
if (!reader.NextResult())
throw new ArgumentException(ExecutionStringManager.InvalidWorkflowChangeEventArgsReader);
//
// There is a result set that we don't care about for this scenario, skip it
if (!reader.NextResult())
throw new ArgumentException(ExecutionStringManager.InvalidWorkflowChangeEventArgsReader);
List<WorkflowChangeAction> actions = new List<WorkflowChangeAction>();
DateTime currDT = DateTime.MinValue;
int currEventOrder = -1;
int currOrder = -1;
while (reader.Read())
{
DateTime dt = reader.GetDateTime(1);
int eventOrder = reader.GetInt32(2);
int order = reader.GetInt32(3);
//
// Build temp lists as we read the results but
// only save the last set of change actions
if (dt > currDT && eventOrder > currEventOrder)
{
currEventOrder = eventOrder;
currOrder = order;
currDT = dt;
actions = new List<WorkflowChangeAction>();
}
using (sr = new StringReader(reader.GetString(0)))
{
using (serializationManager.CreateSession())
{
using (XmlReader xmlReader = XmlReader.Create(sr))
{
ActivityChangeAction aAction = serializer.Deserialize(serializationManager, xmlReader) as ActivityChangeAction;
errors = serializationManager.Errors;
if (null == aAction)
throw new WorkflowMarkupSerializationException(ExecutionStringManager.WorkflowMarkupDeserializationError);
actions.Add(aAction);
aAction.ApplyTo(def);
}
}
}
}
record.EventArgs = new TrackingWorkflowChangedEventArgs(actions, def);
}
private void LoadDef()
{
SqlCommand cmd = null;
//
// If we don't have the definition load it
if (null == _def)
{
cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[dbo].[GetWorkflowDefinition]";
cmd.Parameters.Add(new SqlParameter("@WorkflowInstanceInternalId", _internalId));
ExecuteRetried(cmd, LoadDefFromReader);
}
//
// Now check for changes. If we find changes apply them to the definition
cmd = CreateInternalIdDateTimeCommand("[dbo].[GetWorkflowChanges]", _changesMinDT);
ExecuteRetried(cmd, LoadChangesFromReader);
}
private void LoadDefFromReader(SqlDataReader reader, object parameter)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (!reader.Read())
throw new ArgumentException(ExecutionStringManager.InvalidDefinitionReader);
StringReader sr = new StringReader(reader.GetString(0));
//Deserialize the xoml and set the root activity
WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
DesignerSerializationManager serializationManager = new DesignerSerializationManager();
IList errors = null;
try
{
using (serializationManager.CreateSession())
{
using (XmlReader xmlReader = XmlReader.Create(sr))
{
_def = serializer.Deserialize(serializationManager, xmlReader) as Activity;
errors = serializationManager.Errors;
}
}
}
finally
{
sr.Close();
}
if ((null == _def) || ((null != errors) && (errors.Count > 0)))
throw new WorkflowMarkupSerializationException(ExecutionStringManager.WorkflowMarkupDeserializationError);
}
private void LoadChangesFromReader(SqlDataReader reader, object parameter)
{
if (!reader.Read())
return;
//
// Reset the min to the most recent change event
DateTime tmpDT = _changesMinDT;
if (!reader.IsDBNull(0))
tmpDT = reader.GetDateTime(0);
if (reader.NextResult())
{
WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
DesignerSerializationManager serializationManager = new DesignerSerializationManager();
while (reader.Read())
{
IList errors = null;
using (StringReader sr = new StringReader(reader.GetString(0)))
{
using (serializationManager.CreateSession())
{
using (XmlReader xmlReader = XmlReader.Create(sr))
{
ActivityChangeAction aAction = serializer.Deserialize(serializationManager, xmlReader) as ActivityChangeAction;
errors = serializationManager.Errors;
if (null != aAction)
aAction.ApplyTo(_def);
else
throw new WorkflowMarkupSerializationException(ExecutionStringManager.WorkflowMarkupDeserializationError);
}
}
}
}
}
if (tmpDT > _changesMinDT)
{
_changed = true;
_changesMinDT = tmpDT;
}
}
private void LoadInvokedWorkflows()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "[dbo].[GetInvokedWorkflows]";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("@WorkflowInstanceId", SqlDbType.UniqueIdentifier);
param.Value = _id;
cmd.Parameters.Add(param);
param = new SqlParameter("@BeginDateTime", SqlDbType.DateTime);
param.Value = _invMinDT;
cmd.Parameters.Add(param);
param = new SqlParameter("@EndDateTime", SqlDbType.DateTime);
param.Value = _currDT;
cmd.Parameters.Add(param);
ExecuteRetried(cmd, LoadInvokedWorkflowsFromReader);
}
private void LoadInvokedWorkflowsFromReader(SqlDataReader reader, object parameter)
{
if (null == reader)
throw new ArgumentNullException("reader");
DateTime tmpMin = SqlDateTime.MinValue.Value;
while (reader.Read())
{
SqlTrackingWorkflowInstance inst = SqlTrackingQuery.BuildInstance(reader, _connectionString);
if (inst.Initialized > tmpMin)
tmpMin = inst.Initialized;
_invoked.Add(inst);
}
//
// set the min for the next query to the most recently invoked instance from this query
// Don't overwrite the previous min if nothing came back for this query
if (tmpMin > SqlDateTime.MinValue.Value)
_invMinDT = tmpMin;
}
private void ExecuteRetried(SqlCommand cmd, LoadFromReader loader)
{
ExecuteRetried(cmd, loader, null);
}
private void ExecuteRetried(SqlCommand cmd, LoadFromReader loader, object loadFromReaderParam)
{
SqlDataReader reader = null;
short count = 0;
while (true)
{
try
{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
cmd.Connection = conn;
cmd.Connection.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
loader(reader, loadFromReaderParam);
break;
}
}
catch (SqlException se)
{
//
// Retry if we deadlocked.
// All other exceptions bubble
if ((_deadlock == se.Number) && (++count < _retries))
continue;
throw;
}
finally
{
if ((null != reader) && (!reader.IsClosed))
reader.Close();
}
}
}
private SqlCommand CreateInternalIdDateTimeCommand(string commandText, DateTime minDT)
{
return CreateInternalIdDateTimeCommand(commandText, minDT, _currDT);
}
private SqlCommand CreateInternalIdDateTimeCommand(string commandText, DateTime minDT, DateTime maxDT)
{
if (null == commandText)
throw new ArgumentNullException("commandText");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = commandText;
//
// Add parameter values for GetActivityEvents
SqlParameter param = new SqlParameter("@WorkflowInstanceInternalId", SqlDbType.BigInt);
param.Value = _internalId;
cmd.Parameters.Add(param);
param = new SqlParameter("@BeginDateTime", SqlDbType.DateTime);
param.Value = minDT;
cmd.Parameters.Add(param);
param = new SqlParameter("@EndDateTime", SqlDbType.DateTime);
param.Value = maxDT;
cmd.Parameters.Add(param);
return cmd;
}
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Collections.Generic;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// A simple ast used to store technique/pass parsing result.
/// </summary>
internal class Ast
{
/// <summary>
/// Root node for all ast objects.
/// </summary>
public class Node
{
public SourceSpan Span;
}
/// <summary>
/// Root node for all expressions.
/// </summary>
public class Expression : Node
{
}
/// <summary>
/// Root node for all statements.
/// </summary>
public class Statement : Node
{
}
/// <summary>
/// An identifier.
/// </summary>
public class Identifier : Node
{
/// <summary>
/// Initializes a new instance of the <see cref="Identifier" /> class.
/// </summary>
public Identifier()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Identifier" /> class.
/// </summary>
/// <param name="text">The name.</param>
public Identifier(string text)
{
Text = text;
}
/// <summary>
/// The identifier as a string.
/// </summary>
public string Text;
/// <summary>
/// Is an indirect reference using <...>.
/// </summary>
public bool IsIndirect;
public override string ToString()
{
return string.Format("{0}", IsIndirect ? "<" + Text + ">" : Text);
}
}
/// <summary>
/// An indexed identifier.
/// </summary>
public class IndexedIdentifier : Identifier
{
/// <summary>
/// Initializes a new instance of the <see cref="IndexedIdentifier" /> class.
/// </summary>
public IndexedIdentifier()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="IndexedIdentifier" /> class.
/// </summary>
/// <param name="text">The name.</param>
/// <param name="index">The index.</param>
public IndexedIdentifier(string text, int index)
{
Text = text;
Index = index;
}
/// <summary>
/// The index
/// </summary>
public int Index;
public override string ToString()
{
var str = string.Format("{0}[{1}]", Text, Index);
return string.Format("{0}", IsIndirect ? "<" + str + ">" : str);
}
}
/// <summary>
/// A literal value.
/// </summary>
public class Literal : Node
{
/// <summary>
/// Initializes a new instance of the <see cref="Literal" /> class.
/// </summary>
public Literal()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Literal" /> class.
/// </summary>
/// <param name="value">The value.</param>
public Literal(object value)
{
Value = value;
}
/// <summary>
/// The literal value.
/// </summary>
public object Value;
public override string ToString()
{
if (Value is string)
{
return string.Format("\"{0}\"", Value);
}
if (Value is bool)
{
return (bool)Value ? "true" : "false";
}
if (Value == null)
{
return "null";
}
return string.Format("{0}", Value);
}
}
/// <summary>
/// An expression statement.
/// </summary>
public class ExpressionStatement : Statement
{
/// <summary>
/// Initializes a new instance of the <see cref="ExpressionStatement" /> class.
/// </summary>
public ExpressionStatement()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ExpressionStatement" /> class.
/// </summary>
/// <param name="expression">The expression.</param>
public ExpressionStatement(Expression expression)
{
Expression = expression;
}
/// <summary>
/// The Expression.
/// </summary>
public Expression Expression;
public override string ToString()
{
return string.Format("{0};", Expression);
}
}
/// <summary>
/// An array initializer {...} expression.
/// </summary>
public class ArrayInitializerExpression : Expression
{
/// <summary>
/// Initializes a new instance of the <see cref="ArrayInitializerExpression" /> class.
/// </summary>
public ArrayInitializerExpression()
{
Values = new List<Expression>();
}
/// <summary>
/// List of values.
/// </summary>
public List<Expression> Values;
public override string ToString()
{
return string.Format("{{{0}}}", Utilities.Join(",", Values));
}
}
/// <summary>
/// A reference to an identifier.
/// </summary>
public class IdentifierExpression : Expression
{
/// <summary>
/// Initializes a new instance of the <see cref="IdentifierExpression" /> class.
/// </summary>
public IdentifierExpression()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="IdentifierExpression" /> class.
/// </summary>
/// <param name="name">The name.</param>
public IdentifierExpression(Identifier name)
{
Name = name;
}
/// <summary>
/// The identifier referenced by this expression.
/// </summary>
public Identifier Name;
public override string ToString()
{
return string.Format("{0}", Name);
}
}
/// <summary>
/// An assign expression name = value.
/// </summary>
public class AssignExpression : Expression
{
/// <summary>
/// Initializes a new instance of the <see cref="AssignExpression" /> class.
/// </summary>
public AssignExpression()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AssignExpression" /> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
public AssignExpression(Identifier name, Expression value)
{
Name = name;
Value = value;
}
/// <summary>
/// The identifier receiver.
/// </summary>
public Identifier Name;
/// <summary>
/// The value to assign.
/// </summary>
public Expression Value;
public override string ToString()
{
return string.Format("{0} = {1}", Name, Value);
}
}
/// <summary>
/// A literal expression.
/// </summary>
public class LiteralExpression : Expression
{
/// <summary>
/// Initializes a new instance of the <see cref="LiteralExpression" /> class.
/// </summary>
public LiteralExpression()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LiteralExpression" /> class.
/// </summary>
/// <param name="value">The value.</param>
public LiteralExpression(Literal value)
{
Value = value;
}
public Literal Value;
public override string ToString()
{
return string.Format("{0}", Value);
}
}
/// <summary>
/// A compile expression (old style d3d9: compile vx_2_0 VS();).
/// </summary>
public class CompileExpression : Expression
{
/// <summary>
/// Initializes a new instance of the <see cref="CompileExpression" /> class.
/// </summary>
public CompileExpression()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CompileExpression" /> class.
/// </summary>
/// <param name="profile"></param>
/// <param name="method"></param>
public CompileExpression(Identifier profile, Expression method)
{
Profile = profile;
Method = method;
}
public Identifier Profile;
public Expression Method;
public override string ToString()
{
return string.Format("compile {0} {1}", Profile, Method);
}
}
/// <summary>
/// A method expression.
/// </summary>
public class MethodExpression : Expression
{
/// <summary>
/// Initializes a new instance of the <see cref="MethodExpression" /> class.
/// </summary>
public MethodExpression()
{
Arguments = new List<Expression>();
}
/// <summary>
/// Name of the method.
/// </summary>
public Identifier Name;
/// <summary>
/// Arguments.
/// </summary>
public List<Expression> Arguments;
public override string ToString()
{
return string.Format("{0}({1})", Name, Utilities.Join(",", Arguments));
}
}
/// <summary>
/// A HLSL 'pass'.
/// </summary>
public class Pass : Node
{
/// <summary>
/// Initializes a new instance of the <see cref="Pass" /> class.
/// </summary>
public Pass()
{
Statements = new List<Statement>();
}
/// <summary>
/// Name of the pass.
/// </summary>
/// <remarks>
/// Can be null.
/// </remarks>
public string Name;
/// <summary>
/// List of statements.
/// </summary>
public List<Statement> Statements;
public override string ToString()
{
return string.Format("pass {0}{{...{1} statement...}}", Name == null ? string.Empty : Name + " ", Statements.Count);
}
}
/// <summary>
/// A HLSL 'technique'.
/// </summary>
public class Technique : Node
{
/// <summary>
/// Initializes a new instance of the <see cref="Technique" /> class.
/// </summary>
public Technique()
{
Passes = new List<Pass>();
}
/// <summary>
/// Name of the technique.
/// </summary>
/// <remarks>
/// Can be null.
/// </remarks>
public string Name;
/// <summary>
/// List of passes.
/// </summary>
public List<Pass> Passes;
public override string ToString()
{
return string.Format("technique {0}{{...{1} pass...}}", Name == null ? string.Empty : Name + " ", Passes.Count);
}
}
/// <summary>
/// Root ast for a shader.
/// </summary>
public class Shader : Node
{
/// <summary>
/// Initializes a new instance of the <see cref="Shader" /> class.
/// </summary>
public Shader()
{
Techniques = new List<Technique>();
}
/// <summary>
/// List of techniques.
/// </summary>
public List<Technique> Techniques;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Xml;
using Microsoft.Build.BuildEngine.Shared;
using MetadataDictionary = System.Collections.Generic.Dictionary<string, string>;
using ItemDefinitionsDictionary = System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, string>>;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// A library of default metadata values by item type.
/// Projects each have exactly one of these.
/// BuildItems consult the appropriate library to check
/// for default metadata values when they do not have an
/// explicit value set.
/// </summary>
internal class ItemDefinitionLibrary
{
#region Fields
Project parentProject;
List<ItemDefinitionLibrary.BuildItemDefinitionGroupXml> itemDefinitions;
ItemDefinitionsDictionary itemDefinitionsDictionary;
bool evaluated;
#endregion
#region Constructors
/// <summary>
/// Creates a new item definition library.
/// The project is required only to give error context.
/// </summary>
internal ItemDefinitionLibrary(Project parentProject)
{
this.parentProject = parentProject;
this.itemDefinitions = new List<BuildItemDefinitionGroupXml>();
this.itemDefinitionsDictionary = new ItemDefinitionsDictionary(StringComparer.OrdinalIgnoreCase);
}
#endregion
#region Properties
internal bool IsEvaluated
{
get { return evaluated; }
}
#endregion
#region Methods
/// <summary>
/// Create a BuildItemDefinitionGroupXml element and add it to the end of our ordered list.
/// </summary>
/// <exception cref="InvalidProjectFileException">If element does not represent a valid ItemDefinitionGroup element</exception>
internal void Add(XmlElement element)
{
BuildItemDefinitionGroupXml itemDefinitionGroupXml = new BuildItemDefinitionGroupXml(element, parentProject);
itemDefinitions.Add(itemDefinitionGroupXml);
evaluated = false;
}
/// <summary>
/// Go through each <BuildItemDefinition> element in order, evaluating it using the
/// supplied properties and any previously evaluated definitions, to build up a complete
/// library of item types and their default metadata values.
/// </summary>
internal void Evaluate(BuildPropertyGroup evaluatedProperties)
{
// Clear out previous data first
itemDefinitionsDictionary.Clear();
foreach (BuildItemDefinitionGroupXml itemDefinitionGroupXml in itemDefinitions)
{
itemDefinitionGroupXml.Evaluate(evaluatedProperties, itemDefinitionsDictionary);
}
evaluated = true;
}
/// <summary>
/// Returns any default metadata value for the specified item type and metadata name.
/// If no default exists, returns null.
/// </summary>
internal string GetDefaultMetadataValue(string itemType, string metadataName)
{
MustBeEvaluated();
string value = null;
MetadataDictionary metadataDictionary;
if (itemDefinitionsDictionary.TryGetValue(itemType, out metadataDictionary))
{
metadataDictionary.TryGetValue(metadataName, out value);
}
return value;
}
/// <summary>
/// Count of default metadata for the specified item type
/// </summary>
internal int GetDefaultedMetadataCount(string itemType)
{
MustBeEvaluated();
MetadataDictionary metadataDictionary;
if (itemDefinitionsDictionary.TryGetValue(itemType, out metadataDictionary))
{
return metadataDictionary.Count;
}
return 0;
}
/// <summary>
/// Names of metadata that have defaults for the specified item type.
/// Null if there are none.
/// </summary>
internal ICollection<string> GetDefaultedMetadataNames(string itemType)
{
MustBeEvaluated();
MetadataDictionary metadataDictionary = GetDefaultedMetadata(itemType);
if (metadataDictionary != null)
{
return metadataDictionary.Keys;
}
return null;
}
/// <summary>
/// All default metadata names and values for the specified item type.
/// Null if there are none.
/// </summary>
internal MetadataDictionary GetDefaultedMetadata(string itemType)
{
MustBeEvaluated();
MetadataDictionary metadataDictionary;
if (itemDefinitionsDictionary.TryGetValue(itemType, out metadataDictionary))
{
return metadataDictionary;
}
return null;
}
/// <summary>
/// Verify this library has already been evaluated
/// </summary>
private void MustBeEvaluated()
{
ErrorUtilities.VerifyThrowNoAssert(evaluated, "Must be evaluated to query");
}
#endregion
/// <summary>
/// Encapsulates an <ItemDefinitionGroup> tag.
/// </summary>
/// <remarks>
/// Only used by ItemDefinitionLibrary -- private and nested inside it as no other class should know about this.
/// Since at present this has no OM or editing support, and is not passed around,
/// there are currently no separate classes for the child tags, and no separate BuildItemDefinitionGroup class.
/// They can be broken out in future if necessary.
/// </remarks>
private class BuildItemDefinitionGroupXml
{
#region Fields
XmlElement element;
Project parentProject;
XmlAttribute conditionAttribute;
string condition;
#endregion
#region Constructors
/// <summary>
/// Read in and validate an <ItemDefinitionGroup> element and all its children.
/// This is currently only called from ItemDefinitionLibrary. Projects don't know about it.
/// </summary>
internal BuildItemDefinitionGroupXml(XmlElement element, Project parentProject)
{
ProjectXmlUtilities.VerifyThrowElementName(element, XMakeElements.itemDefinitionGroup);
ProjectXmlUtilities.VerifyThrowProjectValidNamespace(element);
this.element = element;
this.parentProject = parentProject;
this.conditionAttribute = ProjectXmlUtilities.GetConditionAttribute(element, /* sole attribute */ true);
this.condition = ProjectXmlUtilities.GetAttributeValue(conditionAttribute);
// Currently, don't bother validating the children until evaluation time
}
#endregion
#region Public Methods
/// <summary>
/// Given the properties and dictionary of previously encountered item definitions, evaluates
/// this group of item definitions and adds to the dictionary as necessary.
/// </summary>
/// <exception cref="InvalidProjectFileException">If the item definitions are incorrectly defined</exception>
internal void Evaluate(BuildPropertyGroup properties, ItemDefinitionsDictionary itemDefinitionsDictionary)
{
Expander expander = new Expander(properties);
if (!Utilities.EvaluateCondition(condition, conditionAttribute, expander, ParserOptions.AllowProperties, parentProject))
{
return;
}
List<XmlElement> childElements = ProjectXmlUtilities.GetValidChildElements(element);
foreach (XmlElement child in childElements)
{
EvaluateItemDefinitionElement(child, properties, itemDefinitionsDictionary);
}
}
/// <summary>
/// Given the properties and dictionary of previously encountered item definitions, evaluates
/// this specific item definition element and adds to the dictionary as necessary.
/// </summary>
/// <exception cref="InvalidProjectFileException">If the item definition is incorrectly defined</exception>
private void EvaluateItemDefinitionElement(XmlElement itemDefinitionElement, BuildPropertyGroup properties, ItemDefinitionsDictionary itemDefinitionsDictionary)
{
ProjectXmlUtilities.VerifyThrowProjectValidNameAndNamespace(itemDefinitionElement);
XmlAttribute conditionAttribute = ProjectXmlUtilities.GetConditionAttribute(itemDefinitionElement, /* sole attribute */ true);
string condition = ProjectXmlUtilities.GetAttributeValue(conditionAttribute);
string itemType = itemDefinitionElement.Name;
MetadataDictionary metadataDictionary;
itemDefinitionsDictionary.TryGetValue(itemType, out metadataDictionary);
Expander expander = new Expander(properties, itemType, metadataDictionary);
if (!Utilities.EvaluateCondition(condition, conditionAttribute, expander, ParserOptions.AllowPropertiesAndItemMetadata, parentProject))
{
return;
}
List<XmlElement> childElements = ProjectXmlUtilities.GetValidChildElements(itemDefinitionElement);
foreach (XmlElement child in childElements)
{
EvaluateItemDefinitionChildElement(child, properties, itemDefinitionsDictionary);
}
}
/// <summary>
/// Given the properties and dictionary of previously encountered item definitions, evaluates
/// this specific item definition child element and adds to the dictionary as necessary.
/// </summary>
/// <exception cref="InvalidProjectFileException">If the item definition is incorrectly defined</exception>
private void EvaluateItemDefinitionChildElement(XmlElement itemDefinitionChildElement, BuildPropertyGroup properties, ItemDefinitionsDictionary itemDefinitionsDictionary)
{
ProjectXmlUtilities.VerifyThrowProjectValidNameAndNamespace(itemDefinitionChildElement);
ProjectErrorUtilities.VerifyThrowInvalidProject(!FileUtilities.IsItemSpecModifier(itemDefinitionChildElement.Name), itemDefinitionChildElement, "ItemSpecModifierCannotBeCustomMetadata", itemDefinitionChildElement.Name);
ProjectErrorUtilities.VerifyThrowInvalidProject(XMakeElements.IllegalItemPropertyNames[itemDefinitionChildElement.Name] == null, itemDefinitionChildElement, "CannotModifyReservedItemMetadata", itemDefinitionChildElement.Name);
XmlAttribute conditionAttribute = ProjectXmlUtilities.GetConditionAttribute(itemDefinitionChildElement, /* sole attribute */ true);
string condition = ProjectXmlUtilities.GetAttributeValue(conditionAttribute);
string itemType = itemDefinitionChildElement.ParentNode.Name;
MetadataDictionary metadataDictionary;
itemDefinitionsDictionary.TryGetValue(itemType, out metadataDictionary);
Expander expander = new Expander(properties, itemType, metadataDictionary);
if (!Utilities.EvaluateCondition(condition, conditionAttribute, expander, ParserOptions.AllowPropertiesAndItemMetadata, parentProject))
{
return;
}
string unevaluatedMetadataValue = Utilities.GetXmlNodeInnerContents(itemDefinitionChildElement);
bool containsItemVector = ItemExpander.ExpressionContainsItemVector(unevaluatedMetadataValue);
// We don't allow expressions like @(foo) in the value, as no items exist at this point.
ProjectErrorUtilities.VerifyThrowInvalidProject(!containsItemVector, itemDefinitionChildElement, "MetadataDefinitionCannotContainItemVectorExpression", unevaluatedMetadataValue, itemDefinitionChildElement.Name);
string evaluatedMetadataValue = expander.ExpandAllIntoStringLeaveEscaped(unevaluatedMetadataValue, itemDefinitionChildElement);
if (metadataDictionary == null)
{
metadataDictionary = new MetadataDictionary(StringComparer.OrdinalIgnoreCase);
itemDefinitionsDictionary.Add(itemType, metadataDictionary);
}
// We only store the evaluated value; build items store the unevaluated value as well, but apparently only to
// gather recursive portions (its re-evaluation always goes back to the XML).
// Overwrite any existing default value for this particular metadata
metadataDictionary[itemDefinitionChildElement.Name] = evaluatedMetadataValue;
}
#endregion
}
}
#region Related Types
/// <summary>
/// A limited read-only wrapper around an item definition library,
/// specific to a particular item type.
/// </summary>
internal class SpecificItemDefinitionLibrary
{
string itemType;
ItemDefinitionLibrary itemDefinitionLibrary;
/// <summary>
/// Constructor
/// </summary>
internal SpecificItemDefinitionLibrary(string itemType, ItemDefinitionLibrary itemDefinitionLibrary)
{
this.itemType = itemType;
this.itemDefinitionLibrary = itemDefinitionLibrary;
}
/// <summary>
/// Returns the item type for which this library is specific.
/// </summary>
internal string ItemType
{
get { return itemType; }
}
/// <summary>
/// Get the default if any for the specified metadata name.
/// Returns null if there is none.
/// </summary>
internal string GetDefaultMetadataValue(string metadataName)
{
return itemDefinitionLibrary.GetDefaultMetadataValue(itemType, metadataName);
}
}
#endregion
}
| |
/**
* Lexer.cs
* JSON lexer implementation based on a finite state machine.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace LeaderboardExample
{
internal class FsmContext
{
public bool Return;
public int NextState;
public Lexer L;
public int StateStack;
}
internal class Lexer
{
#region Fields
private delegate bool StateHandler (FsmContext ctx);
private static int[] fsm_return_table;
private static StateHandler[] fsm_handler_table;
private bool allow_comments;
private bool allow_single_quoted_strings;
private bool end_of_input;
private FsmContext fsm_context;
private int input_buffer;
private int input_char;
private TextReader reader;
private int state;
private StringBuilder string_buffer;
private string string_value;
private int token;
private int unichar;
#endregion
#region Properties
public bool AllowComments {
get { return allow_comments; }
set { allow_comments = value; }
}
public bool AllowSingleQuotedStrings {
get { return allow_single_quoted_strings; }
set { allow_single_quoted_strings = value; }
}
public bool EndOfInput {
get { return end_of_input; }
}
public int Token {
get { return token; }
}
public string StringValue {
get { return string_value; }
}
#endregion
#region Constructors
static Lexer ()
{
PopulateFsmTables ();
}
public Lexer (TextReader reader)
{
allow_comments = true;
allow_single_quoted_strings = true;
input_buffer = 0;
string_buffer = new StringBuilder (128);
state = 1;
end_of_input = false;
this.reader = reader;
fsm_context = new FsmContext ();
fsm_context.L = this;
}
#endregion
#region Static Methods
private static int HexValue (int digit)
{
switch (digit) {
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
default:
return digit - '0';
}
}
private static void PopulateFsmTables ()
{
fsm_handler_table = new StateHandler[28] {
State1,
State2,
State3,
State4,
State5,
State6,
State7,
State8,
State9,
State10,
State11,
State12,
State13,
State14,
State15,
State16,
State17,
State18,
State19,
State20,
State21,
State22,
State23,
State24,
State25,
State26,
State27,
State28
};
fsm_return_table = new int[28] {
(int) ParserToken.Char,
0,
(int) ParserToken.Number,
(int) ParserToken.Number,
0,
(int) ParserToken.Number,
0,
(int) ParserToken.Number,
0,
0,
(int) ParserToken.True,
0,
0,
0,
(int) ParserToken.False,
0,
0,
(int) ParserToken.Null,
(int) ParserToken.CharSeq,
(int) ParserToken.Char,
0,
0,
(int) ParserToken.CharSeq,
(int) ParserToken.Char,
0,
0,
0,
0
};
}
private static char ProcessEscChar (int esc_char)
{
switch (esc_char) {
case '"':
case '\'':
case '\\':
case '/':
return Convert.ToChar (esc_char);
case 'n':
return '\n';
case 't':
return '\t';
case 'r':
return '\r';
case 'b':
return '\b';
case 'f':
return '\f';
default:
// Unreachable
return '?';
}
}
private static bool State1 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r')
continue;
if (ctx.L.input_char >= '1' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 3;
return true;
}
switch (ctx.L.input_char) {
case '"':
ctx.NextState = 19;
ctx.Return = true;
return true;
case ',':
case ':':
case '[':
case ']':
case '{':
case '}':
ctx.NextState = 1;
ctx.Return = true;
return true;
case '-':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 2;
return true;
case '0':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 4;
return true;
case 'f':
ctx.NextState = 12;
return true;
case 'n':
ctx.NextState = 16;
return true;
case 't':
ctx.NextState = 9;
return true;
case '\'':
if (! ctx.L.allow_single_quoted_strings)
return false;
ctx.L.input_char = '"';
ctx.NextState = 23;
ctx.Return = true;
return true;
case '/':
if (! ctx.L.allow_comments)
return false;
ctx.NextState = 25;
return true;
default:
return false;
}
}
return true;
}
private static bool State2 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '1' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 3;
return true;
}
switch (ctx.L.input_char) {
case '0':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 4;
return true;
default:
return false;
}
}
private static bool State3 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
private static bool State4 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
private static bool State5 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 6;
return true;
}
return false;
}
private static bool State6 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
private static bool State7 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 8;
return true;
}
switch (ctx.L.input_char) {
case '+':
case '-':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 8;
return true;
default:
return false;
}
}
private static bool State8 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char<= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
return true;
}
private static bool State9 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'r':
ctx.NextState = 10;
return true;
default:
return false;
}
}
private static bool State10 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 11;
return true;
default:
return false;
}
}
private static bool State11 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'e':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State12 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'a':
ctx.NextState = 13;
return true;
default:
return false;
}
}
private static bool State13 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'l':
ctx.NextState = 14;
return true;
default:
return false;
}
}
private static bool State14 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 's':
ctx.NextState = 15;
return true;
default:
return false;
}
}
private static bool State15 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'e':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State16 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 17;
return true;
default:
return false;
}
}
private static bool State17 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'l':
ctx.NextState = 18;
return true;
default:
return false;
}
}
private static bool State18 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'l':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State19 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
switch (ctx.L.input_char) {
case '"':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 20;
return true;
case '\\':
ctx.StateStack = 19;
ctx.NextState = 21;
return true;
default:
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
}
return true;
}
private static bool State20 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case '"':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State21 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 22;
return true;
case '"':
case '\'':
case '/':
case '\\':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
ctx.L.string_buffer.Append (
ProcessEscChar (ctx.L.input_char));
ctx.NextState = ctx.StateStack;
return true;
default:
return false;
}
}
private static bool State22 (FsmContext ctx)
{
int counter = 0;
int mult = 4096;
ctx.L.unichar = 0;
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9' ||
ctx.L.input_char >= 'A' && ctx.L.input_char <= 'F' ||
ctx.L.input_char >= 'a' && ctx.L.input_char <= 'f') {
ctx.L.unichar += HexValue (ctx.L.input_char) * mult;
counter++;
mult /= 16;
if (counter == 4) {
ctx.L.string_buffer.Append (
Convert.ToChar (ctx.L.unichar));
ctx.NextState = ctx.StateStack;
return true;
}
continue;
}
return false;
}
return true;
}
private static bool State23 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
switch (ctx.L.input_char) {
case '\'':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 24;
return true;
case '\\':
ctx.StateStack = 23;
ctx.NextState = 21;
return true;
default:
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
}
return true;
}
private static bool State24 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case '\'':
ctx.L.input_char = '"';
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State25 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case '*':
ctx.NextState = 27;
return true;
case '/':
ctx.NextState = 26;
return true;
default:
return false;
}
}
private static bool State26 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == '\n') {
ctx.NextState = 1;
return true;
}
}
return true;
}
private static bool State27 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == '*') {
ctx.NextState = 28;
return true;
}
}
return true;
}
private static bool State28 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == '*')
continue;
if (ctx.L.input_char == '/') {
ctx.NextState = 1;
return true;
}
ctx.NextState = 27;
return true;
}
return true;
}
#endregion
private bool GetChar ()
{
if ((input_char = NextChar ()) != -1)
return true;
end_of_input = true;
return false;
}
private int NextChar ()
{
if (input_buffer != 0) {
int tmp = input_buffer;
input_buffer = 0;
return tmp;
}
return reader.Read ();
}
public bool NextToken ()
{
StateHandler handler;
fsm_context.Return = false;
while (true) {
handler = fsm_handler_table[state - 1];
if (! handler (fsm_context))
throw new JsonException (input_char);
if (end_of_input)
return false;
if (fsm_context.Return) {
string_value = string_buffer.ToString ();
string_buffer.Remove (0, string_buffer.Length);
token = fsm_return_table[state - 1];
if (token == (int) ParserToken.Char)
token = input_char;
state = fsm_context.NextState;
return true;
}
state = fsm_context.NextState;
}
}
private void UngetChar ()
{
input_buffer = input_char;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
namespace Kvant
{
public class WigTemplate : ScriptableObject
{
#region Public properties
/// Number of segments (editable)
public int segmentCount {
get { return _segmentCount; }
}
[SerializeField] int _segmentCount = 8;
[SerializeField] public int _filamentCount = 1;
/// Number of filaments (read only)
public int filamentCount {
get { return /*_foundation.width*/ _filamentCount; }
}
/// Foundation texture (read only)
public Texture2D foundation {
get { return _foundation; }
}
[SerializeField] Texture2D _foundation;
/// Tmplate mesh (read only)
public Mesh mesh {
get { return _mesh; }
}
[SerializeField] Mesh _mesh;
#endregion
#region Public methods
#if UNITY_EDITOR
// Asset initialization method
public void Initialize(Mesh source)
{
if (_foundation != null)
{
Debug.LogError("Already initialized");
return;
}
// Input vertices
var inVertices = source.vertices;
var inNormals = source.normals;
// Output vertices
var outVertices = new List<Vector3>();
var outNormals = new List<Vector3>();
// Enumerate unique vertices
for (var i = 0; i < inVertices.Length; i++)
{
if (!outVertices.Any(_ => _ == inVertices[i]))
{
outVertices.Add(inVertices[i]);
outNormals.Add(inNormals[i]);
}
}
// Create a texture to store the foundation.
var tex = new Texture2D(outVertices.Count, 2, TextureFormat.RGBAFloat, false);
tex.name = "Wig Foundation";
tex.filterMode = FilterMode.Point;
tex.wrapMode = TextureWrapMode.Clamp;
// Store the vertices into the texture.
for (var i = 0; i < outVertices.Count; i++)
{
var v = outVertices[i];
var n = outNormals[i];
tex.SetPixel(i, 0, new Color(v.x, v.y, v.z, 1));
tex.SetPixel(i, 1, new Color(n.x, n.y, n.z, 0));
}
// Finish up the texture.
tex.Apply(false, true);
_foundation = tex;
// Build the initial template mesh.
RebuildMesh();
}
#endif
// Template mesh rebuild method
public void RebuildMesh()
{
_mesh.Clear();
// The number of vertices in the foundation == texture width
var vcount = _foundation.width;
var length = Mathf.Clamp(_segmentCount, 3, 64);
// Create vertex array for the template.
var vertices = new List<Vector3>();
var normals = new List<Vector3>();
var uvs = new List<Vector2>();
for (var i1 = 0; i1 < vcount; i1++)
{
var u = (i1 + 0.5f) / vcount;
for (var i2 = 0; i2 < length; i2++)
{
var v = (i2 + 0.5f) / length;
for (var i3 = 0; i3 < 8; i3++)
uvs.Add(new Vector2(u, v));
vertices.Add(new Vector3(-1, -1, 0));
vertices.Add(new Vector3(+1, -1, 0));
vertices.Add(new Vector3(+1, -1, 0));
vertices.Add(new Vector3(+1, +1, 0));
vertices.Add(new Vector3(+1, +1, 0));
vertices.Add(new Vector3(-1, +1, 0));
vertices.Add(new Vector3(-1, +1, 0));
vertices.Add(new Vector3(-1, -1, 0));
normals.Add(new Vector3(0, -1, 0));
normals.Add(new Vector3(0, -1, 0));
normals.Add(new Vector3(1, 0, 0));
normals.Add(new Vector3(1, 0, 0));
normals.Add(new Vector3(0, 1, 0));
normals.Add(new Vector3(0, 1, 0));
normals.Add(new Vector3(-1, 0, 0));
normals.Add(new Vector3(-1, 0, 0));
}
}
// Construct a index array of the mesh.
var indices = new List<int>();
var refi = 0;
for (var i1 = 0; i1 < vcount; i1++)
{
for (var i2 = 0; i2 < length - 1; i2++)
{
for (var i3 = 0; i3 < 8; i3 += 2)
{
indices.Add(refi + i3);
indices.Add(refi + i3 + 1);
indices.Add(refi + i3 + 8);
indices.Add(refi + i3 + 1);
indices.Add(refi + i3 + 9);
indices.Add(refi + i3 + 8);
}
refi += 8;
}
refi += 8;
}
// Reset the mesh asset.
_mesh.SetVertices(vertices);
_mesh.SetNormals(normals);
_mesh.SetUVs(0, uvs);
_mesh.SetIndices(indices.ToArray(), MeshTopology.Triangles, 0);
_mesh.bounds = new Bounds(Vector3.zero, Vector3.one * 1000);
_mesh.Optimize();
_mesh.UploadMeshData(true);
}
#endregion
#region ScriptableObject functions
void OnEnable()
{
if (_mesh == null)
{
_mesh = new Mesh();
_mesh.name = "Wig Template";
}
}
void Update()
{
Debug.Log ("caca");
}
#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.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Globalization
{
public partial class CompareInfo
{
[NonSerialized]
private Interop.GlobalizationInterop.SafeSortHandle _sortHandle;
[NonSerialized]
private bool _isAsciiEqualityOrdinal;
private void InitSort(CultureInfo culture)
{
_sortName = culture.SortName;
Interop.GlobalizationInterop.ResultCode resultCode = Interop.GlobalizationInterop.GetSortHandle(GetNullTerminatedUtf8String(_sortName), out _sortHandle);
if (resultCode != Interop.GlobalizationInterop.ResultCode.Success)
{
_sortHandle.Dispose();
if (resultCode == Interop.GlobalizationInterop.ResultCode.OutOfMemory)
throw new OutOfMemoryException();
throw new ExternalException(SR.Arg_ExternalException);
}
_isAsciiEqualityOrdinal = (_sortName == "en-US" || _sortName == "");
}
internal static unsafe int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
if (ignoreCase)
{
fixed (char* pSource = source)
{
int index = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + startIndex, count, findLast: false);
return index != -1 ?
startIndex + index :
-1;
}
}
int endIndex = startIndex + (count - value.Length);
for (int i = startIndex; i <= endIndex; i++)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length)
{
return i;
}
}
return -1;
}
internal static unsafe int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
// startIndex is the index into source where we start search backwards from.
// leftStartIndex is the index into source of the start of the string that is
// count characters away from startIndex.
int leftStartIndex = startIndex - count + 1;
if (ignoreCase)
{
fixed (char* pSource = source)
{
int lastIndex = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + leftStartIndex, count, findLast: true);
return lastIndex != -1 ?
leftStartIndex + lastIndex :
-1;
}
}
for (int i = startIndex - value.Length + 1; i >= leftStartIndex; i--)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length) {
return i;
}
}
return -1;
}
private int GetHashCodeOfStringCore(string source, CompareOptions options)
{
Debug.Assert(source != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0);
}
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
return Interop.GlobalizationInterop.CompareStringOrdinalIgnoreCase(string1, count1, string2, count2);
}
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
Debug.Assert(string1 != null);
Debug.Assert(string2 != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
fixed (char* pString1 = string1)
{
fixed (char* pString2 = string2)
{
return Interop.GlobalizationInterop.CompareString(_sortHandle, pString1 + offset1, length1, pString2 + offset2, length2, options);
}
}
}
internal unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
int index;
if (target.Length == 0)
{
if(matchLengthPtr != null)
*matchLengthPtr = 0;
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
index = IndexOfOrdinal(source, target, startIndex, count, ignoreCase: false);
if(index != -1)
{
if(matchLengthPtr != null)
*matchLengthPtr = target.Length;
}
return index;
}
#if CORECLR
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort())
{
index = IndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
if(index != -1)
{
if(matchLengthPtr != null)
*matchLengthPtr = target.Length;
}
return index;
}
#endif
fixed (char* pSource = source)
{
index = Interop.GlobalizationInterop.IndexOf(_sortHandle, target, target.Length, pSource + startIndex, count, options, matchLengthPtr);
return index != -1 ? index + startIndex : -1;
}
}
private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
return LastIndexOfOrdinal(source, target, startIndex, count, ignoreCase: false);
}
#if CORECLR
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort())
{
return LastIndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
}
#endif
// startIndex is the index into source where we start search backwards from. leftStartIndex is the index into source
// of the start of the string that is count characters away from startIndex.
int leftStartIndex = (startIndex - count + 1);
fixed (char* pSource = source)
{
int lastIndex = Interop.GlobalizationInterop.LastIndexOf(_sortHandle, target, target.Length, pSource + (startIndex - count + 1), count, options);
return lastIndex != -1 ? lastIndex + leftStartIndex : -1;
}
}
private bool StartsWith(string source, string prefix, CompareOptions options)
{
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(!string.IsNullOrEmpty(prefix));
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
#if CORECLR
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && prefix.IsFastSort())
{
return IsPrefix(source, prefix, GetOrdinalCompareOptions(options));
}
#endif
return Interop.GlobalizationInterop.StartsWith(_sortHandle, prefix, prefix.Length, source, source.Length, options);
}
private bool EndsWith(string source, string suffix, CompareOptions options)
{
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(!string.IsNullOrEmpty(suffix));
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
#if CORECLR
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && suffix.IsFastSort())
{
return IsSuffix(source, suffix, GetOrdinalCompareOptions(options));
}
#endif
return Interop.GlobalizationInterop.EndsWith(_sortHandle, suffix, suffix.Length, source, source.Length, options);
}
private unsafe SortKey CreateSortKey(String source, CompareOptions options)
{
if (source==null) { throw new ArgumentNullException(nameof(source)); }
Contract.EndContractBlock();
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
byte [] keyData;
if (source.Length == 0)
{
keyData = Array.Empty<Byte>();
}
else
{
int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, null, 0, options);
keyData = new byte[sortKeyLength];
fixed (byte* pSortKey = keyData)
{
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
}
}
return new SortKey(Name, source, options, keyData);
}
private unsafe static bool IsSortable(char *text, int length)
{
int index = 0;
UnicodeCategory uc;
while (index < length)
{
if (Char.IsHighSurrogate(text[index]))
{
if (index == length - 1 || !Char.IsLowSurrogate(text[index+1]))
return false; // unpaired surrogate
uc = CharUnicodeInfo.InternalGetUnicodeCategory(Char.ConvertToUtf32(text[index], text[index+1]));
if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned)
return false;
index += 2;
continue;
}
if (Char.IsLowSurrogate(text[index]))
{
return false; // unpaired surrogate
}
uc = CharUnicodeInfo.GetUnicodeCategory(text[index]);
if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned)
{
return false;
}
index++;
}
return true;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
{
Debug.Assert(source != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
return 0;
}
int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, null, 0, options);
// As an optimization, for small sort keys we allocate the buffer on the stack.
if (sortKeyLength <= 256)
{
byte* pSortKey = stackalloc byte[sortKeyLength];
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
}
byte[] sortKey = new byte[sortKeyLength];
fixed (byte* pSortKey = &sortKey[0])
{
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
}
}
private static unsafe int InternalHashSortKey(byte* sortKey, int sortKeyLength, bool forceRandomizedHashing, long additionalEntropy)
{
if (forceRandomizedHashing || additionalEntropy != 0)
{
// TODO: Random hashing is yet to be done
// Active Issue: https://github.com/dotnet/corert/issues/2588
throw new NotImplementedException();
}
else
{
int hash1 = 5381;
int hash2 = hash1;
if (sortKeyLength == 0)
{
return 0;
}
if (sortKeyLength == 1)
{
return (((hash1 << 5) + hash1) ^ sortKey[0]) + (hash2 * 1566083941);
}
for (int i = 0; i < (sortKeyLength & ~1); i += 2)
{
hash1 = ((hash1 << 5) + hash1) ^ sortKey[i];
hash2 = ((hash2 << 5) + hash2) ^ sortKey[i+1];
}
return hash1 + (hash2 * 1566083941);
}
}
private static CompareOptions GetOrdinalCompareOptions(CompareOptions options)
{
if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase)
{
return CompareOptions.OrdinalIgnoreCase;
}
else
{
return CompareOptions.Ordinal;
}
}
private static bool CanUseAsciiOrdinalForOptions(CompareOptions options)
{
// Unlike the other Ignore options, IgnoreSymbols impacts ASCII characters (e.g. ').
return (options & CompareOptions.IgnoreSymbols) == 0;
}
private static byte[] GetNullTerminatedUtf8String(string s)
{
int byteLen = System.Text.Encoding.UTF8.GetByteCount(s);
// Allocate an extra byte (which defaults to 0) as the null terminator.
byte[] buffer = new byte[byteLen + 1];
int bytesWritten = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, buffer, 0);
Debug.Assert(bytesWritten == byteLen);
return buffer;
}
private SortVersion GetSortVersion()
{
int sortVersion = Interop.GlobalizationInterop.GetSortVersion();
return new SortVersion(sortVersion, LCID, new Guid(sortVersion, 0, 0, 0, 0, 0, 0,
(byte) (LCID >> 24),
(byte) ((LCID & 0x00FF0000) >> 16),
(byte) ((LCID & 0x0000FF00) >> 8),
(byte) (LCID & 0xFF)));
}
}
}
| |
using System;
using System.Globalization;
using System.Xml;
using JetBrains.Annotations;
using Orchard.Comments.Models;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Aspects;
using Orchard.Services;
using Orchard.Localization;
using Orchard.Comments.Services;
using Orchard.UI.Notify;
namespace Orchard.Comments.Drivers {
[UsedImplicitly]
public class CommentPartDriver : ContentPartDriver<CommentPart> {
private readonly IContentManager _contentManager;
private readonly IWorkContextAccessor _workContextAccessor;
private readonly IClock _clock;
private readonly ICommentService _commentService;
private readonly IOrchardServices _orchardServices;
protected override string Prefix { get { return "Comments"; } }
public Localizer T { get; set; }
public CommentPartDriver(
IContentManager contentManager,
IWorkContextAccessor workContextAccessor,
IClock clock,
ICommentService commentService,
IOrchardServices orchardServices) {
_contentManager = contentManager;
_workContextAccessor = workContextAccessor;
_clock = clock;
_commentService = commentService;
_orchardServices = orchardServices;
T = NullLocalizer.Instance;
}
protected override DriverResult Display(CommentPart part, string displayType, dynamic shapeHelper) {
return Combined(
ContentShape("Parts_Comment", () => shapeHelper.Parts_Comment()),
ContentShape("Parts_Comment_SummaryAdmin", () => shapeHelper.Parts_Comment_SummaryAdmin())
);
}
// GET
protected override DriverResult Editor(CommentPart part, dynamic shapeHelper) {
if (UI.Admin.AdminFilter.IsApplied(_workContextAccessor.GetContext().HttpContext.Request.RequestContext)) {
return ContentShape("Parts_Comment_AdminEdit",
() => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment.AdminEdit", Model: part, Prefix: Prefix));
}
else {
return ContentShape("Parts_Comment_Edit",
() => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment", Model: part, Prefix: Prefix));
}
}
// POST
protected override DriverResult Editor(CommentPart part, IUpdateModel updater, dynamic shapeHelper) {
updater.TryUpdateModel(part, Prefix, null, null);
var workContext = _workContextAccessor.GetContext();
// applying moderate/approve actions
var httpContext = workContext.HttpContext;
var name = httpContext.Request.Form["submit.Save"];
if (!string.IsNullOrEmpty(name) && String.Equals(name, "moderate", StringComparison.OrdinalIgnoreCase)) {
if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) {
_commentService.UnapproveComment(part.Id);
_orchardServices.Notifier.Information(T("Comment successfully moderated."));
return Editor(part, shapeHelper);
}
}
if (!string.IsNullOrEmpty(name) && String.Equals(name, "approve", StringComparison.OrdinalIgnoreCase)) {
if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment"))) {
_commentService.ApproveComment(part.Id);
_orchardServices.Notifier.Information(T("Comment approved."));
return Editor(part, shapeHelper);
}
}
if (!string.IsNullOrEmpty(name) && String.Equals(name, "delete", StringComparison.OrdinalIgnoreCase)) {
if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) {
_commentService.DeleteComment(part.Id);
_orchardServices.Notifier.Information(T("Comment successfully deleted."));
return Editor(part, shapeHelper);
}
}
// if editing from the admin, don't update the owner or the status
if (!string.IsNullOrEmpty(name) && String.Equals(name, "save", StringComparison.OrdinalIgnoreCase)) {
_orchardServices.Notifier.Information(T("Comment saved."));
return Editor(part, shapeHelper);
}
part.CommentDateUtc = _clock.UtcNow;
if (!String.IsNullOrEmpty(part.SiteName) && !part.SiteName.StartsWith("http://") && !part.SiteName.StartsWith("https://")) {
part.SiteName = "http://" + part.SiteName;
}
var currentUser = workContext.CurrentUser;
part.UserName = (currentUser != null ? currentUser.UserName : null);
if (currentUser != null) part.Author = currentUser.UserName;
var moderateComments = workContext.CurrentSite.As<CommentSettingsPart>().ModerateComments;
part.Status = moderateComments ? CommentStatus.Pending : CommentStatus.Approved;
var commentedOn = _contentManager.Get<ICommonPart>(part.CommentedOn);
// prevent users from commenting on a closed thread by hijacking the commentedOn property
var commentsPart = commentedOn.As<CommentsPart>();
if (!commentsPart.CommentsActive) {
_orchardServices.TransactionManager.Cancel();
return Editor(part, shapeHelper);
}
if (commentedOn != null && commentedOn.Container != null) {
part.CommentedOnContainer = commentedOn.Container.ContentItem.Id;
}
commentsPart.Record.CommentPartRecords.Add(part.Record);
return Editor(part, shapeHelper);
}
protected override void Importing(CommentPart part, ContentManagement.Handlers.ImportContentContext context) {
var author = context.Attribute(part.PartDefinition.Name, "Author");
if (author != null) {
part.Record.Author = author;
}
var siteName = context.Attribute(part.PartDefinition.Name, "SiteName");
if (siteName != null) {
part.Record.SiteName = siteName;
}
var userName = context.Attribute(part.PartDefinition.Name, "UserName");
if (userName != null) {
part.Record.UserName = userName;
}
var email = context.Attribute(part.PartDefinition.Name, "Email");
if (email != null) {
part.Record.Email = email;
}
var position = context.Attribute(part.PartDefinition.Name, "Position");
if (position != null) {
part.Record.Position = decimal.Parse(position, CultureInfo.InvariantCulture);
}
var status = context.Attribute(part.PartDefinition.Name, "Status");
if (status != null) {
part.Record.Status = (CommentStatus)Enum.Parse(typeof(CommentStatus), status);
}
var commentDate = context.Attribute(part.PartDefinition.Name, "CommentDateUtc");
if (commentDate != null) {
part.Record.CommentDateUtc = XmlConvert.ToDateTime(commentDate, XmlDateTimeSerializationMode.Utc);
}
var text = context.Attribute(part.PartDefinition.Name, "CommentText");
if (text != null) {
part.Record.CommentText = text;
}
var commentedOn = context.Attribute(part.PartDefinition.Name, "CommentedOn");
if (commentedOn != null) {
var contentItem = context.GetItemFromSession(commentedOn);
if (contentItem != null) {
part.Record.CommentedOn = contentItem.Id;
}
contentItem.As<CommentsPart>().Record.CommentPartRecords.Add(part.Record);
}
var repliedOn = context.Attribute(part.PartDefinition.Name, "RepliedOn");
if (repliedOn != null) {
var contentItem = context.GetItemFromSession(repliedOn);
if (contentItem != null) {
part.Record.RepliedOn = contentItem.Id;
}
}
var commentedOnContainer = context.Attribute(part.PartDefinition.Name, "CommentedOnContainer");
if (commentedOnContainer != null) {
var container = context.GetItemFromSession(commentedOnContainer);
if (container != null) {
part.Record.CommentedOnContainer = container.Id;
}
}
}
protected override void Exporting(CommentPart part, ContentManagement.Handlers.ExportContentContext context) {
context.Element(part.PartDefinition.Name).SetAttributeValue("Author", part.Record.Author);
context.Element(part.PartDefinition.Name).SetAttributeValue("SiteName", part.Record.SiteName);
context.Element(part.PartDefinition.Name).SetAttributeValue("UserName", part.Record.UserName);
context.Element(part.PartDefinition.Name).SetAttributeValue("Email", part.Record.Email);
context.Element(part.PartDefinition.Name).SetAttributeValue("Position", part.Record.Position.ToString(CultureInfo.InvariantCulture));
context.Element(part.PartDefinition.Name).SetAttributeValue("Status", part.Record.Status.ToString());
if (part.Record.CommentDateUtc != null) {
context.Element(part.PartDefinition.Name)
.SetAttributeValue("CommentDateUtc", XmlConvert.ToString(part.Record.CommentDateUtc.Value, XmlDateTimeSerializationMode.Utc));
}
context.Element(part.PartDefinition.Name).SetAttributeValue("CommentText", part.Record.CommentText);
var commentedOn = _contentManager.Get(part.Record.CommentedOn);
if (commentedOn != null) {
var commentedOnIdentity = _contentManager.GetItemMetadata(commentedOn).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOn", commentedOnIdentity.ToString());
}
var commentedOnContainer = _contentManager.Get(part.Record.CommentedOnContainer);
if (commentedOnContainer != null) {
var commentedOnContainerIdentity = _contentManager.GetItemMetadata(commentedOnContainer).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOnContainer", commentedOnContainerIdentity.ToString());
}
if (part.Record.RepliedOn.HasValue) {
var repliedOn = _contentManager.Get(part.Record.RepliedOn.Value);
if (repliedOn != null) {
var repliedOnIdentity = _contentManager.GetItemMetadata(repliedOn).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("RepliedOn", repliedOnIdentity.ToString());
}
}
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Text;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.DataMappers;
using NUnit.Framework;
using Sitecore.Data;
using Sitecore.FakeDb;
namespace Glass.Mapper.Sc.FakeDb.DataMappers
{
public class SitecoreFieldStreamMapperFixture
{
#region Method - GetField
[Test]
public void GetField_FieldContainsData_StreamIsReturned()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var fieldValue = "";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
string expected = "hello world";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(expected));
var mapper = new SitecoreFieldStreamMapper();
using (new ItemEditing(item, true))
{
field.SetBlobStream(stream);
}
//Act
var result = mapper.GetField(field, null, null) as Stream;
//Assert
var reader = new StreamReader(result);
var resultStr = reader.ReadToEnd();
Assert.AreEqual(expected, resultStr);
}
}
//TODO: This requires a FakeDb fix
[Test]
public void GetField_FieldContainsDataTestConnectionLimit_StreamIsReturned()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var fieldValue = "";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
string expected = "hello world";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(expected));
var mapper = new SitecoreFieldStreamMapper();
using (new ItemEditing(item, true))
{
field.SetBlobStream(stream);
}
//Act
var results = new List<Stream>();
for (int i = 0; i < 1000; i++)
{
var result = mapper.GetField(field, null, null) as Stream;
if(result == null)
continue;
results.Add(result);
}
//Assert
Assert.AreEqual(1000, results.Count);
}
}
#endregion
#region Method - SetField
[Test]
public void SetField_StreamPassed_FieldContainsStream()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var fieldValue = "";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
string expected = "hello world";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(expected));
var mapper = new SitecoreFieldStreamMapper();
using (new ItemEditing(item, true))
{
field.SetBlobStream(new MemoryStream());
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, stream, null, null);
}
//Assert
var stream1 = field.GetBlobStream();
stream1.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(stream1);
var resultStr = reader.ReadToEnd();
Assert.AreEqual(expected, resultStr);
}
}
[Test]
public void SetField_NullPassed_NoExceptionThrown()
{
//Assign
var templateId = ID.NewID;
var targetId = ID.NewID;
var fieldName = "Field";
using (Db database = new Db
{
new DbTemplate(templateId)
{
{fieldName, ""}
},
new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
})
{
var fieldValue = "";
var item = database.GetItem("/sitecore/content/Target");
var field = item.Fields[fieldName];
string expected = "hello world";
Stream stream = null;
var mapper = new SitecoreFieldStreamMapper();
using (new ItemEditing(item, true))
{
field.SetBlobStream(new MemoryStream());
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, stream, null, null);
}
//Assert
var outStream = field.GetBlobStream();
Assert.AreEqual(0,outStream.Length);
}
}
#endregion
#region Method - CanHandle
[Test]
public void CanHandle_StreamType_ReturnsTrue()
{
//Assign
var mapper = new SitecoreFieldStreamMapper();
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("Stream");
//Act
var result = mapper.CanHandle(config, null);
//Assert
Assert.IsTrue(result);
}
#endregion
#region Stubs
public class StubClass
{
public Stream Stream { get; set; }
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class FirewallruleProperties : IEquatable<FirewallruleProperties>
{
/// <summary>
/// Initializes a new instance of the <see cref="FirewallruleProperties" /> class.
/// </summary>
public FirewallruleProperties()
{
}
/// <summary>
/// A name of that resource
/// </summary>
/// <value>A name of that resource</value>
[DataMember(Name = "name", EmitDefaultValue = false)]
public string Name { get; set; }
/// <summary>
/// The protocol for the rule. Property cannot be modified after creation (disallowed in update requests)
/// </summary>
/// <value>The protocol for the rule. Property cannot be modified after creation (disallowed in update requests)</value>
[DataMember(Name = "protocol", EmitDefaultValue = false)]
public string Protocol { get; set; }
/// <summary>
/// Only traffic originating from the respective MAC address is allowed. Valid format: aa:bb:cc:dd:ee:ff. Value null allows all source MAC address
/// </summary>
/// <value>Only traffic originating from the respective MAC address is allowed. Valid format: aa:bb:cc:dd:ee:ff. Value null allows all source MAC address</value>
[DataMember(Name = "sourceMac", EmitDefaultValue = false)]
public string SourceMac { get; set; }
/// <summary>
/// Only traffic originating from the respective IPv4 address is allowed. Value null allows all source IPs
/// </summary>
/// <value>Only traffic originating from the respective IPv4 address is allowed. Value null allows all source IPs</value>
[DataMember(Name = "sourceIp", EmitDefaultValue = false)]
public string SourceIp { get; set; }
/// <summary>
/// In case the target NIC has multiple IP addresses, only traffic directed to the respective IP address of the NIC is allowed. Value null allows all target IPs
/// </summary>
/// <value>In case the target NIC has multiple IP addresses, only traffic directed to the respective IP address of the NIC is allowed. Value null allows all target IPs</value>
[DataMember(Name = "targetIp", EmitDefaultValue = false)]
public string TargetIp { get; set; }
/// <summary>
/// Defines the allowed code (from 0 to 254) if protocol ICMP is chosen. Value null allows all codes
/// </summary>
/// <value>Defines the allowed code (from 0 to 254) if protocol ICMP is chosen. Value null allows all codes</value>
[DataMember(Name = "icmpCode", EmitDefaultValue = false)]
public int? IcmpCode { get; set; }
/// <summary>
/// Defines the allowed type (from 0 to 254) if the protocol ICMP is chosen. Value null allows all types
/// </summary>
/// <value>Defines the allowed type (from 0 to 254) if the protocol ICMP is chosen. Value null allows all types</value>
[DataMember(Name = "icmpType", EmitDefaultValue = false)]
public int? IcmpType { get; set; }
/// <summary>
/// Defines the start range of the allowed port (from 1 to 65534) if protocol TCP or UDP is chosen. Leave portRangeStart and portRangeEnd value null to allow all ports
/// </summary>
/// <value>Defines the start range of the allowed port (from 1 to 65534) if protocol TCP or UDP is chosen. Leave portRangeStart and portRangeEnd value null to allow all ports</value>
[DataMember(Name = "portRangeStart", EmitDefaultValue = false)]
public int? PortRangeStart { get; set; }
/// <summary>
/// Defines the end range of the allowed port (from 1 to 65534) if the protocol TCP or UDP is chosen. Leave portRangeStart and portRangeEnd null to allow all ports
/// </summary>
/// <value>Defines the end range of the allowed port (from 1 to 65534) if the protocol TCP or UDP is chosen. Leave portRangeStart and portRangeEnd null to allow all ports</value>
[DataMember(Name = "portRangeEnd", EmitDefaultValue = false)]
public int? PortRangeEnd { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class FirewallruleProperties {\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Protocol: ").Append(Protocol).Append("\n");
sb.Append(" SourceMac: ").Append(SourceMac).Append("\n");
sb.Append(" SourceIp: ").Append(SourceIp).Append("\n");
sb.Append(" TargetIp: ").Append(TargetIp).Append("\n");
sb.Append(" IcmpCode: ").Append(IcmpCode).Append("\n");
sb.Append(" IcmpType: ").Append(IcmpType).Append("\n");
sb.Append(" PortRangeStart: ").Append(PortRangeStart).Append("\n");
sb.Append(" PortRangeEnd: ").Append(PortRangeEnd).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as FirewallruleProperties);
}
/// <summary>
/// Returns true if FirewallruleProperties instances are equal
/// </summary>
/// <param name="other">Instance of FirewallruleProperties to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FirewallruleProperties other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Protocol == other.Protocol ||
this.Protocol != null &&
this.Protocol.Equals(other.Protocol)
) &&
(
this.SourceMac == other.SourceMac ||
this.SourceMac != null &&
this.SourceMac.Equals(other.SourceMac)
) &&
(
this.SourceIp == other.SourceIp ||
this.SourceIp != null &&
this.SourceIp.Equals(other.SourceIp)
) &&
(
this.TargetIp == other.TargetIp ||
this.TargetIp != null &&
this.TargetIp.Equals(other.TargetIp)
) &&
(
this.IcmpCode == other.IcmpCode ||
this.IcmpCode != null &&
this.IcmpCode.Equals(other.IcmpCode)
) &&
(
this.IcmpType == other.IcmpType ||
this.IcmpType != null &&
this.IcmpType.Equals(other.IcmpType)
) &&
(
this.PortRangeStart == other.PortRangeStart ||
this.PortRangeStart != null &&
this.PortRangeStart.Equals(other.PortRangeStart)
) &&
(
this.PortRangeEnd == other.PortRangeEnd ||
this.PortRangeEnd != null &&
this.PortRangeEnd.Equals(other.PortRangeEnd)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Protocol != null)
hash = hash * 59 + this.Protocol.GetHashCode();
if (this.SourceMac != null)
hash = hash * 59 + this.SourceMac.GetHashCode();
if (this.SourceIp != null)
hash = hash * 59 + this.SourceIp.GetHashCode();
if (this.TargetIp != null)
hash = hash * 59 + this.TargetIp.GetHashCode();
if (this.IcmpCode != null)
hash = hash * 59 + this.IcmpCode.GetHashCode();
if (this.IcmpType != null)
hash = hash * 59 + this.IcmpType.GetHashCode();
if (this.PortRangeStart != null)
hash = hash * 59 + this.PortRangeStart.GetHashCode();
if (this.PortRangeEnd != null)
hash = hash * 59 + this.PortRangeEnd.GetHashCode();
return hash;
}
}
}
}
| |
// 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.Xml.XPath;
using System.Diagnostics;
using System.Globalization;
namespace System.Xml
{
/// <summary>
/// Contains various static functions and methods for parsing and validating:
/// NCName (not namespace-aware, no colons allowed)
/// QName (prefix:local-name)
/// </summary>
internal static class ValidateNames
{
internal enum Flags
{
NCNames = 0x1, // Validate that each non-empty prefix and localName is a valid NCName
CheckLocalName = 0x2, // Validate the local-name
CheckPrefixMapping = 0x4, // Validate the prefix --> namespace mapping
All = 0x7,
AllExceptNCNames = 0x6,
AllExceptPrefixMapping = 0x3,
};
private static XmlCharType s_xmlCharType = XmlCharType.Instance;
//-----------------------------------------------
// Nmtoken parsing
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as an Nmtoken (see the XML spec production [7] && XML Namespaces spec).
/// Quits parsing when an invalid Nmtoken char is reached or the end of string is reached.
/// Returns the number of valid Nmtoken chars that were parsed.
/// </summary>
internal static unsafe int ParseNmtoken(string s, int offset)
{
Debug.Assert(s != null && offset <= s.Length);
// Keep parsing until the end of string or an invalid NCName character is reached
int i = offset;
while (i < s.Length)
{
if (s_xmlCharType.IsNCNameSingleChar(s[i]))
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i)) {
i += 2;
}
#endif
else
{
break;
}
}
return i - offset;
}
//-----------------------------------------------
// Nmtoken parsing (no XML namespaces support)
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as an Nmtoken (see the XML spec production [7]) without taking
/// into account the XML Namespaces spec. What it means is that the ':' character is allowed at any
/// position and any number of times in the token.
/// Quits parsing when an invalid Nmtoken char is reached or the end of string is reached.
/// Returns the number of valid Nmtoken chars that were parsed.
/// </summary>
[System.Security.SecuritySafeCritical]
internal static unsafe int ParseNmtokenNoNamespaces(string s, int offset)
{
Debug.Assert(s != null && offset <= s.Length);
// Keep parsing until the end of string or an invalid Name character is reached
int i = offset;
while (i < s.Length)
{
if (s_xmlCharType.IsNameSingleChar(s[i]) || s[i] == ':')
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i))
{
i += 2;
}
#endif
else
{
break;
}
}
return i - offset;
}
// helper methods
internal static bool IsNmtokenNoNamespaces(string s)
{
int endPos = ParseNmtokenNoNamespaces(s, 0);
return endPos > 0 && endPos == s.Length;
}
//-----------------------------------------------
// Name parsing (no XML namespaces support)
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as a Name without taking into account the XML Namespaces spec.
/// What it means is that the ':' character does not delimiter prefix and local name, but it is a regular
/// name character, which is allowed to appear at any position and any number of times in the name.
/// Quits parsing when an invalid Name char is reached or the end of string is reached.
/// Returns the number of valid Name chars that were parsed.
/// </summary>
[System.Security.SecuritySafeCritical]
internal static unsafe int ParseNameNoNamespaces(string s, int offset)
{
Debug.Assert(s != null && offset <= s.Length);
// Quit if the first character is not a valid NCName starting character
int i = offset;
if (i < s.Length)
{
if (s_xmlCharType.IsStartNCNameSingleChar(s[i]) || s[i] == ':')
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i))
{
i += 2;
}
#endif
else
{
return 0; // no valid StartNCName char
}
// Keep parsing until the end of string or an invalid NCName character is reached
while (i < s.Length)
{
if (s_xmlCharType.IsNCNameSingleChar(s[i]) || s[i] == ':')
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i))
{
i += 2;
}
#endif
else
{
break;
}
}
}
return i - offset;
}
// helper methods
internal static bool IsNameNoNamespaces(string s)
{
int endPos = ParseNameNoNamespaces(s, 0);
return endPos > 0 && endPos == s.Length;
}
//-----------------------------------------------
// NCName parsing
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as an NCName (see the XML Namespace spec).
/// Quits parsing when an invalid NCName char is reached or the end of string is reached.
/// Returns the number of valid NCName chars that were parsed.
/// </summary>
[System.Security.SecuritySafeCritical]
internal static unsafe int ParseNCName(string s, int offset)
{
Debug.Assert(s != null && offset <= s.Length);
// Quit if the first character is not a valid NCName starting character
int i = offset;
if (i < s.Length)
{
if (s_xmlCharType.IsStartNCNameSingleChar(s[i]))
{
i++;
}
#if XML10_FIFTH_EDITION
else if (s_xmlCharType.IsNCNameSurrogateChar(s, i)) {
i += 2;
}
#endif
else
{
return 0; // no valid StartNCName char
}
// Keep parsing until the end of string or an invalid NCName character is reached
while (i < s.Length)
{
if (s_xmlCharType.IsNCNameSingleChar(s[i]))
{
i++;
}
#if XML10_FIFTH_EDITION
else if (s_xmlCharType.IsNCNameSurrogateChar(s, i)) {
i += 2;
}
#endif
else
{
break;
}
}
}
return i - offset;
}
internal static int ParseNCName(string s)
{
return ParseNCName(s, 0);
}
/// <summary>
/// Calls parseName and throws exception if the resulting name is not a valid NCName.
/// Returns the input string if there is no error.
/// </summary>
internal static string ParseNCNameThrow(string s)
{
// throwOnError = true
ParseNCNameInternal(s, true);
return s;
}
/// <summary>
/// Calls parseName and returns false or throws exception if the resulting name is not
/// a valid NCName. Returns the input string if there is no error.
/// </summary>
private static bool ParseNCNameInternal(string s, bool throwOnError)
{
int len = ParseNCName(s, 0);
if (len == 0 || len != s.Length)
{
// If the string is not a valid NCName, then throw or return false
if (throwOnError) ThrowInvalidName(s, 0, len);
return false;
}
return true;
}
//-----------------------------------------------
// QName parsing
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as a QName (see the XML Namespace spec).
/// Quits parsing when an invalid QName char is reached or the end of string is reached.
/// Returns the number of valid QName chars that were parsed.
/// Sets colonOffset to the offset of a colon character if it exists, or 0 otherwise.
/// </summary>
internal static int ParseQName(string s, int offset, out int colonOffset)
{
int len, lenLocal;
// Assume no colon
colonOffset = 0;
// Parse NCName (may be prefix, may be local name)
len = ParseNCName(s, offset);
if (len != 0)
{
// Non-empty NCName, so look for colon if there are any characters left
offset += len;
if (offset < s.Length && s[offset] == ':')
{
// First NCName was prefix, so look for local name part
lenLocal = ParseNCName(s, offset + 1);
if (lenLocal != 0)
{
// Local name part found, so increase total QName length (add 1 for colon)
colonOffset = offset;
len += lenLocal + 1;
}
}
}
return len;
}
/// <summary>
/// Calls parseQName and throws exception if the resulting name is not a valid QName.
/// Returns the prefix and local name parts.
/// </summary>
internal static void ParseQNameThrow(string s, out string prefix, out string localName)
{
int colonOffset;
int len = ParseQName(s, 0, out colonOffset);
if (len == 0 || len != s.Length)
{
// If the string is not a valid QName, then throw
ThrowInvalidName(s, 0, len);
}
if (colonOffset != 0)
{
prefix = s.Substring(0, colonOffset);
localName = s.Substring(colonOffset + 1);
}
else
{
prefix = "";
localName = s;
}
}
/// <summary>
/// Parses the input string as a NameTest (see the XPath spec), returning the prefix and
/// local name parts. Throws an exception if the given string is not a valid NameTest.
/// If the NameTest contains a star, null values for localName (case NCName':*'), or for
/// both localName and prefix (case '*') are returned.
/// </summary>
internal static void ParseNameTestThrow(string s, out string prefix, out string localName)
{
int len, lenLocal, offset;
if (s.Length != 0 && s[0] == '*')
{
// '*' as a NameTest
prefix = localName = null;
len = 1;
}
else
{
// Parse NCName (may be prefix, may be local name)
len = ParseNCName(s, 0);
if (len != 0)
{
// Non-empty NCName, so look for colon if there are any characters left
localName = s.Substring(0, len);
if (len < s.Length && s[len] == ':')
{
// First NCName was prefix, so look for local name part
prefix = localName;
offset = len + 1;
if (offset < s.Length && s[offset] == '*')
{
// '*' as a local name part, add 2 to len for colon and star
localName = null;
len += 2;
}
else
{
lenLocal = ParseNCName(s, offset);
if (lenLocal != 0)
{
// Local name part found, so increase total NameTest length
localName = s.Substring(offset, lenLocal);
len += lenLocal + 1;
}
}
}
else
{
prefix = string.Empty;
}
}
else
{
// Make the compiler happy
prefix = localName = null;
}
}
if (len == 0 || len != s.Length)
{
// If the string is not a valid NameTest, then throw
ThrowInvalidName(s, 0, len);
}
}
/// <summary>
/// Throws an invalid name exception.
/// </summary>
/// <param name="s">String that was parsed.</param>
/// <param name="offsetStartChar">Offset in string where parsing began.</param>
/// <param name="offsetBadChar">Offset in string where parsing failed.</param>
internal static void ThrowInvalidName(string s, int offsetStartChar, int offsetBadChar)
{
// If the name is empty, throw an exception
if (offsetStartChar >= s.Length)
throw new XmlException(SR.Format(SR.Xml_EmptyName, string.Empty));
Debug.Assert(offsetBadChar < s.Length);
if (s_xmlCharType.IsNCNameSingleChar(s[offsetBadChar]) && !XmlCharType.Instance.IsStartNCNameSingleChar(s[offsetBadChar]))
{
// The error character is a valid name character, but is not a valid start name character
throw new XmlException(SR.Xml_BadStartNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar));
}
else
{
// The error character is an invalid name character
throw new XmlException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar));
}
}
internal static Exception GetInvalidNameException(string s, int offsetStartChar, int offsetBadChar)
{
// If the name is empty, throw an exception
if (offsetStartChar >= s.Length)
return new XmlException(SR.Xml_EmptyName, string.Empty);
Debug.Assert(offsetBadChar < s.Length);
if (s_xmlCharType.IsNCNameSingleChar(s[offsetBadChar]) && !s_xmlCharType.IsStartNCNameSingleChar(s[offsetBadChar]))
{
// The error character is a valid name character, but is not a valid start name character
return new XmlException(SR.Xml_BadStartNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar));
}
else
{
// The error character is an invalid name character
return new XmlException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar));
}
}
/// <summary>
/// Returns true if "prefix" starts with the characters 'x', 'm', 'l' (case-insensitive).
/// </summary>
internal static bool StartsWithXml(string s)
{
if (s.Length < 3)
return false;
if (s[0] != 'x' && s[0] != 'X')
return false;
if (s[1] != 'm' && s[1] != 'M')
return false;
if (s[2] != 'l' && s[2] != 'L')
return false;
return true;
}
/// <summary>
/// Returns true if "s" is a namespace that is reserved by Xml 1.0 or Namespace 1.0.
/// </summary>
internal static bool IsReservedNamespace(string s)
{
return s.Equals(XmlReservedNs.NsXml) || s.Equals(XmlReservedNs.NsXmlNs);
}
/// <summary>
/// Throw if the specified name parts are not valid according to the rules of "nodeKind". Check only rules that are
/// specified by the Flags.
/// NOTE: Namespaces should be passed using a prefix, ns pair. "localName" is always string.Empty.
/// </summary>
internal static void ValidateNameThrow(string prefix, string localName, string ns, XPathNodeType nodeKind, Flags flags)
{
// throwOnError = true
ValidateNameInternal(prefix, localName, ns, nodeKind, flags, true);
}
/// <summary>
/// Return false if the specified name parts are not valid according to the rules of "nodeKind". Check only rules that are
/// specified by the Flags.
/// NOTE: Namespaces should be passed using a prefix, ns pair. "localName" is always string.Empty.
/// </summary>
internal static bool ValidateName(string prefix, string localName, string ns, XPathNodeType nodeKind, Flags flags)
{
// throwOnError = false
return ValidateNameInternal(prefix, localName, ns, nodeKind, flags, false);
}
/// <summary>
/// Return false or throw if the specified name parts are not valid according to the rules of "nodeKind". Check only rules
/// that are specified by the Flags.
/// NOTE: Namespaces should be passed using a prefix, ns pair. "localName" is always string.Empty.
/// </summary>
private static bool ValidateNameInternal(string prefix, string localName, string ns, XPathNodeType nodeKind, Flags flags, bool throwOnError)
{
Debug.Assert(prefix != null && localName != null && ns != null);
if ((flags & Flags.NCNames) != 0)
{
// 1. Verify that each non-empty prefix and localName is a valid NCName
if (prefix.Length != 0)
if (!ParseNCNameInternal(prefix, throwOnError))
{
return false;
}
if (localName.Length != 0)
if (!ParseNCNameInternal(localName, throwOnError))
{
return false;
}
}
if ((flags & Flags.CheckLocalName) != 0)
{
// 2. Determine whether the local name is valid
switch (nodeKind)
{
case XPathNodeType.Element:
// Elements and attributes must have a non-empty local name
if (localName.Length == 0)
{
if (throwOnError) throw new XmlException(SR.Xdom_Empty_LocalName, string.Empty);
return false;
}
break;
case XPathNodeType.Attribute:
// Attribute local name cannot be "xmlns" if namespace is empty
if (ns.Length == 0 && localName.Equals("xmlns"))
{
if (throwOnError) throw new XmlException(SR.XmlBadName, new string[] { nodeKind.ToString(), localName });
return false;
}
goto case XPathNodeType.Element;
case XPathNodeType.ProcessingInstruction:
// PI's local-name must be non-empty and cannot be 'xml' (case-insensitive)
if (localName.Length == 0 || (localName.Length == 3 && StartsWithXml(localName)))
{
if (throwOnError) throw new XmlException(SR.Xml_InvalidPIName, localName);
return false;
}
break;
default:
// All other node types must have empty local-name
if (localName.Length != 0)
{
if (throwOnError) throw new XmlException(SR.XmlNoNameAllowed, nodeKind.ToString());
return false;
}
break;
}
}
if ((flags & Flags.CheckPrefixMapping) != 0)
{
// 3. Determine whether the prefix is valid
switch (nodeKind)
{
case XPathNodeType.Element:
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
if (ns.Length == 0)
{
// If namespace is empty, then prefix must be empty
if (prefix.Length != 0)
{
if (throwOnError) throw new XmlException(SR.Xml_PrefixForEmptyNs, string.Empty);
return false;
}
}
else
{
// Don't allow empty attribute prefix since namespace is non-empty
if (prefix.Length == 0 && nodeKind == XPathNodeType.Attribute)
{
if (throwOnError) throw new XmlException(SR.XmlBadName, new string[] { nodeKind.ToString(), localName });
return false;
}
if (prefix.Equals("xml"))
{
// xml prefix must be mapped to the xml namespace
if (!ns.Equals(XmlReservedNs.NsXml))
{
if (throwOnError) throw new XmlException(SR.Xml_XmlPrefix, string.Empty);
return false;
}
}
else if (prefix.Equals("xmlns"))
{
// Prefix may never be 'xmlns'
if (throwOnError) throw new XmlException(SR.Xml_XmlnsPrefix, string.Empty);
return false;
}
else if (IsReservedNamespace(ns))
{
// Don't allow non-reserved prefixes to map to xml or xmlns namespaces
if (throwOnError) throw new XmlException(SR.Xml_NamespaceDeclXmlXmlns, string.Empty);
return false;
}
}
break;
case XPathNodeType.ProcessingInstruction:
// PI's prefix and namespace must be empty
if (prefix.Length != 0 || ns.Length != 0)
{
if (throwOnError) throw new XmlException(SR.Xml_InvalidPIName, CreateName(prefix, localName));
return false;
}
break;
default:
// All other node types must have empty prefix and namespace
if (prefix.Length != 0 || ns.Length != 0)
{
if (throwOnError) throw new XmlException(SR.XmlNoNameAllowed, nodeKind.ToString());
return false;
}
break;
}
}
return true;
}
/// <summary>
/// Creates a colon-delimited qname from prefix and local name parts.
/// </summary>
private static string CreateName(string prefix, string localName)
{
return (prefix.Length != 0) ? prefix + ":" + localName : localName;
}
/// <summary>
/// Split a QualifiedName into prefix and localname, w/o any checking.
/// (Used for XmlReader/XPathNavigator MoveTo(name) methods)
/// </summary>
internal static void SplitQName(string name, out string prefix, out string lname)
{
int colonPos = name.IndexOf(':');
if (-1 == colonPos)
{
prefix = string.Empty;
lname = name;
}
else if (0 == colonPos || (name.Length - 1) == colonPos)
{
throw new ArgumentException(SR.Format(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(':', '\0')), nameof(name));
}
else
{
prefix = name.Substring(0, colonPos);
colonPos++; // move after colon
lname = name.Substring(colonPos, name.Length - colonPos);
}
}
}
}
| |
//-------------------------------------------------------------------------------
// <copyright file="StateBuilder.cs" company="Appccelerate">
// Copyright (c) 2008-2019 Appccelerate
//
// 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.
// </copyright>
//-------------------------------------------------------------------------------
namespace Appccelerate.StateMachine.Machine
{
using System;
using System.Linq;
using Events;
using States;
using Syntax;
using Transitions;
/// <summary>
/// Provides operations to build a state machine.
/// </summary>
/// <typeparam name="TState">The type of the state.</typeparam>
/// <typeparam name="TEvent">The type of the event.</typeparam>
public sealed class StateBuilder<TState, TEvent> :
IEntryActionSyntax<TState, TEvent>,
IGotoInIfSyntax<TState, TEvent>,
IOtherwiseSyntax<TState, TEvent>,
IIfOrOtherwiseSyntax<TState, TEvent>,
IGotoSyntax<TState, TEvent>,
IIfSyntax<TState, TEvent>,
IOnSyntax<TState, TEvent>
where TState : IComparable
where TEvent : IComparable
{
private readonly StateDefinition<TState, TEvent> stateDefinition;
private readonly IImplicitAddIfNotAvailableStateDefinitionDictionary<TState, TEvent> stateDefinitionDictionary;
private readonly IFactory<TState, TEvent> factory;
private TransitionDefinition<TState, TEvent> currentTransitionDefinition;
private TEvent currentEventId;
public StateBuilder(
TState stateId,
IImplicitAddIfNotAvailableStateDefinitionDictionary<TState, TEvent> stateDefinitionDictionary,
IFactory<TState, TEvent> factory)
{
this.stateDefinitionDictionary = stateDefinitionDictionary;
this.factory = factory;
this.stateDefinition = this.stateDefinitionDictionary[stateId];
}
/// <summary>
/// Defines entry actions.
/// </summary>
/// <param name="action">The action.</param>
/// <returns>Exit action syntax.</returns>
IEntryActionSyntax<TState, TEvent> IEntryActionSyntax<TState, TEvent>.ExecuteOnEntry(Action action)
{
Guard.AgainstNullArgument("action", action);
this.stateDefinition.EntryActionsModifiable.Add(this.factory.CreateActionHolder(action));
return this;
}
public IEntryActionSyntax<TState, TEvent> ExecuteOnEntry<T>(Action<T> action)
{
Guard.AgainstNullArgument("action", action);
this.stateDefinition.EntryActionsModifiable.Add(this.factory.CreateActionHolder(action));
return this;
}
/// <summary>
/// Defines an entry action.
/// </summary>
/// <typeparam name="T">Type of the parameter of the entry action method.</typeparam>
/// <param name="action">The action.</param>
/// <param name="parameter">The parameter that will be passed to the entry action.</param>
/// <returns>Exit action syntax.</returns>
IEntryActionSyntax<TState, TEvent> IEntryActionSyntax<TState, TEvent>.ExecuteOnEntryParametrized<T>(Action<T> action, T parameter)
{
this.stateDefinition.EntryActionsModifiable.Add(this.factory.CreateActionHolder(action, parameter));
return this;
}
/// <summary>
/// Defines an exit action.
/// </summary>
/// <param name="action">The action.</param>
/// <returns>Event syntax.</returns>
IExitActionSyntax<TState, TEvent> IExitActionSyntax<TState, TEvent>.ExecuteOnExit(Action action)
{
Guard.AgainstNullArgument("action", action);
this.stateDefinition.ExitActionsModifiable.Add(this.factory.CreateActionHolder(action));
return this;
}
public IExitActionSyntax<TState, TEvent> ExecuteOnExit<T>(Action<T> action)
{
Guard.AgainstNullArgument("action", action);
this.stateDefinition.ExitActionsModifiable.Add(this.factory.CreateActionHolder(action));
return this;
}
/// <summary>
/// Defines an exit action.
/// </summary>
/// <typeparam name="T">Type of the parameter of the exit action method.</typeparam>
/// <param name="action">The action.</param>
/// <param name="parameter">The parameter that will be passed to the exit action.</param>
/// <returns>Exit action syntax.</returns>
IExitActionSyntax<TState, TEvent> IExitActionSyntax<TState, TEvent>.ExecuteOnExitParametrized<T>(Action<T> action, T parameter)
{
this.stateDefinition.ExitActionsModifiable.Add(this.factory.CreateActionHolder(action, parameter));
return this;
}
/// <summary>
/// Builds a transition.
/// </summary>
/// <param name="eventId">The event that triggers the transition.</param>
/// <returns>Syntax to build the transition.</returns>
IOnSyntax<TState, TEvent> IEventSyntax<TState, TEvent>.On(TEvent eventId)
{
this.currentEventId = eventId;
this.CreateTransition();
return this;
}
private void CreateTransition()
{
this.currentTransitionDefinition = new TransitionDefinition<TState, TEvent>();
this.stateDefinition.TransitionsModifiable.Add(this.currentEventId, this.currentTransitionDefinition);
}
/// <summary>
/// Defines where to go in response to an event.
/// </summary>
/// <param name="target">The target.</param>
/// <returns>Execute syntax.</returns>
IGotoSyntax<TState, TEvent> IOnSyntax<TState, TEvent>.Goto(TState target)
{
this.SetTargetState(target);
return this;
}
IGotoSyntax<TState, TEvent> IOtherwiseSyntax<TState, TEvent>.Goto(TState target)
{
this.SetTargetState(target);
return this;
}
IGotoInIfSyntax<TState, TEvent> IIfSyntax<TState, TEvent>.Goto(TState target)
{
this.SetTargetState(target);
return this;
}
IOtherwiseExecuteSyntax<TState, TEvent> IOtherwiseExecuteSyntax<TState, TEvent>.Execute(Action action)
{
return this.ExecuteInternal(action);
}
IOtherwiseExecuteSyntax<TState, TEvent> IOtherwiseExecuteSyntax<TState, TEvent>.Execute<T>(Action<T> action)
{
return this.ExecuteInternal(action);
}
IGotoInIfSyntax<TState, TEvent> IGotoInIfSyntax<TState, TEvent>.Execute(Action action)
{
return this.ExecuteInternal(action);
}
IGotoInIfSyntax<TState, TEvent> IGotoInIfSyntax<TState, TEvent>.Execute<T>(Action<T> action)
{
return this.ExecuteInternal(action);
}
IGotoSyntax<TState, TEvent> IGotoSyntax<TState, TEvent>.Execute(Action action)
{
return this.ExecuteInternal(action);
}
IGotoSyntax<TState, TEvent> IGotoSyntax<TState, TEvent>.Execute<T>(Action<T> action)
{
return this.ExecuteInternal(action);
}
IIfOrOtherwiseSyntax<TState, TEvent> IIfSyntax<TState, TEvent>.Execute(Action action)
{
return this.ExecuteInternal(action);
}
IIfOrOtherwiseSyntax<TState, TEvent> IIfSyntax<TState, TEvent>.Execute<T>(Action<T> action)
{
return this.ExecuteInternal(action);
}
IOnExecuteSyntax<TState, TEvent> IOnExecuteSyntax<TState, TEvent>.Execute(Action action)
{
return this.ExecuteInternal(action);
}
IOnExecuteSyntax<TState, TEvent> IOnExecuteSyntax<TState, TEvent>.Execute<T>(Action<T> action)
{
return this.ExecuteInternal(action);
}
IIfSyntax<TState, TEvent> IGotoInIfSyntax<TState, TEvent>.If<T>(Func<T, bool> guard)
{
this.CreateTransition();
this.SetGuard(guard);
return this;
}
IIfSyntax<TState, TEvent> IGotoInIfSyntax<TState, TEvent>.If(Func<bool> guard)
{
this.CreateTransition();
this.SetGuard(guard);
return this;
}
IOtherwiseSyntax<TState, TEvent> IGotoInIfSyntax<TState, TEvent>.Otherwise()
{
this.CreateTransition();
return this;
}
IIfOrOtherwiseSyntax<TState, TEvent> IIfOrOtherwiseSyntax<TState, TEvent>.Execute(Action action)
{
return this.ExecuteInternal(action);
}
IIfOrOtherwiseSyntax<TState, TEvent> IIfOrOtherwiseSyntax<TState, TEvent>.Execute<T>(Action<T> action)
{
return this.ExecuteInternal(action);
}
private StateBuilder<TState, TEvent> ExecuteInternal(Action action)
{
this.currentTransitionDefinition.ActionsModifiable.Add(this.factory.CreateTransitionActionHolder(action));
this.CheckGuards();
return this;
}
private StateBuilder<TState, TEvent> ExecuteInternal<T>(Action<T> action)
{
this.currentTransitionDefinition.ActionsModifiable.Add(this.factory.CreateTransitionActionHolder(action));
this.CheckGuards();
return this;
}
IIfSyntax<TState, TEvent> IOnSyntax<TState, TEvent>.If<T>(Func<T, bool> guard)
{
this.SetGuard(guard);
return this;
}
IIfSyntax<TState, TEvent> IOnSyntax<TState, TEvent>.If(Func<bool> guard)
{
this.SetGuard(guard);
return this;
}
IIfSyntax<TState, TEvent> IIfOrOtherwiseSyntax<TState, TEvent>.If<T>(Func<T, bool> guard)
{
this.CreateTransition();
this.SetGuard(guard);
return this;
}
IIfSyntax<TState, TEvent> IIfOrOtherwiseSyntax<TState, TEvent>.If(Func<bool> guard)
{
this.CreateTransition();
this.SetGuard(guard);
return this;
}
IOtherwiseSyntax<TState, TEvent> IIfOrOtherwiseSyntax<TState, TEvent>.Otherwise()
{
this.CreateTransition();
return this;
}
private void SetGuard<T>(Func<T, bool> guard)
{
this.currentTransitionDefinition.Guard = this.factory.CreateGuardHolder(guard);
}
private void SetGuard(Func<bool> guard)
{
this.currentTransitionDefinition.Guard = this.factory.CreateGuardHolder(guard);
}
private void SetTargetState(TState target)
{
this.currentTransitionDefinition.Target = this.stateDefinitionDictionary[target];
this.CheckGuards();
}
private void CheckGuards()
{
var transitionsByEvent = this.stateDefinition.TransitionsModifiable.GetTransitions().GroupBy(t => t.EventId).ToList();
var withMoreThenOneTransitionWithoutGuard = transitionsByEvent.Where(g => g.Count(t => t.Guard == null) > 1);
if (withMoreThenOneTransitionWithoutGuard.Any())
{
throw new InvalidOperationException(ExceptionMessages.OnlyOneTransitionMayHaveNoGuard);
}
if ((from grouping in transitionsByEvent
let transition = grouping.SingleOrDefault(t => t.Guard == null)
where transition != null && grouping.LastOrDefault() != transition
select grouping).Any())
{
throw new InvalidOperationException(ExceptionMessages.TransitionWithoutGuardHasToBeLast);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
#if SILVERLIGHT
#endif
using System.Threading;
using ServiceStack.Common.Support;
namespace ServiceStack.Text
{
/// <summary>
/// Utils to load types
/// </summary>
public static class AssemblyUtils
{
private const string FileUri = "file:///";
private const string DllExt = "dll";
private const string ExeExt = "dll";
private const char UriSeperator = '/';
private static Dictionary<string, Type> TypeCache = new Dictionary<string, Type>();
#if !XBOX
/// <summary>
/// Find the type from the name supplied
/// </summary>
/// <param name="typeName">[typeName] or [typeName, assemblyName]</param>
/// <returns></returns>
public static Type FindType(string typeName)
{
Type type = null;
if (TypeCache.TryGetValue(typeName, out type)) return type;
#if !SILVERLIGHT
type = Type.GetType(typeName);
#endif
if (type == null)
{
var typeDef = new AssemblyTypeDefinition(typeName);
type = !string.IsNullOrEmpty(typeDef.AssemblyName)
? FindType(typeDef.TypeName, typeDef.AssemblyName)
: FindTypeFromLoadedAssemblies(typeDef.TypeName);
}
Dictionary<string, Type> snapshot, newCache;
do
{
snapshot = TypeCache;
newCache = new Dictionary<string, Type>(TypeCache);
newCache[typeName] = type;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref TypeCache, newCache, snapshot), snapshot));
return type;
}
#endif
#if !XBOX
/// <summary>
/// The top-most interface of the given type, if any.
/// </summary>
public static Type MainInterface<T>()
{
var t = typeof(T);
#if NETFX_CORE
if (t.GetTypeInfo().BaseType == typeof(object)) {
// on Windows, this can be just "t.GetInterfaces()" but Mono doesn't return in order.
var interfaceType = t.GetTypeInfo().ImplementedInterfaces.FirstOrDefault(i => !t.GetTypeInfo().ImplementedInterfaces.Any(i2 => i2.GetTypeInfo().ImplementedInterfaces.Contains(i)));
if (interfaceType != null) return interfaceType;
}
#else
if (t.BaseType == typeof(object)) {
// on Windows, this can be just "t.GetInterfaces()" but Mono doesn't return in order.
var interfaceType = t.GetInterfaces().FirstOrDefault(i => !t.GetInterfaces().Any(i2 => i2.GetInterfaces().Contains(i)));
if (interfaceType != null) return interfaceType;
}
#endif
return t; // not safe to use interface, as it might be a superclass's one.
}
/// <summary>
/// Find type if it exists
/// </summary>
/// <param name="typeName"></param>
/// <param name="assemblyName"></param>
/// <returns>The type if it exists</returns>
public static Type FindType(string typeName, string assemblyName)
{
var type = FindTypeFromLoadedAssemblies(typeName);
if (type != null)
{
return type;
}
#if !NETFX_CORE
var binPath = GetAssemblyBinPath(Assembly.GetExecutingAssembly());
Assembly assembly = null;
var assemblyDllPath = binPath + String.Format("{0}.{1}", assemblyName, DllExt);
if (File.Exists(assemblyDllPath))
{
assembly = LoadAssembly(assemblyDllPath);
}
var assemblyExePath = binPath + String.Format("{0}.{1}", assemblyName, ExeExt);
if (File.Exists(assemblyExePath))
{
assembly = LoadAssembly(assemblyExePath);
}
return assembly != null ? assembly.GetType(typeName) : null;
#else
return null;
#endif
}
#endif
#if NETFX_CORE
private sealed class AppDomain
{
public static AppDomain CurrentDomain { get; private set; }
public static Assembly[] cacheObj = null;
static AppDomain()
{
CurrentDomain = new AppDomain();
}
public Assembly[] GetAssemblies()
{
return cacheObj ?? GetAssemblyListAsync().Result.ToArray();
}
private async System.Threading.Tasks.Task<IEnumerable<Assembly>> GetAssemblyListAsync()
{
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
List<Assembly> assemblies = new List<Assembly>();
foreach (Windows.Storage.StorageFile file in await folder.GetFilesAsync())
{
if (file.FileType == ".dll" || file.FileType == ".exe")
{
try
{
var filename = file.Name.Substring(0, file.Name.Length - file.FileType.Length);
AssemblyName name = new AssemblyName() { Name = filename };
Assembly asm = Assembly.Load(name);
assemblies.Add(asm);
}
catch (Exception)
{
// Invalid WinRT assembly!
}
}
}
cacheObj = assemblies.ToArray();
return cacheObj;
}
}
#endif
#if !XBOX
public static Type FindTypeFromLoadedAssemblies(string typeName)
{
#if SILVERLIGHT4
var assemblies = ((dynamic) AppDomain.CurrentDomain).GetAssemblies() as Assembly[];
#else
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
#endif
foreach (var assembly in assemblies)
{
var type = assembly.GetType(typeName);
if (type != null)
{
return type;
}
}
return null;
}
#endif
#if !SILVERLIGHT
private static Assembly LoadAssembly(string assemblyPath)
{
return Assembly.LoadFrom(assemblyPath);
}
#elif NETFX_CORE
private static Assembly LoadAssembly(string assemblyPath)
{
return Assembly.Load(new AssemblyName(assemblyPath));
}
#elif WINDOWS_PHONE
private static Assembly LoadAssembly(string assemblyPath)
{
return Assembly.LoadFrom(assemblyPath);
}
#else
private static Assembly LoadAssembly(string assemblyPath)
{
var sri = System.Windows.Application.GetResourceStream(new Uri(assemblyPath, UriKind.Relative));
var myPart = new System.Windows.AssemblyPart();
var assembly = myPart.Load(sri.Stream);
return assembly;
}
#endif
#if !XBOX
public static string GetAssemblyBinPath(Assembly assembly)
{
#if WINDOWS_PHONE
var codeBase = assembly.GetName().CodeBase;
#elif NETFX_CORE
var codeBase = assembly.GetName().FullName;
#elif SILVERLIGHT
var codeBase = assembly.FullName;
#else
var codeBase = assembly.CodeBase;
#endif
var binPathPos = codeBase.LastIndexOf(UriSeperator);
var assemblyPath = codeBase.Substring(0, binPathPos + 1);
if (assemblyPath.StartsWith(FileUri, StringComparison.OrdinalIgnoreCase))
{
assemblyPath = assemblyPath.Remove(0, FileUri.Length);
}
return assemblyPath;
}
#endif
#if !SILVERLIGHT
static readonly Regex versionRegEx = new Regex(", Version=[^\\]]+", RegexOptions.Compiled);
#else
static readonly Regex versionRegEx = new Regex(", Version=[^\\]]+");
#endif
public static string ToTypeString(this Type type)
{
return versionRegEx.Replace(type.AssemblyQualifiedName, "");
}
public static string WriteType(Type type)
{
return type.ToTypeString();
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (C) Sickhead Games, LLC
//-----------------------------------------------------------------------------
function initializeMeshRoadEditor()
{
echo(" % - Initializing Mesh Road Editor");
exec( "./meshRoadEditor.cs" );
exec( "./meshRoadEditorGui.gui" );
exec( "./meshRoadEditorToolbar.gui");
exec( "./meshRoadEditorGui.cs" );
MeshRoadEditorGui.setVisible( false );
MeshRoadEditorOptionsWindow.setVisible( false );
MeshRoadEditorToolbar.setVisible( false );
MeshRoadEditorTreeWindow.setVisible( false );
EditorGui.add( MeshRoadEditorGui );
EditorGui.add( MeshRoadEditorOptionsWindow );
EditorGui.add( MeshRoadEditorToolbar );
EditorGui.add( MeshRoadEditorTreeWindow );
new ScriptObject( MeshRoadEditorPlugin )
{
superClass = "EditorPlugin";
editorGui = MeshRoadEditorGui;
};
%map = new ActionMap();
%map.bindCmd( keyboard, "backspace", "MeshRoadEditorGui.deleteNode();", "" );
%map.bindCmd( keyboard, "1", "MeshRoadEditorGui.prepSelectionMode();", "" );
%map.bindCmd( keyboard, "2", "ToolsPaletteArray->MeshRoadEditorMoveMode.performClick();", "" );
%map.bindCmd( keyboard, "3", "ToolsPaletteArray->MeshRoadEditorRotateMode.performClick();", "" );
%map.bindCmd( keyboard, "4", "ToolsPaletteArray->MeshRoadEditorScaleMode.performClick();", "" );
%map.bindCmd( keyboard, "5", "ToolsPaletteArray->MeshRoadEditorAddRoadMode.performClick();", "" );
%map.bindCmd( keyboard, "=", "ToolsPaletteArray->MeshRoadEditorInsertPointMode.performClick();", "" );
%map.bindCmd( keyboard, "numpadadd", "ToolsPaletteArray->MeshRoadEditorInsertPointMode.performClick();", "" );
%map.bindCmd( keyboard, "-", "ToolsPaletteArray->MeshRoadEditorRemovePointMode.performClick();", "" );
%map.bindCmd( keyboard, "numpadminus", "ToolsPaletteArray->MeshRoadEditorRemovePointMode.performClick();", "" );
%map.bindCmd( keyboard, "z", "MeshRoadEditorShowSplineBtn.performClick();", "" );
%map.bindCmd( keyboard, "x", "MeshRoadEditorWireframeBtn.performClick();", "" );
%map.bindCmd( keyboard, "v", "MeshRoadEditorShowRoadBtn.performClick();", "" );
MeshRoadEditorPlugin.map = %map;
MeshRoadEditorPlugin.initSettings();
}
function destroyMeshRoadEditor()
{
}
function MeshRoadEditorPlugin::onWorldEditorStartup( %this )
{
// Add ourselves to the window menu.
%accel = EditorGui.addToEditorsMenu( "Mesh Road Editor", "", MeshRoadEditorPlugin );
// Add ourselves to the ToolsToolbar
%tooltip = "Mesh Road Editor (" @ %accel @ ")";
EditorGui.addToToolsToolbar( "MeshRoadEditorPlugin", "MeshRoadEditorPalette", expandFilename("tools/worldEditor/images/toolbar/mesh-road-editor"), %tooltip );
//connect editor windows
GuiWindowCtrl::attach( MeshRoadEditorOptionsWindow, MeshRoadEditorTreeWindow);
// Add ourselves to the Editor Settings window
exec( "./meshRoadEditorSettingsTab.gui" );
ESettingsWindow.addTabPage( EMeshRoadEditorSettingsPage );
}
function MeshRoadEditorPlugin::onActivated( %this )
{
%this.readSettings();
ToolsPaletteArray->MeshRoadEditorAddRoadMode.performClick();
EditorGui.bringToFront( MeshRoadEditorGui );
MeshRoadEditorGui.setVisible( true );
MeshRoadEditorGui.makeFirstResponder( true );
MeshRoadEditorOptionsWindow.setVisible( true );
MeshRoadEditorToolbar.setVisible( true );
MeshRoadEditorTreeWindow.setVisible( true );
MeshRoadTreeView.open(ServerMeshRoadSet,true);
%this.map.push();
// Store this on a dynamic field
// in order to restore whatever setting
// the user had before.
%this.prevGizmoAlignment = GlobalGizmoProfile.alignment;
// The DecalEditor always uses Object alignment.
GlobalGizmoProfile.alignment = "Object";
// Set the status bar here until all tool have been hooked up
EditorGuiStatusBar.setInfo("Mesh road editor.");
EditorGuiStatusBar.setSelection("");
Parent::onActivated(%this);
}
function MeshRoadEditorPlugin::onDeactivated( %this )
{
%this.writeSettings();
MeshRoadEditorGui.setVisible( false );
MeshRoadEditorOptionsWindow.setVisible( false );
MeshRoadEditorToolbar.setVisible( false );
MeshRoadEditorTreeWindow.setVisible( false );
%this.map.pop();
// Restore the previous Gizmo
// alignment settings.
GlobalGizmoProfile.alignment = %this.prevGizmoAlignment;
Parent::onDeactivated(%this);
}
function MeshRoadEditorPlugin::onEditMenuSelect( %this, %editMenu )
{
%hasSelection = false;
if( isObject( MeshRoadEditorGui.road ) )
%hasSelection = true;
%editMenu.enableItem( 3, false ); // Cut
%editMenu.enableItem( 4, false ); // Copy
%editMenu.enableItem( 5, false ); // Paste
%editMenu.enableItem( 6, %hasSelection ); // Delete
%editMenu.enableItem( 8, false ); // Deselect
}
function MeshRoadEditorPlugin::handleDelete( %this )
{
MeshRoadEditorGui.deleteNode();
}
function MeshRoadEditorPlugin::handleEscape( %this )
{
return MeshRoadEditorGui.onEscapePressed();
}
function MeshRoadEditorPlugin::isDirty( %this )
{
return MeshRoadEditorGui.isDirty;
}
function MeshRoadEditorPlugin::onSaveMission( %this, %missionFile )
{
if( MeshRoadEditorGui.isDirty )
{
MissionGroup.save( %missionFile );
MeshRoadEditorGui.isDirty = false;
}
}
//-----------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------
function MeshRoadEditorPlugin::initSettings( %this )
{
EditorSettings.beginGroup( "MeshRoadEditor", true );
EditorSettings.setDefaultValue( "DefaultWidth", "10" );
EditorSettings.setDefaultValue( "DefaultDepth", "5" );
EditorSettings.setDefaultValue( "DefaultNormal", "0 0 1" );
EditorSettings.setDefaultValue( "HoverSplineColor", "255 0 0 255" );
EditorSettings.setDefaultValue( "SelectedSplineColor", "0 255 0 255" );
EditorSettings.setDefaultValue( "HoverNodeColor", "255 255 255 255" ); //<-- Not currently used
EditorSettings.setDefaultValue( "TopMaterialName", "DefaultRoadMaterialTop" );
EditorSettings.setDefaultValue( "BottomMaterialName", "DefaultRoadMaterialOther" );
EditorSettings.setDefaultValue( "SideMaterialName", "DefaultRoadMaterialOther" );
EditorSettings.endGroup();
}
function MeshRoadEditorPlugin::readSettings( %this )
{
EditorSettings.beginGroup( "MeshRoadEditor", true );
MeshRoadEditorGui.DefaultWidth = EditorSettings.value("DefaultWidth");
MeshRoadEditorGui.DefaultDepth = EditorSettings.value("DefaultDepth");
MeshRoadEditorGui.DefaultNormal = EditorSettings.value("DefaultNormal");
MeshRoadEditorGui.HoverSplineColor = EditorSettings.value("HoverSplineColor");
MeshRoadEditorGui.SelectedSplineColor = EditorSettings.value("SelectedSplineColor");
MeshRoadEditorGui.HoverNodeColor = EditorSettings.value("HoverNodeColor");
MeshRoadEditorGui.topMaterialName = EditorSettings.value("TopMaterialName");
MeshRoadEditorGui.bottomMaterialName = EditorSettings.value("BottomMaterialName");
MeshRoadEditorGui.sideMaterialName = EditorSettings.value("SideMaterialName");
EditorSettings.endGroup();
}
function MeshRoadEditorPlugin::writeSettings( %this )
{
EditorSettings.beginGroup( "MeshRoadEditor", true );
EditorSettings.setValue( "DefaultWidth", MeshRoadEditorGui.DefaultWidth );
EditorSettings.setValue( "DefaultDepth", MeshRoadEditorGui.DefaultDepth );
EditorSettings.setValue( "DefaultNormal", MeshRoadEditorGui.DefaultNormal );
EditorSettings.setValue( "HoverSplineColor", MeshRoadEditorGui.HoverSplineColor );
EditorSettings.setValue( "SelectedSplineColor", MeshRoadEditorGui.SelectedSplineColor );
EditorSettings.setValue( "HoverNodeColor", MeshRoadEditorGui.HoverNodeColor );
EditorSettings.setValue( "TopMaterialName", MeshRoadEditorGui.topMaterialName );
EditorSettings.setValue( "BottomMaterialName", MeshRoadEditorGui.bottomMaterialName );
EditorSettings.setValue( "SideMaterialName", MeshRoadEditorGui.sideMaterialName );
EditorSettings.endGroup();
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System.Collections.Generic;
using System.Data;
using DotSpatial.NTSExtension;
using NetTopologySuite.Geometries;
using NetTopologySuite.Operation.Buffer;
namespace DotSpatial.Data
{
/// <summary>
/// Extension Methods for the Features.
/// </summary>
public static class FeatureExt
{
#region Methods
/// <summary>
/// Generates a new feature from the buffer of this feature. The DataRow of
/// the new feature will be null.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="distance">The double distance.</param>
/// <returns>An IFeature representing the output from the buffer operation.</returns>
public static IFeature Buffer(this IFeature self, double distance)
{
Geometry g = self.Geometry.Buffer(distance);
return new Feature(g);
}
/// <summary>
/// Generates a new feature from the buffer of this feature. The DataRow of
/// the new feature will be null.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="distance">The double distance.</param>
/// <param name="endCapStyle">The end cap style to use.</param>
/// <returns>An IFeature representing the output from the buffer operation.</returns>
public static IFeature Buffer(this IFeature self, double distance, EndCapStyle endCapStyle)
{
Geometry g = self.Geometry.Buffer(
distance,
new BufferParameters
{
EndCapStyle = endCapStyle
});
return new Feature(g);
}
/// <summary>
/// Generates a new feature from the buffer of this feature. The DataRow of
/// the new feature will be null.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="distance">The double distance.</param>
/// <param name="quadrantSegments">The number of segments to use to approximate a quadrant of a circle.</param>
/// <returns>An IFeature representing the output from the buffer operation.</returns>
public static IFeature Buffer(this IFeature self, double distance, int quadrantSegments)
{
Geometry g = self.Geometry.Buffer(distance, quadrantSegments);
return new Feature(g);
}
/// <summary>
/// Generates a new feature from the buffer of this feature. The DataRow of
/// the new feature will be null.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="distance">The double distance.</param>
/// <param name="quadrantSegments">The number of segments to use to approximate a quadrant of a circle.</param>
/// <param name="endCapStyle">The end cap style to use.</param>
/// <returns>An IFeature representing the output from the buffer operation.</returns>
public static IFeature Buffer(this IFeature self, double distance, int quadrantSegments, EndCapStyle endCapStyle)
{
Geometry g = self.Geometry.Buffer(distance, quadrantSegments, endCapStyle);
return new Feature(g);
}
/// <summary>
/// Generates a buffer, but also adds the newly created feature to the specified output featureset.
/// This will also compare the field names of the input featureset with the destination featureset.
/// If a column name exists in both places, it will copy those values to the destination featureset.
/// </summary>
/// <param name="self">The feature to calcualate the buffer for.</param>
/// <param name="distance">The double distance to use for calculating the buffer.</param>
/// <param name="destinationFeatureset">The output featureset to add this feature to and use
/// as a reference for determining which data columns to copy.</param>
/// <returns>The IFeature that represents the buffer feature.</returns>
public static IFeature Buffer(this IFeature self, double distance, IFeatureSet destinationFeatureset)
{
IFeature f = Buffer(self, distance);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// Generates a buffer, but also adds the newly created feature to the specified output featureset.
/// This will also compare the field names of the input featureset with the destination featureset.
/// If a column name exists in both places, it will copy those values to the destination featureset.
/// </summary>
/// <param name="self">The feature to calcualate the buffer for.</param>
/// <param name="distance">The double distance to use for calculating the buffer.</param>
/// <param name="endCapStyle">The end cap style to use.</param>
/// <param name="destinationFeatureset">The output featureset to add this feature to and use
/// as a reference for determining which data columns to copy.</param>
/// <returns>The IFeature that represents the buffer feature.</returns>
public static IFeature Buffer(this IFeature self, double distance, EndCapStyle endCapStyle, IFeatureSet destinationFeatureset)
{
IFeature f = Buffer(self, distance, endCapStyle);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// Generates a buffer, but also adds the newly created feature to the specified output featureset.
/// This will also compare the field names of the input featureset with the destination featureset.
/// If a column name exists in both places, it will copy those values to the destination featureset.
/// </summary>
/// <param name="self">The feature to calcualate the buffer for.</param>
/// <param name="distance">The double distance to use for calculating the buffer.</param>
/// <param name="quadrantSegments">The number of segments to use to approximate a quadrant of a circle.</param>
/// <param name="destinationFeatureset">The output featureset to add this feature to and use
/// as a reference for determining which data columns to copy.</param>
/// <returns>The IFeature that represents the buffer feature.</returns>
public static IFeature Buffer(this IFeature self, double distance, int quadrantSegments, IFeatureSet destinationFeatureset)
{
IFeature f = Buffer(self, distance, quadrantSegments);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// Generates a buffer, but also adds the newly created feature to the specified output featureset.
/// This will also compare the field names of the input featureset with the destination featureset.
/// If a column name exists in both places, it will copy those values to the destination featureset.
/// </summary>
/// <param name="self">The feature to calcualate the buffer for.</param>
/// <param name="distance">The double distance to use for calculating the buffer.</param>
/// <param name="quadrantSegments">The number of segments to use to approximate a quadrant of a circle.</param>
/// <param name="endCapStyle">The end cap style to use.</param>
/// <param name="destinationFeatureset">The output featureset to add this feature to and use
/// as a reference for determining which data columns to copy.</param>
/// <returns>The IFeature that represents the buffer feature.</returns>
public static IFeature Buffer(this IFeature self, double distance, int quadrantSegments, EndCapStyle endCapStyle, IFeatureSet destinationFeatureset)
{
IFeature f = Buffer(self, distance, quadrantSegments, endCapStyle);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// If the geometry for this shape was loaded from a file, this contains the size
/// of this shape in 16-bit words as per the Esri Shapefile specification.
/// </summary>
/// <param name="self">This feature.</param>
/// <returns>The content length.</returns>
public static int ContentLength(this IFeature self)
{
return self.ShapeIndex?.ContentLength ?? 0;
}
/// <summary>
/// Calculates a new feature that has a geometry that is the convex hull of this feature.
/// </summary>
/// <param name="self">This feature.</param>
/// <returns>A new feature that is the convex hull of this feature.</returns>
public static IFeature ConvexHull(this IFeature self)
{
return new Feature(self.Geometry.ConvexHull());
}
/// <summary>
/// Calculates a new feature that has a geometry that is the convex hull of this feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="destinationFeatureset">The destination featureset to add this feature to.</param>
/// <returns>The newly created IFeature.</returns>
public static IFeature ConvexHull(this IFeature self, IFeatureSet destinationFeatureset)
{
IFeature f = ConvexHull(self);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// Creates a new Feature that has a geometry that is the difference between this feature and the specified feature.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="other">The other feature to compare to.</param>
/// <returns>A new feature that is the geometric difference between this feature and the specified feature.</returns>
public static IFeature Difference(this IFeature self, Geometry other)
{
if (other == null) return self.Copy();
Geometry g = self.Geometry.Difference(other);
if (g == null || g.IsEmpty) return null;
return new Feature(g);
}
/// <summary>
/// Creates a new Feature that has a geometry that is the difference between this feature and the specified feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="other">The other feature to compare to.</param>
/// <param name="destinationFeatureSet">The featureset to add the new feature to.</param>
/// <param name="joinType">This clarifies the overall join strategy being used with regards to attribute fields.</param>
/// <returns>A new feature that is the geometric difference between this feature and the specified feature.</returns>
public static IFeature Difference(this IFeature self, IFeature other, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
IFeature f = Difference(self, other.Geometry);
if (f != null)
{
UpdateFields(self, other, f, destinationFeatureSet, joinType);
}
return f;
}
/// <summary>
/// Creates a new GML string describing the location of this point.
/// </summary>
/// <param name="self">This feature.</param>
/// <returns>A String representing the Geographic Markup Language version of this point.</returns>
public static string ExportToGml(this IFeature self)
{
var geo = self.Geometry as Geometry;
return geo == null ? string.Empty : geo.ToGMLFeature().ToString();
}
/// <summary>
/// Creates a new Feature that has a geometry that is the intersection between this feature and the specified feature.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="other">The other feature to compare to.</param>
/// <returns>A new feature that is the geometric intersection between this feature and the specified feature.</returns>
public static IFeature Intersection(this IFeature self, Geometry other)
{
Geometry g = self.Geometry.Intersection(other);
if (g == null || g.IsEmpty) return null;
return new Feature(g);
}
/// <summary>
/// Creates a new Feature that has a geometry that is the intersection between this feature and the specified feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="other">The other feature to compare to.</param>
/// <param name="destinationFeatureSet">The featureset to add the new feature to.</param>
/// <param name="joinType">This clarifies the overall join strategy being used with regards to attribute fields.</param>
/// <returns>A new feature that is the geometric intersection between this feature and the specified feature.</returns>
public static IFeature Intersection(this IFeature self, IFeature other, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
IFeature f = Intersection(self, other.Geometry);
if (f != null)
{
UpdateFields(self, other, f, destinationFeatureSet, joinType);
}
return f;
}
/// <summary>
/// Gets the integer number of parts associated with this feature.
/// </summary>
/// <param name="self">This feature.</param>
/// <returns>The number of parts.</returns>
public static int NumParts(this IFeature self)
{
int count = 0;
if (self.FeatureType != FeatureType.Polygon) return self.Geometry.NumGeometries;
Polygon p = self.Geometry as Polygon;
if (p == null)
{
// we have a multi-polygon situation
for (int i = 0; i < self.Geometry.NumGeometries; i++)
{
p = self.Geometry.GetGeometryN(i) as Polygon;
if (p == null) continue;
count += 1; // Shell
count += p.NumInteriorRings; // Holes
}
}
else
{
// The feature is a polygon, not a multi-polygon
count += 1; // Shell
count += p.NumInteriorRings; // Holes
}
return count;
}
/// <summary>
/// An index value that is saved in some file formats.
/// </summary>
/// <param name="self">This feature.</param>
/// <returns>The record number.</returns>
public static int RecordNumber(this IFeature self)
{
return self.ShapeIndex?.RecordNumber ?? -1;
}
/// <summary>
/// Rotates the BasicGeometry of the feature by the given radian angle around the given Origin.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="origin">The coordinate the feature gets rotated around.</param>
/// <param name="radAngle">The rotation angle in radian.</param>
public static void Rotate(this IFeature self, Coordinate origin, double radAngle)
{
Geometry geo = self.Geometry.Copy();
geo.Rotate(origin, radAngle);
self.Geometry = geo;
self.UpdateEnvelope();
}
/// <summary>
/// When a shape is loaded from a Shapefile, this will identify whether M or Z values are used
/// and whether or not the shape is null.
/// </summary>
/// <param name="self">This feature.</param>
/// <returns>The shape type.</returns>
public static ShapeType ShapeType(this IFeature self)
{
return self.ShapeIndex?.ShapeType ?? Data.ShapeType.NullShape;
}
/// <summary>
/// Creates a new Feature that has a geometry that is the symmetric difference between this feature and the specified feature.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="other">The other feature to compare to.</param>
/// <returns>A new feature that is the geometric symmetric difference between this feature and the specified feature.</returns>
public static IFeature SymmetricDifference(this IFeature self, Geometry other)
{
Geometry g = self.Geometry.SymmetricDifference(other);
if (g == null || g.IsEmpty) return null;
return new Feature(g);
}
/// <summary>
/// Creates a new Feature that has a geometry that is the symmetric difference between this feature and the specified feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="other">The other feature to compare to.</param>
/// <param name="destinationFeatureSet">The featureset to add the new feature to.</param>
/// <param name="joinType">This clarifies the overall join strategy being used with regards to attribute fields.</param>
/// <returns>A new feature that is the geometric symmetric difference between this feature and the specified feature.</returns>
public static IFeature SymmetricDifference(this IFeature self, IFeature other, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
IFeature f = SymmetricDifference(self, other.Geometry);
if (f != null)
{
UpdateFields(self, other, f, destinationFeatureSet, joinType);
}
return f;
}
/// <summary>
/// Creates a new Feature that has a geometry that is the union between this feature and the specified feature.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="other">The other feature to compare to.</param>
/// <returns>A new feature that is the geometric union between this feature and the specified feature.</returns>
public static IFeature Union(this IFeature self, Geometry other)
{
Geometry g = self.Geometry.Union(other);
if (g == null || g.IsEmpty) return null;
return new Feature(g);
}
/// <summary>
/// Creates a new Feature that has a geometry that is the union between this feature and the specified feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="other">The other feature to compare to.</param>
/// <param name="destinationFeatureSet">The featureset to add the new feature to.</param>
/// <param name="joinType">Clarifies how the attributes should be handled during the union.</param>
/// <returns>A new feature that is the geometric symmetric difference between this feature and the specified feature.</returns>
public static IFeature Union(this IFeature self, IFeature other, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
IFeature f = Union(self, other.Geometry);
if (f != null)
{
UpdateFields(self, other, f, destinationFeatureSet, joinType);
}
return f;
}
// This handles the slightly complex business of attribute outputs.
private static void UpdateFields(IFeature self, IFeature other, IFeature result, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
if (destinationFeatureSet.FeatureType != result.FeatureType) return;
destinationFeatureSet.Features.Add(result);
if (joinType == FieldJoinType.None) return;
if (joinType == FieldJoinType.All)
{
// This overly complex mess is concerned with preventing duplicate field names.
// This assumes that numbers were appended when duplicates occured, and will
// repeat the process here to establish one set of string names and values.
Dictionary<string, object> mappings = new Dictionary<string, object>();
foreach (DataColumn dc in self.ParentFeatureSet.DataTable.Columns)
{
string name = dc.ColumnName;
int i = 1;
while (mappings.ContainsKey(name))
{
name = dc.ColumnName + i;
i++;
}
mappings.Add(name, self.DataRow[dc.ColumnName]);
}
foreach (DataColumn dc in other.ParentFeatureSet.DataTable.Columns)
{
string name = dc.ColumnName;
int i = 1;
while (mappings.ContainsKey(name))
{
name = dc.ColumnName + i;
i++;
}
mappings.Add(name, other.DataRow[dc.ColumnName]);
}
foreach (KeyValuePair<string, object> pair in mappings)
{
if (!result.DataRow.Table.Columns.Contains(pair.Key))
{
result.DataRow.Table.Columns.Add(pair.Key);
}
result.DataRow[pair.Key] = pair.Value;
}
}
if (joinType == FieldJoinType.LocalOnly)
{
foreach (DataColumn dc in destinationFeatureSet.DataTable.Columns)
{
if (self.DataRow.Table.Columns.Contains(dc.ColumnName))
{
result.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
}
if (joinType == FieldJoinType.ForeignOnly)
{
foreach (DataColumn dc in destinationFeatureSet.DataTable.Columns)
{
if (other.DataRow[dc.ColumnName] != null)
{
result.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Services.GridService
{
public class GridService : GridServiceBase, IGridService
{
protected static HypergridLinker m_HypergridLinker;
protected bool m_AllowDuplicateNames = false;
protected bool m_AllowHypergridMapSearch = false;
protected IAuthenticationService m_AuthenticationService = null;
protected IConfigSource m_config;
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private static GridService m_RootInstance = null;
private bool m_DeleteOnUnregister = true;
public GridService(IConfigSource config)
: base(config)
{
m_log.DebugFormat("[GRID SERVICE]: Starting...");
m_config = config;
IConfig gridConfig = config.Configs["GridService"];
if (gridConfig != null)
{
m_DeleteOnUnregister = gridConfig.GetBoolean("DeleteOnUnregister", true);
string authService = gridConfig.GetString("AuthenticationService", String.Empty);
if (authService != String.Empty)
{
Object[] args = new Object[] { config };
m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args);
}
m_AllowDuplicateNames = gridConfig.GetBoolean("AllowDuplicateNames", m_AllowDuplicateNames);
m_AllowHypergridMapSearch = gridConfig.GetBoolean("AllowHypergridMapSearch", m_AllowHypergridMapSearch);
}
if (m_RootInstance == null)
{
m_RootInstance = this;
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand("Regions", true,
"deregister region id",
"deregister region id <region-id>+",
"Deregister a region manually.",
String.Empty,
HandleDeregisterRegion);
// A messy way of stopping this command being added if we are in standalone (since the simulator
// has an identically named command
//
// XXX: We're relying on the OpenSimulator version being registered first, which is not well defined.
if (MainConsole.Instance.Commands.Resolve(new string[] { "show", "regions" }).Length == 0)
MainConsole.Instance.Commands.AddCommand("Regions", true,
"show regions",
"show regions",
"Show details on all regions",
String.Empty,
HandleShowRegions);
MainConsole.Instance.Commands.AddCommand("Regions", true,
"show region name",
"show region name <Region name>",
"Show details on a region",
String.Empty,
HandleShowRegion);
MainConsole.Instance.Commands.AddCommand("Regions", true,
"show region at",
"show region at <x-coord> <y-coord>",
"Show details on a region at the given co-ordinate.",
"For example, show region at 1000 1000",
HandleShowRegionAt);
MainConsole.Instance.Commands.AddCommand("Regions", true,
"set region flags",
"set region flags <Region name> <flags>",
"Set database flags for region",
String.Empty,
HandleSetFlags);
}
m_HypergridLinker = new HypergridLinker(m_config, this, m_Database);
}
}
#region IGridService
public bool DeregisterRegion(UUID regionID)
{
RegionData region = m_Database.Get(regionID, UUID.Zero);
if (region == null)
return false;
m_log.DebugFormat(
"[GRID SERVICE]: Deregistering region {0} ({1}) at {2}-{3}",
region.RegionName, region.RegionID, region.coordX, region.coordY);
int flags = Convert.ToInt32(region.Data["flags"]);
if (!m_DeleteOnUnregister || (flags & (int)OpenSim.Framework.RegionFlags.Persistent) != 0)
{
flags &= ~(int)OpenSim.Framework.RegionFlags.RegionOnline;
region.Data["flags"] = flags.ToString();
region.Data["last_seen"] = Util.UnixTimeSinceEpoch();
try
{
m_Database.Store(region);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
}
return true;
}
return m_Database.Delete(regionID);
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
List<GridRegion> rinfos = new List<GridRegion>();
RegionData region = m_Database.Get(regionID, scopeID);
if (region != null)
{
// Not really? Maybe?
// The adjacent regions are presumed to be the same size as the current region
List<RegionData> rdatas = m_Database.Get(
region.posX - region.sizeX - 1, region.posY - region.sizeY - 1,
region.posX + region.sizeX + 1, region.posY + region.sizeY + 1, scopeID);
foreach (RegionData rdata in rdatas)
{
if (rdata.RegionID != regionID)
{
int flags = Convert.ToInt32(rdata.Data["flags"]);
if ((flags & (int)Framework.RegionFlags.Hyperlink) == 0) // no hyperlinks as neighbours
rinfos.Add(RegionData2RegionInfo(rdata));
}
}
// m_log.DebugFormat("[GRID SERVICE]: region {0} has {1} neighbours", region.RegionName, rinfos.Count);
}
else
{
m_log.WarnFormat(
"[GRID SERVICE]: GetNeighbours() called for scope {0}, region {1} but no such region found",
scopeID, regionID);
}
return rinfos;
}
public GridRegion GetRegionByName(UUID scopeID, string name)
{
List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(name), scopeID);
if ((rdatas != null) && (rdatas.Count > 0))
return RegionData2RegionInfo(rdatas[0]); // get the first
if (m_AllowHypergridMapSearch)
{
GridRegion r = GetHypergridRegionByName(scopeID, name);
if (r != null)
return r;
}
return null;
}
// Get a region given its base coordinates.
// NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST
// be the base coordinate of the region.
// The snapping is technically unnecessary but is harmless because regions are always
// multiples of the legacy region size (256).
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
int snapX = (int)(x / Constants.RegionSize) * (int)Constants.RegionSize;
int snapY = (int)(y / Constants.RegionSize) * (int)Constants.RegionSize;
RegionData rdata = m_Database.Get(snapX, snapY, scopeID);
if (rdata != null)
return RegionData2RegionInfo(rdata);
return null;
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
RegionData rdata = m_Database.Get(regionID, scopeID);
if (rdata != null)
return RegionData2RegionInfo(rdata);
return null;
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
int xminSnap = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize;
int xmaxSnap = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;
int yminSnap = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize;
int ymaxSnap = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize;
List<RegionData> rdatas = m_Database.Get(xminSnap, yminSnap, xmaxSnap, ymaxSnap, scopeID);
List<GridRegion> rinfos = new List<GridRegion>();
foreach (RegionData rdata in rdatas)
rinfos.Add(RegionData2RegionInfo(rdata));
return rinfos;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
// m_log.DebugFormat("[GRID SERVICE]: GetRegionsByName {0}", name);
List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(name) + "%", scopeID);
int count = 0;
List<GridRegion> rinfos = new List<GridRegion>();
if (rdatas != null)
{
// m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count);
foreach (RegionData rdata in rdatas)
{
if (count++ < maxNumber)
rinfos.Add(RegionData2RegionInfo(rdata));
}
}
if (m_AllowHypergridMapSearch && (rdatas == null || (rdatas != null && rdatas.Count == 0)))
{
GridRegion r = GetHypergridRegionByName(scopeID, name);
if (r != null)
rinfos.Add(r);
}
return rinfos;
}
public string RegisterRegion(UUID scopeID, GridRegion regionInfos)
{
IConfig gridConfig = m_config.Configs["GridService"];
if (regionInfos.RegionID == UUID.Zero)
return "Invalid RegionID - cannot be zero UUID";
RegionData region = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);
if ((region != null) && (region.RegionID != regionInfos.RegionID))
{
m_log.WarnFormat("[GRID SERVICE]: Region {0} tried to register in coordinates {1}, {2} which are already in use in scope {3}.",
regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);
return "Region overlaps another region";
}
if (region != null)
{
// There is a preexisting record
//
// Get it's flags
//
OpenSim.Framework.RegionFlags rflags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(region.Data["flags"]);
// Is this a reservation?
//
if ((rflags & OpenSim.Framework.RegionFlags.Reservation) != 0)
{
// Regions reserved for the null key cannot be taken.
if ((string)region.Data["PrincipalID"] == UUID.Zero.ToString())
return "Region location is reserved";
// Treat it as an auth request
//
// NOTE: Fudging the flags value here, so these flags
// should not be used elsewhere. Don't optimize
// this with the later retrieval of the same flags!
rflags |= OpenSim.Framework.RegionFlags.Authenticate;
}
if ((rflags & OpenSim.Framework.RegionFlags.Authenticate) != 0)
{
// Can we authenticate at all?
//
if (m_AuthenticationService == null)
return "No authentication possible";
if (!m_AuthenticationService.Verify(new UUID(region.Data["PrincipalID"].ToString()), regionInfos.Token, 30))
return "Bad authentication";
}
}
// If we get here, the destination is clear. Now for the real check.
if (!m_AllowDuplicateNames)
{
List<RegionData> dupe = m_Database.Get(Util.EscapeForLike(regionInfos.RegionName), scopeID);
if (dupe != null && dupe.Count > 0)
{
foreach (RegionData d in dupe)
{
if (d.RegionID != regionInfos.RegionID)
{
m_log.WarnFormat("[GRID SERVICE]: Region tried to register using a duplicate name. New region: {0} ({1}), existing region: {2} ({3}).",
regionInfos.RegionName, regionInfos.RegionID, d.RegionName, d.RegionID);
return "Duplicate region name";
}
}
}
}
// If there is an old record for us, delete it if it is elsewhere.
region = m_Database.Get(regionInfos.RegionID, scopeID);
if ((region != null) && (region.RegionID == regionInfos.RegionID) &&
((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY)))
{
if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.NoMove) != 0)
return "Can't move this region";
if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.LockedOut) != 0)
return "Region locked out";
// Region reregistering in other coordinates. Delete the old entry
m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.",
regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY);
try
{
m_Database.Delete(regionInfos.RegionID);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
}
}
// Everything is ok, let's register
RegionData rdata = RegionInfo2RegionData(regionInfos);
rdata.ScopeID = scopeID;
if (region != null)
{
int oldFlags = Convert.ToInt32(region.Data["flags"]);
oldFlags &= ~(int)OpenSim.Framework.RegionFlags.Reservation;
rdata.Data["flags"] = oldFlags.ToString(); // Preserve flags
}
else
{
rdata.Data["flags"] = "0";
if ((gridConfig != null) && rdata.RegionName != string.Empty)
{
int newFlags = 0;
string regionName = rdata.RegionName.Trim().Replace(' ', '_');
newFlags = ParseFlags(newFlags, gridConfig.GetString("DefaultRegionFlags", String.Empty));
newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + regionName, String.Empty));
newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + rdata.RegionID.ToString(), String.Empty));
rdata.Data["flags"] = newFlags.ToString();
}
}
int flags = Convert.ToInt32(rdata.Data["flags"]);
flags |= (int)OpenSim.Framework.RegionFlags.RegionOnline;
rdata.Data["flags"] = flags.ToString();
try
{
rdata.Data["last_seen"] = Util.UnixTimeSinceEpoch();
m_Database.Store(rdata);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
}
m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) registered successfully at {2}-{3} with flags {4}",
regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionCoordX, regionInfos.RegionCoordY,
(OpenSim.Framework.RegionFlags)flags);
return String.Empty;
}
/// <summary>
/// Get a hypergrid region.
/// </summary>
/// <param name="scopeID"></param>
/// <param name="name"></param>
/// <returns>null if no hypergrid region could be found.</returns>
protected GridRegion GetHypergridRegionByName(UUID scopeID, string name)
{
if (name.Contains("."))
return m_HypergridLinker.LinkRegion(scopeID, name);
else
return null;
}
#endregion IGridService
#region Data structure conversions
public GridRegion RegionData2RegionInfo(RegionData rdata)
{
GridRegion rinfo = new GridRegion(rdata.Data);
rinfo.RegionLocX = rdata.posX;
rinfo.RegionLocY = rdata.posY;
rinfo.RegionSizeX = rdata.sizeX;
rinfo.RegionSizeY = rdata.sizeY;
rinfo.RegionID = rdata.RegionID;
rinfo.RegionName = rdata.RegionName;
rinfo.ScopeID = rdata.ScopeID;
return rinfo;
}
public RegionData RegionInfo2RegionData(GridRegion rinfo)
{
RegionData rdata = new RegionData();
rdata.posX = (int)rinfo.RegionLocX;
rdata.posY = (int)rinfo.RegionLocY;
rdata.sizeX = rinfo.RegionSizeX;
rdata.sizeY = rinfo.RegionSizeY;
rdata.RegionID = rinfo.RegionID;
rdata.RegionName = rinfo.RegionName;
rdata.Data = rinfo.ToKeyValuePairs();
rdata.Data["regionHandle"] = Utils.UIntsToLong((uint)rdata.posX, (uint)rdata.posY);
rdata.Data["owner_uuid"] = rinfo.EstateOwner.ToString();
return rdata;
}
#endregion Data structure conversions
public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetDefaultHypergridRegions(scopeID);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
int hgDefaultRegionsFoundOnline = regions.Count;
// For now, hypergrid default regions will always be given precedence but we will also return simple default
// regions in case no specific hypergrid regions are specified.
ret.AddRange(GetDefaultRegions(scopeID));
int normalDefaultRegionsFoundOnline = ret.Count - hgDefaultRegionsFoundOnline;
m_log.DebugFormat(
"[GRID SERVICE]: GetDefaultHypergridRegions returning {0} hypergrid default and {1} normal default regions",
hgDefaultRegionsFoundOnline, normalDefaultRegionsFoundOnline);
return ret;
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetDefaultRegions(scopeID);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
m_log.DebugFormat("[GRID SERVICE]: GetDefaultRegions returning {0} regions", ret.Count);
return ret;
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetFallbackRegions(scopeID, x, y);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
m_log.DebugFormat("[GRID SERVICE]: Fallback returned {0} regions", ret.Count);
return ret;
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetHyperlinks(scopeID);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
m_log.DebugFormat("[GRID SERVICE]: Hyperlinks returned {0} regions", ret.Count);
return ret;
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
RegionData region = m_Database.Get(regionID, scopeID);
if (region != null)
{
int flags = Convert.ToInt32(region.Data["flags"]);
//m_log.DebugFormat("[GRID SERVICE]: Request for flags of {0}: {1}", regionID, flags);
return flags;
}
else
return -1;
}
private void HandleDeregisterRegion(string module, string[] cmd)
{
if (cmd.Length < 4)
{
MainConsole.Instance.Output("Usage: degregister region id <region-id>+");
return;
}
for (int i = 3; i < cmd.Length; i++)
{
string rawRegionUuid = cmd[i];
UUID regionUuid;
if (!UUID.TryParse(rawRegionUuid, out regionUuid))
{
MainConsole.Instance.OutputFormat("{0} is not a valid region uuid", rawRegionUuid);
return;
}
GridRegion region = GetRegionByUUID(UUID.Zero, regionUuid);
if (region == null)
{
MainConsole.Instance.OutputFormat("No region with UUID {0}", regionUuid);
return;
}
if (DeregisterRegion(regionUuid))
{
MainConsole.Instance.OutputFormat("Deregistered {0} {1}", region.RegionName, regionUuid);
}
else
{
// I don't think this can ever occur if we know that the region exists.
MainConsole.Instance.OutputFormat("Error deregistering {0} {1}", region.RegionName, regionUuid);
}
}
}
private void HandleSetFlags(string module, string[] cmd)
{
if (cmd.Length < 5)
{
MainConsole.Instance.Output("Syntax: set region flags <region name> <flags>");
return;
}
List<RegionData> regions = m_Database.Get(Util.EscapeForLike(cmd[3]), UUID.Zero);
if (regions == null || regions.Count < 1)
{
MainConsole.Instance.Output("Region not found");
return;
}
foreach (RegionData r in regions)
{
int flags = Convert.ToInt32(r.Data["flags"]);
flags = ParseFlags(flags, cmd[4]);
r.Data["flags"] = flags.ToString();
OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)flags;
MainConsole.Instance.Output(String.Format("Set region {0} to {1}", r.RegionName, f));
m_Database.Store(r);
}
}
private void HandleShowRegion(string module, string[] cmd)
{
if (cmd.Length != 4)
{
MainConsole.Instance.Output("Syntax: show region name <region name>");
return;
}
string regionName = cmd[3];
List<RegionData> regions = m_Database.Get(Util.EscapeForLike(regionName), UUID.Zero);
if (regions == null || regions.Count < 1)
{
MainConsole.Instance.Output("No region with name {0} found", regionName);
return;
}
OutputRegionsToConsole(regions);
}
private void HandleShowRegionAt(string module, string[] cmd)
{
if (cmd.Length != 5)
{
MainConsole.Instance.Output("Syntax: show region at <x-coord> <y-coord>");
return;
}
uint x, y;
if (!uint.TryParse(cmd[3], out x))
{
MainConsole.Instance.Output("x-coord must be an integer");
return;
}
if (!uint.TryParse(cmd[4], out y))
{
MainConsole.Instance.Output("y-coord must be an integer");
return;
}
RegionData region = m_Database.Get((int)Util.RegionToWorldLoc(x), (int)Util.RegionToWorldLoc(y), UUID.Zero);
if (region == null)
{
MainConsole.Instance.OutputFormat("No region found at {0},{1}", x, y);
return;
}
OutputRegionToConsole(region);
}
private void HandleShowRegions(string module, string[] cmd)
{
if (cmd.Length != 2)
{
MainConsole.Instance.Output("Syntax: show regions");
return;
}
List<RegionData> regions = m_Database.Get(int.MinValue, int.MinValue, int.MaxValue, int.MaxValue, UUID.Zero);
OutputRegionsToConsoleSummary(regions);
}
private void OutputRegionsToConsole(List<RegionData> regions)
{
foreach (RegionData r in regions)
OutputRegionToConsole(r);
}
private void OutputRegionsToConsoleSummary(List<RegionData> regions)
{
ConsoleDisplayTable dispTable = new ConsoleDisplayTable();
dispTable.AddColumn("Name", 16);
dispTable.AddColumn("ID", 36);
dispTable.AddColumn("Position", 11);
dispTable.AddColumn("Owner ID", 36);
dispTable.AddColumn("Flags", 60);
foreach (RegionData r in regions)
{
OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]);
dispTable.AddRow(
r.RegionName,
r.RegionID.ToString(),
string.Format("{0},{1}", r.coordX, r.coordY),
r.Data["owner_uuid"].ToString(),
flags.ToString());
}
MainConsole.Instance.Output(dispTable.ToString());
}
private void OutputRegionToConsole(RegionData r)
{
OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]);
ConsoleDisplayList dispList = new ConsoleDisplayList();
dispList.AddRow("Region Name", r.RegionName);
dispList.AddRow("Region ID", r.RegionID);
dispList.AddRow("Location", string.Format("{0},{1}", r.coordX, r.coordY));
dispList.AddRow("URI", r.Data["serverURI"]);
dispList.AddRow("Owner ID", r.Data["owner_uuid"]);
dispList.AddRow("Flags", flags);
MainConsole.Instance.Output(dispList.ToString());
}
private int ParseFlags(int prev, string flags)
{
OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)prev;
string[] parts = flags.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string p in parts)
{
int val;
try
{
if (p.StartsWith("+"))
{
val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1));
f |= (OpenSim.Framework.RegionFlags)val;
}
else if (p.StartsWith("-"))
{
val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1));
f &= ~(OpenSim.Framework.RegionFlags)val;
}
else
{
val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p);
f |= (OpenSim.Framework.RegionFlags)val;
}
}
catch (Exception)
{
MainConsole.Instance.Output("Error in flag specification: " + p);
}
}
return (int)f;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Text;
namespace System.Net
{
public sealed unsafe partial class HttpListenerRequest
{
public Encoding ContentEncoding
{
get
{
if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP"))
{
string postDataCharset = Headers["x-up-devcap-post-charset"];
if (postDataCharset != null && postDataCharset.Length > 0)
{
try
{
return Encoding.GetEncoding(postDataCharset);
}
catch (ArgumentException)
{
}
}
}
if (HasEntityBody)
{
if (ContentType != null)
{
string charSet = Helpers.GetAttributeFromHeader(ContentType, "charset");
if (charSet != null)
{
try
{
return Encoding.GetEncoding(charSet);
}
catch (ArgumentException)
{
}
}
}
}
return Encoding.Default;
}
}
private static class Helpers
{
//
// Get attribute off header value
//
internal static string GetAttributeFromHeader(string headerValue, string attrName)
{
if (headerValue == null)
return null;
int l = headerValue.Length;
int k = attrName.Length;
// find properly separated attribute name
int i = 1; // start searching from 1
while (i < l)
{
i = CultureInfo.InvariantCulture.CompareInfo.IndexOf(headerValue, attrName, i, CompareOptions.IgnoreCase);
if (i < 0)
break;
if (i + k >= l)
break;
char chPrev = headerValue[i - 1];
char chNext = headerValue[i + k];
if ((chPrev == ';' || chPrev == ',' || char.IsWhiteSpace(chPrev)) && (chNext == '=' || char.IsWhiteSpace(chNext)))
break;
i += k;
}
if (i < 0 || i >= l)
return null;
// skip to '=' and the following whitespace
i += k;
while (i < l && char.IsWhiteSpace(headerValue[i]))
i++;
if (i >= l || headerValue[i] != '=')
return null;
i++;
while (i < l && char.IsWhiteSpace(headerValue[i]))
i++;
if (i >= l)
return null;
// parse the value
string attrValue = null;
int j;
if (i < l && headerValue[i] == '"')
{
if (i == l - 1)
return null;
j = headerValue.IndexOf('"', i + 1);
if (j < 0 || j == i + 1)
return null;
attrValue = headerValue.Substring(i + 1, j - i - 1).Trim();
}
else
{
for (j = i; j < l; j++)
{
if (headerValue[j] == ' ' || headerValue[j] == ',')
break;
}
if (j == i)
return null;
attrValue = headerValue.Substring(i, j - i).Trim();
}
return attrValue;
}
internal static string[] ParseMultivalueHeader(string s)
{
if (s == null)
return null;
int l = s.Length;
// collect comma-separated values into list
List<string> values = new List<string>();
int i = 0;
while (i < l)
{
// find next ,
int ci = s.IndexOf(',', i);
if (ci < 0)
ci = l;
// append corresponding server value
values.Add(s.Substring(i, ci - i));
// move to next
i = ci + 1;
// skip leading space
if (i < l && s[i] == ' ')
i++;
}
// return list as array of strings
int n = values.Count;
string[] strings;
// if n is 0 that means s was empty string
if (n == 0)
{
strings = new string[1];
strings[0] = string.Empty;
}
else
{
strings = new string[n];
values.CopyTo(0, strings, 0, n);
}
return strings;
}
private static string UrlDecodeStringFromStringInternal(string s, Encoding e)
{
int count = s.Length;
UrlDecoder helper = new UrlDecoder(count, e);
// go through the string's chars collapsing %XX and %uXXXX and
// appending each char as char, with exception of %XX constructs
// that are appended as bytes
for (int pos = 0; pos < count; pos++)
{
char ch = s[pos];
if (ch == '+')
{
ch = ' ';
}
else if (ch == '%' && pos < count - 2)
{
if (s[pos + 1] == 'u' && pos < count - 5)
{
int h1 = HexToInt(s[pos + 2]);
int h2 = HexToInt(s[pos + 3]);
int h3 = HexToInt(s[pos + 4]);
int h4 = HexToInt(s[pos + 5]);
if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0)
{ // valid 4 hex chars
ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
pos += 5;
// only add as char
helper.AddChar(ch);
continue;
}
}
else
{
int h1 = HexToInt(s[pos + 1]);
int h2 = HexToInt(s[pos + 2]);
if (h1 >= 0 && h2 >= 0)
{ // valid 2 hex chars
byte b = (byte)((h1 << 4) | h2);
pos += 2;
// don't add as char
helper.AddByte(b);
continue;
}
}
}
if ((ch & 0xFF80) == 0)
helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode
else
helper.AddChar(ch);
}
return helper.GetString();
}
private static int HexToInt(char h)
{
return (h >= '0' && h <= '9') ? h - '0' :
(h >= 'a' && h <= 'f') ? h - 'a' + 10 :
(h >= 'A' && h <= 'F') ? h - 'A' + 10 :
-1;
}
private class UrlDecoder
{
private int _bufferSize;
// Accumulate characters in a special array
private int _numChars;
private char[] _charBuffer;
// Accumulate bytes for decoding into characters in a special array
private int _numBytes;
private byte[] _byteBuffer;
// Encoding to convert chars to bytes
private Encoding _encoding;
private void FlushBytes()
{
if (_numBytes > 0)
{
_numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars);
_numBytes = 0;
}
}
internal UrlDecoder(int bufferSize, Encoding encoding)
{
_bufferSize = bufferSize;
_encoding = encoding;
_charBuffer = new char[bufferSize];
// byte buffer created on demand
}
internal void AddChar(char ch)
{
if (_numBytes > 0)
FlushBytes();
_charBuffer[_numChars++] = ch;
}
internal void AddByte(byte b)
{
{
if (_byteBuffer == null)
_byteBuffer = new byte[_bufferSize];
_byteBuffer[_numBytes++] = b;
}
}
internal string GetString()
{
if (_numBytes > 0)
FlushBytes();
if (_numChars > 0)
return new string(_charBuffer, 0, _numChars);
else
return string.Empty;
}
}
internal static void FillFromString(NameValueCollection nvc, string s, bool urlencoded, Encoding encoding)
{
int l = (s != null) ? s.Length : 0;
int i = (s.Length > 0 && s[0] == '?') ? 1 : 0;
while (i < l)
{
// find next & while noting first = on the way (and if there are more)
int si = i;
int ti = -1;
while (i < l)
{
char ch = s[i];
if (ch == '=')
{
if (ti < 0)
ti = i;
}
else if (ch == '&')
{
break;
}
i++;
}
// extract the name / value pair
string name = null;
string value = null;
if (ti >= 0)
{
name = s.Substring(si, ti - si);
value = s.Substring(ti + 1, i - ti - 1);
}
else
{
value = s.Substring(si, i - si);
}
// add name / value pair to the collection
if (urlencoded)
nvc.Add(
name == null ? null : UrlDecodeStringFromStringInternal(name, encoding),
UrlDecodeStringFromStringInternal(value, encoding));
else
nvc.Add(name, value);
// trailing '&'
if (i == l - 1 && s[i] == '&')
nvc.Add(null, "");
i++;
}
}
}
}
}
| |
// 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.Runtime.CompilerServices;
using Xunit;
namespace System.Threading.Tasks.Tests
{
public class TaskAwaiterTests
{
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(false, null)]
[InlineData(true, false)]
[InlineData(true, true)]
[InlineData(true, null)]
public static void OnCompleted_CompletesInAnotherSynchronizationContext(bool generic, bool? continueOnCapturedContext)
{
SynchronizationContext origCtx = SynchronizationContext.Current;
try
{
// Create a context that tracks operations, and set it as current
var validateCtx = new ValidateCorrectContextSynchronizationContext();
Assert.Equal(0, validateCtx.PostCount);
SynchronizationContext.SetSynchronizationContext(validateCtx);
// Create a not-completed task and get an awaiter for it
var mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
// Hook up a callback
bool postedInContext = false;
Action callback = () =>
{
postedInContext = ValidateCorrectContextSynchronizationContext.t_isPostedInContext;
mres.Set();
};
if (generic)
{
if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
else tcs.Task.GetAwaiter().OnCompleted(callback);
}
else
{
if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback);
}
Assert.False(mres.IsSet, "Callback should not yet have run.");
// Complete the task in another context and wait for the callback to run
Task.Run(() => tcs.SetResult(null));
mres.Wait();
// Validate the callback ran and in the correct context
bool shouldHavePosted = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value;
Assert.Equal(shouldHavePosted ? 1 : 0, validateCtx.PostCount);
Assert.Equal(shouldHavePosted, postedInContext);
}
finally
{
// Reset back to the original context
SynchronizationContext.SetSynchronizationContext(origCtx);
}
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(false, null)]
[InlineData(true, false)]
[InlineData(true, true)]
[InlineData(true, null)]
public static void OnCompleted_CompletesInAnotherTaskScheduler(bool generic, bool? continueOnCapturedContext)
{
SynchronizationContext origCtx = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null); // get off xunit's SynchronizationContext to avoid interactions with await
var quwi = new QUWITaskScheduler();
RunWithSchedulerAsCurrent(quwi, delegate
{
Assert.True(TaskScheduler.Current == quwi, "Expected to be on target scheduler");
// Create the not completed task and get its awaiter
var mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
// Hook up the callback
bool ranOnScheduler = false;
Action callback = () =>
{
ranOnScheduler = (TaskScheduler.Current == quwi);
mres.Set();
};
if (generic)
{
if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
else tcs.Task.GetAwaiter().OnCompleted(callback);
}
else
{
if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback);
}
Assert.False(mres.IsSet, "Callback should not yet have run.");
// Complete the task in another scheduler and wait for the callback to run
Task.Run(delegate { tcs.SetResult(null); });
mres.Wait();
// Validate the callback ran on the right scheduler
bool shouldHaveRunOnScheduler = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value;
Assert.Equal(shouldHaveRunOnScheduler, ranOnScheduler);
});
}
finally
{
SynchronizationContext.SetSynchronizationContext(origCtx);
}
}
[Fact]
public async Task Await_TaskCompletesOnNonDefaultSyncCtx_ContinuesOnDefaultSyncCtx()
{
await Task.Run(async delegate // escape xunit's sync context
{
Assert.Null(SynchronizationContext.Current);
Assert.Same(TaskScheduler.Default, TaskScheduler.Current);
var ctx = new ValidateCorrectContextSynchronizationContext();
var tcs = new TaskCompletionSource<bool>();
var ignored = Task.Delay(1).ContinueWith(_ =>
{
SynchronizationContext orig = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(ctx);
try
{
tcs.SetResult(true);
}
finally
{
SynchronizationContext.SetSynchronizationContext(orig);
}
}, TaskScheduler.Default);
await tcs.Task;
Assert.Null(SynchronizationContext.Current);
Assert.Same(TaskScheduler.Default, TaskScheduler.Current);
});
}
[Fact]
public async Task Await_TaskCompletesOnNonDefaultScheduler_ContinuesOnDefaultScheduler()
{
await Task.Run(async delegate // escape xunit's sync context
{
Assert.Null(SynchronizationContext.Current);
Assert.Same(TaskScheduler.Default, TaskScheduler.Current);
var tcs = new TaskCompletionSource<bool>();
var ignored = Task.Delay(1).ContinueWith(_ => tcs.SetResult(true), new QUWITaskScheduler());
await tcs.Task;
Assert.Null(SynchronizationContext.Current);
Assert.Same(TaskScheduler.Default, TaskScheduler.Current);
});
}
[Fact]
public static void GetResult_Completed_Success()
{
Task task = Task.CompletedTask;
task.GetAwaiter().GetResult();
task.ConfigureAwait(false).GetAwaiter().GetResult();
task.ConfigureAwait(true).GetAwaiter().GetResult();
const string expectedResult = "42";
Task<string> taskOfString = Task.FromResult(expectedResult);
Assert.Equal(expectedResult, taskOfString.GetAwaiter().GetResult());
Assert.Equal(expectedResult, taskOfString.ConfigureAwait(false).GetAwaiter().GetResult());
Assert.Equal(expectedResult, taskOfString.ConfigureAwait(true).GetAwaiter().GetResult());
}
[OuterLoop]
[Fact]
public static void GetResult_NotCompleted_BlocksUntilCompletion()
{
var tcs = new TaskCompletionSource<bool>();
// Kick off tasks that should all block
var tasks = new[] {
Task.Run(() => tcs.Task.GetAwaiter().GetResult()),
Task.Run(() => ((Task)tcs.Task).GetAwaiter().GetResult()),
Task.Run(() => tcs.Task.ConfigureAwait(false).GetAwaiter().GetResult()),
Task.Run(() => ((Task)tcs.Task).ConfigureAwait(false).GetAwaiter().GetResult())
};
Assert.Equal(-1, Task.WaitAny(tasks, 100)); // "Tasks should not have completed"
// Now complete the tasks, after which all the tasks should complete successfully.
tcs.SetResult(true);
Task.WaitAll(tasks);
}
[Fact]
public static void GetResult_CanceledTask_ThrowsCancellationException()
{
// Validate cancellation
Task<string> canceled = Task.FromCanceled<string>(new CancellationToken(true));
// Task.GetAwaiter and Task<T>.GetAwaiter
Assert.Throws<TaskCanceledException>(() => ((Task)canceled).GetAwaiter().GetResult());
Assert.Throws<TaskCanceledException>(() => canceled.GetAwaiter().GetResult());
// w/ ConfigureAwait false and true
Assert.Throws<TaskCanceledException>(() => ((Task)canceled).ConfigureAwait(false).GetAwaiter().GetResult());
Assert.Throws<TaskCanceledException>(() => ((Task)canceled).ConfigureAwait(true).GetAwaiter().GetResult());
Assert.Throws<TaskCanceledException>(() => canceled.ConfigureAwait(false).GetAwaiter().GetResult());
Assert.Throws<TaskCanceledException>(() => canceled.ConfigureAwait(true).GetAwaiter().GetResult());
}
[Fact]
public static void GetResult_FaultedTask_OneException_ThrowsOriginalException()
{
var exception = new ArgumentException("uh oh");
Task<string> task = Task.FromException<string>(exception);
// Task.GetAwaiter and Task<T>.GetAwaiter
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.GetAwaiter().GetResult()));
// w/ ConfigureAwait false and true
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).ConfigureAwait(false).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).ConfigureAwait(true).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.ConfigureAwait(false).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.ConfigureAwait(true).GetAwaiter().GetResult()));
}
[Fact]
public static void GetResult_FaultedTask_MultipleExceptions_ThrowsFirstException()
{
var exception = new ArgumentException("uh oh");
var tcs = new TaskCompletionSource<string>();
tcs.SetException(new Exception[] { exception, new InvalidOperationException("uh oh") });
Task<string> task = tcs.Task;
// Task.GetAwaiter and Task<T>.GetAwaiter
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.GetAwaiter().GetResult()));
// w/ ConfigureAwait false and true
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).ConfigureAwait(false).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).ConfigureAwait(true).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.ConfigureAwait(false).GetAwaiter().GetResult()));
Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.ConfigureAwait(true).GetAwaiter().GetResult()));
}
[Fact]
public static void AwaiterAndAwaitableEquality()
{
var completed = new TaskCompletionSource<string>();
Task task = completed.Task;
// TaskAwaiter
task.GetAwaiter().Equals(task.GetAwaiter());
// ConfiguredTaskAwaitable
Assert.Equal(task.ConfigureAwait(false), task.ConfigureAwait(false));
Assert.NotEqual(task.ConfigureAwait(false), task.ConfigureAwait(true));
Assert.NotEqual(task.ConfigureAwait(true), task.ConfigureAwait(false));
// ConfiguredTaskAwaitable<T>
Assert.Equal(task.ConfigureAwait(false), task.ConfigureAwait(false));
Assert.NotEqual(task.ConfigureAwait(false), task.ConfigureAwait(true));
Assert.NotEqual(task.ConfigureAwait(true), task.ConfigureAwait(false));
// ConfiguredTaskAwaitable.ConfiguredTaskAwaiter
Assert.Equal(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(true).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(true).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter());
// ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter
Assert.Equal(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(true).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(true).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter());
}
[Fact]
public static void BaseSynchronizationContext_SameAsNoSynchronizationContext()
{
var quwi = new QUWITaskScheduler();
SynchronizationContext origCtx = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
RunWithSchedulerAsCurrent(quwi, delegate
{
ManualResetEventSlim mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
var awaiter = ((Task)tcs.Task).GetAwaiter();
bool ranOnScheduler = false;
bool ranWithoutSyncCtx = false;
awaiter.OnCompleted(() =>
{
ranOnScheduler = (TaskScheduler.Current == quwi);
ranWithoutSyncCtx = SynchronizationContext.Current == null;
mres.Set();
});
Assert.False(mres.IsSet, "Callback should not yet have run.");
Task.Run(delegate { tcs.SetResult(null); });
mres.Wait();
Assert.True(ranOnScheduler, "Should have run on scheduler");
Assert.True(ranWithoutSyncCtx, "Should have run with a null sync ctx");
});
}
finally
{
SynchronizationContext.SetSynchronizationContext(origCtx);
}
}
[Theory]
[MemberData(nameof(CanceledTasksAndExpectedCancellationExceptions))]
public static void OperationCanceledException_PropagatesThroughCanceledTask(int lineNumber, Task task, OperationCanceledException expected)
{
var caught = Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult());
Assert.Same(expected, caught);
}
public static IEnumerable<object[]> CanceledTasksAndExpectedCancellationExceptions()
{
var cts = new CancellationTokenSource();
var oce = new OperationCanceledException(cts.Token);
// Scheduled Task
Task<int> generic = Task.Run<int>(new Func<int>(() =>
{
cts.Cancel();
throw oce;
}), cts.Token);
yield return new object[] { LineNumber(), generic, oce };
Task nonGeneric = generic;
// WhenAll Task and Task<int>
yield return new object[] { LineNumber(), Task.WhenAll(generic), oce };
yield return new object[] { LineNumber(), Task.WhenAll(generic, Task.FromResult(42)), oce };
yield return new object[] { LineNumber(), Task.WhenAll(Task.FromResult(42), generic), oce };
yield return new object[] { LineNumber(), Task.WhenAll(generic, generic, generic), oce };
yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric), oce };
yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric, Task.FromResult(42)), oce };
yield return new object[] { LineNumber(), Task.WhenAll(Task.FromResult(42), nonGeneric), oce };
yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric, nonGeneric, nonGeneric), oce };
// Task.Run Task and Task<int> with unwrapping
yield return new object[] { LineNumber(), Task.Run(() => generic), oce };
yield return new object[] { LineNumber(), Task.Run(() => nonGeneric), oce };
// A FromAsync Task and Task<int>
yield return new object[] { LineNumber(), Task.Factory.FromAsync(generic, new Action<IAsyncResult>(ar => { throw oce; })), oce };
yield return new object[] { LineNumber(), Task<int>.Factory.FromAsync(nonGeneric, new Func<IAsyncResult, int>(ar => { throw oce; })), oce };
// AsyncTaskMethodBuilder
var atmb = new AsyncTaskMethodBuilder();
atmb.SetException(oce);
yield return new object[] { LineNumber(), atmb.Task, oce };
}
private static int LineNumber([CallerLineNumber]int lineNumber = 0) => lineNumber;
private class ValidateCorrectContextSynchronizationContext : SynchronizationContext
{
[ThreadStatic]
internal static bool t_isPostedInContext;
internal int PostCount;
internal int SendCount;
public override void Post(SendOrPostCallback d, object state)
{
Interlocked.Increment(ref PostCount);
Task.Run(() =>
{
try
{
t_isPostedInContext = true;
d(state);
}
finally
{
t_isPostedInContext = false;
}
});
}
public override void Send(SendOrPostCallback d, object state)
{
Interlocked.Increment(ref SendCount);
d(state);
}
}
/// <summary>A scheduler that queues to the TP and tracks the number of times QueueTask and TryExecuteTaskInline are invoked.</summary>
private class QUWITaskScheduler : TaskScheduler
{
private int _queueTaskCount;
private int _tryExecuteTaskInlineCount;
public int QueueTaskCount { get { return _queueTaskCount; } }
public int TryExecuteTaskInlineCount { get { return _tryExecuteTaskInlineCount; } }
protected override IEnumerable<Task> GetScheduledTasks() { return null; }
protected override void QueueTask(Task task)
{
Interlocked.Increment(ref _queueTaskCount);
Task.Run(() => TryExecuteTask(task));
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
Interlocked.Increment(ref _tryExecuteTaskInlineCount);
return TryExecuteTask(task);
}
}
/// <summary>Runs the action with TaskScheduler.Current equal to the specified scheduler.</summary>
private static void RunWithSchedulerAsCurrent(TaskScheduler scheduler, Action action)
{
var t = new Task(action);
t.RunSynchronously(scheduler);
t.GetAwaiter().GetResult();
}
}
}
| |
// 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;
/// <summary>
/// MoveNext()
/// </summary>
public class EnumeratorMoveNext
{
public static int Main()
{
EnumeratorMoveNext test = new EnumeratorMoveNext();
TestLibrary.TestFramework.BeginTestCase("EnumeratorMoveNext");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: The enumerator should be positioned at the first element in the collection after MoveNext().");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
TestQueue.Enqueue("three");
Queue<string>.Enumerator TestEnumerator;
TestEnumerator = TestQueue.GetEnumerator();
TestEnumerator.MoveNext();
string TestString = TestEnumerator.Current;
if (TestString != "one")
{
TestLibrary.TestFramework.LogError("P01.1", "The enumerator is not positioned at the first element in the collection after MoveNext()!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: The enumerator should be positioned at the next element in the collection after MoveNext().");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
TestQueue.Enqueue("three");
Queue<string>.Enumerator TestEnumerator = TestQueue.GetEnumerator();
TestEnumerator.MoveNext();
if (TestEnumerator.Current != "one")
{
TestLibrary.TestFramework.LogError("P01.1", "Current() failed!");
retVal = false;
}
TestEnumerator.MoveNext();
if (TestEnumerator.Current != "two")
{
TestLibrary.TestFramework.LogError("P01.2", "Current() failed!");
retVal = false;
}
TestEnumerator.MoveNext();
if (TestEnumerator.Current != "three")
{
TestLibrary.TestFramework.LogError("P01.3", "Current() failed!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P02.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: The enumerator should be positioned after the last element in the collection after MoveNext() passed the end of collection.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
TestQueue.Enqueue("three");
Queue<string>.Enumerator TestEnumerator;
TestEnumerator = TestQueue.GetEnumerator();
bool bSuc;
bSuc = TestEnumerator.MoveNext();
bSuc = TestEnumerator.MoveNext();
bSuc = TestEnumerator.MoveNext();
bSuc = TestEnumerator.MoveNext();
bSuc = TestEnumerator.MoveNext();
bSuc = TestEnumerator.MoveNext();
if (bSuc)
{
TestLibrary.TestFramework.LogError("P03.1", "The enumerator is not positioned after the last element in the collection after MoveNext() passed the end of collection!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P03.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: With a Queue that contains three items, MoveNext returns true the first three times and returns false every time it is called after that.");
try
{
bool b;
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
TestQueue.Enqueue("three");
Queue<string>.Enumerator TestEnumerator;
TestEnumerator = TestQueue.GetEnumerator();
for (int i = 0; i < 3; i++)
{
b = TestEnumerator.MoveNext();
if (!b)
{
TestLibrary.TestFramework.LogError("P04.1", "MoveNext() failed!");
retVal = false;
}
}
b = TestEnumerator.MoveNext();
if (b)
{
TestLibrary.TestFramework.LogError("P04.1", "MoveNext() failed!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P04.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: InvalidOperationException should be thrown when the collection was modified after the enumerator was created.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
TestQueue.Enqueue("three");
Queue<string>.Enumerator TestEnumerator;
TestEnumerator = TestQueue.GetEnumerator();
TestQueue.Enqueue("four");
TestEnumerator.MoveNext();
TestLibrary.TestFramework.LogError("N01.1", "InvalidOperationException is not thrown when the collection was modified after the enumerator was created!");
retVal = false;
}
catch (InvalidOperationException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N01.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyComplex
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Array operations.
/// </summary>
public partial class Array : IServiceOperations<AutoRestComplexTestService>, IArray
{
/// <summary>
/// Initializes a new instance of the Array class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Array(AutoRestComplexTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestComplexTestService
/// </summary>
public AutoRestComplexTestService Client { get; private set; }
/// <summary>
/// Get complex types with array property
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<ArrayWrapper>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<ArrayWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types with array property
/// </summary>
/// <param name='array'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(IList<string> array = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
ArrayWrapper complexBody = new ArrayWrapper();
if (array != null)
{
complexBody.Array = array;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get complex types with array property which is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<ArrayWrapper>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<ArrayWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types with array property which is empty
/// </summary>
/// <param name='array'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(IList<string> array = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
ArrayWrapper complexBody = new ArrayWrapper();
if (array != null)
{
complexBody.Array = array;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get complex types with array property while server doesn't provide a
/// response payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<ArrayWrapper>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/notprovided").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<ArrayWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>CarrierConstant</c> resource.</summary>
public sealed partial class CarrierConstantName : gax::IResourceName, sys::IEquatable<CarrierConstantName>
{
/// <summary>The possible contents of <see cref="CarrierConstantName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>carrierConstants/{criterion_id}</c>.</summary>
Criterion = 1,
}
private static gax::PathTemplate s_criterion = new gax::PathTemplate("carrierConstants/{criterion_id}");
/// <summary>Creates a <see cref="CarrierConstantName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CarrierConstantName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CarrierConstantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CarrierConstantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CarrierConstantName"/> with the pattern <c>carrierConstants/{criterion_id}</c>.
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CarrierConstantName"/> constructed from the provided ids.</returns>
public static CarrierConstantName FromCriterion(string criterionId) =>
new CarrierConstantName(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CarrierConstantName"/> with pattern
/// <c>carrierConstants/{criterion_id}</c>.
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CarrierConstantName"/> with pattern
/// <c>carrierConstants/{criterion_id}</c>.
/// </returns>
public static string Format(string criterionId) => FormatCriterion(criterionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CarrierConstantName"/> with pattern
/// <c>carrierConstants/{criterion_id}</c>.
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CarrierConstantName"/> with pattern
/// <c>carrierConstants/{criterion_id}</c>.
/// </returns>
public static string FormatCriterion(string criterionId) =>
s_criterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="CarrierConstantName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>carrierConstants/{criterion_id}</c></description></item></list>
/// </remarks>
/// <param name="carrierConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CarrierConstantName"/> if successful.</returns>
public static CarrierConstantName Parse(string carrierConstantName) => Parse(carrierConstantName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CarrierConstantName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>carrierConstants/{criterion_id}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="carrierConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CarrierConstantName"/> if successful.</returns>
public static CarrierConstantName Parse(string carrierConstantName, bool allowUnparsed) =>
TryParse(carrierConstantName, allowUnparsed, out CarrierConstantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CarrierConstantName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>carrierConstants/{criterion_id}</c></description></item></list>
/// </remarks>
/// <param name="carrierConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CarrierConstantName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string carrierConstantName, out CarrierConstantName result) =>
TryParse(carrierConstantName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CarrierConstantName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>carrierConstants/{criterion_id}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="carrierConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CarrierConstantName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string carrierConstantName, bool allowUnparsed, out CarrierConstantName result)
{
gax::GaxPreconditions.CheckNotNull(carrierConstantName, nameof(carrierConstantName));
gax::TemplatedResourceName resourceName;
if (s_criterion.TryParseName(carrierConstantName, out resourceName))
{
result = FromCriterion(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(carrierConstantName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CarrierConstantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string criterionId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CriterionId = criterionId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CarrierConstantName"/> class from the component parts of pattern
/// <c>carrierConstants/{criterion_id}</c>
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
public CarrierConstantName(string criterionId) : this(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Criterion: return s_criterion.Expand(CriterionId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CarrierConstantName);
/// <inheritdoc/>
public bool Equals(CarrierConstantName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CarrierConstantName a, CarrierConstantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CarrierConstantName a, CarrierConstantName b) => !(a == b);
}
public partial class CarrierConstant
{
/// <summary>
/// <see cref="gagvr::CarrierConstantName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal CarrierConstantName ResourceNameAsCarrierConstantName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CarrierConstantName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::CarrierConstantName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal CarrierConstantName CarrierConstantName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::CarrierConstantName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008-2016 Charlie Poole
//
// 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.
// ***********************************************************************
#if ASYNC
using System;
using System.Threading.Tasks;
using NUnit.Framework.Internal;
using NUnit.TestUtilities;
namespace NUnit.Framework.Assertions
{
[TestFixture]
public class AssertThrowsAsyncTests
{
[Test]
public void ThrowsAsyncSucceedsWithDelegate()
{
Assert.ThrowsAsync(typeof(ArgumentException), AsyncTestDelegates.ThrowsArgumentException);
Assert.ThrowsAsync(typeof(ArgumentException),
delegate { throw new ArgumentException(); });
}
[Test]
public void GenericThrowsAsyncSucceedsWithDelegate()
{
Assert.ThrowsAsync<ArgumentException>(
delegate { throw new ArgumentException(); });
Assert.ThrowsAsync<ArgumentException>(AsyncTestDelegates.ThrowsArgumentException);
}
[Test]
public void ThrowsConstraintSucceedsWithDelegate()
{
// Without cast, delegate is ambiguous before C# 3.0.
Assert.That((AsyncTestDelegate)delegate { throw new ArgumentException(); },
Throws.Exception.TypeOf<ArgumentException>());
}
[Test]
public async Task AsyncRegionThrowsDoesNotDisposeAsyncRegion()
{
await AsyncTestDelegates.Delay(100);
Assert.ThrowsAsync<ArgumentException>(async () => await AsyncTestDelegates.ThrowsArgumentExceptionAsync());
Assert.That(async () => await AsyncTestDelegates.ThrowsArgumentExceptionAsync(), Throws.ArgumentException);
}
[Test]
public void ThrowsAsyncReturnsCorrectException()
{
Assert.ThrowsAsync(typeof(ArgumentException), AsyncTestDelegates.ThrowsArgumentExceptionAsync);
Assert.ThrowsAsync(typeof(ArgumentException),
delegate { return AsyncTestDelegates.Delay(5).ContinueWith(t => { throw new ArgumentException(); }, TaskScheduler.Default); });
CheckForSpuriousAssertionResults();
}
[Test]
public void GenericThrowsAsyncReturnsCorrectException()
{
Assert.ThrowsAsync<ArgumentException>(
delegate { return AsyncTestDelegates.Delay(5).ContinueWith(t => { throw new ArgumentException(); }, TaskScheduler.Default); });
Assert.ThrowsAsync<ArgumentException>(AsyncTestDelegates.ThrowsArgumentExceptionAsync);
CheckForSpuriousAssertionResults();
}
[Test]
public void ThrowsConstraintReturnsCorrectException()
{
// Without cast, delegate is ambiguous before C# 3.0.
Assert.That(
(AsyncTestDelegate)delegate { return AsyncTestDelegates.Delay(5).ContinueWith(t => { throw new ArgumentException(); }, TaskScheduler.Default); },
Throws.Exception.TypeOf<ArgumentException>());
CheckForSpuriousAssertionResults();
}
[Test]
public void CorrectExceptionIsReturnedToMethod()
{
ArgumentException ex = Assert.ThrowsAsync(typeof(ArgumentException),
new AsyncTestDelegate(AsyncTestDelegates.ThrowsArgumentException)) as ArgumentException;
Assert.IsNotNull(ex, "No ArgumentException thrown");
Assert.That(ex.Message, Does.StartWith("myMessage"));
#if !PORTABLE
Assert.That(ex.ParamName, Is.EqualTo("myParam"));
#endif
ex = Assert.ThrowsAsync<ArgumentException>(
delegate { throw new ArgumentException("myMessage", "myParam"); });
Assert.IsNotNull(ex, "No ArgumentException thrown");
Assert.That(ex.Message, Does.StartWith("myMessage"));
#if !PORTABLE
Assert.That(ex.ParamName, Is.EqualTo("myParam"));
#endif
ex = Assert.ThrowsAsync(typeof(ArgumentException),
delegate { throw new ArgumentException("myMessage", "myParam"); }) as ArgumentException;
Assert.IsNotNull(ex, "No ArgumentException thrown");
Assert.That(ex.Message, Does.StartWith("myMessage"));
#if !PORTABLE
Assert.That(ex.ParamName, Is.EqualTo("myParam"));
#endif
ex = Assert.ThrowsAsync<ArgumentException>(AsyncTestDelegates.ThrowsArgumentException);
Assert.IsNotNull(ex, "No ArgumentException thrown");
Assert.That(ex.Message, Does.StartWith("myMessage"));
#if !PORTABLE
Assert.That(ex.ParamName, Is.EqualTo("myParam"));
#endif
}
[Test]
public void CorrectExceptionIsReturnedToMethodAsync()
{
ArgumentException ex = Assert.ThrowsAsync(typeof(ArgumentException),
new AsyncTestDelegate(AsyncTestDelegates.ThrowsArgumentExceptionAsync)) as ArgumentException;
Assert.IsNotNull(ex, "No ArgumentException thrown");
Assert.That(ex.Message, Does.StartWith("myMessage"));
#if !PORTABLE
Assert.That(ex.ParamName, Is.EqualTo("myParam"));
#endif
ex = Assert.ThrowsAsync<ArgumentException>(
delegate { return AsyncTestDelegates.Delay(5).ContinueWith(t => { throw new ArgumentException("myMessage", "myParam"); }, TaskScheduler.Default); });
Assert.IsNotNull(ex, "No ArgumentException thrown");
Assert.That(ex.Message, Does.StartWith("myMessage"));
#if !PORTABLE
Assert.That(ex.ParamName, Is.EqualTo("myParam"));
#endif
ex = Assert.ThrowsAsync(typeof(ArgumentException),
delegate { return AsyncTestDelegates.Delay(5).ContinueWith(t => { throw new ArgumentException("myMessage", "myParam"); }, TaskScheduler.Default); }) as ArgumentException;
Assert.IsNotNull(ex, "No ArgumentException thrown");
Assert.That(ex.Message, Does.StartWith("myMessage"));
#if !PORTABLE
Assert.That(ex.ParamName, Is.EqualTo("myParam"));
#endif
ex = Assert.ThrowsAsync<ArgumentException>(AsyncTestDelegates.ThrowsArgumentExceptionAsync);
Assert.IsNotNull(ex, "No ArgumentException thrown");
Assert.That(ex.Message, Does.StartWith("myMessage"));
#if !PORTABLE
Assert.That(ex.ParamName, Is.EqualTo("myParam"));
#endif
}
[Test]
public void NoExceptionThrown()
{
var ex = CatchException(() => Assert.ThrowsAsync<ArgumentException>(AsyncTestDelegates.ThrowsNothing));
Assert.That(ex.Message, Is.EqualTo(
" Expected: <System.ArgumentException>" + Environment.NewLine +
" But was: null" + Environment.NewLine));
CheckForSpuriousAssertionResults();
}
[Test]
public void UnrelatedExceptionThrown()
{
var ex = CatchException(() => Assert.ThrowsAsync<ArgumentException>(AsyncTestDelegates.ThrowsNullReferenceException));
Assert.That(ex.Message, Does.StartWith(
" Expected: <System.ArgumentException>" + Environment.NewLine +
" But was: <System.NullReferenceException: my message" + Environment.NewLine));
CheckForSpuriousAssertionResults();
}
[Test]
public void UnrelatedExceptionThrownAsync()
{
var ex = CatchException(() => Assert.ThrowsAsync<ArgumentException>(AsyncTestDelegates.ThrowsNullReferenceExceptionAsync));
Assert.That(ex.Message, Does.StartWith(
" Expected: <System.ArgumentException>" + Environment.NewLine +
" But was: <System.NullReferenceException: my message" + Environment.NewLine));
CheckForSpuriousAssertionResults();
}
[Test]
public void BaseExceptionThrown()
{
var ex = CatchException(() => Assert.ThrowsAsync<ArgumentException>(AsyncTestDelegates.ThrowsSystemException));
Assert.That(ex.Message, Does.StartWith(
" Expected: <System.ArgumentException>" + Environment.NewLine +
" But was: <System.Exception: my message" + Environment.NewLine));
CheckForSpuriousAssertionResults();
}
[Test]
public void BaseExceptionThrownAsync()
{
var ex = CatchException(() => Assert.ThrowsAsync<ArgumentException>(AsyncTestDelegates.ThrowsSystemExceptionAsync));
Assert.That(ex.Message, Does.StartWith(
" Expected: <System.ArgumentException>" + Environment.NewLine +
" But was: <System.Exception: my message" + Environment.NewLine));
}
[Test]
public void DerivedExceptionThrown()
{
var ex = CatchException(() => Assert.ThrowsAsync<Exception>(AsyncTestDelegates.ThrowsArgumentException));
Assert.That(ex.Message, Does.StartWith(
" Expected: <System.Exception>" + Environment.NewLine +
" But was: <System.ArgumentException: myMessage" + Environment.NewLine + "Parameter name: myParam" + Environment.NewLine));
CheckForSpuriousAssertionResults();
}
[Test]
public void DerivedExceptionThrownAsync()
{
var ex = CatchException(() => Assert.ThrowsAsync<Exception>(AsyncTestDelegates.ThrowsArgumentExceptionAsync));
Assert.That(ex.Message, Does.StartWith(
" Expected: <System.Exception>" + Environment.NewLine +
" But was: <System.ArgumentException: myMessage" + Environment.NewLine + "Parameter name: myParam" + Environment.NewLine));
}
[Test]
public void DoesNotThrowSucceeds()
{
Assert.DoesNotThrowAsync(AsyncTestDelegates.ThrowsNothing);
}
[Test]
public void DoesNotThrowFails()
{
var ex = CatchException(() => Assert.DoesNotThrowAsync(AsyncTestDelegates.ThrowsArgumentException));
Assert.That(ex, Is.Not.Null.With.TypeOf<AssertionException>());
CheckForSpuriousAssertionResults();
}
[Test]
public void DoesNotThrowFailsAsync()
{
var ex = CatchException(() => Assert.DoesNotThrowAsync(AsyncTestDelegates.ThrowsArgumentExceptionAsync));
Assert.That(ex, Is.Not.Null.With.TypeOf<AssertionException>());
CheckForSpuriousAssertionResults();
}
private static void CheckForSpuriousAssertionResults()
{
var result = TestExecutionContext.CurrentContext.CurrentResult;
Assert.That(result.AssertionResults.Count, Is.EqualTo(0),
"Spurious result left by Assert.Fail()");
}
private Exception CatchException(TestDelegate del)
{
using (new TestExecutionContext.IsolatedContext())
{
try
{
del();
return null;
}
catch (Exception ex)
{
return ex;
}
}
}
}
}
#endif
| |
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading;
using Hazelcast.Client.Protocol;
using Hazelcast.Client.Protocol.Codec;
using Hazelcast.Client.Proxy;
using Hazelcast.Config;
using Hazelcast.Core;
using Hazelcast.IO;
using Hazelcast.IO.Serialization;
using Hazelcast.Logging;
using Hazelcast.Util;
#pragma warning disable CS1591
namespace Hazelcast.Client.Spi
{
internal sealed class ProxyManager
{
private static readonly ILogger Logger = Logging.Logger.GetLogger(typeof(ProxyManager));
private readonly HazelcastClient _client;
private readonly ConcurrentDictionary<DistributedObjectInfo, ClientProxy> _proxies =
new ConcurrentDictionary<DistributedObjectInfo, ClientProxy>();
private readonly ConcurrentDictionary<string, ClientProxyFactory> _proxyFactories =
new ConcurrentDictionary<string, ClientProxyFactory>();
public ProxyManager(HazelcastClient client)
{
_client = client;
var listenerConfigs = client.GetClientConfig().GetListenerConfigs();
if (listenerConfigs != null && listenerConfigs.Count > 0)
{
foreach (var listenerConfig in listenerConfigs.Where(listenerConfig =>
listenerConfig.GetImplementation() is IDistributedObjectListener))
{
AddDistributedObjectListener((IDistributedObjectListener) listenerConfig.GetImplementation());
}
}
}
public string AddDistributedObjectListener(IDistributedObjectListener listener)
{
var isSmart = _client.GetClientConfig().GetNetworkConfig().IsSmartRouting();
var request = ClientAddDistributedObjectListenerCodec.EncodeRequest(isSmart);
var context = new ClientContext(_client.GetSerializationService(), _client.GetClientClusterService(),
_client.GetClientPartitionService(), _client.GetInvocationService(), _client.GetClientExecutionService(),
_client.GetListenerService(), _client.GetNearCacheManager(), this, _client.GetClientConfig());
DistributedEventHandler eventHandler = delegate(IClientMessage message)
{
ClientAddDistributedObjectListenerCodec.EventHandler.HandleEvent(message, (name, serviceName, eventType) =>
{
var _event = new LazyDistributedObjectEvent(eventType, serviceName, name, this);
switch (eventType)
{
case DistributedObjectEvent.EventType.Created:
listener.DistributedObjectCreated(_event);
break;
case DistributedObjectEvent.EventType.Destroyed:
listener.DistributedObjectDestroyed(_event);
break;
default:
Logger.Warning(string.Format("Undefined DistributedObjectListener event type received: {0} !!!",
eventType));
break;
}
});
};
return context.GetListenerService().RegisterListener(request,
m => ClientAddDistributedObjectListenerCodec.DecodeResponse(m).response,
ClientRemoveDistributedObjectListenerCodec.EncodeRequest, eventHandler);
}
public void Shutdown()
{
foreach (var proxy in _proxies)
{
proxy.Value.OnShutdown();
}
_proxies.Clear();
}
public ICollection<IDistributedObject> GetDistributedObjects()
{
try
{
var request = ClientGetDistributedObjectsCodec.EncodeRequest();
var task = _client.GetInvocationService().InvokeOnRandomTarget(request);
var response = ThreadUtil.GetResult(task);
var result = ClientGetDistributedObjectsCodec.DecodeResponse(response).response;
foreach (var distributedObjectInfo in result)
{
var proxy = InitProxyLocal(distributedObjectInfo.ServiceName, distributedObjectInfo.ObjectName,
typeof(IDistributedObject));
_proxies.TryAdd(distributedObjectInfo, proxy);
}
return GetLocalDistributedObjects();
}
catch (Exception e)
{
throw ExceptionUtil.Rethrow(e);
}
}
private ICollection<IDistributedObject> GetLocalDistributedObjects()
{
return new ReadOnlyCollection<IDistributedObject>(_proxies.Values.ToList<IDistributedObject>());
}
private ClientProxy InitProxyLocal(string service, string id, Type requestedInterface)
{
var proxy = MakeProxy(service, id, requestedInterface);
proxy.SetContext(new ClientContext(_client.GetSerializationService(), _client.GetClientClusterService(),
_client.GetClientPartitionService(), _client.GetInvocationService(), _client.GetClientExecutionService(),
_client.GetListenerService(), _client.GetNearCacheManager(), this, _client.GetClientConfig()));
proxy.Init();
return proxy;
}
public ClientProxy GetOrCreateProxy<T>(string service, string id) where T : IDistributedObject
{
var objectInfo = new DistributedObjectInfo(service, id);
var requestedInterface = typeof(T);
var clientProxy = _proxies.GetOrAdd(objectInfo, distributedObjectInfo =>
{
// create a new proxy, which needs initialization on server.
var proxy = InitProxyLocal(service, id, requestedInterface);
InitializeWithRetry(proxy);
return proxy;
});
// only return the existing proxy, if the requested type args match
var proxyInterface = clientProxy.GetType().GetInterface(requestedInterface.Name);
var proxyArgs = proxyInterface.GetGenericArguments();
var requestedArgs = requestedInterface.GetGenericArguments();
if (proxyArgs.SequenceEqual(requestedArgs))
{
// the proxy we found matches what we were looking for
return clientProxy;
}
var isAssignable = true;
for (int i = 0; i < proxyArgs.Length; i++)
{
if (!proxyArgs[i].IsAssignableFrom(requestedArgs[i]))
{
isAssignable = false;
break;
}
}
if (isAssignable)
{
_proxies.TryRemove(objectInfo, out clientProxy);
return GetOrCreateProxy<T>(service, id);
}
throw new InvalidCastException(string.Format("Distributed object is already created with incompatible types [{0}]",
string.Join(", ", (object[]) proxyArgs)));
}
private ClientProxy MakeProxy(string service, string id, Type requestedInterface)
{
ClientProxyFactory factory;
_proxyFactories.TryGetValue(service, out factory);
if (factory == null)
{
throw new ArgumentException("No factory registered for service: " + service);
}
var clientProxy = factory(requestedInterface, id);
return clientProxy;
}
public void Init(ClientConfig config)
{
// register defaults
Register(ServiceNames.Map, (type, id) =>
{
var clientConfig = _client.GetClientConfig();
var nearCacheConfig = clientConfig.GetNearCacheConfig(id);
var proxyType = nearCacheConfig != null ? typeof(ClientMapNearCacheProxy<,>) : typeof(ClientMapProxy<,>);
return ProxyFactory(proxyType, type, ServiceNames.Map, id);
});
Register(ServiceNames.Queue,
(type, id) => ProxyFactory(typeof(ClientQueueProxy<>), type, ServiceNames.Queue, id));
Register(ServiceNames.MultiMap,
(type, id) => ProxyFactory(typeof(ClientMultiMapProxy<,>), type, ServiceNames.MultiMap, id));
Register(ServiceNames.List,
(type, id) => ProxyFactory(typeof(ClientListProxy<>), type, ServiceNames.List, id));
Register(ServiceNames.Set,
(type, id) => ProxyFactory(typeof(ClientSetProxy<>), type, ServiceNames.Set, id));
Register(ServiceNames.Topic,
(type, id) => ProxyFactory(typeof(ClientTopicProxy<>), type, ServiceNames.Topic, id));
Register(ServiceNames.AtomicLong,
(type, id) => ProxyFactory(typeof(ClientAtomicLongProxy), type, ServiceNames.AtomicLong, id));
Register(ServiceNames.Lock, (type, id) => ProxyFactory(typeof(ClientLockProxy), type, ServiceNames.Lock, id));
Register(ServiceNames.CountDownLatch,
(type, id) => ProxyFactory(typeof(ClientCountDownLatchProxy), type, ServiceNames.CountDownLatch, id));
Register(ServiceNames.Semaphore,
(type, id) => ProxyFactory(typeof(ClientSemaphoreProxy), type, ServiceNames.Semaphore, id));
Register(ServiceNames.Ringbuffer,
(type, id) => ProxyFactory(typeof(ClientRingbufferProxy<>), type, ServiceNames.Ringbuffer, id));
Register(ServiceNames.ReplicatedMap,
(type, id) => ProxyFactory(typeof(ClientReplicatedMapProxy<,>), type, ServiceNames.ReplicatedMap, id));
Register(ServiceNames.IdGenerator, delegate(Type type, string id)
{
var atomicLong = _client.GetAtomicLong("IdGeneratorService.ATOMIC_LONG_NAME" + id);
return Activator.CreateInstance(typeof(ClientIdGeneratorProxy), ServiceNames.IdGenerator, id, atomicLong) as
ClientProxy;
});
foreach (var proxyFactoryConfig in config.GetProxyFactoryConfigs())
{
try
{
ClientProxyFactory clientProxyFactory = null;
var type = Type.GetType(proxyFactoryConfig.GetClassName());
if (type != null)
{
clientProxyFactory = (ClientProxyFactory) Activator.CreateInstance(type);
}
Register(proxyFactoryConfig.GetService(), clientProxyFactory);
}
catch (Exception e)
{
Logger.Severe(e);
}
}
}
public void Register(string serviceName, ClientProxyFactory factory)
{
if (_proxyFactories.ContainsKey(serviceName))
{
throw new ArgumentException("Factory for service: " + serviceName + " is already registered!");
}
_proxyFactories.GetOrAdd(serviceName, factory);
}
public bool RemoveDistributedObjectListener(string id)
{
var context = new ClientContext(_client.GetSerializationService(), _client.GetClientClusterService(),
_client.GetClientPartitionService(), _client.GetInvocationService(), _client.GetClientExecutionService(),
_client.GetListenerService(), _client.GetNearCacheManager(), this, _client.GetClientConfig());
return context.GetListenerService().DeregisterListener(id);
}
public ClientProxy RemoveProxy(string service, string id)
{
var ns = new DistributedObjectInfo(service, id);
ClientProxy removed;
_proxies.TryRemove(ns, out removed);
return removed;
}
internal static ClientProxy ProxyFactory(Type proxyType, Type interfaceType, string name, string id)
{
if (proxyType.ContainsGenericParameters)
{
var typeWithParams = GetTypeWithParameters(proxyType, interfaceType);
return Activator.CreateInstance(typeWithParams, name, id) as ClientProxy;
}
return Activator.CreateInstance(proxyType, name, id) as ClientProxy;
}
public HazelcastClient GetHazelcastInstance()
{
return _client;
}
private Address FindNextAddressToCreateARequest()
{
var clusterSize = _client.GetClientClusterService().GetSize();
IMember liteMember = null;
var loadBalancer = _client.GetLoadBalancer();
for (var i = 0; i < clusterSize; i++)
{
var member = loadBalancer.Next();
if (member != null && !member.IsLiteMember)
{
return member.GetAddress();
}
if (liteMember == null)
{
liteMember = member;
}
}
return liteMember != null ? liteMember.GetAddress() : null;
}
private static Type GetTypeWithParameters(Type proxyType, Type interfaceType)
{
var genericTypeArguments = interfaceType.GetGenericArguments();
if (genericTypeArguments.Length == proxyType.GetGenericArguments().Length)
{
return proxyType.MakeGenericType(genericTypeArguments);
}
var types = new Type[proxyType.GetGenericArguments().Length];
for (var i = 0; i < types.Length; i++)
{
types[i] = typeof(object);
}
return proxyType.MakeGenericType(types);
}
private void InitializeOnServer(ClientProxy clientProxy)
{
var initializationTarget = FindNextAddressToCreateARequest();
var invocationTarget = initializationTarget;
if (initializationTarget != null && _client.GetConnectionManager().GetConnection(initializationTarget) == null)
{
invocationTarget = _client.GetClientClusterService().GetOwnerConnectionAddress();
}
if (invocationTarget == null)
{
throw new IOException("Not able to setup owner connection!");
}
var request =
ClientCreateProxyCodec.EncodeRequest(clientProxy.GetName(), clientProxy.GetServiceName(), initializationTarget);
try
{
ThreadUtil.GetResult(_client.GetInvocationService().InvokeOnTarget(request, invocationTarget));
}
catch (Exception e)
{
throw ExceptionUtil.Rethrow(e);
}
}
private void InitializeWithRetry(ClientProxy clientProxy)
{
var clientInvocationService = (ClientInvocationService) _client.GetInvocationService();
long retryCountLimit = clientInvocationService.InvocationRetryCount;
for (var retryCount = 0; retryCount < retryCountLimit; retryCount++)
{
try
{
InitializeOnServer(clientProxy);
return;
}
catch (Exception e)
{
Logger.Warning("Got error initializing proxy", e);
if (IsRetryable(e))
{
try
{
Thread.Sleep(clientInvocationService.InvocationRetryWaitTime);
}
catch (ThreadInterruptedException)
{
}
}
else
{
throw;
}
}
}
}
private bool IsRetryable(Exception exception)
{
return exception is RetryableHazelcastException || exception is IOException || exception is AuthenticationException ||
exception is HazelcastInstanceNotActiveException;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// LVHD SR specific operations
/// First published in XenServer 7.0.
/// </summary>
public partial class LVHD : XenObject<LVHD>
{
#region Constructors
public LVHD()
{
}
public LVHD(string uuid)
{
this.uuid = uuid;
}
/// <summary>
/// Creates a new LVHD from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public LVHD(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new LVHD from a Proxy_LVHD.
/// </summary>
/// <param name="proxy"></param>
public LVHD(Proxy_LVHD proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given LVHD.
/// </summary>
public override void UpdateFrom(LVHD record)
{
uuid = record.uuid;
}
internal void UpdateFrom(Proxy_LVHD proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this LVHD
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
}
public Proxy_LVHD ToProxy()
{
Proxy_LVHD result_ = new Proxy_LVHD();
result_.uuid = uuid ?? "";
return result_;
}
public bool DeepEquals(LVHD other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid);
}
public override string SaveChanges(Session session, string opaqueRef, LVHD server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given LVHD.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_lvhd">The opaque_ref of the given lvhd</param>
public static LVHD get_record(Session session, string _lvhd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.lvhd_get_record(session.opaque_ref, _lvhd);
else
return new LVHD(session.XmlRpcProxy.lvhd_get_record(session.opaque_ref, _lvhd ?? "").parse());
}
/// <summary>
/// Get a reference to the LVHD instance with the specified UUID.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<LVHD> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.lvhd_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<LVHD>.Create(session.XmlRpcProxy.lvhd_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given LVHD.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_lvhd">The opaque_ref of the given lvhd</param>
public static string get_uuid(Session session, string _lvhd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.lvhd_get_uuid(session.opaque_ref, _lvhd);
else
return session.XmlRpcProxy.lvhd_get_uuid(session.opaque_ref, _lvhd ?? "").parse();
}
/// <summary>
/// Upgrades an LVHD SR to enable thin-provisioning. Future VDIs created in this SR will be thinly-provisioned, although existing VDIs will be left alone. Note that the SR must be attached to the SRmaster for upgrade to work.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The LVHD Host to upgrade to being thin-provisioned.</param>
/// <param name="_sr">The LVHD SR to upgrade to being thin-provisioned.</param>
/// <param name="_initial_allocation">The initial amount of space to allocate to a newly-created VDI in bytes</param>
/// <param name="_allocation_quantum">The amount of space to allocate to a VDI when it needs to be enlarged in bytes</param>
public static string enable_thin_provisioning(Session session, string _host, string _sr, long _initial_allocation, long _allocation_quantum)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.lvhd_enable_thin_provisioning(session.opaque_ref, _host, _sr, _initial_allocation, _allocation_quantum);
else
return session.XmlRpcProxy.lvhd_enable_thin_provisioning(session.opaque_ref, _host ?? "", _sr ?? "", _initial_allocation.ToString(), _allocation_quantum.ToString()).parse();
}
/// <summary>
/// Upgrades an LVHD SR to enable thin-provisioning. Future VDIs created in this SR will be thinly-provisioned, although existing VDIs will be left alone. Note that the SR must be attached to the SRmaster for upgrade to work.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The LVHD Host to upgrade to being thin-provisioned.</param>
/// <param name="_sr">The LVHD SR to upgrade to being thin-provisioned.</param>
/// <param name="_initial_allocation">The initial amount of space to allocate to a newly-created VDI in bytes</param>
/// <param name="_allocation_quantum">The amount of space to allocate to a VDI when it needs to be enlarged in bytes</param>
public static XenRef<Task> async_enable_thin_provisioning(Session session, string _host, string _sr, long _initial_allocation, long _allocation_quantum)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_lvhd_enable_thin_provisioning(session.opaque_ref, _host, _sr, _initial_allocation, _allocation_quantum);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_lvhd_enable_thin_provisioning(session.opaque_ref, _host ?? "", _sr ?? "", _initial_allocation.ToString(), _allocation_quantum.ToString()).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
}
}
| |
// 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
{
internal static partial class Number
{
internal static unsafe class Grisu3
{
private const int Alpha = -59;
private const double D1Log210 = 0.301029995663981195;
private const int Gamma = -32;
private const int PowerDecimalExponentDistance = 8;
private const int PowerMinDecimalExponent = -348;
private const int PowerMaxDecimalExponent = 340;
private const int PowerOffset = -PowerMinDecimalExponent;
private const uint Ten4 = 10000;
private const uint Ten5 = 100000;
private const uint Ten6 = 1000000;
private const uint Ten7 = 10000000;
private const uint Ten8 = 100000000;
private const uint Ten9 = 1000000000;
private static readonly short[] s_CachedPowerBinaryExponents = new short[]
{
-1220,
-1193,
-1166,
-1140,
-1113,
-1087,
-1060,
-1034,
-1007,
-980,
-954,
-927,
-901,
-874,
-847,
-821,
-794,
-768,
-741,
-715,
-688,
-661,
-635,
-608,
-582,
-555,
-529,
-502,
-475,
-449,
-422,
-396,
-369,
-343,
-316,
-289,
-263,
-236,
-210,
-183,
-157,
-130,
-103,
-77,
-50,
-24,
3,
30,
56,
83,
109,
136,
162,
189,
216,
242,
269,
295,
322,
348,
375,
402,
428,
455,
481,
508,
534,
561,
588,
614,
641,
667,
694,
720,
747,
774,
800,
827,
853,
880,
907,
933,
960,
986,
1013,
1039,
1066,
};
private static readonly short[] s_CachedPowerDecimalExponents = new short[]
{
PowerMinDecimalExponent,
-340,
-332,
-324,
-316,
-308,
-300,
-292,
-284,
-276,
-268,
-260,
-252,
-244,
-236,
-228,
-220,
-212,
-204,
-196,
-188,
-180,
-172,
-164,
-156,
-148,
-140,
-132,
-124,
-116,
-108,
-100,
-92,
-84,
-76,
-68,
-60,
-52,
-44,
-36,
-28,
-20,
-12,
-4,
4,
12,
20,
28,
36,
44,
52,
60,
68,
76,
84,
92,
100,
108,
116,
124,
132,
140,
148,
156,
164,
172,
180,
188,
196,
204,
212,
220,
228,
236,
244,
252,
260,
268,
276,
284,
292,
300,
308,
316,
324,
332,
PowerMaxDecimalExponent,
};
private static readonly uint[] s_CachedPowerOfTen = new uint[]
{
1, // 10^0
10, // 10^1
100, // 10^2
1000, // 10^3
10000, // 10^4
100000, // 10^5
1000000, // 10^6
10000000, // 10^7
100000000, // 10^8
1000000000, // 10^9
};
private static readonly ulong[] s_CachedPowerSignificands = new ulong[]
{
0xFA8FD5A0081C0288,
0xBAAEE17FA23EBF76,
0x8B16FB203055AC76,
0xCF42894A5DCE35EA,
0x9A6BB0AA55653B2D,
0xE61ACF033D1A45DF,
0xAB70FE17C79AC6CA,
0xFF77B1FCBEBCDC4F,
0xBE5691EF416BD60C,
0x8DD01FAD907FFC3C,
0xD3515C2831559A83,
0x9D71AC8FADA6C9B5,
0xEA9C227723EE8BCB,
0xAECC49914078536D,
0x823C12795DB6CE57,
0xC21094364DFB5637,
0x9096EA6F3848984F,
0xD77485CB25823AC7,
0xA086CFCD97BF97F4,
0xEF340A98172AACE5,
0xB23867FB2A35B28E,
0x84C8D4DFD2C63F3B,
0xC5DD44271AD3CDBA,
0x936B9FCEBB25C996,
0xDBAC6C247D62A584,
0xA3AB66580D5FDAF6,
0xF3E2F893DEC3F126,
0xB5B5ADA8AAFF80B8,
0x87625F056C7C4A8B,
0xC9BCFF6034C13053,
0x964E858C91BA2655,
0xDFF9772470297EBD,
0xA6DFBD9FB8E5B88F,
0xF8A95FCF88747D94,
0xB94470938FA89BCF,
0x8A08F0F8BF0F156B,
0xCDB02555653131B6,
0x993FE2C6D07B7FAC,
0xE45C10C42A2B3B06,
0xAA242499697392D3,
0xFD87B5F28300CA0E,
0xBCE5086492111AEB,
0x8CBCCC096F5088CC,
0xD1B71758E219652C,
0x9C40000000000000,
0xE8D4A51000000000,
0xAD78EBC5AC620000,
0x813F3978F8940984,
0xC097CE7BC90715B3,
0x8F7E32CE7BEA5C70,
0xD5D238A4ABE98068,
0x9F4F2726179A2245,
0xED63A231D4C4FB27,
0xB0DE65388CC8ADA8,
0x83C7088E1AAB65DB,
0xC45D1DF942711D9A,
0x924D692CA61BE758,
0xDA01EE641A708DEA,
0xA26DA3999AEF774A,
0xF209787BB47D6B85,
0xB454E4A179DD1877,
0x865B86925B9BC5C2,
0xC83553C5C8965D3D,
0x952AB45CFA97A0B3,
0xDE469FBD99A05FE3,
0xA59BC234DB398C25,
0xF6C69A72A3989F5C,
0xB7DCBF5354E9BECE,
0x88FCF317F22241E2,
0xCC20CE9BD35C78A5,
0x98165AF37B2153DF,
0xE2A0B5DC971F303A,
0xA8D9D1535CE3B396,
0xFB9B7CD9A4A7443C,
0xBB764C4CA7A44410,
0x8BAB8EEFB6409C1A,
0xD01FEF10A657842C,
0x9B10A4E5E9913129,
0xE7109BFBA19C0C9D,
0xAC2820D9623BF429,
0x80444B5E7AA7CF85,
0xBF21E44003ACDD2D,
0x8E679C2F5E44FF8F,
0xD433179D9C8CB841,
0x9E19DB92B4E31BA9,
0xEB96BF6EBADF77D9,
0xAF87023B9BF0EE6B,
};
public static bool Run(double value, int precision, ref NumberBuffer number)
{
// ========================================================================================================================================
// This implementation is based on the paper: http://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf
// You must read this paper to fully understand the code.
//
// Deviation: Instead of generating shortest digits, we generate the digits according to the input count.
// Therefore, we do not need m+ and m- which are used to determine the exact range of values.
// ========================================================================================================================================
//
// Overview:
//
// The idea of Grisu3 is to leverage additional bits and cached power of ten to produce the digits.
// We need to create a handmade floating point data structure DiyFp to extend the bits of double.
// We also need to cache the powers of ten for digits generation. By choosing the correct index of powers
// we need to start with, we can eliminate the expensive big num divide operation.
//
// Grisu3 is imprecision for some numbers. Fortunately, the algorithm itself can determine that and give us
// a success/fail flag. We may fall back to other algorithms (For instance, Dragon4) if it fails.
//
// w: the normalized DiyFp from the input value.
// mk: The index of the cached powers.
// cmk: The cached power.
// D: Product: w * cmk.
// kappa: A factor used for generating digits. See step 5 of the Grisu3 procedure in the paper.
// Handle sign bit.
if (double.IsNegative(value))
{
value = -value;
number.sign = true;
}
else
{
number.sign = false;
}
// Step 1: Determine the normalized DiyFp w.
DiyFp.GenerateNormalizedDiyFp(value, out DiyFp w);
// Step 2: Find the cached power of ten.
// Compute the proper index mk.
int mk = KComp(w.e + DiyFp.SignificandLength);
// Retrieve the cached power of ten.
CachedPower(mk, out DiyFp cmk, out int decimalExponent);
// Step 3: Scale the w with the cached power of ten.
DiyFp.Multiply(ref w, ref cmk, out DiyFp D);
// Step 4: Generate digits.
bool isSuccess = DigitGen(ref D, precision, number.GetDigitsPointer(), out int length, out int kappa);
if (isSuccess)
{
number.digits[precision] = '\0';
number.scale = (length - decimalExponent + kappa);
}
return isSuccess;
}
// Returns the biggest power of ten that is less than or equal to the given number.
static void BiggestPowerTenLessThanOrEqualTo(uint number, int bits, out uint power, out int exponent)
{
switch (bits)
{
case 32:
case 31:
case 30:
{
if (Ten9 <= number)
{
power = Ten9;
exponent = 9;
break;
}
goto case 29;
}
case 29:
case 28:
case 27:
{
if (Ten8 <= number)
{
power = Ten8;
exponent = 8;
break;
}
goto case 26;
}
case 26:
case 25:
case 24:
{
if (Ten7 <= number)
{
power = Ten7;
exponent = 7;
break;
}
goto case 23;
}
case 23:
case 22:
case 21:
case 20:
{
if (Ten6 <= number)
{
power = Ten6;
exponent = 6;
break;
}
goto case 19;
}
case 19:
case 18:
case 17:
{
if (Ten5 <= number)
{
power = Ten5;
exponent = 5;
break;
}
goto case 16;
}
case 16:
case 15:
case 14:
{
if (Ten4 <= number)
{
power = Ten4;
exponent = 4;
break;
}
goto case 13;
}
case 13:
case 12:
case 11:
case 10:
{
if (1000 <= number)
{
power = 1000;
exponent = 3;
break;
}
goto case 9;
}
case 9:
case 8:
case 7:
{
if (100 <= number)
{
power = 100;
exponent = 2;
break;
}
goto case 6;
}
case 6:
case 5:
case 4:
{
if (10 <= number)
{
power = 10;
exponent = 1;
break;
}
goto case 3;
}
case 3:
case 2:
case 1:
{
if (1 <= number)
{
power = 1;
exponent = 0;
break;
}
goto case 0;
}
case 0:
{
power = 0;
exponent = -1;
break;
}
default:
{
power = 0;
exponent = 0;
Debug.Fail("unreachable");
break;
}
}
}
private static void CachedPower(int k, out DiyFp cmk, out int decimalExponent)
{
int index = ((PowerOffset + k - 1) / PowerDecimalExponentDistance) + 1;
cmk = new DiyFp(s_CachedPowerSignificands[index], s_CachedPowerBinaryExponents[index]);
decimalExponent = s_CachedPowerDecimalExponents[index];
}
private static bool DigitGen(ref DiyFp mp, int precision, char* digits, out int length, out int k)
{
// Split the input mp to two parts. Part 1 is integral. Part 2 can be used to calculate
// fractional.
//
// mp: the input DiyFp scaled by cached power.
// K: final kappa.
// p1: part 1.
// p2: part 2.
Debug.Assert(precision > 0);
Debug.Assert(digits != null);
Debug.Assert(mp.e >= Alpha);
Debug.Assert(mp.e <= Gamma);
ulong mpF = mp.f;
int mpE = mp.e;
var one = new DiyFp(1UL << -mpE, mpE);
ulong oneF = one.f;
int oneNegE = -one.e;
ulong ulp = 1;
uint p1 = (uint)(mpF >> oneNegE);
ulong p2 = mpF & (oneF - 1);
// When p2 (fractional part) is zero, we can predicate if p1 is good to produce the numbers in requested digit count:
//
// - When requested digit count >= 11, p1 is not be able to exhaust the count as 10^(11 - 1) > uint.MaxValue >= p1.
// - When p1 < 10^(count - 1), p1 is not be able to exhaust the count.
// - Otherwise, p1 may have chance to exhaust the count.
if ((p2 == 0) && ((precision >= 11) || (p1 < s_CachedPowerOfTen[precision - 1])))
{
length = 0;
k = 0;
return false;
}
// Note: The code in the paper simply assigns div to Ten9 and kappa to 10 directly.
// That means we need to check if any leading zero of the generated
// digits during the while loop, which hurts the performance.
//
// Now if we can estimate what the div and kappa, we do not need to check the leading zeros.
// The idea is to find the biggest power of 10 that is less than or equal to the given number.
// Then we don't need to worry about the leading zeros and we can get 10% performance gain.
int index = 0;
BiggestPowerTenLessThanOrEqualTo(p1, (DiyFp.SignificandLength - oneNegE), out uint div, out int kappa);
kappa++;
// Produce integral.
while (kappa > 0)
{
int d = (int)(Math.DivRem(p1, div, out p1));
digits[index] = (char)('0' + d);
index++;
precision--;
kappa--;
if (precision == 0)
{
break;
}
div /= 10;
}
// End up here if we already exhausted the digit count.
if (precision == 0)
{
ulong rest = ((ulong)(p1) << oneNegE) + p2;
length = index;
k = kappa;
return RoundWeed(
digits,
index,
rest,
((ulong)(div)) << oneNegE,
ulp,
ref k
);
}
// We have to generate digits from part2 if we have requested digit count left
// and part2 is greater than ulp.
while ((precision > 0) && (p2 > ulp))
{
p2 *= 10;
int d = (int)(p2 >> oneNegE);
digits[index] = (char)('0' + d);
index++;
precision--;
kappa--;
p2 &= (oneF - 1);
ulp *= 10;
}
// If we haven't exhausted the requested digit counts, the Grisu3 algorithm fails.
if (precision != 0)
{
length = 0;
k = 0;
return false;
}
length = index;
k = kappa;
return RoundWeed(digits, index, p2, oneF, ulp, ref k);
}
private static int KComp(int e)
{
return (int)(Math.Ceiling((Alpha - e + DiyFp.SignificandLength - 1) * D1Log210));
}
private static bool RoundWeed(char* buffer, int len, ulong rest, ulong tenKappa, ulong ulp, ref int kappa)
{
Debug.Assert(rest < tenKappa);
// 1. tenKappa <= ulp: we don't have an idea which way to round.
// 2. Even if tenKappa > ulp, but if tenKappa <= 2 * ulp we cannot find the way to round.
// Note: to prevent overflow, we need to use tenKappa - ulp <= ulp.
if ((tenKappa <= ulp) || ((tenKappa - ulp) <= ulp))
{
return false;
}
// tenKappa >= 2 * (rest + ulp). We should round down.
// Note: to prevent overflow, we need to check if tenKappa > 2 * rest as a prerequisite.
if (((tenKappa - rest) > rest) && ((tenKappa - (2 * rest)) >= (2 * ulp)))
{
return true;
}
// tenKappa <= 2 * (rest - ulp). We should round up.
// Note: to prevent overflow, we need to check if rest > ulp as a prerequisite.
if ((rest > ulp) && (tenKappa <= (rest - ulp) || ((tenKappa - (rest - ulp)) <= (rest - ulp))))
{
// Find all 9s from end to start.
buffer[len - 1]++;
for (int i = len - 1; i > 0; i--)
{
if (buffer[i] != (char)('0' + 10))
{
// We end up a number less than 9.
break;
}
// Current number becomes 0 and add the promotion to the next number.
buffer[i] = '0';
buffer[i - 1]++;
}
if (buffer[0] == (char)('0' + 10))
{
// First number is '0' + 10 means all numbers are 9.
// We simply make the first number to 1 and increase the kappa.
buffer[0] = '1';
kappa++;
}
return true;
}
return false;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.