context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
// using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Framework.Capabilities
{
public delegate void UpLoadedAsset(
string assetName, string description, UUID assetID, UUID inventoryItem, UUID parentFolder,
byte[] data, string inventoryType, string assetType);
public delegate void UploadedBakedTexture(UUID assetID, byte[] data);
public delegate UUID UpdateItem(UUID itemID, byte[] data);
public delegate void UpdateTaskScript(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors);
public delegate void NewInventoryItem(UUID userID, InventoryItemBase item);
public delegate void NewAsset(AssetBase asset);
public delegate UUID ItemUpdatedCallback(UUID userID, UUID itemID, byte[] data);
public delegate ArrayList TaskScriptUpdatedCallback(UUID userID, UUID itemID, UUID primID,
bool isScriptRunning, byte[] data);
public delegate InventoryCollection FetchInventoryDescendentsCAPS(UUID agentID, UUID folderID, UUID ownerID,
bool fetchFolders, bool fetchItems, int sortOrder, out int version);
/// <summary>
/// XXX Probably not a particularly nice way of allow us to get the scene presence from the scene (chiefly so that
/// we can popup a message on the user's client if the inventory service has permanently failed). But I didn't want
/// to just pass the whole Scene into CAPS.
/// </summary>
public delegate IClientAPI GetClientDelegate(UUID agentID);
public class Caps
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_httpListenerHostName;
private uint m_httpListenPort;
/// <summary>
/// This is the uuid portion of every CAPS path. It is used to make capability urls private to the requester.
/// </summary>
private string m_capsObjectPath;
public string CapsObjectPath { get { return m_capsObjectPath; } }
private CapsHandlers m_capsHandlers;
private static readonly string m_requestPath = "0000/";
// private static readonly string m_mapLayerPath = "0001/";
private static readonly string m_newInventory = "0002/";
//private static readonly string m_requestTexture = "0003/";
private static readonly string m_notecardUpdatePath = "0004/";
private static readonly string m_notecardTaskUpdatePath = "0005/";
// private static readonly string m_fetchInventoryPath = "0006/";
// The following entries are in a module, however, they are also here so that we don't re-assign
// the path to another cap by mistake.
// private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; // This is in a module.
// private static readonly string m_provisionVoiceAccountRequestPath = "0008/";// This is in a module.
// private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule.
private static readonly string m_uploadBakedTexturePath = "0010/";// This is in the LandManagementModule.
//private string eventQueue = "0100/";
private IScene m_Scene;
private IHttpServer m_httpListener;
private UUID m_agentID;
private IAssetService m_assetCache;
private int m_eventQueueCount = 1;
private Queue<string> m_capsEventQueue = new Queue<string>();
private bool m_dumpAssetsToFile;
private string m_regionName;
private object m_fetchLock = new Object();
public bool SSLCaps
{
get { return m_httpListener.UseSSL; }
}
public string SSLCommonName
{
get { return m_httpListener.SSLCommonName; }
}
public CapsHandlers CapsHandlers
{
get { return m_capsHandlers; }
}
// These are callbacks which will be setup by the scene so that we can update scene data when we
// receive capability calls
public NewInventoryItem AddNewInventoryItem = null;
public NewAsset AddNewAsset = null;
public ItemUpdatedCallback ItemUpdatedCall = null;
public TaskScriptUpdatedCallback TaskScriptUpdatedCall = null;
public FetchInventoryDescendentsCAPS CAPSFetchInventoryDescendents = null;
public GetClientDelegate GetClient = null;
public Caps(IScene scene, IAssetService assetCache, IHttpServer httpServer, string httpListen, uint httpPort, string capsPath,
UUID agent, bool dumpAssetsToFile, string regionName)
{
m_Scene = scene;
m_assetCache = assetCache;
m_capsObjectPath = capsPath;
m_httpListener = httpServer;
m_httpListenerHostName = httpListen;
m_httpListenPort = httpPort;
if (httpServer != null && httpServer.UseSSL)
{
m_httpListenPort = httpServer.SSLPort;
httpListen = httpServer.SSLCommonName;
httpPort = httpServer.SSLPort;
}
m_agentID = agent;
m_dumpAssetsToFile = dumpAssetsToFile;
m_capsHandlers = new CapsHandlers(httpServer, httpListen, httpPort, (httpServer == null) ? false : httpServer.UseSSL);
m_regionName = regionName;
}
/// <summary>
/// Register all CAPS http service handlers
/// </summary>
public void RegisterHandlers()
{
DeregisterHandlers();
string capsBase = "/CAPS/" + m_capsObjectPath;
RegisterRegionServiceHandlers(capsBase);
RegisterInventoryServiceHandlers(capsBase);
}
public void RegisterRegionServiceHandlers(string capsBase)
{
try
{
// the root of all evil
m_capsHandlers["SEED"] = new RestStreamHandler("POST", capsBase + m_requestPath, CapsRequest);
m_log.DebugFormat(
"[CAPS]: Registered seed capability {0} for {1}", capsBase + m_requestPath, m_agentID);
//m_capsHandlers["MapLayer"] =
// new LLSDStreamhandler<OSDMapRequest, OSDMapLayerResponse>("POST",
// capsBase + m_mapLayerPath,
// GetMapLayer);
m_capsHandlers["UpdateScriptTaskInventory"] =
new RestStreamHandler("POST", capsBase + m_notecardTaskUpdatePath, ScriptTaskInventory);
m_capsHandlers["UpdateScriptTask"] = m_capsHandlers["UpdateScriptTaskInventory"];
m_capsHandlers["UploadBakedTexture"] =
new RestStreamHandler("POST", capsBase + m_uploadBakedTexturePath, UploadBakedTexture);
}
catch (Exception e)
{
m_log.Error("[CAPS]: " + e.ToString());
}
}
public void RegisterInventoryServiceHandlers(string capsBase)
{
try
{
// I don't think this one works...
m_capsHandlers["NewFileAgentInventory"] =
new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDAssetUploadResponse>("POST",
capsBase + m_newInventory,
NewAgentInventoryRequest);
m_capsHandlers["UpdateNotecardAgentInventory"] =
new RestStreamHandler("POST", capsBase + m_notecardUpdatePath, NoteCardAgentInventory);
m_capsHandlers["UpdateScriptAgentInventory"] = m_capsHandlers["UpdateNotecardAgentInventory"];
m_capsHandlers["UpdateScriptAgent"] = m_capsHandlers["UpdateScriptAgentInventory"];
// As of RC 1.22.9 of the Linden client this is
// supported
//m_capsHandlers["WebFetchInventoryDescendents"] =new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryDescendentsRequest);
// justincc: I've disabled the CAPS service for now to fix problems with selecting textures, and
// subsequent inventory breakage, in the edit object pane (such as mantis 1085). This requires
// enhancements (probably filling out the folder part of the LLSD reply) to our CAPS service,
// but when I went on the Linden grid, the
// simulators I visited (version 1.21) were, surprisingly, no longer supplying this capability. Instead,
// the 1.19.1.4 client appeared to be happily flowing inventory data over UDP
//
// This is very probably just a temporary measure - once the CAPS service appears again on the Linden grid
// we will be
// able to get the data we need to implement the necessary part of the protocol to fix the issue above.
// m_capsHandlers["FetchInventoryDescendents"] =
// new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryRequest);
// m_capsHandlers["FetchInventoryDescendents"] =
// new LLSDStreamhandler<LLSDFetchInventoryDescendents, LLSDInventoryDescendents>("POST",
// capsBase + m_fetchInventory,
// FetchInventory));
// m_capsHandlers["RequestTextureDownload"] = new RestStreamHandler("POST",
// capsBase + m_requestTexture,
// RequestTexture);
}
catch (Exception e)
{
m_log.Error("[CAPS]: " + e.ToString());
}
}
/// <summary>
/// Register a handler. This allows modules to register handlers.
/// </summary>
/// <param name="capName"></param>
/// <param name="handler"></param>
public void RegisterHandler(string capName, IRequestHandler handler)
{
m_capsHandlers[capName] = handler;
//m_log.DebugFormat("[CAPS]: Registering handler for \"{0}\": path {1}", capName, handler.Path);
}
/// <summary>
/// Remove all CAPS service handlers.
///
/// </summary>
/// <param name="httpListener"></param>
/// <param name="path"></param>
/// <param name="restMethod"></param>
public void DeregisterHandlers()
{
if (m_capsHandlers != null)
{
foreach (string capsName in m_capsHandlers.Caps)
{
m_capsHandlers.Remove(capsName);
}
}
}
/// <summary>
/// Construct a client response detailing all the capabilities this server can provide.
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="httpRequest">HTTP request header object</param>
/// <param name="httpResponse">HTTP response header object</param>
/// <returns></returns>
public string CapsRequest(string request, string path, string param,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
m_log.Debug("[CAPS]: Seed Caps Request in region: " + m_regionName);
if (!m_Scene.CheckClient(m_agentID, httpRequest.RemoteIPEndPoint))
{
m_log.DebugFormat("[CAPS]: Unauthorized CAPS client");
return string.Empty;
}
string result = LLSDHelpers.SerialiseLLSDReply(m_capsHandlers.CapsDetails);
//m_log.DebugFormat("[CAPS] CapsRequest {0}", result);
return result;
}
// FIXME: these all should probably go into the respective region
// modules
/// <summary>
/// Processes a fetch inventory request and sends the reply
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
// Request is like:
//<llsd>
// <map><key>folders</key>
// <array>
// <map>
// <key>fetch-folders</key><boolean>1</boolean><key>fetch-items</key><boolean>1</boolean><key>folder-id</key><uuid>8e1e3a30-b9bf-11dc-95ff-0800200c9a66</uuid><key>owner-id</key><uuid>11111111-1111-0000-0000-000100bba000</uuid><key>sort-order</key><integer>1</integer>
// </map>
// </array>
// </map>
//</llsd>
//
// multiple fetch-folder maps are allowed within the larger folders map.
public string FetchInventoryRequest(string request, string path, string param)
{
// string unmodifiedRequest = request.ToString();
//m_log.DebugFormat("[AGENT INVENTORY]: Received CAPS fetch inventory request {0}", unmodifiedRequest);
m_log.Debug("[CAPS]: Inventory Request in region: " + m_regionName);
Hashtable hash = new Hashtable();
try
{
hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
}
catch (LLSD.LLSDParseException pe)
{
m_log.Error("[AGENT INVENTORY]: Fetch error: " + pe.Message);
m_log.Error("Request: " + request.ToString());
}
ArrayList foldersrequested = (ArrayList)hash["folders"];
string response = "";
for (int i = 0; i < foldersrequested.Count; i++)
{
string inventoryitemstr = "";
Hashtable inventoryhash = (Hashtable)foldersrequested[i];
LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents();
LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest);
LLSDInventoryDescendents reply = FetchInventoryReply(llsdRequest);
inventoryitemstr = LLSDHelpers.SerialiseLLSDReply(reply);
inventoryitemstr = inventoryitemstr.Replace("<llsd><map><key>folders</key><array>", "");
inventoryitemstr = inventoryitemstr.Replace("</array></map></llsd>", "");
response += inventoryitemstr;
}
if (response.Length == 0)
{
// Ter-guess: If requests fail a lot, the client seems to stop requesting descendants.
// Therefore, I'm concluding that the client only has so many threads available to do requests
// and when a thread stalls.. is stays stalled.
// Therefore we need to return something valid
response = "<llsd><map><key>folders</key><array /></map></llsd>";
}
else
{
response = "<llsd><map><key>folders</key><array>" + response + "</array></map></llsd>";
}
//m_log.DebugFormat("[AGENT INVENTORY]: Replying to CAPS fetch inventory request with following xml");
//m_log.Debug(Util.GetFormattedXml(response));
return response;
}
public string FetchInventoryDescendentsRequest(string request, string path, string param,OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// nasty temporary hack here, the linden client falsely
// identifies the uuid 00000000-0000-0000-0000-000000000000
// as a string which breaks us
//
// correctly mark it as a uuid
//
request = request.Replace("<string>00000000-0000-0000-0000-000000000000</string>", "<uuid>00000000-0000-0000-0000-000000000000</uuid>");
// another hack <integer>1</integer> results in a
// System.ArgumentException: Object type System.Int32 cannot
// be converted to target type: System.Boolean
//
request = request.Replace("<key>fetch_folders</key><integer>0</integer>", "<key>fetch_folders</key><boolean>0</boolean>");
request = request.Replace("<key>fetch_folders</key><integer>1</integer>", "<key>fetch_folders</key><boolean>1</boolean>");
Hashtable hash = new Hashtable();
try
{
hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
}
catch (LLSD.LLSDParseException pe)
{
m_log.Error("[AGENT INVENTORY]: Fetch error: " + pe.Message);
m_log.Error("Request: " + request.ToString());
}
ArrayList foldersrequested = (ArrayList)hash["folders"];
string response = "";
lock (m_fetchLock)
{
for (int i = 0; i < foldersrequested.Count; i++)
{
string inventoryitemstr = "";
Hashtable inventoryhash = (Hashtable)foldersrequested[i];
LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents();
try{
LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest);
}
catch(Exception e)
{
m_log.Debug("[CAPS]: caught exception doing OSD deserialize" + e);
}
LLSDInventoryDescendents reply = FetchInventoryReply(llsdRequest);
inventoryitemstr = LLSDHelpers.SerialiseLLSDReply(reply);
inventoryitemstr = inventoryitemstr.Replace("<llsd><map><key>folders</key><array>", "");
inventoryitemstr = inventoryitemstr.Replace("</array></map></llsd>", "");
response += inventoryitemstr;
}
if (response.Length == 0)
{
// Ter-guess: If requests fail a lot, the client seems to stop requesting descendants.
// Therefore, I'm concluding that the client only has so many threads available to do requests
// and when a thread stalls.. is stays stalled.
// Therefore we need to return something valid
response = "<llsd><map><key>folders</key><array /></map></llsd>";
}
else
{
response = "<llsd><map><key>folders</key><array>" + response + "</array></map></llsd>";
}
//m_log.DebugFormat("[CAPS]: Replying to CAPS fetch inventory request with following xml");
//m_log.Debug("[CAPS] "+response);
}
return response;
}
/// <summary>
/// Construct an LLSD reply packet to a CAPS inventory request
/// </summary>
/// <param name="invFetch"></param>
/// <returns></returns>
private LLSDInventoryDescendents FetchInventoryReply(LLSDFetchInventoryDescendents invFetch)
{
LLSDInventoryDescendents reply = new LLSDInventoryDescendents();
LLSDInventoryFolderContents contents = new LLSDInventoryFolderContents();
contents.agent_id = m_agentID;
contents.owner_id = invFetch.owner_id;
contents.folder_id = invFetch.folder_id;
reply.folders.Array.Add(contents);
InventoryCollection inv = new InventoryCollection();
inv.Folders = new List<InventoryFolderBase>();
inv.Items = new List<InventoryItemBase>();
int version = 0;
if (CAPSFetchInventoryDescendents != null)
{
inv = CAPSFetchInventoryDescendents(m_agentID, invFetch.folder_id, invFetch.owner_id, invFetch.fetch_folders, invFetch.fetch_items, invFetch.sort_order, out version);
}
if (inv.Folders != null)
{
foreach (InventoryFolderBase invFolder in inv.Folders)
{
contents.categories.Array.Add(ConvertInventoryFolder(invFolder));
}
}
if (inv.Items != null)
{
foreach (InventoryItemBase invItem in inv.Items)
{
contents.items.Array.Add(ConvertInventoryItem(invItem));
}
}
contents.descendents = contents.items.Array.Count + contents.categories.Array.Count;
contents.version = version;
return reply;
}
/// <summary>
/// Convert an internal inventory folder object into an LLSD object.
/// </summary>
/// <param name="invFolder"></param>
/// <returns></returns>
private LLSDInventoryFolder ConvertInventoryFolder(InventoryFolderBase invFolder)
{
LLSDInventoryFolder llsdFolder = new LLSDInventoryFolder();
llsdFolder.folder_id = invFolder.ID;
llsdFolder.parent_id = invFolder.ParentID;
llsdFolder.name = invFolder.Name;
if (invFolder.Type < 0 || invFolder.Type >= TaskInventoryItem.Types.Length)
llsdFolder.type = "-1";
else
llsdFolder.type = TaskInventoryItem.Types[invFolder.Type];
llsdFolder.preferred_type = "-1";
return llsdFolder;
}
/// <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;
try
{
// TODO reevaluate after upgrade to libomv >= r2566. Probably should use UtilsConversions.
llsdItem.type = TaskInventoryItem.Types[invItem.AssetType];
llsdItem.inv_type = TaskInventoryItem.InvTypes[invItem.InvType];
}
catch (Exception e)
{
m_log.Error("[CAPS]: Problem setting asset/inventory type while converting inventory item " + invItem.Name + " to LLSD:", e);
}
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 = m_agentID;
llsdItem.permissions.owner_mask = (int)invItem.CurrentPermissions;
llsdItem.sale_info = new LLSDSaleInfo();
llsdItem.sale_info.sale_price = invItem.SalePrice;
switch (invItem.SaleType)
{
default:
llsdItem.sale_info.sale_type = "not";
break;
case 1:
llsdItem.sale_info.sale_type = "original";
break;
case 2:
llsdItem.sale_info.sale_type = "copy";
break;
case 3:
llsdItem.sale_info.sale_type = "contents";
break;
}
return llsdItem;
}
/// <summary>
///
/// </summary>
/// <param name="mapReq"></param>
/// <returns></returns>
public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq)
{
m_log.Debug("[CAPS]: MapLayer Request in region: " + m_regionName);
LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
return mapResponse;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected static OSDMapLayer GetOSDMapLayerResponse()
{
OSDMapLayer mapLayer = new OSDMapLayer();
mapLayer.Right = 5000;
mapLayer.Top = 5000;
mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006");
return mapLayer;
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
public string RequestTexture(string request, string path, string param)
{
m_log.Debug("texture request " + request);
// Needs implementing (added to remove compiler warning)
return String.Empty;
}
#region EventQueue (Currently not enabled)
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
public string ProcessEventQueue(string request, string path, string param)
{
string res = String.Empty;
if (m_capsEventQueue.Count > 0)
{
lock (m_capsEventQueue)
{
string item = m_capsEventQueue.Dequeue();
res = item;
}
}
else
{
res = CreateEmptyEventResponse();
}
return res;
}
/// <summary>
///
/// </summary>
/// <param name="caps"></param>
/// <param name="ipAddressPort"></param>
/// <returns></returns>
public string CreateEstablishAgentComms(string caps, string ipAddressPort)
{
LLSDCapEvent eventItem = new LLSDCapEvent();
eventItem.id = m_eventQueueCount;
//should be creating a EstablishAgentComms item, but there isn't a class for it yet
eventItem.events.Array.Add(new LLSDEmpty());
string res = LLSDHelpers.SerialiseLLSDReply(eventItem);
m_eventQueueCount++;
m_capsEventQueue.Enqueue(res);
return res;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public string CreateEmptyEventResponse()
{
LLSDCapEvent eventItem = new LLSDCapEvent();
eventItem.id = m_eventQueueCount;
eventItem.events.Array.Add(new LLSDEmpty());
string res = LLSDHelpers.SerialiseLLSDReply(eventItem);
m_eventQueueCount++;
return res;
}
#endregion
/// <summary>
/// Called by the script task 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>
/// <param name="httpRequest">HTTP request header object</param>
/// <param name="httpResponse">HTTP response header object</param>
/// <returns></returns>
public string ScriptTaskInventory(string request, string path, string param,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
try
{
m_log.Debug("[CAPS]: ScriptTaskInventory Request in region: " + m_regionName);
//m_log.DebugFormat("[CAPS]: request: {0}, path: {1}, param: {2}", request, path, param);
Hashtable hash = (Hashtable) LLSD.LLSDDeserialize(Utils.StringToBytes(request));
LLSDTaskScriptUpdate llsdUpdateRequest = new LLSDTaskScriptUpdate();
LLSDHelpers.DeserialiseOSDMap(hash, llsdUpdateRequest);
string capsBase = "/CAPS/" + m_capsObjectPath;
string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
TaskInventoryScriptUpdater uploader =
new TaskInventoryScriptUpdater(
llsdUpdateRequest.item_id,
llsdUpdateRequest.task_id,
llsdUpdateRequest.is_script_running,
capsBase + uploaderPath,
m_httpListener,
m_dumpAssetsToFile);
uploader.OnUpLoad += TaskScriptUpdated;
m_httpListener.AddStreamHandler(
new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
string protocol = "http://";
if (m_httpListener.UseSSL)
protocol = "https://";
string uploaderURL = protocol + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + capsBase +
uploaderPath;
LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
uploadResponse.uploader = uploaderURL;
uploadResponse.state = "upload";
// m_log.InfoFormat("[CAPS]: " +
// "ScriptTaskInventory response: {0}",
// LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
}
catch (Exception e)
{
m_log.Error("[CAPS]: " + e.ToString());
}
return null;
}
public string UploadBakedTexture(string request, string path,
string param, OSHttpRequest httpRequest,
OSHttpResponse httpResponse)
{
try
{
m_log.Debug("[CAPS]: UploadBakedTexture Request in region: " +
m_regionName);
string capsBase = "/CAPS/" + m_capsObjectPath;
string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
BakedTextureUploader uploader =
new BakedTextureUploader( capsBase + uploaderPath,
m_httpListener);
uploader.OnUpLoad += BakedTextureUploaded;
m_httpListener.AddStreamHandler(
new BinaryStreamHandler("POST", capsBase + uploaderPath,
uploader.uploaderCaps));
string protocol = "http://";
if (m_httpListener.UseSSL)
protocol = "https://";
string uploaderURL = protocol + m_httpListenerHostName + ":" +
m_httpListenPort.ToString() + capsBase + uploaderPath;
LLSDAssetUploadResponse uploadResponse =
new LLSDAssetUploadResponse();
uploadResponse.uploader = uploaderURL;
uploadResponse.state = "upload";
return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
}
catch (Exception e)
{
m_log.Error("[CAPS]: " + e.ToString());
}
return null;
}
/// <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.DeserialiseOSDMap(hash, llsdRequest);
string capsBase = "/CAPS/" + m_capsObjectPath;
string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
ItemUpdater uploader =
new ItemUpdater(llsdRequest.item_id, capsBase + uploaderPath, m_httpListener, m_dumpAssetsToFile);
uploader.OnUpLoad += ItemUpdated;
m_httpListener.AddStreamHandler(
new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
string protocol = "http://";
if (m_httpListener.UseSSL)
protocol = "https://";
string uploaderURL = protocol + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + capsBase +
uploaderPath;
LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
uploadResponse.uploader = uploaderURL;
uploadResponse.state = "upload";
// m_log.InfoFormat("[CAPS]: " +
// "NoteCardAgentInventory response: {0}",
// LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
}
/// <summary>
///
/// </summary>
/// <param name="llsdRequest"></param>
/// <returns></returns>
public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest llsdRequest)
{
//m_log.Debug("[CAPS]: NewAgentInventoryRequest Request is: " + llsdRequest.ToString());
//m_log.Debug("asset upload request via CAPS" + llsdRequest.inventory_type + " , " + llsdRequest.asset_type);
if (llsdRequest.asset_type == "texture" ||
llsdRequest.asset_type == "animation" ||
llsdRequest.asset_type == "sound")
{
IClientAPI client = null;
IScene scene = null;
if (GetClient != null)
{
client = GetClient(m_agentID);
scene = client.Scene;
IMoneyModule mm = scene.RequestModuleInterface<IMoneyModule>();
if (mm != null)
{
if (!mm.UploadCovered(client))
{
if (client != null)
client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false);
LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
errorResponse.uploader = "";
errorResponse.state = "error";
return errorResponse;
}
}
}
}
string assetName = llsdRequest.name;
string assetDes = llsdRequest.description;
string capsBase = "/CAPS/" + m_capsObjectPath;
UUID newAsset = UUID.Random();
UUID newInvItem = UUID.Random();
UUID parentFolder = llsdRequest.folder_id;
string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
AssetUploader uploader =
new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, llsdRequest.inventory_type,
llsdRequest.asset_type, capsBase + uploaderPath, m_httpListener, m_dumpAssetsToFile);
m_httpListener.AddStreamHandler(
new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
string protocol = "http://";
if (m_httpListener.UseSSL)
protocol = "https://";
string uploaderURL = protocol + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + capsBase +
uploaderPath;
LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
uploadResponse.uploader = uploaderURL;
uploadResponse.state = "upload";
uploader.OnUpLoad += UploadCompleteHandler;
return uploadResponse;
}
/// <summary>
///
/// </summary>
/// <param name="assetID"></param>
/// <param name="inventoryItem"></param>
/// <param name="data"></param>
public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
string assetType)
{
sbyte assType = 0;
sbyte inType = 0;
if (inventoryType == "sound")
{
inType = 1;
assType = 1;
}
else if (inventoryType == "animation")
{
inType = 19;
assType = 20;
}
else if (inventoryType == "wearable")
{
inType = 18;
switch (assetType)
{
case "bodypart":
assType = 13;
break;
case "clothing":
assType = 5;
break;
}
}
AssetBase asset;
asset = new AssetBase(assetID, assetName, assType, m_agentID.ToString());
asset.Data = data;
if (AddNewAsset != null)
AddNewAsset(asset);
else if (m_assetCache != null)
m_assetCache.Store(asset);
InventoryItemBase item = new InventoryItemBase();
item.Owner = m_agentID;
item.CreatorId = m_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.CurrentPermissions = 2147483647;
item.BasePermissions = 2147483647;
item.EveryOnePermissions = 0;
item.NextPermissions = 2147483647;
item.CreationDate = Util.UnixTimeSinceEpoch();
if (AddNewInventoryItem != null)
{
AddNewInventoryItem(m_agentID, item);
}
}
public void BakedTextureUploaded(UUID assetID, byte[] data)
{
m_log.DebugFormat("[CAPS]: Received baked texture {0}", assetID.ToString());
AssetBase asset;
asset = new AssetBase(assetID, "Baked Texture", (sbyte)AssetType.Texture, m_agentID.ToString());
asset.Data = data;
asset.Temporary = true;
asset.Local = true;
m_assetCache.Store(asset);
}
/// <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 UUID ItemUpdated(UUID itemID, byte[] data)
{
if (ItemUpdatedCall != null)
{
return ItemUpdatedCall(m_agentID, itemID, data);
}
return UUID.Zero;
}
/// <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 void TaskScriptUpdated(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors)
{
if (TaskScriptUpdatedCall != null)
{
ArrayList e = TaskScriptUpdatedCall(m_agentID, itemID, primID, isScriptRunning, data);
foreach (Object item in e)
errors.Add(item);
}
}
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 bool m_dumpAssetsToFile;
private string m_assetName = String.Empty;
private string m_assetDes = String.Empty;
private string m_invType = String.Empty;
private string m_assetType = String.Empty;
public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem,
UUID parentFolderID, string invType, string assetType, string path,
IHttpServer httpServer, bool dumpAssetsToFile)
{
m_assetName = assetName;
m_assetDes = description;
newAssetID = assetID;
inventoryItemID = inventoryItem;
uploaderPath = path;
httpListener = httpServer;
parentFolder = parentFolderID;
m_assetType = assetType;
m_invType = invType;
m_dumpAssetsToFile = dumpAssetsToFile;
}
/// <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.SerialiseLLSDReply(uploadComplete);
httpListener.RemoveStreamHandler("POST", uploaderPath);
// TODO: probably make this a better set of extensions here
string extension = ".jp2";
if (m_invType != "image")
{
extension = ".dat";
}
if (m_dumpAssetsToFile)
{
SaveAssetToFile(m_assetName + extension, data);
}
handlerUpLoad = OnUpLoad;
if (handlerUpLoad != null)
{
handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType);
}
return res;
}
///Left this in and commented in case there are unforseen issues
//private void SaveAssetToFile(string filename, byte[] data)
//{
// FileStream fs = File.Create(filename);
// BinaryWriter bw = new BinaryWriter(fs);
// bw.Write(data);
// bw.Close();
// fs.Close();
//}
private static void SaveAssetToFile(string filename, byte[] data)
{
string assetPath = "UserAssets";
if (!Directory.Exists(assetPath))
{
Directory.CreateDirectory(assetPath);
}
FileStream fs = File.Create(Path.Combine(assetPath, Util.safeFileName(filename)));
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(data);
bw.Close();
fs.Close();
}
}
/// <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;
private bool m_dumpAssetToFile;
public ItemUpdater(UUID inventoryItem, string path, IHttpServer httpServer, bool dumpAssetToFile)
{
m_dumpAssetToFile = dumpAssetToFile;
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;
LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
UUID assetID = UUID.Zero;
handlerUpdateItem = OnUpLoad;
if (handlerUpdateItem != null)
{
assetID = handlerUpdateItem(inv, data);
}
uploadComplete.new_asset = assetID.ToString();
uploadComplete.new_inventory_item = inv;
uploadComplete.state = "complete";
res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
httpListener.RemoveStreamHandler("POST", uploaderPath);
if (m_dumpAssetToFile)
{
SaveAssetToFile("updateditem" + Util.RandomClass.Next(1, 1000) + ".dat", data);
}
return res;
}
///Left this in and commented in case there are unforseen issues
//private void SaveAssetToFile(string filename, byte[] data)
//{
// FileStream fs = File.Create(filename);
// BinaryWriter bw = new BinaryWriter(fs);
// bw.Write(data);
// bw.Close();
// fs.Close();
//}
private static void SaveAssetToFile(string filename, byte[] data)
{
string assetPath = "UserAssets";
if (!Directory.Exists(assetPath))
{
Directory.CreateDirectory(assetPath);
}
FileStream fs = File.Create(Path.Combine(assetPath, filename));
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(data);
bw.Close();
fs.Close();
}
}
/// <summary>
/// This class is a callback invoked when a client sends asset data to
/// a task inventory script update url
/// </summary>
public 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;
private bool m_dumpAssetToFile;
public TaskInventoryScriptUpdater(UUID inventoryItemID, UUID primID, int isScriptRunning,
string path, IHttpServer httpServer, bool dumpAssetToFile)
{
m_dumpAssetToFile = dumpAssetToFile;
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;
LLSDTaskScriptUploadComplete uploadComplete = new LLSDTaskScriptUploadComplete();
ArrayList errors = new ArrayList();
handlerUpdateTaskScript = OnUpLoad;
if (handlerUpdateTaskScript != null)
{
handlerUpdateTaskScript(inventoryItemID, primID, isScriptRunning, data, ref errors);
}
uploadComplete.new_asset = inventoryItemID;
uploadComplete.compiled = errors.Count > 0 ? false : true;
uploadComplete.state = "complete";
uploadComplete.errors = new OSDArray();
uploadComplete.errors.Array = errors;
res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
httpListener.RemoveStreamHandler("POST", uploaderPath);
if (m_dumpAssetToFile)
{
SaveAssetToFile("updatedtaskscript" + Util.RandomClass.Next(1, 1000) + ".dat", data);
}
// 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;
}
///Left this in and commented in case there are unforseen issues
//private void SaveAssetToFile(string filename, byte[] data)
//{
// FileStream fs = File.Create(filename);
// BinaryWriter bw = new BinaryWriter(fs);
// bw.Write(data);
// bw.Close();
// fs.Close();
//}
private static void SaveAssetToFile(string filename, byte[] data)
{
string assetPath = "UserAssets";
if (!Directory.Exists(assetPath))
{
Directory.CreateDirectory(assetPath);
}
FileStream fs = File.Create(Path.Combine(assetPath, filename));
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(data);
bw.Close();
fs.Close();
}
}
public class BakedTextureUploader
{
public event UploadedBakedTexture OnUpLoad;
private UploadedBakedTexture handlerUpLoad = null;
private string uploaderPath = String.Empty;
private UUID newAssetID;
private IHttpServer httpListener;
public BakedTextureUploader(string path, IHttpServer httpServer)
{
newAssetID = UUID.Random();
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)
{
string res = String.Empty;
LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
uploadComplete.new_asset = newAssetID.ToString();
uploadComplete.new_inventory_item = UUID.Zero;
uploadComplete.state = "complete";
res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
httpListener.RemoveStreamHandler("POST", uploaderPath);
handlerUpLoad = OnUpLoad;
if (handlerUpLoad != null)
{
handlerUpLoad(newAssetID, data);
}
return res;
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// HMAC.cs
//
//
// For test vectors, see RFC2104, e.g. http://www.faqs.org/rfcs/rfc2104.html
//
using System.Diagnostics.Contracts;
namespace System.Security.Cryptography {
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class HMAC : KeyedHashAlgorithm {
//
// protected members
//
// an HMAC uses a hash function where data is hashed by iterating a basic compression
// function on blocks of data. BlockSizeValue is the byte size of such a block
private int blockSizeValue = 64;
protected int BlockSizeValue {
get {
return blockSizeValue;
}
set {
blockSizeValue = value;
}
}
internal string m_hashName;
internal HashAlgorithm m_hash1;
internal HashAlgorithm m_hash2;
//
// private members
//
// m_inner = PaddedKey ^ {0x36,...,0x36}
// m_outer = PaddedKey ^ {0x5C,...,0x5C}
private byte[] m_inner;
private byte[] m_outer;
private bool m_hashing = false;
private void UpdateIOPadBuffers () {
if (m_inner == null)
m_inner = new byte[BlockSizeValue];
if (m_outer == null)
m_outer = new byte[BlockSizeValue];
int i;
for (i=0; i < BlockSizeValue; i++) {
m_inner[i] = 0x36;
m_outer[i] = 0x5C;
}
for (i=0; i < KeyValue.Length; i++) {
m_inner[i] ^= KeyValue[i];
m_outer[i] ^= KeyValue[i];
}
}
internal void InitializeKey (byte[] key) {
// When we change the key value, we'll need to update the initial values of the inner and outter
// computation buffers. In the case of correct HMAC vs Whidbey HMAC, these buffers could get
// generated to a different size than when we started.
m_inner = null;
m_outer = null;
if (key.Length > BlockSizeValue) {
KeyValue = m_hash1.ComputeHash(key);
// No need to call Initialize, ComputeHash will do it for us
} else {
KeyValue = (byte[]) key.Clone();
}
UpdateIOPadBuffers();
}
//
// public properties
//
public override byte[] Key {
get { return (byte[]) KeyValue.Clone(); }
set {
if (m_hashing)
throw new CryptographicException(Environment.GetResourceString("Cryptography_HashKeySet"));
InitializeKey(value);
}
}
public string HashName {
get { return m_hashName; }
#if FEATURE_CRYPTO
set {
if (m_hashing)
throw new CryptographicException(Environment.GetResourceString("Cryptography_HashNameSet"));
m_hashName = value;
// create the hash algorithms
m_hash1 = HashAlgorithm.Create(m_hashName);
m_hash2 = HashAlgorithm.Create(m_hashName);
}
#endif // FEATURE_CRYPTO
}
//
// public methods
//
new static public HMAC Create () {
#if FULL_AOT_RUNTIME
return new System.Security.Cryptography.HMACSHA1 ();
#else
return Create("System.Security.Cryptography.HMAC");
#endif
}
new static public HMAC Create (string algorithmName) {
return (HMAC) CryptoConfig.CreateFromName(algorithmName);
}
public override void Initialize () {
m_hash1.Initialize();
m_hash2.Initialize();
m_hashing = false;
}
protected override void HashCore (byte[] rgb, int ib, int cb) {
if (m_hashing == false) {
m_hash1.TransformBlock(m_inner, 0, m_inner.Length, m_inner, 0);
m_hashing = true;
}
m_hash1.TransformBlock(rgb, ib, cb, rgb, ib);
}
protected override byte[] HashFinal () {
if (m_hashing == false) {
m_hash1.TransformBlock(m_inner, 0, m_inner.Length, m_inner, 0);
m_hashing = true;
}
// finalize the original hash
m_hash1.TransformFinalBlock(EmptyArray<Byte>.Value, 0, 0);
byte[] hashValue1 = m_hash1.HashValue;
// write the outer array
m_hash2.TransformBlock(m_outer, 0, m_outer.Length, m_outer, 0);
// write the inner hash and finalize the hash
m_hash2.TransformBlock(hashValue1, 0, hashValue1.Length, hashValue1, 0);
m_hashing = false;
m_hash2.TransformFinalBlock(EmptyArray<Byte>.Value, 0, 0);
return m_hash2.HashValue;
}
//
// IDisposable methods
//
protected override void Dispose (bool disposing) {
if (disposing) {
if (m_hash1 != null)
((IDisposable)m_hash1).Dispose();
if (m_hash2 != null)
((IDisposable)m_hash2).Dispose();
if (m_inner != null)
Array.Clear(m_inner, 0, m_inner.Length);
if (m_outer != null)
Array.Clear(m_outer, 0, m_outer.Length);
}
// call the base class's Dispose
base.Dispose(disposing);
}
#if FEATURE_CRYPTO
/// <summary>
/// Get a hash algorithm instance falling back to a second algorithm in FIPS mode. For instance,
/// use SHA256Managed by default but fall back to SHA256CryptoServiceProvider which is FIPS
/// certified if FIPS is enabled.
/// </summary>
/// <returns></returns>
internal static HashAlgorithm GetHashAlgorithmWithFipsFallback(Func<HashAlgorithm> createStandardHashAlgorithmCallback,
Func<HashAlgorithm> createFipsHashAlgorithmCallback) {
Contract.Requires(createStandardHashAlgorithmCallback != null);
Contract.Requires(createFipsHashAlgorithmCallback != null);
// Use the standard algorithm implementation by default - in FIPS mode try to fall back to the
// FIPS implementation.
if (CryptoConfig.AllowOnlyFipsAlgorithms) {
try {
return createFipsHashAlgorithmCallback();
}
catch (PlatformNotSupportedException e) {
// We need to wrap the PlatformNotSupportedException into an InvalidOperationException to
// remain compatible with the error that would be triggered in previous runtimes.
throw new InvalidOperationException(e.Message, e);
}
}
else {
return createStandardHashAlgorithmCallback();
}
}
#endif // FEATURE_CRYPTO
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Expert: A <see cref="Directory"/> instance that switches files between
/// two other <see cref="Directory"/> instances.
///
/// <para/>Files with the specified extensions are placed in the
/// primary directory; others are placed in the secondary
/// directory. The provided <see cref="T:ISet{string}"/> must not change once passed
/// to this class, and must allow multiple threads to call
/// contains at once.
/// <para/>
/// @lucene.experimental
/// </summary>
public class FileSwitchDirectory : BaseDirectory
{
private readonly Directory secondaryDir;
private readonly Directory primaryDir;
private readonly ISet<string> primaryExtensions;
private bool doClose;
public FileSwitchDirectory(ISet<string> primaryExtensions, Directory primaryDir, Directory secondaryDir, bool doClose)
{
this.primaryExtensions = primaryExtensions;
this.primaryDir = primaryDir;
this.secondaryDir = secondaryDir;
this.doClose = doClose;
this.m_lockFactory = primaryDir.LockFactory;
}
/// <summary>
/// Return the primary directory </summary>
public virtual Directory PrimaryDir
{
get
{
return primaryDir;
}
}
/// <summary>
/// Return the secondary directory </summary>
public virtual Directory SecondaryDir
{
get
{
return secondaryDir;
}
}
protected override void Dispose(bool disposing)
{
if (disposing && doClose)
{
try
{
secondaryDir.Dispose();
}
finally
{
primaryDir.Dispose();
}
doClose = false;
}
}
public override string[] ListAll()
{
ISet<string> files = new HashSet<string>();
// LUCENE-3380: either or both of our dirs could be FSDirs,
// but if one underlying delegate is an FSDir and mkdirs() has not
// yet been called, because so far everything is written to the other,
// in this case, we don't want to throw a NoSuchDirectoryException
DirectoryNotFoundException exc = null;
try
{
foreach (string f in primaryDir.ListAll())
{
files.Add(f);
}
}
catch (DirectoryNotFoundException e)
{
exc = e;
}
try
{
foreach (string f in secondaryDir.ListAll())
{
files.Add(f);
}
}
catch (DirectoryNotFoundException e)
{
// we got NoSuchDirectoryException from both dirs
// rethrow the first.
if (exc != null)
{
throw exc;
}
// we got NoSuchDirectoryException from the secondary,
// and the primary is empty.
if (files.Count == 0)
{
throw e;
}
}
// we got NoSuchDirectoryException from the primary,
// and the secondary is empty.
if (exc != null && files.Count == 0)
{
throw exc;
}
return files.ToArray();
}
/// <summary>
/// Utility method to return a file's extension. </summary>
public static string GetExtension(string name)
{
int i = name.LastIndexOf('.');
if (i == -1)
{
return "";
}
return name.Substring(i + 1, name.Length - (i + 1));
}
private Directory GetDirectory(string name)
{
string ext = GetExtension(name);
if (primaryExtensions.Contains(ext))
{
return primaryDir;
}
else
{
return secondaryDir;
}
}
[Obsolete("this method will be removed in 5.0")]
public override bool FileExists(string name)
{
return GetDirectory(name).FileExists(name);
}
public override void DeleteFile(string name)
{
GetDirectory(name).DeleteFile(name);
}
public override long FileLength(string name)
{
return GetDirectory(name).FileLength(name);
}
public override IndexOutput CreateOutput(string name, IOContext context)
{
return GetDirectory(name).CreateOutput(name, context);
}
public override void Sync(ICollection<string> names)
{
IList<string> primaryNames = new List<string>();
IList<string> secondaryNames = new List<string>();
foreach (string name in names)
{
if (primaryExtensions.Contains(GetExtension(name)))
{
primaryNames.Add(name);
}
else
{
secondaryNames.Add(name);
}
}
primaryDir.Sync(primaryNames);
secondaryDir.Sync(secondaryNames);
}
public override IndexInput OpenInput(string name, IOContext context)
{
return GetDirectory(name).OpenInput(name, context);
}
public override IndexInputSlicer CreateSlicer(string name, IOContext context)
{
return GetDirectory(name).CreateSlicer(name, context);
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using NUnit.Framework;
using NServiceKit.Common.Utils;
using NServiceKit.OrmLite.Firebird;
using NServiceKit.DataAnnotations;
namespace NServiceKit.OrmLite.FirebirdTests
{
/// <summary>Values that represent PhoneType.</summary>
public enum PhoneType
{
/// <summary>An enum constant representing the home option.</summary>
Home,
/// <summary>An enum constant representing the work option.</summary>
Work,
/// <summary>An enum constant representing the mobile option.</summary>
Mobile,
}
/// <summary>Values that represent AddressType.</summary>
public enum AddressType
{
/// <summary>An enum constant representing the home option.</summary>
Home,
/// <summary>An enum constant representing the work option.</summary>
Work,
/// <summary>An enum constant representing the other option.</summary>
Other,
}
/// <summary>An address.</summary>
public class Address
{
/// <summary>Gets or sets the line 1.</summary>
/// <value>The line 1.</value>
public string Line1 { get; set; }
/// <summary>Gets or sets the line 2.</summary>
/// <value>The line 2.</value>
public string Line2 { get; set; }
/// <summary>Gets or sets the zip code.</summary>
/// <value>The zip code.</value>
public string ZipCode { get; set; }
/// <summary>Gets or sets the state.</summary>
/// <value>The state.</value>
public string State { get; set; }
/// <summary>Gets or sets the city.</summary>
/// <value>The city.</value>
public string City { get; set; }
/// <summary>Gets or sets the country.</summary>
/// <value>The country.</value>
public string Country { get; set; }
}
/// <summary>A customer.</summary>
public class Customer
{
/// <summary>
/// Initializes a new instance of the NServiceKit.OrmLite.FirebirdTests.Customer class.
/// </summary>
public Customer()
{
this.PhoneNumbers = new Dictionary<PhoneType, string>();
this.Addresses = new Dictionary<AddressType, Address>();
}
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
[AutoIncrement] // Creates Auto primary key
public int Id { get; set; }
/// <summary>Gets or sets the person's first name.</summary>
/// <value>The name of the first.</value>
public string FirstName { get; set; }
/// <summary>Gets or sets the person's last name.</summary>
/// <value>The name of the last.</value>
public string LastName { get; set; }
/// <summary>Gets or sets the email.</summary>
/// <value>The email.</value>
[Index(Unique = true)] // Creates Unique Index
public string Email { get; set; }
/// <summary>Gets or sets the phone numbers.</summary>
/// <value>The phone numbers.</value>
public Dictionary<PhoneType, string> PhoneNumbers { get; set; }
/// <summary>Gets or sets the addresses.</summary>
/// <value>The addresses.</value>
public Dictionary<AddressType, Address> Addresses { get; set; }
/// <summary>Gets or sets the Date/Time of the timestamp.</summary>
/// <value>The timestamp.</value>
public DateTime Timestamp { get; set; }
}
/// <summary>An order.</summary>
public class Order
{
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
[AutoIncrement]
public int Id { get; set; }
/// <summary>Gets or sets the identifier of the customer.</summary>
/// <value>The identifier of the customer.</value>
[References(typeof(Customer))] //Creates Foreign Key
public int CustomerId { get; set; }
/// <summary>Gets or sets the identifier of the employee.</summary>
/// <value>The identifier of the employee.</value>
[References(typeof(Employee))] //Creates Foreign Key
public int EmployeeId { get; set; }
/// <summary>Gets or sets the shipping address.</summary>
/// <value>The shipping address.</value>
public Address ShippingAddress { get; set; } //Blobbed (no Address table)
/// <summary>Gets or sets the order date.</summary>
/// <value>The order date.</value>
public DateTime? OrderDate { get; set; }
/// <summary>Gets or sets the required date.</summary>
/// <value>The required date.</value>
public DateTime? RequiredDate { get; set; }
/// <summary>Gets or sets the shipped date.</summary>
/// <value>The shipped date.</value>
public DateTime? ShippedDate { get; set; }
/// <summary>Gets or sets the ship via.</summary>
/// <value>The ship via.</value>
public int? ShipVia { get; set; }
/// <summary>Gets or sets the freight.</summary>
/// <value>The freight.</value>
public decimal Freight { get; set; }
/// <summary>Gets or sets the number of. </summary>
/// <value>The total.</value>
public decimal Total { get; set; }
}
/// <summary>An order detail.</summary>
public class OrderDetail
{
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
[AutoIncrement]
public int Id { get; set; }
/// <summary>Gets or sets the identifier of the order.</summary>
/// <value>The identifier of the order.</value>
[References(typeof(Order))] //Creates Foreign Key
public int OrderId { get; set; }
/// <summary>Gets or sets the identifier of the product.</summary>
/// <value>The identifier of the product.</value>
public int ProductId { get; set; }
/// <summary>Gets or sets the unit price.</summary>
/// <value>The unit price.</value>
public decimal UnitPrice { get; set; }
/// <summary>Gets or sets the quantity.</summary>
/// <value>The quantity.</value>
public short Quantity { get; set; }
/// <summary>Gets or sets the discount.</summary>
/// <value>The discount.</value>
public decimal Discount { get; set; }
}
/// <summary>An employee.</summary>
public class Employee
{
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
public int Id { get; set; }
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
public string Name { get; set; }
}
/// <summary>A product.</summary>
public class Product
{
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
public int Id { get; set; }
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
public string Name { get; set; }
/// <summary>Gets or sets the unit price.</summary>
/// <value>The unit price.</value>
public decimal UnitPrice { get; set; }
}
/// <summary>A customer orders use case.</summary>
[TestFixture]
public class CustomerOrdersUseCase
{
/// <summary>Stand-alone class, No other configs, nothing but POCOs.</summary>
[Test]
public void Run()
{
//Setup FirebridSQL Server Connection Factory
var dbFactory = new OrmLiteConnectionFactory(
"User=SYSDBA;Password=masterkey;Database=ormlite-tests.fdb;DataSource=localhost;Dialect=3;charset=ISO8859_1;",
FirebirdOrmLiteDialectProvider.Instance);
IDbConnection db = dbFactory.OpenDbConnection();
//Re-Create all table schemas:
db.DropTable<OrderDetail>();
db.DropTable<Order>();
db.DropTable<Customer>();
db.DropTable<Product>();
db.DropTable<Employee>();
db.CreateTable<Employee>();
db.CreateTable<Product>();
db.CreateTable<Customer>();
db.CreateTable<Order>();
db.CreateTable<OrderDetail>();
db.Insert(new Employee { Id = 1, Name = "Employee 1" });
db.Insert(new Employee { Id = 2, Name = "Employee 2" });
var product1 = new Product { Id = 1, Name = "Product 1", UnitPrice = 10 };
var product2 = new Product { Id = 2, Name = "Product 2", UnitPrice = 20 };
db.Save(product1, product2);
var customer = new Customer
{
FirstName = "Orm",
LastName = "Lite",
Email = "ormlite@servicestack.net",
PhoneNumbers =
{
{ PhoneType.Home, "555-1234" },
{ PhoneType.Work, "1-800-1234" },
{ PhoneType.Mobile, "818-123-4567" },
},
Addresses =
{
{ AddressType.Work, new Address { Line1 = "1 Street", Country = "US", State = "NY", City = "New York", ZipCode = "10101" } },
},
Timestamp = DateTime.UtcNow,
};
db.Insert(customer);
var customerId = db.GetLastInsertId(); //Get Auto Inserted Id
customer = db.QuerySingle<Customer>(new { customer.Email }); //Query
Assert.That(customer.Id, Is.EqualTo(customerId));
//Direct access to System.Data.Transactions:
using (var trans = db.BeginTransaction(IsolationLevel.ReadCommitted))
{
var order = new Order
{
CustomerId = customer.Id,
EmployeeId = 1,
OrderDate = DateTime.UtcNow,
Freight = 10.50m,
ShippingAddress = new Address { Line1 = "3 Street", Country = "US", State = "NY", City = "New York", ZipCode = "12121" },
};
db.Save(order); //Inserts 1st time
order.Id = (int)db.GetLastInsertId(); //Get Auto Inserted Id
var orderDetails = new[] {
new OrderDetail
{
OrderId = order.Id,
ProductId = product1.Id,
Quantity = 2,
UnitPrice = product1.UnitPrice,
},
new OrderDetail
{
OrderId = order.Id,
ProductId = product2.Id,
Quantity = 2,
UnitPrice = product2.UnitPrice,
Discount = .15m,
}
};
db.Insert(orderDetails);
order.Total = orderDetails.Sum(x => x.UnitPrice * x.Quantity * x.Discount) + order.Freight;
db.Save(order); //Updates 2nd Time
trans.Commit();
}
db.Dispose();
}
}
}
| |
using NUnit.Framework;
using static NSelene.Selene;
namespace NSelene.Tests.Integration.SharedDriver.SeleneSpec
{
using System;
using System.Linq;
using Harness;
[TestFixture]
public class SeleneElement_DoubleClick_Specs : BaseTest
{
// TODO: move here error messages tests, and at least some ClickByJs tests...
[Test]
public void DoubleClick_WaitsForVisibility_OfInitiialyAbsent()
{
Configuration.Timeout = 1.0;
Configuration.PollDuringWaits = 0.1;
Given.OpenedEmptyPage();
var beforeCall = DateTime.Now;
Given.OpenedPageWithBodyTimedOut(
@"
<span ondblclick='window.location=this.href + ""#second""'>to h2</span>
<h2 id='second'>Heading 2</h2>
",
300
);
S("span").DoubleClick();
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(1.0));
Assert.IsTrue(Configuration.Driver.Url.Contains("second"));
}
[Test]
public void DoubleClick_WaitsForVisibility_OfInitiialyHidden()
{
Configuration.Timeout = 1.0;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<span
id='link'
ondblclick='window.location=this.href + ""#second""'
style='display:none'
>to h2</span>
<h2 id='second'>Heading 2</h2>
"
);
var beforeCall = DateTime.Now;
Given.ExecuteScriptWithTimeout(
@"
document.getElementById('link').style.display = 'block';
",
300
);
S("span").DoubleClick();
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(1.0));
StringAssert.Contains("second", Configuration.Driver.Url);
}
[Test]
public void DoubleClick_IsRenderedInError_OnHiddenFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<span
id='link'
ondblclick='window.location=this.href + ""#second""'
style='display:none'
>to h2</span>
<h2 id='second'>Heading 2</h2>
"
);
var beforeCall = DateTime.Now;
try
{
S("span").DoubleClick();
Assert.Fail("should fail with exception");
}
catch (TimeoutException error)
{
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.25));
Assert.Less(afterCall, beforeCall.AddSeconds(1.0));
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains(
"Browser.Element(span).Actions.DoubleClick(self.ActualWebElement).Perform()",
lines
);
Assert.Contains("Reason:", lines);
Assert.Contains(
"element not interactable: [object HTMLSpanElement] has no size and location",
lines
);
StringAssert.DoesNotContain("second", Configuration.Driver.Url);
}
}
[Test]
public void DoubleClick_IsRenderedInError_OnHiddenFailure_WhenCustomizedToWaitForNoOverlap()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<span
id='link'
ondbclick='window.location=this.href + ""#second""'
style='display:none'
>to h2</span>
<h2 id='second'>Heading 2</h2>
"
);
var beforeCall = DateTime.Now;
try
{
S("span").With(waitForNoOverlapFoundByJs: true).DoubleClick();
Assert.Fail("should fail with exception");
}
catch (TimeoutException error)
{
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.25));
Assert.Less(afterCall, beforeCall.AddSeconds(1.0));
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains(
"Browser.Element(span).Actions.DoubleClick(self.ActualNotOverlappedWebElement).Perform()",
lines
);
Assert.Contains("Reason:", lines);
Assert.Contains("javascript error: element is not visible", lines);
StringAssert.DoesNotContain("second", Configuration.Driver.Url);
}
}
[Test]
public void DoubleClick_PassesWithoutEffect_UnderOverlay()
{
Configuration.Timeout = 1.0;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<div
id='overlay'
style='
display:block;
position: fixed;
display: block;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.1);
z-index: 2;
cursor: pointer;
'
>
</div>
<span
id='link'
ondblclick='window.location=this.href + ""#second""'
>to h2</span>
<h2 id='second'>Heading 2</h2>
"
);
var beforeCall = DateTime.Now;
S("span").DoubleClick();
var afterCall = DateTime.Now;
Assert.Less(afterCall, beforeCall.AddSeconds(1.0));
StringAssert.DoesNotContain("second", Configuration.Driver.Url);
}
[Test]
public void DoubleClick_Waits_For_NoOverlay_IfCustomized()
{
Configuration.Timeout = 1.0;
Configuration.PollDuringWaits = 0.05;
Given.OpenedPageWithBody(
@"
<div
id='overlay'
style='
display:block;
position: fixed;
display: block;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.1);
z-index: 2;
cursor: pointer;
'
>
</div>
<span
id='link'
ondblclick='window.location=this.href + ""#second""'
>to h2</span>
<h2 id='second'>Heading 2</h2>
"
);
var beforeCall = DateTime.Now;
Given.ExecuteScriptWithTimeout(
@"
document.getElementById('overlay').style.display = 'none';
",
300
);
S("span").With(waitForNoOverlapFoundByJs: true).DoubleClick();
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(1.0));
StringAssert.Contains("second", Configuration.Driver.Url);
}
[Test]
public void DoubleClick_IsRenderedInError_OnOverlappedWithOverlayFailure_IfCustomizedToWaitForNoOverlayByJs()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<div
id='overlay'
style='
display: block;
position: fixed;
display: block;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.1);
z-index: 2;
cursor: pointer;
'
>
</div>
<span
id='link'
ondblclick='window.location=this.href + ""#second""'
>to h2</span>
<h2 id='second'>Heading 2</h2>
"
);
var beforeCall = DateTime.Now;
try
{
S("span").With(waitForNoOverlapFoundByJs: true).DoubleClick();
Assert.Fail("should fail with exception");
}
catch (TimeoutException error)
{
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.25));
Assert.Less(afterCall, beforeCall.AddSeconds(1.25));
StringAssert.DoesNotContain("second", Configuration.Driver.Url);
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains(
"Browser.Element(span).Actions.DoubleClick(self.ActualNotOverlappedWebElement).Perform()",
lines
);
Assert.Contains("Reason:", lines);
Assert.Contains(
"Element: <span "
+ "id=\"link\" "
+ "ondblclick=\"window.location=this.href + "#second"\""
+ ">to h2</span>"
,
lines
);
Assert.NotNull(lines.Find(item => item.Contains(
"is overlapped by: <div id=\"overlay\" "
)));
}
}
}
}
| |
/* ====================================================================
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.Record.Chart
{
using System;
using System.Text;
using NPOI.Util;
/**
* The axis options record provides Unit information and other various tidbits about the axis.
* NOTE: This source is automatically generated please do not modify this file. Either subclass or
* Remove the record in src/records/definitions.
* @author Andrew C. Oliver(acoliver at apache.org)
*/
internal class AxisOptionsRecord
: StandardRecord
{
public const short sid = 0x1062;
private short field_1_minimumCategory;
private short field_2_maximumCategory;
private short field_3_majorUnitValue;
private short field_4_majorUnit;
private short field_5_minorUnitValue;
private short field_6_minorUnit;
private short field_7_baseUnit;
private short field_8_crossingPoint;
private short field_9_options;
private BitField defaultMinimum = BitFieldFactory.GetInstance(0x1);
private BitField defaultMaximum = BitFieldFactory.GetInstance(0x2);
private BitField defaultMajor = BitFieldFactory.GetInstance(0x4);
private BitField defaultMinorUnit = BitFieldFactory.GetInstance(0x8);
private BitField isDate = BitFieldFactory.GetInstance(0x10);
private BitField defaultBase = BitFieldFactory.GetInstance(0x20);
private BitField defaultCross = BitFieldFactory.GetInstance(0x40);
private BitField defaultDateSettings = BitFieldFactory.GetInstance(0x80);
public AxisOptionsRecord()
{
}
/**
* Constructs a AxisOptions record and Sets its fields appropriately.
*
* @param in the RecordInputstream to Read the record from
*/
public AxisOptionsRecord(RecordInputStream in1)
{
field_1_minimumCategory = in1.ReadShort();
field_2_maximumCategory = in1.ReadShort();
field_3_majorUnitValue = in1.ReadShort();
field_4_majorUnit = in1.ReadShort();
field_5_minorUnitValue = in1.ReadShort();
field_6_minorUnit = in1.ReadShort();
field_7_baseUnit = in1.ReadShort();
field_8_crossingPoint = in1.ReadShort();
field_9_options = in1.ReadShort();
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[AXCEXT]\n");
buffer.Append(" .minimumCategory = ")
.Append("0x").Append(HexDump.ToHex(MinimumCategory))
.Append(" (").Append(MinimumCategory).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .maximumCategory = ")
.Append("0x").Append(HexDump.ToHex(MaximumCategory))
.Append(" (").Append(MaximumCategory).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .majorUnitValue = ")
.Append("0x").Append(HexDump.ToHex(MajorUnitValue))
.Append(" (").Append(MajorUnitValue).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .majorUnit = ")
.Append("0x").Append(HexDump.ToHex(MajorUnit))
.Append(" (").Append(MajorUnit).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .minorUnitValue = ")
.Append("0x").Append(HexDump.ToHex(MinorUnitValue))
.Append(" (").Append(MinorUnitValue).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .minorUnit = ")
.Append("0x").Append(HexDump.ToHex(MinorUnit))
.Append(" (").Append(MinorUnit).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .baseUnit = ")
.Append("0x").Append(HexDump.ToHex(BaseUnit))
.Append(" (").Append(BaseUnit).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .crossingPoint = ")
.Append("0x").Append(HexDump.ToHex(CrossingPoint))
.Append(" (").Append(CrossingPoint).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .options = ")
.Append("0x").Append(HexDump.ToHex(Options))
.Append(" (").Append(Options).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .defaultMinimum = ").Append(IsDefaultMinimum).Append('\n');
buffer.Append(" .defaultMaximum = ").Append(IsDefaultMaximum).Append('\n');
buffer.Append(" .defaultMajor = ").Append(IsDefaultMajor).Append('\n');
buffer.Append(" .defaultMinorUnit = ").Append(IsDefaultMinorUnit).Append('\n');
buffer.Append(" .IsDate = ").Append(IsDate).Append('\n');
buffer.Append(" .defaultBase = ").Append(IsDefaultBase).Append('\n');
buffer.Append(" .defaultCross = ").Append(IsDefaultCross).Append('\n');
buffer.Append(" .defaultDateSettings = ").Append(IsDefaultDateSettings).Append('\n');
buffer.Append("[/AXCEXT]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(field_1_minimumCategory);
out1.WriteShort(field_2_maximumCategory);
out1.WriteShort(field_3_majorUnitValue);
out1.WriteShort(field_4_majorUnit);
out1.WriteShort(field_5_minorUnitValue);
out1.WriteShort(field_6_minorUnit);
out1.WriteShort(field_7_baseUnit);
out1.WriteShort(field_8_crossingPoint);
out1.WriteShort(field_9_options);
}
/**
* Size of record (exluding 4 byte header)
*/
protected override int DataSize
{
get { return 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2; }
}
public override short Sid
{
get { return sid; }
}
public override Object Clone()
{
AxisOptionsRecord rec = new AxisOptionsRecord();
rec.field_1_minimumCategory = field_1_minimumCategory;
rec.field_2_maximumCategory = field_2_maximumCategory;
rec.field_3_majorUnitValue = field_3_majorUnitValue;
rec.field_4_majorUnit = field_4_majorUnit;
rec.field_5_minorUnitValue = field_5_minorUnitValue;
rec.field_6_minorUnit = field_6_minorUnit;
rec.field_7_baseUnit = field_7_baseUnit;
rec.field_8_crossingPoint = field_8_crossingPoint;
rec.field_9_options = field_9_options;
return rec;
}
/**
* Get the minimum category field for the AxisOptions record.
*/
public short MinimumCategory
{
get
{
return field_1_minimumCategory;
}
set
{
this.field_1_minimumCategory = value;
}
}
/**
* Get the maximum category field for the AxisOptions record.
*/
public short MaximumCategory
{
get
{
return field_2_maximumCategory;
}
set
{
this.field_2_maximumCategory = value;
}
}
/**
* Get the major Unit value field for the AxisOptions record.
*/
public short MajorUnitValue
{
get
{
return field_3_majorUnitValue;
}
set
{
this.field_3_majorUnitValue = value;
}
}
/**
* Get the major Unit field for the AxisOptions record.
*/
public short MajorUnit
{
get
{
return field_4_majorUnit;
}
set
{
this.field_4_majorUnit = value;
}
}
/**
* Get the minor Unit value field for the AxisOptions record.
*/
public short MinorUnitValue
{
get
{
return field_5_minorUnitValue;
}
set
{
this.field_5_minorUnitValue = value;
}
}
/**
* Get the minor Unit field for the AxisOptions record.
*/
public short MinorUnit
{
get
{
return field_6_minorUnit;
}
set
{
this.field_6_minorUnit = value;
}
}
/**
* Get the base Unit field for the AxisOptions record.
*/
public short BaseUnit
{
get
{
return field_7_baseUnit;
}
set
{
this.field_7_baseUnit = value;
}
}
/**
* Get the crossing point field for the AxisOptions record.
*/
public short CrossingPoint
{
get
{
return field_8_crossingPoint;
}
set
{
this.field_8_crossingPoint = value;
}
}
/**
* Get the options field for the AxisOptions record.
*/
public short Options
{
get { return field_9_options; }
set { this.field_9_options = value; }
}
/**
* use the default minimum category
* @return the default minimum field value.
*/
public bool IsDefaultMinimum
{
get
{
return defaultMinimum.IsSet(field_9_options);
}
set { field_9_options = defaultMinimum.SetShortBoolean(field_9_options, value); }
}
/**
* use the default maximum category
* @return the default maximum field value.
*/
public bool IsDefaultMaximum
{
get
{
return defaultMaximum.IsSet(field_9_options);
}
set
{
field_9_options = defaultMaximum.SetShortBoolean(field_9_options, value);
}
}
/**
* use the default major Unit
* @return the default major field value.
*/
public bool IsDefaultMajor
{
get
{
return defaultMajor.IsSet(field_9_options);
}
set
{
field_9_options = defaultMajor.SetShortBoolean(field_9_options, value);
}
}
/**
* use the default minor Unit
* @return the default minor Unit field value.
*/
public bool IsDefaultMinorUnit
{
get
{
return defaultMinorUnit.IsSet(field_9_options);
}
set { field_9_options = defaultMinorUnit.SetShortBoolean(field_9_options, value); }
}
/**
* this is a date axis
* @return the IsDate field value.
*/
public bool IsDate
{
get
{
return isDate.IsSet(field_9_options);
}
set
{
field_9_options = isDate.SetShortBoolean(field_9_options, value);
}
}
/**
* use the default base Unit
* @return the default base field value.
*/
public bool IsDefaultBase
{
get
{
return defaultBase.IsSet(field_9_options);
}
set { field_9_options = defaultBase.SetShortBoolean(field_9_options, value); }
}
/**
* use the default crossing point
* @return the default cross field value.
*/
public bool IsDefaultCross
{
get
{
return defaultCross.IsSet(field_9_options);
}
set
{
field_9_options = defaultCross.SetShortBoolean(field_9_options, value);
}
}
/**
* use default date Setttings for this axis
* @return the default date Settings field value.
*/
public bool IsDefaultDateSettings
{
get
{
return defaultDateSettings.IsSet(field_9_options);
}
set { field_9_options = defaultDateSettings.SetShortBoolean(field_9_options, value); }
}
}
}
| |
namespace AutoMapper.UnitTests.Tests
{
using System;
using System.Linq;
using System.Reflection;
using Should;
using Xunit;
public abstract class using_generic_configuration : AutoMapperSpecBase
{
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>()
.ForMember(d => d.Ignored, o => o.Ignore())
.ForMember(d => d.RenamedField, o => o.MapFrom(s => s.NamedProperty))
.ForMember(d => d.IntField, o => o.ResolveUsing<FakeResolver>().FromMember(s => s.StringField))
.ForMember("IntProperty", o => o.ResolveUsing<FakeResolver>().FromMember("AnotherStringField"))
.ForMember(d => d.IntProperty3,
o => o.ResolveUsing(typeof (FakeResolver)).FromMember(s => s.StringField3))
.ForMember(d => d.IntField4, o => o.ResolveUsing(new FakeResolver()).FromMember("StringField4"));
}
protected class Source
{
public int PropertyWithMatchingName { get; set; }
public NestedSource NestedSource { get; set; }
public int NamedProperty { get; set; }
public string StringField;
public string AnotherStringField;
public string StringField3;
public string StringField4;
}
protected class NestedSource
{
public int SomeField;
}
protected class Destination
{
public int PropertyWithMatchingName { get; set; }
public string NestedSourceSomeField;
public string Ignored { get; set; }
public string RenamedField;
public int IntField;
public int IntProperty { get; set; }
public int IntProperty3 { get; set; }
public int IntField4;
}
private class FakeResolver : ValueResolver<string, int>
{
protected override int ResolveCore(string source)
{
return default(int);
}
}
}
public class when_members_have_matching_names : using_generic_configuration
{
private const string _memberName = "PropertyWithMatchingName";
private static MemberInfo _sourceMember;
protected override void Because_of()
{
_sourceMember = Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == _memberName)
.SourceMember;
}
[Fact]
public void should_not_be_null()
{
_sourceMember.ShouldNotBeNull();
}
[Fact]
public void should_have_the_matching_member_of_the_source_type_as_value()
{
_sourceMember.ShouldBeSameAs(typeof (Source).GetProperty(_memberName));
}
}
public class when_the_destination_member_is_flattened : using_generic_configuration
{
private static MemberInfo _sourceMember;
protected override void Because_of()
{
_sourceMember = Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "NestedSourceSomeField")
.SourceMember;
}
[Fact]
public void should_not_be_null()
{
_sourceMember.ShouldNotBeNull();
}
[Fact]
public void should_have_the_member_of_the_nested_source_type_as_value()
{
_sourceMember.ShouldBeSameAs(typeof (NestedSource).GetField("SomeField"));
}
}
public class when_the_destination_member_is_ignored : using_generic_configuration
{
private static Exception _exception;
private static MemberInfo _sourceMember;
protected override void Because_of()
{
try
{
_sourceMember = Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "Ignored")
.SourceMember;
}
catch (Exception ex)
{
_exception = ex;
}
}
[Fact]
public void should_not_throw_an_exception()
{
_exception.ShouldBeNull();
}
[Fact]
public void should_be_null()
{
_sourceMember.ShouldBeNull();
}
}
public class when_the_destination_member_is_projected : using_generic_configuration
{
private static MemberInfo _sourceMember;
protected override void Because_of()
{
_sourceMember = Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "RenamedField")
.SourceMember;
}
[Fact]
public void should_not_be_null()
{
_sourceMember.ShouldNotBeNull();
}
[Fact]
public void should_have_the_projected_member_of_the_source_type_as_value()
{
_sourceMember.ShouldBeSameAs(typeof (Source).GetProperty("NamedProperty"));
}
}
public class when_the_destination_member_is_resolved_from_a_source_member : using_generic_configuration
{
private static MemberInfo _sourceMember;
protected override void Because_of()
{
_sourceMember = Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "IntField")
.SourceMember;
}
[Fact]
public void should_not_be_null()
{
_sourceMember.ShouldNotBeNull();
}
[Fact]
public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value()
{
_sourceMember.ShouldBeSameAs(typeof (Source).GetField("StringField"));
}
}
public class when_the_destination_property_is_resolved_from_a_source_member_using_the_Magic_String_overload :
using_generic_configuration
{
private static MemberInfo _sourceMember;
protected override void Because_of()
{
_sourceMember = Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "IntProperty")
.SourceMember;
}
[Fact]
public void should_not_be_null()
{
_sourceMember.ShouldNotBeNull();
}
[Fact]
public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value()
{
_sourceMember.ShouldBeSameAs(typeof (Source).GetField("AnotherStringField"));
}
}
public class when_the_destination_property_is_resolved_from_a_source_member_using_the_non_generic_resolve_method :
using_generic_configuration
{
private static MemberInfo _sourceMember;
protected override void Because_of()
{
_sourceMember = Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "IntProperty3")
.SourceMember;
}
[Fact]
public void should_not_be_null()
{
_sourceMember.ShouldNotBeNull();
}
[Fact]
public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value()
{
_sourceMember.ShouldBeSameAs(typeof (Source).GetField("StringField3"));
}
}
public class
when_the_destination_property_is_resolved_from_a_source_member_using_non_the_generic_resolve_method_and_the_Magic_String_overload :
using_generic_configuration
{
private static MemberInfo _sourceMember;
protected override void Because_of()
{
_sourceMember = Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "IntField4")
.SourceMember;
}
[Fact]
public void should_not_be_null()
{
_sourceMember.ShouldNotBeNull();
}
[Fact]
public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value()
{
_sourceMember.ShouldBeSameAs(typeof (Source).GetField("StringField4"));
}
}
public abstract class using_nongeneric_configuration : AutoMapperSpecBase
{
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap(typeof (Source), typeof (Destination))
.ForMember("RenamedProperty", o => o.MapFrom("NamedProperty"));
});
}
protected class Source
{
public int NamedProperty { get; set; }
}
protected class Destination
{
public string RenamedProperty { get; set; }
}
}
public class when_the_destination_property_is_projected : using_nongeneric_configuration
{
private static MemberInfo _sourceMember;
protected override void Because_of()
{
_sourceMember = Mapper.FindTypeMapFor<Source, Destination>()
.GetPropertyMaps()
.Single(pm => pm.DestinationProperty.Name == "RenamedProperty")
.SourceMember;
}
[Fact]
public void should_not_be_null()
{
_sourceMember.ShouldNotBeNull();
}
[Fact]
public void should_have_the_projected_member_of_the_source_type_as_value()
{
_sourceMember.ShouldBeSameAs(typeof (Source).GetProperty("NamedProperty"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using OmniSharp.Cake.Services.RequestHandlers.Buffer;
using OmniSharp.Cake.Services.RequestHandlers.Refactoring.V2;
using OmniSharp.Mef;
using OmniSharp.Models;
using OmniSharp.Models.UpdateBuffer;
using OmniSharp.Models.V2;
using OmniSharp.Models.V2.CodeActions;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
using Range = OmniSharp.Models.V2.Range;
namespace OmniSharp.Cake.Tests
{
public class CodeActionsV2Facts : AbstractTestFixture
{
public CodeActionsV2Facts(ITestOutputHelper output)
: base(output)
{
}
[Fact]
public async Task Can_get_code_actions_from_roslyn()
{
const string code = "var regex = new Reg[||]ex();";
var refactorings = await FindRefactoringNamesAsync(code);
Assert.Contains("using System.Text.RegularExpressions;", refactorings);
}
[Fact]
public async Task Can_get_ranged_code_action()
{
const string code =
@"public class Class1
{
public void Whatever()
{
[|Console.Write(""should be using System;"");|]
}
}";
var refactorings = await FindRefactoringNamesAsync(code);
Assert.Contains("Extract method", refactorings);
}
[Fact]
public async Task Returns_ordered_code_actions()
{
const string code =
@"public class Class1
{
public void Whatever()
{
[|Regex.Match(""foo"", ""bar"");|]
}
}";
var refactorings = await FindRefactoringNamesAsync(code);
var expected = new List<string>
{
"using System.Text.RegularExpressions;",
"System.Text.RegularExpressions.Regex",
"Extract method",
"Extract local function",
"Introduce local for 'Regex.Match(\"foo\", \"bar\")'",
"Introduce parameter for 'Regex.Match(\"foo\", \"bar\")' -> and update call sites directly",
"Introduce parameter for 'Regex.Match(\"foo\", \"bar\")' -> into extracted method to invoke at call sites",
"Introduce parameter for 'Regex.Match(\"foo\", \"bar\")' -> into new overload",
"Introduce parameter for all occurrences of 'Regex.Match(\"foo\", \"bar\")' -> and update call sites directly",
"Introduce parameter for all occurrences of 'Regex.Match(\"foo\", \"bar\")' -> into extracted method to invoke at call sites",
"Introduce parameter for all occurrences of 'Regex.Match(\"foo\", \"bar\")' -> into new overload"
};
Assert.Equal(expected, refactorings);
}
[Fact]
public async Task Can_extract_method()
{
const string code =
@"public class Class1
{
public void Whatever()
{
[|Console.Write(""should be using System;"");|]
}
}";
var expected = new LinePositionSpanTextChange
{
NewText = "NewMethod();\n }\n\n private static void NewMethod()\n {\n ",
StartLine = 4,
StartColumn = 8,
EndLine = 4,
EndColumn = 8
};
var response = await RunRefactoringAsync(code, "Extract method");
var modifiedFile = response.Changes.FirstOrDefault() as ModifiedFileResponse;
Assert.Single(response.Changes);
Assert.NotNull(modifiedFile);
Assert.Single(modifiedFile.Changes);
Assert.Equal(expected, modifiedFile.Changes.FirstOrDefault());
}
[Fact]
public async Task Should_Not_Find_Rename_File()
{
const string code =
@"public class Class[||]1
{
public void Whatever()
{
Console.Write(""should be using System;"");
}
}";
var refactorings = await FindRefactoringNamesAsync(code);
Assert.Empty(refactorings.Where(x => x.StartsWith("Rename file to")));
}
private async Task<RunCodeActionResponse> RunRefactoringAsync(string code, string refactoringName)
{
var refactorings = await FindRefactoringsAsync(code);
Assert.Contains(refactoringName, refactorings.Select(x => x.Name), StringComparer.OrdinalIgnoreCase);
var identifier = refactorings.First(action => action.Name.Equals(refactoringName, StringComparison.OrdinalIgnoreCase)).Identifier;
return await RunRefactoringsAsync(code, identifier);
}
private async Task<IEnumerable<string>> FindRefactoringNamesAsync(string code)
{
var codeActions = await FindRefactoringsAsync(code);
return codeActions.Select(a => a.Name);
}
private async Task<IEnumerable<OmniSharpCodeAction>> FindRefactoringsAsync(string code)
{
using (var testProject = await TestAssets.Instance.GetTestProjectAsync("CakeProject", shadowCopy: false))
using (var host = CreateOmniSharpHost(testProject.Directory))
{
var testFile = new TestFile(Path.Combine(testProject.Directory, "build.cake"), code);
var requestHandler = GetGetCodeActionsHandler(host);
var span = testFile.Content.GetSpans().Single();
var range = testFile.Content.GetRangeFromSpan(span);
var request = new GetCodeActionsRequest
{
Line = range.Start.Line,
Column = range.Start.Offset,
FileName = testFile.FileName,
Buffer = testFile.Content.Code,
Selection = GetSelection(range),
};
var updateBufferRequest = new UpdateBufferRequest
{
Buffer = request.Buffer,
Column = request.Column,
FileName = request.FileName,
Line = request.Line,
FromDisk = false
};
await GetUpdateBufferHandler(host).Handle(updateBufferRequest);
var response = await requestHandler.Handle(request);
return response.CodeActions;
}
}
private async Task<RunCodeActionResponse> RunRefactoringsAsync(string code, string identifier)
{
using (var testProject = await TestAssets.Instance.GetTestProjectAsync("CakeProject", shadowCopy: false))
using (var host = CreateOmniSharpHost(testProject.Directory))
{
var testFile = new TestFile(Path.Combine(testProject.Directory, "build.cake"), code);
var requestHandler = GetRunCodeActionsHandler(host);
var span = testFile.Content.GetSpans().Single();
var range = testFile.Content.GetRangeFromSpan(span);
var request = new RunCodeActionRequest
{
Line = range.Start.Line,
Column = range.Start.Offset,
Selection = GetSelection(range),
FileName = testFile.FileName,
Buffer = testFile.Content.Code,
Identifier = identifier,
WantsTextChanges = true,
WantsAllCodeActionOperations = true
};
var updateBufferRequest = new UpdateBufferRequest
{
Buffer = request.Buffer,
Column = request.Column,
FileName = request.FileName,
Line = request.Line,
FromDisk = false
};
await GetUpdateBufferHandler(host).Handle(updateBufferRequest);
return await requestHandler.Handle(request);
}
}
private static Range GetSelection(TextRange range)
{
if (range.IsEmpty)
{
return null;
}
return new Range
{
Start = new Point { Line = range.Start.Line, Column = range.Start.Offset },
End = new Point { Line = range.End.Line, Column = range.End.Offset }
};
}
private static GetCodeActionsHandler GetGetCodeActionsHandler(OmniSharpTestHost host)
{
return GetRequestHandler<GetCodeActionsHandler>(host, OmniSharpEndpoints.V2.GetCodeActions);
}
private static RunCodeActionsHandler GetRunCodeActionsHandler(OmniSharpTestHost host)
{
return GetRequestHandler<RunCodeActionsHandler>(host, OmniSharpEndpoints.V2.RunCodeAction);
}
private static UpdateBufferHandler GetUpdateBufferHandler(OmniSharpTestHost host)
{
return GetRequestHandler<UpdateBufferHandler>(host, OmniSharpEndpoints.UpdateBuffer);
}
private static TRequestHandler GetRequestHandler<TRequestHandler>(OmniSharpTestHost host, string endpoint) where TRequestHandler : IRequestHandler
{
return host.GetRequestHandler<TRequestHandler>(endpoint, Constants.LanguageNames.Cake);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
#if LEGACY
using Excel;
using Excel.Exceptions;
#else
using ExcelDataReader.Portable.Exceptions;
#endif
namespace ExcelDataReader.Portable.Core.BinaryFormat
{
/// <summary>
/// Represents Excel file header
/// </summary>
internal class XlsHeader
{
private readonly byte[] m_bytes;
private readonly Stream m_file;
private XlsFat m_fat;
private XlsFat m_minifat;
private XlsHeader(Stream file)
{
m_bytes = new byte[512];
m_file = file;
}
/// <summary>
/// Returns file signature
/// </summary>
public ulong Signature
{
get { return BitConverter.ToUInt64(m_bytes, 0x0); }
}
/// <summary>
/// Checks if file signature is valid
/// </summary>
public bool IsSignatureValid
{
get { return (Signature == 0xE11AB1A1E011CFD0); }
}
/// <summary>
/// Typically filled with zeroes
/// </summary>
public Guid ClassId
{
get
{
byte[] tmp = new byte[16];
Buffer.BlockCopy(m_bytes, 0x8, tmp, 0, 16);
return new Guid(tmp);
}
}
/// <summary>
/// Must be 0x003E
/// </summary>
public ushort Version
{
get { return BitConverter.ToUInt16(m_bytes, 0x18); }
}
/// <summary>
/// Must be 0x0003
/// </summary>
public ushort DllVersion
{
get { return BitConverter.ToUInt16(m_bytes, 0x1A); }
}
/// <summary>
/// Must be 0xFFFE
/// </summary>
public ushort ByteOrder
{
get { return BitConverter.ToUInt16(m_bytes, 0x1C); }
}
/// <summary>
/// Typically 512
/// </summary>
public int SectorSize
{
get { return (1 << BitConverter.ToUInt16(m_bytes, 0x1E)); }
}
/// <summary>
/// Typically 64
/// </summary>
public int MiniSectorSize
{
get { return (1 << BitConverter.ToUInt16(m_bytes, 0x20)); }
}
/// <summary>
/// Number of FAT sectors
/// </summary>
public int FatSectorCount
{
get { return BitConverter.ToInt32(m_bytes, 0x2C); }
}
/// <summary>
/// Number of first Root Directory Entry (Property Set Storage, FAT Directory) sector
/// </summary>
public uint RootDirectoryEntryStart
{
get { return BitConverter.ToUInt32(m_bytes, 0x30); }
}
/// <summary>
/// Transaction signature, 0 for Excel
/// </summary>
public uint TransactionSignature
{
get { return BitConverter.ToUInt32(m_bytes, 0x34); }
}
/// <summary>
/// Maximum size for small stream, typically 4096 bytes
/// </summary>
public uint MiniStreamCutoff
{
get { return BitConverter.ToUInt32(m_bytes, 0x38); }
}
/// <summary>
/// First sector of Mini FAT, FAT_EndOfChain if there's no one
/// </summary>
public uint MiniFatFirstSector
{
get { return BitConverter.ToUInt32(m_bytes, 0x3C); }
}
/// <summary>
/// Number of sectors in Mini FAT, 0 if there's no one
/// </summary>
public int MiniFatSectorCount
{
get { return BitConverter.ToInt32(m_bytes, 0x40); }
}
/// <summary>
/// First sector of DIF, FAT_EndOfChain if there's no one
/// </summary>
public uint DifFirstSector
{
get { return BitConverter.ToUInt32(m_bytes, 0x44); }
}
/// <summary>
/// Number of sectors in DIF, 0 if there's no one
/// </summary>
public int DifSectorCount
{
get { return BitConverter.ToInt32(m_bytes, 0x48); }
}
public Stream FileStream
{
get { return m_file; }
}
/// <summary>
/// Returns mini FAT table
/// </summary>
public XlsFat GetMiniFAT(XlsRootDirectory rootDir)
{
if (m_minifat != null)
return m_minifat;
//if no minifat then return null
if (MiniFatSectorCount == 0 || MiniSectorSize == 0xFFFFFFFE)
return null;
uint value;
int miniSectorSize = MiniSectorSize;
List<uint> sectors = new List<uint>(MiniFatSectorCount);
//find the sector where the minifat starts
var miniFatStartSector = BitConverter.ToUInt32(m_bytes, 0x3c);
sectors.Add(miniFatStartSector);
//lock (m_file)
//{
// //work out the file location of minifat then read each sector
// var miniFatStartOffset = (miniFatStartSector + 1)*SectorSize;
// var miniFatSize = MiniFatSectorCount * SectorSize;
// m_file.Seek(miniFatStartOffset, SeekOrigin.Begin);
// byte[] sectorBuff = new byte[SectorSize];
// for (var i = 0; i < MiniFatSectorCount; i += SectorSize)
// {
// m_file.Read(sectorBuff, 0, 4);
// var secId = BitConverter.ToUInt32(sectorBuff, 0);
// sectors.Add(secId);
// }
//}
m_minifat = new XlsFat(this, sectors, this.MiniSectorSize, true, rootDir);
return m_minifat;
}
/// <summary>
/// Returns full FAT table, including DIF sectors
/// </summary>
public XlsFat FAT
{
get
{
if (m_fat != null)
return m_fat;
uint value;
int sectorSize = SectorSize;
List<uint> sectors = new List<uint>(FatSectorCount);
for (int i = 0x4C; i < sectorSize; i += 4)
{
value = BitConverter.ToUInt32(m_bytes, i);
if (value == (uint)FATMARKERS.FAT_FreeSpace)
goto XlsHeader_Fat_Ready;
sectors.Add(value);
}
int difCount;
if ((difCount = DifSectorCount) == 0)
goto XlsHeader_Fat_Ready;
lock (m_file)
{
uint difSector = DifFirstSector;
byte[] buff = new byte[sectorSize];
uint prevSector = 0;
while (difCount > 0)
{
sectors.Capacity += 128;
if (prevSector == 0 || (difSector - prevSector) != 1)
m_file.Seek((difSector + 1) * sectorSize, SeekOrigin.Begin);
prevSector = difSector;
m_file.Read(buff, 0, sectorSize);
for (int i = 0; i < 508; i += 4)
{
value = BitConverter.ToUInt32(buff, i);
if (value == (uint)FATMARKERS.FAT_FreeSpace)
goto XlsHeader_Fat_Ready;
sectors.Add(value);
}
value = BitConverter.ToUInt32(buff, 508);
if (value == (uint)FATMARKERS.FAT_FreeSpace)
break;
if ((difCount--) > 1)
difSector = value;
else
sectors.Add(value);
}
}
XlsHeader_Fat_Ready:
m_fat = new XlsFat(this, sectors, this.SectorSize, false, null);
return m_fat;
}
}
/// <summary>
/// Reads Excel header from Stream
/// </summary>
/// <param name="file">Stream with Excel file</param>
/// <returns>XlsHeader representing specified file</returns>
public static XlsHeader ReadHeader(Stream file)
{
XlsHeader hdr = new XlsHeader(file);
lock (file)
{
file.Seek(0, SeekOrigin.Begin);
file.Read(hdr.m_bytes, 0, 512);
}
if (!hdr.IsSignatureValid)
throw new HeaderException(Errors.ErrorHeaderSignature);
if (hdr.ByteOrder != 0xFFFE)
throw new FormatException(Errors.ErrorHeaderOrder);
return hdr;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace MixedRealityToolkit.Common
{
/// <summary>
/// A MonoBehaviour that interpolates a transform's position, rotation or scale.
/// </summary>
public class Interpolator : MonoBehaviour
{
[Tooltip("When interpolating, use unscaled time. This is useful for games that have a pause mechanism or otherwise adjust the game timescale.")]
public bool UseUnscaledTime = true;
// A very small number that is used in determining if the Interpolator
// needs to run at all.
private const float smallNumber = 0.0000001f;
// The movement speed in meters per second
public float PositionPerSecond = 30.0f;
// The rotation speed, in degrees per second
public float RotationDegreesPerSecond = 720.0f;
// Adjusts rotation speed based on angular distance
public float RotationSpeedScaler = 0.0f;
// The amount to scale per second
public float ScalePerSecond = 5.0f;
// Lerp the estimated targets towards the object each update,
// slowing and smoothing movement.
[HideInInspector]
public bool SmoothLerpToTarget = false;
[HideInInspector]
public float SmoothPositionLerpRatio = 0.5f;
[HideInInspector]
public float SmoothRotationLerpRatio = 0.5f;
[HideInInspector]
public float SmoothScaleLerpRatio = 0.5f;
// Position data
private Vector3 targetPosition;
/// <summary>
/// True if the transform's position is animating; false otherwise.
/// </summary>
public bool AnimatingPosition { get; private set; }
// Rotation data
private Quaternion targetRotation;
/// <summary>
/// True if the transform's rotation is animating; false otherwise.
/// </summary>
public bool AnimatingRotation { get; private set; }
// Local Rotation data
private Quaternion targetLocalRotation;
/// <summary>
/// True if the transform's local rotation is animating; false otherwise.
/// </summary>
public bool AnimatingLocalRotation { get; private set; }
// Scale data
private Vector3 targetLocalScale;
/// <summary>
/// True if the transform's scale is animating; false otherwise.
/// </summary>
public bool AnimatingLocalScale { get; private set; }
/// <summary>
/// The event fired when an Interpolation is started.
/// </summary>
public event System.Action InterpolationStarted;
/// <summary>
/// The event fired when an Interpolation is completed.
/// </summary>
public event System.Action InterpolationDone;
/// <summary>
/// The velocity of a transform whose position is being interpolated.
/// </summary>
public Vector3 PositionVelocity { get; private set; }
private Vector3 oldPosition = Vector3.zero;
/// <summary>
/// True if position, rotation or scale are animating; false otherwise.
/// </summary>
public bool Running
{
get
{
return (AnimatingPosition || AnimatingRotation || AnimatingLocalRotation || AnimatingLocalScale);
}
}
public void Awake()
{
targetPosition = transform.position;
targetRotation = transform.rotation;
targetLocalRotation = transform.localRotation;
targetLocalScale = transform.localScale;
enabled = false;
}
/// <summary>
/// Sets the target position for the transform and if position wasn't
/// already animating, fires the InterpolationStarted event.
/// </summary>
/// <param name="target">The new target position to for the transform.</param>
public void SetTargetPosition(Vector3 target)
{
bool wasRunning = Running;
targetPosition = target;
float magsq = (targetPosition - transform.position).sqrMagnitude;
if (magsq > smallNumber)
{
AnimatingPosition = true;
enabled = true;
if (InterpolationStarted != null && !wasRunning)
{
InterpolationStarted();
}
}
else
{
// Set immediately to prevent accumulation of error.
transform.position = target;
AnimatingPosition = false;
}
}
/// <summary>
/// Sets the target rotation for the transform and if rotation wasn't
/// already animating, fires the InterpolationStarted event.
/// </summary>
/// <param name="target">The new target rotation for the transform.</param>
public void SetTargetRotation(Quaternion target)
{
bool wasRunning = Running;
targetRotation = target;
if (Quaternion.Dot(transform.rotation, target) < 1.0f)
{
AnimatingRotation = true;
enabled = true;
if (InterpolationStarted != null && !wasRunning)
{
InterpolationStarted();
}
}
else
{
// Set immediately to prevent accumulation of error.
transform.rotation = target;
AnimatingRotation = false;
}
}
/// <summary>
/// Sets the target local rotation for the transform and if rotation
/// wasn't already animating, fires the InterpolationStarted event.
/// </summary>
/// <param name="target">The new target local rotation for the transform.</param>
public void SetTargetLocalRotation(Quaternion target)
{
bool wasRunning = Running;
targetLocalRotation = target;
if (Quaternion.Dot(transform.localRotation, target) < 1.0f)
{
AnimatingLocalRotation = true;
enabled = true;
if (InterpolationStarted != null && !wasRunning)
{
InterpolationStarted();
}
}
else
{
// Set immediately to prevent accumulation of error.
transform.localRotation = target;
AnimatingLocalRotation = false;
}
}
/// <summary>
/// Sets the target local scale for the transform and if scale
/// wasn't already animating, fires the InterpolationStarted event.
/// </summary>
/// <param name="target">The new target local rotation for the transform.</param>
public void SetTargetLocalScale(Vector3 target)
{
bool wasRunning = Running;
targetLocalScale = target;
float magsq = (targetLocalScale - transform.localScale).sqrMagnitude;
if (magsq > Mathf.Epsilon)
{
AnimatingLocalScale = true;
enabled = true;
if (InterpolationStarted != null && !wasRunning)
{
InterpolationStarted();
}
}
else
{
// set immediately to prevent accumulation of error
transform.localScale = target;
AnimatingLocalScale = false;
}
}
/// <summary>
/// Interpolates smoothly to a target position.
/// </summary>
/// <param name="start">The starting position.</param>
/// <param name="target">The destination position.</param>
/// <param name="deltaTime">Caller-provided Time.deltaTime.</param>
/// <param name="speed">The speed to apply to the interpolation.</param>
/// <returns>New interpolated position closer to target</returns>
public static Vector3 NonLinearInterpolateTo(Vector3 start, Vector3 target, float deltaTime, float speed)
{
// If no interpolation speed, jump to target value.
if (speed <= 0.0f)
{
return target;
}
Vector3 distance = (target - start);
// When close enough, jump to the target
if (distance.sqrMagnitude <= Mathf.Epsilon)
{
return target;
}
// Apply the delta, then clamp so we don't overshoot the target
Vector3 deltaMove = distance * Mathf.Clamp(deltaTime * speed, 0.0f, 1.0f);
return start + deltaMove;
}
public void Update()
{
float deltaTime = UseUnscaledTime
? Time.unscaledDeltaTime
: Time.deltaTime;
bool interpOccuredThisFrame = false;
if (AnimatingPosition)
{
Vector3 lerpTargetPosition = targetPosition;
if (SmoothLerpToTarget)
{
lerpTargetPosition = Vector3.Lerp(transform.position, lerpTargetPosition, SmoothPositionLerpRatio);
}
Vector3 newPosition = NonLinearInterpolateTo(transform.position, lerpTargetPosition, deltaTime, PositionPerSecond);
if ((targetPosition - newPosition).sqrMagnitude <= smallNumber)
{
// Snap to final position
newPosition = targetPosition;
AnimatingPosition = false;
}
else
{
interpOccuredThisFrame = true;
}
transform.position = newPosition;
//calculate interpolatedVelocity and store position for next frame
PositionVelocity = oldPosition - newPosition;
oldPosition = newPosition;
}
// Determine how far we need to rotate
if (AnimatingRotation)
{
Quaternion lerpTargetRotation = targetRotation;
if (SmoothLerpToTarget)
{
lerpTargetRotation = Quaternion.Lerp(transform.rotation, lerpTargetRotation, SmoothRotationLerpRatio);
}
float angleDiff = Quaternion.Angle(transform.rotation, lerpTargetRotation);
float speedScale = 1.0f + (Mathf.Pow(angleDiff, RotationSpeedScaler) / 180.0f);
float ratio = Mathf.Clamp01((speedScale * RotationDegreesPerSecond * deltaTime) / angleDiff);
if (angleDiff < Mathf.Epsilon)
{
AnimatingRotation = false;
transform.rotation = targetRotation;
}
else
{
// Only lerp rotation here, as ratio is NaN if angleDiff is 0.0f
transform.rotation = Quaternion.Slerp(transform.rotation, lerpTargetRotation, ratio);
interpOccuredThisFrame = true;
}
}
// Determine how far we need to rotate
if (AnimatingLocalRotation)
{
Quaternion lerpTargetLocalRotation = targetLocalRotation;
if (SmoothLerpToTarget)
{
lerpTargetLocalRotation = Quaternion.Lerp(transform.localRotation, lerpTargetLocalRotation, SmoothRotationLerpRatio);
}
float angleDiff = Quaternion.Angle(transform.localRotation, lerpTargetLocalRotation);
float speedScale = 1.0f + (Mathf.Pow(angleDiff, RotationSpeedScaler) / 180.0f);
float ratio = Mathf.Clamp01((speedScale * RotationDegreesPerSecond * deltaTime) / angleDiff);
if (angleDiff < Mathf.Epsilon)
{
AnimatingLocalRotation = false;
transform.localRotation = targetLocalRotation;
}
else
{
// Only lerp rotation here, as ratio is NaN if angleDiff is 0.0f
transform.localRotation = Quaternion.Slerp(transform.localRotation, lerpTargetLocalRotation, ratio);
interpOccuredThisFrame = true;
}
}
if (AnimatingLocalScale)
{
Vector3 lerpTargetLocalScale = targetLocalScale;
if (SmoothLerpToTarget)
{
lerpTargetLocalScale = Vector3.Lerp(transform.localScale, lerpTargetLocalScale, SmoothScaleLerpRatio);
}
Vector3 newScale = NonLinearInterpolateTo(transform.localScale, lerpTargetLocalScale, deltaTime, ScalePerSecond);
if ((targetLocalScale - newScale).sqrMagnitude <= smallNumber)
{
// Snap to final scale
newScale = targetLocalScale;
AnimatingLocalScale = false;
}
else
{
interpOccuredThisFrame = true;
}
transform.localScale = newScale;
}
// If all interpolations have completed, stop updating
if (!interpOccuredThisFrame)
{
if (InterpolationDone != null)
{
InterpolationDone();
}
enabled = false;
}
}
/// <summary>
/// Snaps to the final target and stops interpolating
/// </summary>
public void SnapToTarget()
{
if (enabled)
{
transform.position = TargetPosition;
transform.rotation = TargetRotation;
transform.localRotation = TargetLocalRotation;
transform.localScale = TargetLocalScale;
AnimatingPosition = false;
AnimatingLocalScale = false;
AnimatingRotation = false;
AnimatingLocalRotation = false;
enabled = false;
if (InterpolationDone != null)
{
InterpolationDone();
}
}
}
/// <summary>
/// Stops the interpolation regardless if it has reached the target
/// </summary>
public void StopInterpolating()
{
if (enabled)
{
Reset();
if (InterpolationDone != null)
{
InterpolationDone();
}
}
}
/// <summary>
/// Stops the transform in place and terminates any animations.
/// </summary>
public void Reset()
{
targetPosition = transform.position;
targetRotation = transform.rotation;
targetLocalRotation = transform.localRotation;
targetLocalScale = transform.localScale;
AnimatingPosition = false;
AnimatingRotation = false;
AnimatingLocalRotation = false;
AnimatingLocalScale = false;
enabled = false;
}
/// <summary>
/// If animating position, specifies the target position as specified
/// by SetTargetPosition. Otherwise returns the current position of
/// the transform.
/// </summary>
public Vector3 TargetPosition
{
get
{
if (AnimatingPosition)
{
return targetPosition;
}
return transform.position;
}
}
/// <summary>
/// If animating rotation, specifies the target rotation as specified
/// by SetTargetRotation. Otherwise returns the current rotation of
/// the transform.
/// </summary>
public Quaternion TargetRotation
{
get
{
if (AnimatingRotation)
{
return targetRotation;
}
return transform.rotation;
}
}
/// <summary>
/// If animating local rotation, specifies the target local rotation as
/// specified by SetTargetLocalRotation. Otherwise returns the current
/// local rotation of the transform.
/// </summary>
public Quaternion TargetLocalRotation
{
get
{
if (AnimatingLocalRotation)
{
return targetLocalRotation;
}
return transform.localRotation;
}
}
/// <summary>
/// If animating local scale, specifies the target local scale as
/// specified by SetTargetLocalScale. Otherwise returns the current
/// local scale of the transform.
/// </summary>
public Vector3 TargetLocalScale
{
get
{
if (AnimatingLocalScale)
{
return targetLocalScale;
}
return transform.localScale;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using BizHawk.Common.StringExtensions;
using BizHawk.Common.NumberExtensions;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Common.IEmulatorExtensions;
using BizHawk.Client.Common;
using BizHawk.Client.EmuHawk.WinFormExtensions;
using BizHawk.Client.EmuHawk.ToolExtensions;
namespace BizHawk.Client.EmuHawk
{
/// <summary>
/// A form designed to search through ram values
/// </summary>
public partial class RamSearch : ToolFormBase, IToolForm
{
// TODO: DoSearch grabs the state of widgets and passes it to the engine before running, so rip out code that is attempting to keep the state up to date through change events
private string _currentFileName = string.Empty;
private RamSearchEngine _searches;
private RamSearchEngine.Settings _settings;
private int _defaultWidth;
private int _defaultHeight;
private string _sortedColumn = string.Empty;
private bool _sortReverse;
private bool _forcePreviewClear;
private bool _autoSearch;
private bool _dropdownDontfire; // Used as a hack to get around lame .net dropdowns, there's no way to set their index without firing the selectedindexchanged event!
public const int MaxDetailedSize = 1024 * 1024; // 1mb, semi-arbituary decision, sets the size to check for and automatically switch to fast mode for the user
public const int MaxSupportedSize = 1024 * 1024 * 64; // 64mb, semi-arbituary decision, sets the maximum size RAM Search will support (as it will crash beyond this)
#region Initialize, Load, and Save
public RamSearch()
{
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
InitializeComponent();
WatchListView.QueryItemText += ListView_QueryItemText;
WatchListView.QueryItemBkColor += ListView_QueryItemBkColor;
WatchListView.VirtualMode = true;
Closing += (o, e) => SaveConfigSettings();
_sortedColumn = string.Empty;
_sortReverse = false;
Settings = new RamSearchSettings();
}
[RequiredService]
public IMemoryDomains MemoryDomains { get; set; }
[RequiredService]
public IEmulator Emu { get; set; }
[OptionalService]
public IInputPollable InputPollableCore { get; set; }
[ConfigPersist]
public RamSearchSettings Settings { get; set; }
public bool AskSaveChanges()
{
return true;
}
public bool UpdateBefore
{
get { return false; }
}
private void HardSetDisplayTypeDropDown(BizHawk.Client.Common.DisplayType type)
{
foreach (var item in DisplayTypeDropdown.Items)
{
if (Watch.DisplayTypeToString(type) == item.ToString())
{
DisplayTypeDropdown.SelectedItem = item;
}
}
}
private void HardSetSizeDropDown(WatchSize size)
{
switch (size)
{
case WatchSize.Byte:
SizeDropdown.SelectedIndex = 0;
break;
case WatchSize.Word:
SizeDropdown.SelectedIndex = 1;
break;
case WatchSize.DWord:
SizeDropdown.SelectedIndex = 2;
break;
}
}
private void ColumnToggleCallback()
{
SaveColumnInfo(WatchListView, Settings.Columns);
LoadColumnInfo(WatchListView, Settings.Columns);
}
private void RamSearch_Load(object sender, EventArgs e)
{
TopMost = Settings.TopMost;
RamSearchMenu.Items.Add(Settings.Columns.GenerateColumnsMenu(ColumnToggleCallback));
_settings = new RamSearchEngine.Settings(MemoryDomains);
_searches = new RamSearchEngine(_settings, MemoryDomains);
ErrorIconButton.Visible = false;
_dropdownDontfire = true;
LoadConfigSettings();
SpecificValueBox.ByteSize = _settings.Size;
SpecificValueBox.Type = _settings.Type;
DifferentByBox.Type = Common.DisplayType.Unsigned;
DifferenceBox.Type = Common.DisplayType.Unsigned;
MessageLabel.Text = string.Empty;
SpecificAddressBox.MaxLength = (MemoryDomains.MainMemory.Size - 1).NumHexDigits();
HardSetSizeDropDown(_settings.Size);
PopulateTypeDropDown();
HardSetDisplayTypeDropDown(_settings.Type);
DoDomainSizeCheck();
SetReboot(false);
SpecificAddressBox.SetHexProperties(_settings.Domain.Size);
SpecificValueBox.ResetText();
SpecificAddressBox.ResetText();
NumberOfChangesBox.ResetText();
DifferenceBox.ResetText();
DifferentByBox.ResetText();
_dropdownDontfire = false;
if (_settings.Mode == RamSearchEngine.Settings.SearchMode.Fast)
{
SetToFastMode();
}
NewSearch();
}
private void OutOfRangeCheck()
{
ErrorIconButton.Visible = _searches.OutOfRangeAddress.Any();
}
private void ListView_QueryItemBkColor(int index, int column, ref Color color)
{
if (column == 0)
{
if (_searches.Count > 0 && column == 0)
{
var nextColor = Color.White;
var isCheat = Global.CheatList.IsActive(_settings.Domain, _searches[index].Address);
var isWeeded = Settings.PreviewMode && !_forcePreviewClear && _searches.Preview(_searches[index].Address);
if (_searches[index].Address >= _searches[index].Domain.Size)
{
nextColor = Color.PeachPuff;
}
else if (isCheat)
{
nextColor = isWeeded ? Color.Lavender : Color.LightCyan;
}
else
{
if (isWeeded)
{
nextColor = Color.Pink;
}
}
color = nextColor;
}
}
}
private void ListView_QueryItemText(int index, int column, out string text)
{
text = string.Empty;
if (index >= _searches.Count)
{
return;
}
var columnName = WatchListView.Columns[column].Name;
switch (columnName)
{
case WatchList.ADDRESS:
text = _searches[index].AddressString;
break;
case WatchList.VALUE:
text = _searches[index].ValueString;
break;
case WatchList.PREV:
text = _searches[index].PreviousStr;
break;
case WatchList.CHANGES:
text = _searches[index].ChangeCount.ToString();
break;
case WatchList.DIFF:
text = _searches[index].Diff;
break;
}
}
private void LoadConfigSettings()
{
_defaultWidth = Size.Width;
_defaultHeight = Size.Height;
if (Settings.UseWindowPosition)
{
Location = Settings.WindowPosition;
}
if (Settings.UseWindowSize)
{
Size = Settings.WindowSize;
}
TopMost = Settings.TopMost;
LoadColumnInfo(WatchListView, Settings.Columns);
}
#endregion
#region Public
/// <summary>
/// This should be called anytime the search list changes
/// </summary>
private void UpdateList()
{
WatchListView.ItemCount = _searches.Count;
SetTotal();
}
public void NewUpdate(ToolFormUpdateType type) { }
/// <summary>
/// This should only be called when the values of the list need an update such as after a poke or emulation occured
/// </summary>
public void UpdateValues()
{
if (_searches.Count > 0)
{
_searches.Update();
if (_autoSearch)
{
if (InputPollableCore != null && Settings.AutoSearchTakeLagFramesIntoAccount && InputPollableCore.IsLagFrame)
{
// Do nothing
}
else
{
DoSearch();
}
}
_forcePreviewClear = false;
WatchListView.BlazingFast = true;
WatchListView.Invalidate();
WatchListView.BlazingFast = false;
}
}
public void FastUpdate()
{
if (_searches.Count > 0)
{
_searches.Update();
if (_autoSearch)
{
DoSearch();
}
}
}
public void Restart()
{
_settings = new RamSearchEngine.Settings(MemoryDomains);
_searches = new RamSearchEngine(_settings, MemoryDomains);
MessageLabel.Text = "Search restarted";
DoDomainSizeCheck();
NewSearch();
}
public void SaveConfigSettings()
{
SaveColumnInfo(WatchListView, Settings.Columns);
if (WindowState == FormWindowState.Normal)
{
Settings.Wndx = Location.X;
Settings.Wndy = Location.Y;
Settings.Width = Right - Left;
Settings.Height = Bottom - Top;
}
}
public void NewSearch()
{
var compareTo = _searches.CompareTo;
var compareVal = _searches.CompareValue;
var differentBy = _searches.DifferentBy;
_searches = new RamSearchEngine(_settings, MemoryDomains, compareTo, compareVal, differentBy);
_searches.Start();
if (Settings.AlwaysExcludeRamWatch)
{
RemoveRamWatchesFromList();
}
UpdateList();
ToggleSearchDependentToolBarItems();
SetReboot(false);
MessageLabel.Text = string.Empty;
SetDomainLabel();
}
public void NextCompareTo(bool reverse = false)
{
var radios = CompareToBox.Controls
.OfType<RadioButton>()
.Select(control => control)
.OrderBy(x => x.TabIndex)
.ToList();
var selected = radios.FirstOrDefault(x => x.Checked);
var index = radios.IndexOf(selected);
if (reverse)
{
if (index == 0)
{
index = radios.Count - 1;
}
else
{
index--;
}
}
else
{
index++;
if (index >= radios.Count)
{
index = 0;
}
}
radios[index].Checked = true;
var mi = radios[index].GetType().GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic);
mi.Invoke(radios[index], new object[] { new EventArgs() });
}
public void NextOperator(bool reverse = false)
{
var radios = ComparisonBox.Controls
.OfType<RadioButton>()
.Select(control => control)
.OrderBy(x => x.TabIndex)
.ToList();
var selected = radios.FirstOrDefault(x => x.Checked);
var index = radios.IndexOf(selected);
if (reverse)
{
if (index == 0)
{
index = radios.Count - 1;
}
else
{
index--;
}
}
else
{
index++;
if (index >= radios.Count)
{
index = 0;
}
}
radios[index].Checked = true;
var mi = radios[index].GetType().GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic);
mi.Invoke(radios[index], new object[] { new EventArgs() });
}
#endregion
#region Private
private void ToggleSearchDependentToolBarItems()
{
DoSearchToolButton.Enabled =
CopyValueToPrevToolBarItem.Enabled =
_searches.Count > 0;
UpdateUndoToolBarButtons();
OutOfRangeCheck();
PokeAddressToolBarItem.Enabled =
FreezeAddressToolBarItem.Enabled =
SelectedIndices.Any() &&
_searches.Domain.CanPoke();
}
private long? CompareToValue
{
get
{
if (PreviousValueRadio.Checked)
{
return null;
}
if (SpecificValueRadio.Checked)
{
return (long)SpecificValueBox.ToRawInt() & 0x00000000FFFFFFFF;
}
if (SpecificAddressRadio.Checked)
{
return SpecificAddressBox.ToRawInt();
}
if (NumberOfChangesRadio.Checked)
{
return NumberOfChangesBox.ToRawInt();
}
if (DifferenceRadio.Checked)
{
return DifferenceBox.ToRawInt();
}
return null;
}
}
private int? DifferentByValue
{
get
{
return DifferentByRadio.Checked ? DifferentByBox.ToRawInt() : null;
}
}
private RamSearchEngine.ComparisonOperator Operator
{
get
{
if (NotEqualToRadio.Checked)
{
return RamSearchEngine.ComparisonOperator.NotEqual;
}
if (LessThanRadio.Checked)
{
return RamSearchEngine.ComparisonOperator.LessThan;
}
if (GreaterThanRadio.Checked)
{
return RamSearchEngine.ComparisonOperator.GreaterThan;
}
if (LessThanOrEqualToRadio.Checked)
{
return RamSearchEngine.ComparisonOperator.LessThanEqual;
}
if (GreaterThanOrEqualToRadio.Checked)
{
return RamSearchEngine.ComparisonOperator.GreaterThanEqual;
}
if (DifferentByRadio.Checked)
{
return RamSearchEngine.ComparisonOperator.DifferentBy;
}
return RamSearchEngine.ComparisonOperator.Equal;
}
}
private RamSearchEngine.Compare Compare
{
get
{
if (SpecificValueRadio.Checked)
{
return RamSearchEngine.Compare.SpecificValue;
}
if (SpecificAddressRadio.Checked)
{
return RamSearchEngine.Compare.SpecificAddress;
}
if (NumberOfChangesRadio.Checked)
{
return RamSearchEngine.Compare.Changes;
}
if (DifferenceRadio.Checked)
{
return RamSearchEngine.Compare.Difference;
}
return RamSearchEngine.Compare.Previous;
}
}
public void DoSearch()
{
_searches.CompareValue = CompareToValue;
_searches.DifferentBy = DifferentByValue;
_searches.Operator = Operator;
_searches.CompareTo = Compare;
var removed = _searches.DoSearch();
UpdateList();
SetRemovedMessage(removed);
ToggleSearchDependentToolBarItems();
_forcePreviewClear = true;
}
private IEnumerable<int> SelectedIndices
{
get { return WatchListView.SelectedIndices.Cast<int>(); }
}
private IEnumerable<Watch> SelectedItems
{
get { return SelectedIndices.Select(index => _searches[index]); }
}
private IEnumerable<Watch> SelectedWatches
{
get { return SelectedItems.Where(x => !x.IsSeparator); }
}
private void SetRemovedMessage(int val)
{
MessageLabel.Text = val + " address" + (val != 1 ? "es" : string.Empty) + " removed";
}
private void SetTotal()
{
TotalSearchLabel.Text = string.Format("{0:n0}", _searches.Count) + " addresses";
}
private void SetDomainLabel()
{
MemDomainLabel.Text = _searches.Domain.Name;
}
private void LoadFileFromRecent(string path)
{
var file = new FileInfo(path);
if (!file.Exists)
{
Settings.RecentSearches.HandleLoadError(path);
}
else
{
LoadWatchFile(file, append: false);
}
}
private void SetMemoryDomain(string name)
{
_settings.Domain = MemoryDomains[name];
SetReboot(true);
SpecificAddressBox.MaxLength = (_settings.Domain.Size - 1).NumHexDigits();
DoDomainSizeCheck();
}
private void DoDomainSizeCheck()
{
if (_settings.Domain.Size >= MaxDetailedSize
&& _settings.Mode == RamSearchEngine.Settings.SearchMode.Detailed)
{
_settings.Mode = RamSearchEngine.Settings.SearchMode.Fast;
SetReboot(true);
MessageLabel.Text = "Large domain, switching to fast mode";
}
}
private void DoDisplayTypeClick(Client.Common.DisplayType type)
{
if (_settings.Type != type)
{
if (!string.IsNullOrEmpty(SpecificValueBox.Text))
SpecificValueBox.Text = "0";
if (!string.IsNullOrEmpty(DifferenceBox.Text))
DifferenceBox.Text = "0";
if (!string.IsNullOrEmpty(DifferentByBox.Text))
DifferentByBox.Text = "0";
}
SpecificValueBox.Type = _settings.Type = type;
DifferenceBox.Type = type;
DifferentByBox.Type = type;
_searches.SetType(type);
_dropdownDontfire = true;
DisplayTypeDropdown.SelectedItem = Watch.DisplayTypeToString(type);
_dropdownDontfire = false;
WatchListView.Refresh();
}
private void SetPreviousStype(PreviousType type)
{
_settings.PreviousType = type;
_searches.SetPreviousType(type);
}
private void SetSize(WatchSize size)
{
_settings.Size = size;
SpecificValueBox.ByteSize = size;
if (!string.IsNullOrEmpty(SpecificAddressBox.Text))
{
SpecificAddressBox.Text = "0";
}
if (!string.IsNullOrEmpty(SpecificValueBox.Text))
{
SpecificValueBox.Text = "0";
}
bool isTypeCompatible = false;
switch (size)
{
case WatchSize.Byte:
isTypeCompatible = ByteWatch.ValidTypes.Any(t => t == _settings.Type);
SizeDropdown.SelectedIndex = 0;
break;
case WatchSize.Word:
isTypeCompatible = WordWatch.ValidTypes.Any(t => t == _settings.Type);
SizeDropdown.SelectedIndex = 1;
break;
case WatchSize.DWord:
isTypeCompatible = DWordWatch.ValidTypes.Any(t => t == _settings.Type);
SizeDropdown.SelectedIndex = 2;
break;
}
if (!isTypeCompatible)
{
_settings.Type = Client.Common.DisplayType.Unsigned;
}
_dropdownDontfire = true;
PopulateTypeDropDown();
_dropdownDontfire = false;
SpecificValueBox.Type = _settings.Type;
SetReboot(true);
NewSearch();
}
private void PopulateTypeDropDown()
{
var previous = DisplayTypeDropdown.SelectedItem != null ? DisplayTypeDropdown.SelectedItem.ToString() : string.Empty;
var next = string.Empty;
DisplayTypeDropdown.Items.Clear();
IEnumerable<Client.Common.DisplayType> types = null;
switch (_settings.Size)
{
case WatchSize.Byte:
types = ByteWatch.ValidTypes;
break;
case WatchSize.Word:
types = WordWatch.ValidTypes;
break;
case WatchSize.DWord:
types = DWordWatch.ValidTypes;
break;
}
foreach (var type in types)
{
var typeStr = Watch.DisplayTypeToString(type);
DisplayTypeDropdown.Items.Add(typeStr);
if (previous == typeStr)
{
next = typeStr;
}
}
if (!string.IsNullOrEmpty(next))
{
DisplayTypeDropdown.SelectedItem = next;
}
else
{
DisplayTypeDropdown.SelectedIndex = 0;
}
}
private void SetComparisonOperator(RamSearchEngine.ComparisonOperator op)
{
_searches.Operator = op;
WatchListView.Refresh();
}
private void SetCompareTo(RamSearchEngine.Compare comp)
{
_searches.CompareTo = comp;
WatchListView.Refresh();
}
private void SetCompareValue(int? value)
{
_searches.CompareValue = value;
WatchListView.Refresh();
}
private void SetReboot(bool rebootNeeded)
{
RebootToolBarSeparator.Visible =
RebootToolbarButton.Visible =
rebootNeeded;
}
private void SetToDetailedMode()
{
_settings.Mode = RamSearchEngine.Settings.SearchMode.Detailed;
NumberOfChangesRadio.Enabled = true;
NumberOfChangesBox.Enabled = true;
DifferenceRadio.Enabled = true;
DifferentByBox.Enabled = true;
ClearChangeCountsToolBarItem.Enabled = true;
WatchListView.Columns[WatchList.CHANGES].Width = Settings.Columns[WatchList.CHANGES].Width;
SetReboot(true);
}
private void SetToFastMode()
{
_settings.Mode = RamSearchEngine.Settings.SearchMode.Fast;
if (_settings.PreviousType == PreviousType.LastFrame || _settings.PreviousType == PreviousType.LastChange)
{
SetPreviousStype(PreviousType.LastSearch);
}
NumberOfChangesRadio.Enabled = false;
NumberOfChangesBox.Enabled = false;
NumberOfChangesBox.Text = string.Empty;
ClearChangeCountsToolBarItem.Enabled = false;
if (NumberOfChangesRadio.Checked || DifferenceRadio.Checked)
{
PreviousValueRadio.Checked = true;
}
Settings.Columns[WatchList.CHANGES].Width = WatchListView.Columns[WatchList.CHANGES].Width;
WatchListView.Columns[WatchList.CHANGES].Width = 0;
SetReboot(true);
}
private void RemoveAddresses()
{
var indices = SelectedIndices.ToList();
if (indices.Any())
{
SetRemovedMessage(indices.Count);
_searches.RemoveRange(indices);
UpdateList();
WatchListView.SelectedIndices.Clear();
ToggleSearchDependentToolBarItems();
}
}
public void LoadWatchFile(FileInfo file, bool append, bool truncate = false)
{
if (file != null)
{
if (!truncate)
{
_currentFileName = file.FullName;
}
var watches = new WatchList(MemoryDomains, Emu.SystemId);
watches.Load(file.FullName, append);
Settings.RecentSearches.Add(watches.CurrentFileName);
var watchList = watches.Where(x => !x.IsSeparator);
var addresses = watchList.Select(x => x.Address).ToList();
if (truncate)
{
SetRemovedMessage(addresses.Count);
_searches.RemoveSmallWatchRange(watchList);
}
else
{
_searches.AddRange(addresses, append);
MessageLabel.Text = file.Name + " loaded";
}
UpdateList();
Settings.RecentSearches.Add(file.FullName);
if (!append && !truncate)
{
_searches.ClearHistory();
}
ToggleSearchDependentToolBarItems();
}
}
private void AddToRamWatch()
{
var watches = SelectedWatches.ToList();
if (watches.Any())
{
GlobalWin.Tools.LoadRamWatch(true);
watches.ForEach(GlobalWin.Tools.RamWatch.AddWatch);
if (Settings.AlwaysExcludeRamWatch)
{
RemoveRamWatchesFromList();
}
}
}
private void PokeAddress()
{
if (SelectedIndices.Any())
{
var poke = new RamPoke
{
InitialLocation = this.ChildPointToScreen(WatchListView)
};
poke.SetWatch(SelectedIndices.Select(t => _searches[t]).ToList());
poke.ShowHawkDialog();
UpdateList();
}
}
private void RemoveRamWatchesFromList()
{
if (GlobalWin.Tools.Has<RamWatch>())
{
_searches.RemoveSmallWatchRange(GlobalWin.Tools.RamWatch.Watches);
UpdateList();
}
}
private void UpdateUndoToolBarButtons()
{
UndoToolBarButton.Enabled = _searches.CanUndo;
RedoToolBarItem.Enabled = _searches.CanRedo;
}
private string GetColumnValue(string name, int index)
{
switch (name)
{
default:
return string.Empty;
case WatchList.ADDRESS:
return _searches[index].AddressString;
case WatchList.VALUE:
return _searches[index].ValueString;
case WatchList.PREV:
return _searches[index].PreviousStr;
case WatchList.CHANGES:
return _searches[index].ChangeCount.ToString();
case WatchList.DIFF:
return _searches[index].Diff;
}
}
private void GoToSpecifiedAddress()
{
WatchListView.SelectedIndices.Clear();
var prompt = new InputPrompt
{
Text = "Go to Address",
StartLocation = this.ChildPointToScreen(WatchListView),
Message = "Enter a hexadecimal value"
};
var result = prompt.ShowHawkDialog();
if (result == DialogResult.OK)
{
if (prompt.PromptText.IsHex())
{
var addr = int.Parse(prompt.PromptText, NumberStyles.HexNumber);
for (int index = 0; index < _searches.Count; index++)
{
if (addr == _searches[index].Address)
{
WatchListView.SelectItem(index, true);
WatchListView.ensureVisible();
break;
}
}
}
}
}
#endregion
public class RamSearchSettings : ToolDialogSettings
{
public RamSearchSettings()
{
Columns = new ColumnList
{
new Column { Name = WatchList.ADDRESS, Visible = true, Index = 0, Width = 60 },
new Column { Name = WatchList.VALUE, Visible = true, Index = 1, Width = 59 },
new Column { Name = WatchList.PREV, Visible = true, Index = 2, Width = 59 },
new Column { Name = WatchList.CHANGES, Visible = true, Index = 3, Width = 55 },
new Column { Name = WatchList.DIFF, Visible = false, Index = 4, Width = 59 },
};
PreviewMode = true;
RecentSearches = new RecentFiles(8);
AutoSearchTakeLagFramesIntoAccount = true;
}
public ColumnList Columns { get; set; }
public bool PreviewMode { get; set; }
public bool AlwaysExcludeRamWatch { get; set; }
public bool AutoSearchTakeLagFramesIntoAccount { get; set; }
public RecentFiles RecentSearches { get; set; }
}
#region Winform Events
#region File
private void FileSubMenu_DropDownOpened(object sender, EventArgs e)
{
SaveMenuItem.Enabled = !string.IsNullOrWhiteSpace(_currentFileName);
}
private void RecentSubMenu_DropDownOpened(object sender, EventArgs e)
{
RecentSubMenu.DropDownItems.Clear();
RecentSubMenu.DropDownItems.AddRange(
Settings.RecentSearches.RecentMenu(LoadFileFromRecent));
}
private void OpenMenuItem_Click(object sender, EventArgs e)
{
LoadWatchFile(
GetWatchFileFromUser(string.Empty),
sender == AppendFileMenuItem,
sender == TruncateFromFileMenuItem
);
}
private void SaveMenuItem_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(_currentFileName))
{
var watches = new WatchList(MemoryDomains, Emu.SystemId) { CurrentFileName = _currentFileName };
for (var i = 0; i < _searches.Count; i++)
{
watches.Add(_searches[i]);
}
if (!string.IsNullOrWhiteSpace(watches.CurrentFileName))
{
if (watches.Save())
{
_currentFileName = watches.CurrentFileName;
MessageLabel.Text = Path.GetFileName(_currentFileName) + " saved";
Settings.RecentSearches.Add(watches.CurrentFileName);
}
}
else
{
var result = watches.SaveAs(GetWatchSaveFileFromUser(watches.CurrentFileName));
if (result)
{
MessageLabel.Text = Path.GetFileName(_currentFileName) + " saved";
Settings.RecentSearches.Add(watches.CurrentFileName);
}
}
}
}
private void SaveAsMenuItem_Click(object sender, EventArgs e)
{
var watches = new WatchList(MemoryDomains, Emu.SystemId) { CurrentFileName = _currentFileName };
for (var i = 0; i < _searches.Count; i++)
{
watches.Add(_searches[i]);
}
if (watches.SaveAs(GetWatchSaveFileFromUser(watches.CurrentFileName)))
{
_currentFileName = watches.CurrentFileName;
MessageLabel.Text = Path.GetFileName(_currentFileName) + " saved";
Settings.RecentSearches.Add(watches.CurrentFileName);
}
}
private void CloseMenuItem_Click(object sender, EventArgs e)
{
Close();
}
#endregion
#region Settings
private void SettingsSubMenu_DropDownOpened(object sender, EventArgs e)
{
CheckMisalignedMenuItem.Checked = _settings.CheckMisAligned;
BigEndianMenuItem.Checked = _settings.BigEndian;
}
private void ModeSubMenu_DropDownOpened(object sender, EventArgs e)
{
DetailedMenuItem.Checked = _settings.Mode == RamSearchEngine.Settings.SearchMode.Detailed;
FastMenuItem.Checked = _settings.Mode == RamSearchEngine.Settings.SearchMode.Fast;
}
private void MemoryDomainsSubMenu_DropDownOpened(object sender, EventArgs e)
{
MemoryDomainsSubMenu.DropDownItems.Clear();
MemoryDomainsSubMenu.DropDownItems.AddRange(
MemoryDomains.MenuItems(SetMemoryDomain, _searches.Domain.Name, MaxSupportedSize)
.ToArray());
}
private void SizeSubMenu_DropDownOpened(object sender, EventArgs e)
{
ByteMenuItem.Checked = _settings.Size == WatchSize.Byte;
WordMenuItem.Checked = _settings.Size == WatchSize.Word;
DWordMenuItem.Checked = _settings.Size == WatchSize.DWord;
}
private void DisplayTypeSubMenu_DropDownOpened(object sender, EventArgs e)
{
DisplayTypeSubMenu.DropDownItems.Clear();
IEnumerable<Client.Common.DisplayType> types = null;
switch (_settings.Size)
{
case WatchSize.Byte:
types = ByteWatch.ValidTypes;
break;
case WatchSize.Word:
types = WordWatch.ValidTypes;
break;
case WatchSize.DWord:
types = DWordWatch.ValidTypes;
break;
}
foreach (var type in types)
{
var item = new ToolStripMenuItem
{
Name = type + "ToolStripMenuItem",
Text = Watch.DisplayTypeToString(type),
Checked = _settings.Type == type,
};
var type1 = type;
item.Click += (o, ev) => DoDisplayTypeClick(type1);
DisplayTypeSubMenu.DropDownItems.Add(item);
}
}
private void DefinePreviousValueSubMenu_DropDownOpened(object sender, EventArgs e)
{
Previous_LastSearchMenuItem.Checked = false;
PreviousFrameMenuItem.Checked = false;
Previous_OriginalMenuItem.Checked = false;
Previous_LastChangeMenuItem.Checked = false;
switch (_settings.PreviousType)
{
default:
case PreviousType.LastSearch:
Previous_LastSearchMenuItem.Checked = true;
break;
case PreviousType.LastFrame:
PreviousFrameMenuItem.Checked = true;
break;
case PreviousType.Original:
Previous_OriginalMenuItem.Checked = true;
break;
case PreviousType.LastChange:
Previous_LastChangeMenuItem.Checked = true;
break;
}
PreviousFrameMenuItem.Enabled = _settings.Mode != RamSearchEngine.Settings.SearchMode.Fast;
Previous_LastChangeMenuItem.Enabled = _settings.Mode != RamSearchEngine.Settings.SearchMode.Fast;
}
private void DetailedMenuItem_Click(object sender, EventArgs e)
{
SetToDetailedMode();
}
private void FastMenuItem_Click(object sender, EventArgs e)
{
SetToFastMode();
}
private void ByteMenuItem_Click(object sender, EventArgs e)
{
SetSize(WatchSize.Byte);
}
private void WordMenuItem_Click(object sender, EventArgs e)
{
SetSize(WatchSize.Word);
}
private void DWordMenuItem_Click_Click(object sender, EventArgs e)
{
SetSize(WatchSize.DWord);
}
private void CheckMisalignedMenuItem_Click(object sender, EventArgs e)
{
_settings.CheckMisAligned ^= true;
SetReboot(true);
}
private void Previous_LastFrameMenuItem_Click(object sender, EventArgs e)
{
SetPreviousStype(PreviousType.LastFrame);
}
private void Previous_LastSearchMenuItem_Click(object sender, EventArgs e)
{
SetPreviousStype(PreviousType.LastSearch);
}
private void Previous_OriginalMenuItem_Click(object sender, EventArgs e)
{
SetPreviousStype(PreviousType.Original);
}
private void Previous_LastChangeMenuItem_Click(object sender, EventArgs e)
{
SetPreviousStype(PreviousType.LastChange);
}
private void BigEndianMenuItem_Click(object sender, EventArgs e)
{
_settings.BigEndian ^= true;
_searches.SetEndian(_settings.BigEndian);
}
#endregion
#region Search
private void SearchSubMenu_DropDownOpened(object sender, EventArgs e)
{
ClearChangeCountsMenuItem.Enabled = _settings.Mode == RamSearchEngine.Settings.SearchMode.Detailed;
RemoveMenuItem.Enabled =
AddToRamWatchMenuItem.Enabled =
SelectedIndices.Any();
PokeAddressMenuItem.Enabled =
FreezeAddressMenuItem.Enabled =
SelectedIndices.Any() &&
SelectedWatches.All(w => w.Domain.CanPoke());
UndoMenuItem.Enabled =
ClearUndoMenuItem.Enabled =
_searches.CanUndo;
RedoMenuItem.Enabled = _searches.CanRedo;
}
private void NewSearchMenuMenuItem_Click(object sender, EventArgs e)
{
NewSearch();
}
private void SearchMenuItem_Click(object sender, EventArgs e)
{
DoSearch();
}
private void UndoMenuItem_Click(object sender, EventArgs e)
{
if (_searches.CanUndo)
{
_searches.Undo();
UpdateList();
ToggleSearchDependentToolBarItems();
_forcePreviewClear = true;
UpdateUndoToolBarButtons();
}
}
private void RedoMenuItem_Click(object sender, EventArgs e)
{
if (_searches.CanRedo)
{
_searches.Redo();
UpdateList();
ToggleSearchDependentToolBarItems();
_forcePreviewClear = true;
UpdateUndoToolBarButtons();
}
}
private void CopyValueToPrevMenuItem_Click(object sender, EventArgs e)
{
_searches.SetPreviousToCurrent();
WatchListView.Refresh();
}
private void ClearChangeCountsMenuItem_Click(object sender, EventArgs e)
{
_searches.ClearChangeCounts();
WatchListView.Refresh();
}
private void RemoveMenuItem_Click(object sender, EventArgs e)
{
RemoveAddresses();
}
private void GoToAddressMenuItem_Click(object sender, EventArgs e)
{
GoToSpecifiedAddress();
}
private void AddToRamWatchMenuItem_Click(object sender, EventArgs e)
{
AddToRamWatch();
}
private void PokeAddressMenuItem_Click(object sender, EventArgs e)
{
PokeAddress();
}
private void FreezeAddressMenuItem_Click(object sender, EventArgs e)
{
var allCheats = SelectedWatches.All(x => Global.CheatList.IsActive(x.Domain, x.Address));
if (allCheats)
{
SelectedWatches.UnfreezeAll();
}
else
{
SelectedWatches.FreezeAll();
}
}
private void ClearUndoMenuItem_Click(object sender, EventArgs e)
{
_searches.ClearHistory();
UpdateUndoToolBarButtons();
}
#endregion
#region Options
private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e)
{
AutoloadDialogMenuItem.Checked = Settings.AutoLoad;
SaveWinPositionMenuItem.Checked = Settings.SaveWindowPosition;
ExcludeRamWatchMenuItem.Checked = Settings.AlwaysExcludeRamWatch;
UseUndoHistoryMenuItem.Checked = _searches.UndoEnabled;
PreviewModeMenuItem.Checked = Settings.PreviewMode;
AlwaysOnTopMenuItem.Checked = Settings.TopMost;
FloatingWindowMenuItem.Checked = Settings.FloatingWindow;
AutoSearchMenuItem.Checked = _autoSearch;
AutoSearchAccountForLagMenuItem.Checked = Settings.AutoSearchTakeLagFramesIntoAccount;
}
private void PreviewModeMenuItem_Click(object sender, EventArgs e)
{
Settings.PreviewMode ^= true;
}
private void AutoSearchMenuItem_Click(object sender, EventArgs e)
{
_autoSearch ^= true;
AutoSearchCheckBox.Checked = _autoSearch;
DoSearchToolButton.Enabled =
SearchButton.Enabled =
!_autoSearch;
}
private void AutoSearchAccountForLagMenuItem_Click(object sender, EventArgs e)
{
Settings.AutoSearchTakeLagFramesIntoAccount ^= true;
}
private void ExcludeRamWatchMenuItem_Click(object sender, EventArgs e)
{
Settings.AlwaysExcludeRamWatch ^= true;
if (Settings.AlwaysExcludeRamWatch)
{
RemoveRamWatchesFromList();
}
}
private void UseUndoHistoryMenuItem_Click(object sender, EventArgs e)
{
_searches.UndoEnabled ^= true;
}
private void AutoloadDialogMenuItem_Click(object sender, EventArgs e)
{
Settings.AutoLoad ^= true;
}
private void SaveWinPositionMenuItem_Click(object sender, EventArgs e)
{
Settings.SaveWindowPosition ^= true;
}
private void AlwaysOnTopMenuItem_Click(object sender, EventArgs e)
{
TopMost = Settings.TopMost ^= true;
}
private void FloatingWindowMenuItem_Click(object sender, EventArgs e)
{
Settings.FloatingWindow ^= true;
RefreshFloatingWindowControl(Settings.FloatingWindow);
}
private void RestoreDefaultsMenuItem_Click(object sender, EventArgs e)
{
var recentFiles = Settings.RecentSearches; // We don't want to wipe recent files when restoring
Settings = new RamSearchSettings();
Settings.RecentSearches = recentFiles;
Size = new Size(_defaultWidth, _defaultHeight);
RamSearchMenu.Items.Remove(
RamSearchMenu.Items
.OfType<ToolStripMenuItem>()
.First(x => x.Name == "GeneratedColumnsSubMenu")
);
RamSearchMenu.Items.Add(Settings.Columns.GenerateColumnsMenu(ColumnToggleCallback));
_settings = new RamSearchEngine.Settings(MemoryDomains);
if (_settings.Mode == RamSearchEngine.Settings.SearchMode.Fast)
{
SetToFastMode();
}
RefreshFloatingWindowControl(Settings.FloatingWindow);
LoadColumnInfo(WatchListView, Settings.Columns);
}
#endregion
#region ContextMenu and Toolbar
private void ListViewContextMenu_Opening(object sender, CancelEventArgs e)
{
DoSearchContextMenuItem.Enabled = _searches.Count > 0;
RemoveContextMenuItem.Visible =
AddToRamWatchContextMenuItem.Visible =
FreezeContextMenuItem.Visible =
ContextMenuSeparator2.Visible =
ViewInHexEditorContextMenuItem.Visible =
SelectedIndices.Any();
PokeContextMenuItem.Enabled =
FreezeContextMenuItem.Visible =
SelectedIndices.Any() &&
SelectedWatches.All(w => w.Domain.CanPoke());
UnfreezeAllContextMenuItem.Visible = Global.CheatList.ActiveCount > 0;
ContextMenuSeparator3.Visible = SelectedIndices.Any() || (Global.CheatList.ActiveCount > 0);
var allCheats = true;
foreach (var index in SelectedIndices)
{
if (!Global.CheatList.IsActive(_settings.Domain, _searches[index].Address))
{
allCheats = false;
}
}
if (allCheats)
{
FreezeContextMenuItem.Text = "&Unfreeze Address";
FreezeContextMenuItem.Image = Properties.Resources.Unfreeze;
}
else
{
FreezeContextMenuItem.Text = "&Freeze Address";
FreezeContextMenuItem.Image = Properties.Resources.Freeze;
}
}
private void UnfreezeAllContextMenuItem_Click(object sender, EventArgs e)
{
Global.CheatList.RemoveAll();
}
private void ViewInHexEditorContextMenuItem_Click(object sender, EventArgs e)
{
if (SelectedWatches.Any())
{
ViewInHexEditor(_searches.Domain, SelectedWatches.Select(x => x.Address), SelectedSize);
}
}
private void ClearPreviewContextMenuItem_Click(object sender, EventArgs e)
{
_forcePreviewClear = true;
WatchListView.Refresh();
}
private WatchSize SelectedSize
{
get
{
switch (SizeDropdown.SelectedIndex)
{
default:
case 0:
return WatchSize.Byte;
case 1:
return WatchSize.Word;
case 2:
return WatchSize.DWord;
}
}
}
private void SizeDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
if (_dropdownDontfire)
{
return;
}
SetSize(SelectedSize);
}
private void DisplayTypeDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
if (!_dropdownDontfire)
{
DoDisplayTypeClick(Watch.StringToDisplayType(DisplayTypeDropdown.SelectedItem.ToString()));
}
}
private void ErrorIconButton_Click(object sender, EventArgs e)
{
var outOfRangeAddresses = _searches.OutOfRangeAddress.ToList();
SetRemovedMessage(outOfRangeAddresses.Count);
UpdateList();
ToggleSearchDependentToolBarItems();
}
private void CopyWatchesToClipBoard()
{
if (SelectedItems.Any())
{
var sb = new StringBuilder();
foreach (var watch in SelectedItems)
{
sb.AppendLine(watch.ToString());
}
if (sb.Length > 0)
{
Clipboard.SetDataObject(sb.ToString());
}
}
}
#endregion
#region Compare To Box
private void PreviousValueRadio_Click(object sender, EventArgs e)
{
SpecificValueBox.Enabled = false;
SpecificAddressBox.Enabled = false;
NumberOfChangesBox.Enabled = false;
DifferenceBox.Enabled = false;
SetCompareTo(RamSearchEngine.Compare.Previous);
}
private void SpecificValueRadio_Click(object sender, EventArgs e)
{
SpecificValueBox.Enabled = true;
if (string.IsNullOrWhiteSpace(SpecificValueBox.Text))
{
SpecificAddressBox.ResetText();
}
_searches.CompareValue = SpecificValueBox.ToRawInt();
if (Focused)
{
SpecificValueBox.Focus();
}
SpecificAddressBox.Enabled = false;
NumberOfChangesBox.Enabled = false;
DifferenceBox.Enabled = false;
SetCompareTo(RamSearchEngine.Compare.SpecificValue);
}
private void SpecificAddressRadio_Click(object sender, EventArgs e)
{
SpecificValueBox.Enabled = false;
SpecificAddressBox.Enabled = true;
if (string.IsNullOrWhiteSpace(SpecificAddressBox.Text))
{
SpecificAddressBox.ResetText();
}
_searches.CompareValue = SpecificAddressBox.ToRawInt();
if (Focused)
{
SpecificAddressBox.Focus();
}
NumberOfChangesBox.Enabled = false;
DifferenceBox.Enabled = false;
SetCompareTo(RamSearchEngine.Compare.SpecificAddress);
}
private void NumberOfChangesRadio_Click(object sender, EventArgs e)
{
SpecificValueBox.Enabled = false;
SpecificAddressBox.Enabled = false;
NumberOfChangesBox.Enabled = true;
if (string.IsNullOrWhiteSpace(NumberOfChangesBox.Text))
{
NumberOfChangesBox.ResetText();
}
_searches.CompareValue = NumberOfChangesBox.ToRawInt();
if (Focused)
{
NumberOfChangesBox.Focus();
}
DifferenceBox.Enabled = false;
SetCompareTo(RamSearchEngine.Compare.Changes);
}
private void DifferenceRadio_Click(object sender, EventArgs e)
{
SpecificValueBox.Enabled = false;
SpecificAddressBox.Enabled = false;
NumberOfChangesBox.Enabled = false;
DifferenceBox.Enabled = true;
if (string.IsNullOrWhiteSpace(DifferenceBox.Text))
{
DifferenceBox.ResetText();
}
_searches.CompareValue = DifferenceBox.ToRawInt();
if (Focused)
{
DifferenceBox.Focus();
}
SetCompareTo(RamSearchEngine.Compare.Difference);
}
private void CompareToValue_TextChanged(object sender, EventArgs e)
{
SetCompareValue((sender as INumberBox).ToRawInt());
}
#endregion
#region Comparison Operator Box
private void EqualToRadio_Click(object sender, EventArgs e)
{
DifferentByBox.Enabled = false;
SetComparisonOperator(RamSearchEngine.ComparisonOperator.Equal);
}
private void NotEqualToRadio_Click(object sender, EventArgs e)
{
DifferentByBox.Enabled = false;
SetComparisonOperator(RamSearchEngine.ComparisonOperator.NotEqual);
}
private void LessThanRadio_Click(object sender, EventArgs e)
{
DifferentByBox.Enabled = false;
SetComparisonOperator(RamSearchEngine.ComparisonOperator.LessThan);
}
private void GreaterThanRadio_Click(object sender, EventArgs e)
{
DifferentByBox.Enabled = false;
SetComparisonOperator(RamSearchEngine.ComparisonOperator.GreaterThan);
}
private void LessThanOrEqualToRadio_Click(object sender, EventArgs e)
{
DifferentByBox.Enabled = false;
SetComparisonOperator(RamSearchEngine.ComparisonOperator.LessThanEqual);
}
private void GreaterThanOrEqualToRadio_Click(object sender, EventArgs e)
{
DifferentByBox.Enabled = false;
SetComparisonOperator(RamSearchEngine.ComparisonOperator.GreaterThanEqual);
}
private void DifferentByRadio_Click(object sender, EventArgs e)
{
DifferentByBox.Enabled = true;
if (string.IsNullOrWhiteSpace(DifferentByBox.Text))
{
DifferentByBox.ResetText();
}
_searches.DifferentBy = DifferenceBox.ToRawInt();
if (Focused)
{
DifferentByBox.Focus();
}
SetComparisonOperator(RamSearchEngine.ComparisonOperator.DifferentBy);
}
private void DifferentByBox_TextChanged(object sender, EventArgs e)
{
_searches.DifferentBy = !string.IsNullOrWhiteSpace(DifferentByBox.Text) ? DifferentByBox.ToRawInt() : null;
WatchListView.Refresh();
}
#endregion
#region ListView Events
private void WatchListView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete && !e.Control && !e.Alt && !e.Shift)
{
RemoveAddresses();
}
else if (e.KeyCode == Keys.C && e.Control && !e.Alt && !e.Shift) // Copy
{
CopyWatchesToClipBoard();
}
else if (e.KeyCode == Keys.Escape && !e.Control && !e.Alt && !e.Shift)
{
WatchListView.SelectedIndices.Clear();
}
}
private void WatchListView_SelectedIndexChanged(object sender, EventArgs e)
{
if (WatchListView.SelectAllInProgress)
{
return;
}
RemoveToolBarItem.Enabled =
AddToRamWatchToolBarItem.Enabled =
SelectedIndices.Any();
PokeAddressToolBarItem.Enabled =
FreezeAddressToolBarItem.Enabled =
SelectedIndices.Any() &&
_searches.Domain.CanPoke();
}
private void WatchListView_VirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e)
{
WatchListView_SelectedIndexChanged(sender, e);
}
private void WatchListView_Enter(object sender, EventArgs e)
{
WatchListView.Refresh();
}
private void WatchListView_ColumnClick(object sender, ColumnClickEventArgs e)
{
var column = WatchListView.Columns[e.Column];
if (column.Name != _sortedColumn)
{
_sortReverse = false;
}
_searches.Sort(column.Name, _sortReverse);
_sortedColumn = column.Name;
_sortReverse ^= true;
WatchListView.Refresh();
}
private void WatchListView_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (SelectedIndices.Any())
{
AddToRamWatch();
}
}
#endregion
#region Dialog Events
private void NewRamSearch_Activated(object sender, EventArgs e)
{
WatchListView.Refresh();
}
private void NewRamSearch_DragDrop(object sender, DragEventArgs e)
{
var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop);
if (Path.GetExtension(filePaths[0]) == ".wch")
{
var file = new FileInfo(filePaths[0]);
if (file.Exists)
{
LoadWatchFile(file, false);
}
}
}
protected override void OnShown(EventArgs e)
{
RefreshFloatingWindowControl(Settings.FloatingWindow);
base.OnShown(e);
}
// Stupid designer
protected void DragEnterWrapper(object sender, DragEventArgs e)
{
base.GenericDragEnter(sender, e);
}
#endregion
#endregion
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Microsoft.Extensions.Logging;
using NUnit.Framework;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement;
using Umbraco.Cms.Tests.Common.Testing;
using Umbraco.Cms.Tests.Integration.Testing;
namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositories
{
[TestFixture]
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)]
public class ServerRegistrationRepositoryTest : UmbracoIntegrationTest
{
private AppCaches _appCaches;
[SetUp]
public void SetUp()
{
_appCaches = AppCaches.Disabled;
CreateTestData();
}
private ServerRegistrationRepository CreateRepository(IScopeProvider provider) =>
new ServerRegistrationRepository((IScopeAccessor)provider, LoggerFactory.CreateLogger<ServerRegistrationRepository>());
[Test]
public void Cannot_Add_Duplicate_Server_Identities()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (provider.CreateScope())
{
ServerRegistrationRepository repository = CreateRepository(provider);
var server = new ServerRegistration("http://shazwazza.com", "COMPUTER1", DateTime.Now);
Assert.Throws<SqlException>(() => repository.Save(server));
}
}
[Test]
public void Cannot_Update_To_Duplicate_Server_Identities()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (provider.CreateScope())
{
ServerRegistrationRepository repository = CreateRepository(provider);
IServerRegistration server = repository.Get(1);
server.ServerIdentity = "COMPUTER2";
Assert.Throws<SqlException>(() => repository.Save(server));
}
}
[Test]
public void Can_Instantiate_Repository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (provider.CreateScope())
{
ServerRegistrationRepository repository = CreateRepository(provider);
// Assert
Assert.That(repository, Is.Not.Null);
}
}
[Test]
public void Can_Perform_Get_On_Repository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (provider.CreateScope())
{
ServerRegistrationRepository repository = CreateRepository(provider);
// Act
IServerRegistration server = repository.Get(1);
// Assert
Assert.That(server, Is.Not.Null);
Assert.That(server.HasIdentity, Is.True);
Assert.That(server.ServerAddress, Is.EqualTo("http://localhost"));
}
}
[Test]
public void Can_Perform_GetAll_On_Repository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (provider.CreateScope())
{
ServerRegistrationRepository repository = CreateRepository(provider);
// Act
IEnumerable<IServerRegistration> servers = repository.GetMany();
// Assert
Assert.That(servers.Count(), Is.EqualTo(3));
}
}
// queries are not supported due to in-memory caching
//// [Test]
//// public void Can_Perform_GetByQuery_On_Repository()
//// {
//// // Arrange
//// var provider = ScopeProvider;
//// using (var unitOfWork = provider.GetUnitOfWork())
//// using (var repository = CreateRepository(provider))
//// {
//// // Act
//// var query = Query<IServerRegistration>.Builder.Where(x => x.ServerIdentity.ToUpper() == "COMPUTER3");
//// var result = repository.GetByQuery(query);
//// // Assert
//// Assert.AreEqual(1, result.Count());
//// }
//// }
//// [Test]
//// public void Can_Perform_Count_On_Repository()
//// {
//// // Arrange
//// var provider = ScopeProvider;
//// using (var unitOfWork = provider.GetUnitOfWork())
//// using (var repository = CreateRepository(provider))
//// {
//// // Act
//// var query = Query<IServerRegistration>.Builder.Where(x => x.ServerAddress.StartsWith("http://"));
//// int count = repository.Count(query);
//// // Assert
//// Assert.That(count, Is.EqualTo(2));
//// }
//// }
[Test]
public void Can_Perform_Add_On_Repository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (provider.CreateScope())
{
ServerRegistrationRepository repository = CreateRepository(provider);
// Act
var server = new ServerRegistration("http://shazwazza.com", "COMPUTER4", DateTime.Now);
repository.Save(server);
// Assert
Assert.That(server.HasIdentity, Is.True);
Assert.That(server.Id, Is.EqualTo(4)); // With 3 existing entries the Id should be 4
}
}
[Test]
public void Can_Perform_Update_On_Repository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (provider.CreateScope())
{
ServerRegistrationRepository repository = CreateRepository(provider);
// Act
IServerRegistration server = repository.Get(2);
server.ServerAddress = "https://umbraco.com";
server.IsActive = true;
repository.Save(server);
IServerRegistration serverUpdated = repository.Get(2);
// Assert
Assert.That(serverUpdated, Is.Not.Null);
Assert.That(serverUpdated.ServerAddress, Is.EqualTo("https://umbraco.com"));
Assert.That(serverUpdated.IsActive, Is.EqualTo(true));
}
}
[Test]
public void Can_Perform_Delete_On_Repository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (provider.CreateScope())
{
ServerRegistrationRepository repository = CreateRepository(provider);
// Act
IServerRegistration server = repository.Get(3);
Assert.IsNotNull(server);
repository.Delete(server);
bool exists = repository.Exists(3);
// Assert
Assert.That(exists, Is.False);
}
}
[Test]
public void Can_Perform_Exists_On_Repository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (provider.CreateScope())
{
ServerRegistrationRepository repository = CreateRepository(provider);
// Act
bool exists = repository.Exists(3);
bool doesntExist = repository.Exists(10);
// Assert
Assert.That(exists, Is.True);
Assert.That(doesntExist, Is.False);
}
}
public void CreateTestData()
{
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
ServerRegistrationRepository repository = CreateRepository(provider);
repository.Save(new ServerRegistration("http://localhost", "COMPUTER1", DateTime.Now) { IsActive = true });
repository.Save(new ServerRegistration("http://www.mydomain.com", "COMPUTER2", DateTime.Now));
repository.Save(new ServerRegistration("https://www.another.domain.com", "Computer3", DateTime.Now));
scope.Complete();
}
}
}
}
| |
using System;
using System.Collections;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using Rainbow.Framework;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Site.Configuration;
using Rainbow.Framework.Web.UI;
using Rainbow.Framework.Web.UI.WebControls;
using History=Rainbow.Framework.History;
using LinkButton=Rainbow.Framework.Web.UI.WebControls.LinkButton;
namespace Rainbow.Content.Web.Modules
{
/// <summary>
/// Announcmeent Edit
/// </summary>
[History("Jes1111", "2003/03/04", "Cache flushing now handled by inherited page")]
public partial class AnnouncementsEdit : AddEditItemPage
{
#region Declarations
/// <summary>
///
/// </summary>
protected IHtmlEditor DesktopText;
#endregion
/// <summary>
/// The Page_Load event on this Page is used to obtain the ModuleID
/// and ItemID of the announcement to edit.
/// It then uses the Rainbow.AnnouncementsDB() data component
/// to populate the page's edit controls with the annoucement details.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void Page_Load(object sender, EventArgs e)
{
// If the page is being requested the first time, determine if an
// announcement itemID value is specified, and if so populate page
// contents with the announcement details
//Indah Fuldner
HtmlEditorDataType h = new HtmlEditorDataType();
h.Value = moduleSettings["Editor"].ToString();
DesktopText =
h.GetEditor(PlaceHolderHTMLEditor, ModuleID, bool.Parse(moduleSettings["ShowUpload"].ToString()),
portalSettings);
DesktopText.Width = new Unit(moduleSettings["Width"].ToString());
DesktopText.Height = new Unit(moduleSettings["Height"].ToString());
//End Indah Fuldner
// Construct the page
// Added css Styles by Mario Endara <mario@softworks.com.uy> (2004/10/26)
updateButton.CssClass = "CommandButton";
PlaceHolderButtons.Controls.Add(updateButton);
PlaceHolderButtons.Controls.Add(new LiteralControl(" "));
cancelButton.CssClass = "CommandButton";
PlaceHolderButtons.Controls.Add(cancelButton);
PlaceHolderButtons.Controls.Add(new LiteralControl(" "));
deleteButton.CssClass = "CommandButton";
PlaceHolderButtons.Controls.Add(deleteButton);
if (Page.IsPostBack == false)
{
if (ItemID != 0)
{
// Obtain a single row of announcement information
AnnouncementsDB announcementDB = new AnnouncementsDB();
SqlDataReader dr = announcementDB.GetSingleAnnouncement(ItemID, WorkFlowVersion.Staging);
try
{
// Load first row into DataReader
if (dr.Read())
{
TitleField.Text = (string) dr["Title"];
MoreLinkField.Text = (string) dr["MoreLink"];
MobileMoreField.Text = (string) dr["MobileMoreLink"];
DesktopText.Text = (string) dr["Description"];
ExpireField.Text = ((DateTime) dr["ExpireDate"]).ToShortDateString();
CreatedBy.Text = (string) dr["CreatedByUser"];
CreatedDate.Text = ((DateTime) dr["CreatedDate"]).ToShortDateString();
// 15/7/2004 added localization by Mario Endara mario@softworks.com.uy
if (CreatedBy.Text == "unknown")
{
CreatedBy.Text = General.GetString("UNKNOWN", "unknown");
}
}
}
finally
{
// Close the datareader
dr.Close();
}
}
else
{
ExpireField.Text =
DateTime.Now.AddDays(Int32.Parse(moduleSettings["DelayExpire"].ToString())).ToShortDateString();
deleteButton.Visible = false; // Cannot delete an unexsistent item
}
}
}
/// <summary>
/// Set the module guids with free access to this page
/// </summary>
/// <value>The allowed modules.</value>
protected override ArrayList AllowedModules
{
get
{
ArrayList al = new ArrayList();
al.Add("CE55A821-2449-4903-BA1A-EC16DB93F8DB");
return al;
}
}
/// <summary>
/// The UpdateBtn_Click event handler on this Page is used to either
/// create or update an announcement. It uses the Rainbow.AnnouncementsDB()
/// data component to encapsulate all data functionality.
/// </summary>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
protected override void OnUpdate(EventArgs e)
{
base.OnUpdate(e);
// Only Update if the Entered Data is Valid
if (Page.IsValid == true)
{
// Create an instance of the Announcement DB component
AnnouncementsDB announcementDB = new AnnouncementsDB();
if (ItemID == 0)
{
// Add the announcement within the Announcements table
announcementDB.AddAnnouncement(ModuleID, ItemID, PortalSettings.CurrentUser.Identity.Email,
TitleField.Text, DateTime.Parse(ExpireField.Text), DesktopText.Text,
MoreLinkField.Text, MobileMoreField.Text);
}
else
{
// Update the announcement within the Announcements table
announcementDB.UpdateAnnouncement(ModuleID, ItemID, PortalSettings.CurrentUser.Identity.Email,
TitleField.Text, DateTime.Parse(ExpireField.Text),
DesktopText.Text, MoreLinkField.Text, MobileMoreField.Text);
}
// Redirect back to the portal home page
RedirectBackToReferringPage();
}
}
/// <summary>
/// The DeleteBtn_Click event handler on this Page is used to delete an
/// an announcement. It uses the Rainbow.AnnouncementsDB()
/// data component to encapsulate all data functionality.
/// </summary>
protected override void OnDelete(EventArgs e)
{
base.OnDelete(e);
// Only attempt to delete the item if it is an existing item
// (new items will have "ItemID" of 0)
if (ItemID != 0)
{
AnnouncementsDB announcementDB = new AnnouncementsDB();
announcementDB.DeleteAnnouncement(ItemID);
}
// Redirect back to the portal home page
RedirectBackToReferringPage();
}
#region Web Form Designer generated code
/// <summary>
/// Raises OnInitEvent
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
//Controls must be created here
updateButton = new LinkButton();
cancelButton = new LinkButton();
deleteButton = new LinkButton();
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new EventHandler(this.Page_Load);
}
#endregion
}
}
| |
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Topshelf.Runtime.Windows
{
using System;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.ServiceProcess;
using Logging;
using HostConfigurators;
public class WindowsHostEnvironment :
HostEnvironment
{
readonly LogWriter _log = HostLogger.Get(typeof(WindowsHostEnvironment));
private HostConfigurator _hostConfigurator;
public WindowsHostEnvironment(HostConfigurator configurator)
{
_hostConfigurator = configurator;
}
public bool IsServiceInstalled(string serviceName)
{
if (Type.GetType("Mono.Runtime") != null)
{
return false;
}
return IsServiceListed(serviceName);
}
public bool IsServiceStopped(string serviceName)
{
using (var sc = new ServiceController(serviceName))
{
return sc.Status == ServiceControllerStatus.Stopped;
}
}
public void StartService(string serviceName, TimeSpan startTimeOut)
{
using (var sc = new ServiceController(serviceName))
{
if (sc.Status == ServiceControllerStatus.Running)
{
_log.InfoFormat("The {0} service is already running.", serviceName);
return;
}
if (sc.Status == ServiceControllerStatus.StartPending)
{
_log.InfoFormat("The {0} service is already starting.", serviceName);
return;
}
if (sc.Status == ServiceControllerStatus.Stopped || sc.Status == ServiceControllerStatus.Paused)
{
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, startTimeOut);
}
else
{
// Status is StopPending, ContinuePending or PausedPending, print warning
_log.WarnFormat("The {0} service can't be started now as it has the status {1}. Try again later...", serviceName, sc.Status.ToString());
}
}
}
public void StopService(string serviceName, TimeSpan stopTimeOut)
{
using (var sc = new ServiceController(serviceName))
{
if (sc.Status == ServiceControllerStatus.Stopped)
{
_log.InfoFormat("The {0} service is not running.", serviceName);
return;
}
if (sc.Status == ServiceControllerStatus.StopPending)
{
_log.InfoFormat("The {0} service is already stopping.", serviceName);
return;
}
if (sc.Status == ServiceControllerStatus.Running || sc.Status == ServiceControllerStatus.Paused)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, stopTimeOut);
}
else
{
// Status is StartPending, ContinuePending or PausedPending, print warning
_log.WarnFormat("The {0} service can't be stopped now as it has the status {1}. Try again later...", serviceName, sc.Status.ToString());
}
}
}
public string CommandLine
{
get { return CommandLineParser.CommandLine.GetUnparsedCommandLine(); }
}
public bool IsAdministrator
{
get
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
public bool IsRunningAsAService
{
get
{
try
{
Process process = GetParent(Process.GetCurrentProcess());
if (process != null && process.ProcessName == "services")
{
_log.Debug("Started by the Windows services process");
return true;
}
}
catch (InvalidOperationException)
{
// again, mono seems to fail with this, let's just return false okay?
}
return false;
}
}
public bool RunAsAdministrator()
{
if (Environment.OSVersion.Version.Major == 6)
{
string commandLine = CommandLine.Replace("--sudo", "");
var startInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().Location, commandLine)
{
Verb = "runas",
UseShellExecute = true,
CreateNoWindow = true,
};
try
{
HostLogger.Shutdown();
Process process = Process.Start(startInfo);
process.WaitForExit();
return true;
}
catch (Win32Exception ex)
{
_log.Debug("Process Start Exception", ex);
}
}
return false;
}
public Host CreateServiceHost(HostSettings settings, ServiceHandle serviceHandle)
{
return new WindowsServiceHost(this, settings, serviceHandle, this._hostConfigurator);
}
public void SendServiceCommand(string serviceName, int command)
{
using (var sc = new ServiceController(serviceName))
{
if (sc.Status == ServiceControllerStatus.Running)
{
sc.ExecuteCommand(command);
}
else
{
_log.WarnFormat("The {0} service can't be commanded now as it has the status {1}. Try again later...",
serviceName, sc.Status.ToString());
}
}
}
public void InstallService(InstallHostSettings settings, Action<InstallHostSettings> beforeInstall, Action afterInstall, Action beforeRollback, Action afterRollback)
{
using (var installer = new HostServiceInstaller(settings))
{
Action<InstallEventArgs> before = x =>
{
if (beforeInstall != null)
{
beforeInstall(settings);
installer.ServiceProcessInstaller.Username = settings.Credentials.Username;
installer.ServiceProcessInstaller.Account = settings.Credentials.Account;
bool gMSA = false;
// Group Managed Service Account (gMSA) workaround per
// https://connect.microsoft.com/VisualStudio/feedback/details/795196/service-process-installer-should-support-virtual-service-accounts
if (settings.Credentials.Account == ServiceAccount.User &&
settings.Credentials.Username != null &&
((gMSA = settings.Credentials.Username.EndsWith("$", StringComparison.InvariantCulture)) ||
string.Equals(settings.Credentials.Username, "NT SERVICE\\" + settings.ServiceName, StringComparison.InvariantCulture)))
{
_log.InfoFormat(gMSA ? "Installing as gMSA {0}." : "Installing as virtual service account", settings.Credentials.Username);
installer.ServiceProcessInstaller.Password = null;
installer.ServiceProcessInstaller
.GetType()
.GetField("haveLoginInfo", BindingFlags.Instance | BindingFlags.NonPublic)
.SetValue(installer.ServiceProcessInstaller, true);
}
else
{
installer.ServiceProcessInstaller.Password = settings.Credentials.Password;
}
}
};
Action<InstallEventArgs> after = x =>
{
if (afterInstall != null)
afterInstall();
};
Action<InstallEventArgs> before2 = x =>
{
if (beforeRollback != null)
beforeRollback();
};
Action<InstallEventArgs> after2 = x =>
{
if (afterRollback != null)
afterRollback();
};
installer.InstallService(before, after, before2, after2);
}
}
public void UninstallService(HostSettings settings, Action beforeUninstall, Action afterUninstall)
{
using (var installer = new HostServiceInstaller(settings))
{
Action<InstallEventArgs> before = x =>
{
if (beforeUninstall != null)
beforeUninstall();
};
Action<InstallEventArgs> after = x =>
{
if (afterUninstall != null)
afterUninstall();
};
installer.UninstallService(before, after);
}
}
Process GetParent(Process child)
{
if (child == null)
throw new ArgumentNullException("child");
try
{
int parentPid = 0;
IntPtr hnd = Kernel32.CreateToolhelp32Snapshot(Kernel32.TH32CS_SNAPPROCESS, 0);
if (hnd == IntPtr.Zero)
return null;
var processInfo = new Kernel32.PROCESSENTRY32
{
dwSize = (uint)Marshal.SizeOf(typeof(Kernel32.PROCESSENTRY32))
};
if (Kernel32.Process32First(hnd, ref processInfo) == false)
return null;
do
{
if (child.Id == processInfo.th32ProcessID)
parentPid = (int)processInfo.th32ParentProcessID;
}
while (parentPid == 0 && Kernel32.Process32Next(hnd, ref processInfo));
if (parentPid > 0)
return Process.GetProcessById(parentPid);
}
catch (Exception ex)
{
_log.Error("Unable to get parent process (ignored)", ex);
}
return null;
}
bool IsServiceListed(string serviceName)
{
bool result = false;
try
{
result = ServiceController.GetServices()
.Any(service => string.Equals(service.ServiceName, serviceName, StringComparison.OrdinalIgnoreCase));
}
catch (InvalidOperationException)
{
_log.Debug("Cannot access Service List due to permissions. Assuming the service is not installed.");
}
return result;
}
}
}
| |
// Copyright 2015, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: api.anash@gmail.com (Anash P. Oommen)
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.Util.v201502;
using Google.Api.Ads.Dfp.v201502;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Threading;
namespace Google.Api.Ads.Dfp.Tests.v201502 {
/// <summary>
/// UnitTests for <see cref="LineItemService"/> class.
/// </summary>
[TestFixture]
public class LineItemServiceTests : BaseTests {
/// <summary>
/// UnitTests for <see cref="LineItemService"/> class.
/// </summary>
private LineItemService lineItemService;
/// <summary>
/// Advertiser company id for running tests.
/// </summary>
private long advertiserId;
/// <summary>
/// Salesperson user id for running tests.
/// </summary>
private long salespersonId;
/// <summary>
/// Trafficker user id for running tests.
/// </summary>
private long traffickerId;
/// <summary>
/// Ad unit id for running tests.
/// </summary>
private string adUnitId;
/// <summary>
/// Placement id for running tests.
/// </summary>
private long placementId;
/// <summary>
/// Order id for running tests.
/// </summary>
private long orderId;
/// <summary>
/// Line item 1 for running tests.
/// </summary>
private LineItem lineItem1;
/// <summary>
/// Line item 2 for running tests.
/// </summary>
private LineItem lineItem2;
/// <summary>
/// Default public constructor.
/// </summary>
public LineItemServiceTests() : base() {
}
/// <summary>
/// Initialize the test case.
/// </summary>
[SetUp]
public void Init() {
TestUtils utils = new TestUtils();
lineItemService = (LineItemService)user.GetService(DfpService.v201502.LineItemService);
advertiserId = utils.CreateCompany(user, CompanyType.ADVERTISER).id;
salespersonId = utils.GetSalesperson(user).id;
traffickerId = utils.GetTrafficker(user).id;
orderId = utils.CreateOrder(user, advertiserId, salespersonId, traffickerId).id;
adUnitId = utils.CreateAdUnit(user).id;
placementId = utils.CreatePlacement(user, new string[] {adUnitId}).id;
lineItem1 = utils.CreateLineItem(user, orderId, adUnitId);
lineItem2 = utils.CreateLineItem(user, orderId, adUnitId);
}
/// <summary>
/// Test whether we can create a list of line items.
/// </summary>
[Test]
public void TestCreateLineItems() {
// Create inventory targeting.
InventoryTargeting inventoryTargeting = new InventoryTargeting();
inventoryTargeting.targetedPlacementIds = new long[] {placementId};
// Create geographical targeting.
GeoTargeting geoTargeting = new GeoTargeting();
// Include the US and Quebec, Canada.
Location countryLocation = new Location();
countryLocation.id = 2840L;
Location regionLocation = new Location();
regionLocation.id = 20123L;
geoTargeting.targetedLocations = new Location[] {countryLocation, regionLocation};
// Exclude Chicago and the New York metro area.
Location cityLocation = new Location();
cityLocation.id = 1016367L;
Location metroLocation = new Location();
metroLocation.id = 200501L;
geoTargeting.excludedLocations = new Location[] {cityLocation, metroLocation};
// Exclude domains that are not under the network's control.
UserDomainTargeting userDomainTargeting = new UserDomainTargeting();
userDomainTargeting.domains = new String[] {"usa.gov"};
userDomainTargeting.targeted = false;
// Create day-part targeting.
DayPartTargeting dayPartTargeting = new DayPartTargeting();
dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER;
// Target only the weekend in the browser's timezone.
DayPart saturdayDayPart = new DayPart();
saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201502.DayOfWeek.SATURDAY;
saturdayDayPart.startTime = new TimeOfDay();
saturdayDayPart.startTime.hour = 0;
saturdayDayPart.startTime.minute = MinuteOfHour.ZERO;
saturdayDayPart.endTime = new TimeOfDay();
saturdayDayPart.endTime.hour = 24;
saturdayDayPart.endTime.minute = MinuteOfHour.ZERO;
DayPart sundayDayPart = new DayPart();
sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201502.DayOfWeek.SUNDAY;
sundayDayPart.startTime = new TimeOfDay();
sundayDayPart.startTime.hour = 0;
sundayDayPart.startTime.minute = MinuteOfHour.ZERO;
sundayDayPart.endTime = new TimeOfDay();
sundayDayPart.endTime.hour = 24;
sundayDayPart.endTime.minute = MinuteOfHour.ZERO;
dayPartTargeting.dayParts = new DayPart[] {saturdayDayPart, sundayDayPart};
// Create technology targeting.
TechnologyTargeting technologyTargeting = new TechnologyTargeting();
// Create browser targeting.
BrowserTargeting browserTargeting = new BrowserTargeting();
browserTargeting.isTargeted = true;
// Target just the Chrome browser.
Technology browserTechnology = new Technology();
browserTechnology.id = 500072L;
browserTargeting.browsers = new Technology[] {browserTechnology};
technologyTargeting.browserTargeting = browserTargeting;
// Create an array to store local line item objects.
LineItem[] lineItems = new LineItem[2];
for (int i = 0; i < lineItems.Length; i++) {
LineItem lineItem = new LineItem();
lineItem.name = "Line item #" + new TestUtils().GetTimeStamp();
lineItem.orderId = orderId;
lineItem.targeting = new Targeting();
lineItem.targeting.inventoryTargeting = inventoryTargeting;
lineItem.targeting.geoTargeting = geoTargeting;
lineItem.targeting.userDomainTargeting = userDomainTargeting;
lineItem.targeting.dayPartTargeting = dayPartTargeting;
lineItem.targeting.technologyTargeting = technologyTargeting;
lineItem.lineItemType = LineItemType.STANDARD;
lineItem.allowOverbook = true;
// Set the creative rotation type to even.
lineItem.creativeRotationType = CreativeRotationType.EVEN;
// Set the size of creatives that can be associated with this line item.
Size size = new Size();
size.width = 300;
size.height = 250;
size.isAspectRatio = false;
// Create the creative placeholder.
CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
creativePlaceholder.size = size;
lineItem.creativePlaceholders = new CreativePlaceholder[] {creativePlaceholder};
// Set the length of the line item to run.
//lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
lineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1));
// Set the cost per unit to $2.
lineItem.costType = CostType.CPM;
lineItem.costPerUnit = new Money();
lineItem.costPerUnit.currencyCode = "USD";
lineItem.costPerUnit.microAmount = 2000000L;
// Set the number of units bought to 500,000 so that the budget is
// $1,000.
Goal goal = new Goal();
goal.units = 500000L;
goal.unitType = UnitType.IMPRESSIONS;
lineItem.primaryGoal = goal;
lineItems[i] = lineItem;
}
LineItem[] localLineItems = null;
Assert.DoesNotThrow(delegate() {
localLineItems = lineItemService.createLineItems(lineItems);
});
Assert.NotNull(localLineItems);
Assert.AreEqual(localLineItems.Length, 2);
Assert.AreEqual(localLineItems[0].name, lineItems[0].name);
Assert.AreEqual(localLineItems[0].orderId, lineItems[0].orderId);
Assert.AreEqual(localLineItems[1].name, lineItems[1].name);
Assert.AreEqual(localLineItems[1].orderId, lineItems[1].orderId);
}
/// <summary>
/// Test whether we can fetch a list of existing line items that match given
/// statement.
/// </summary>
[Test]
public void TestGetLineItemsByStatement() {
Statement statement = new Statement();
statement.query = string.Format("WHERE id = '{0}' LIMIT 1", lineItem1.id);
LineItemPage page = null;
Assert.DoesNotThrow(delegate() {
page = lineItemService.getLineItemsByStatement(statement);
});
Assert.NotNull(page);
Assert.AreEqual(page.totalResultSetSize, 1);
Assert.NotNull(page.results);
Assert.AreEqual(page.results[0].id, lineItem1.id);
Assert.AreEqual(page.results[0].name, lineItem1.name);
Assert.AreEqual(page.results[0].orderId, lineItem1.orderId);
}
/// <summary>
/// Test whether we can activate a line item.
/// </summary>
[Test]
public void TestPerformLineItemAction() {
Statement statement = new Statement();
statement.query = string.Format("WHERE orderId = '{0}' and status = '{1}'",
orderId, ComputedStatus.INACTIVE);
ActivateLineItems action = new ActivateLineItems();
UpdateResult result = null;
Assert.DoesNotThrow(delegate() {
result = lineItemService.performLineItemAction(action, statement);
});
Assert.NotNull(result);
}
/// <summary>
/// Test whether we can update a list of line items.
/// </summary>
[Test]
public void TestUpdateLineItems() {
lineItem1.costPerUnit.microAmount = 3500000;
lineItem2.costPerUnit.microAmount = 3500000;
LineItem[] localLineItems = null;
Assert.DoesNotThrow(delegate() {
localLineItems = lineItemService.updateLineItems(new LineItem[] {lineItem1, lineItem2});
});
Assert.NotNull(localLineItems);
Assert.AreEqual(localLineItems.Length, 2);
Assert.AreEqual(localLineItems[0].id, lineItem1.id);
Assert.AreEqual(localLineItems[0].name, lineItem1.name);
Assert.AreEqual(localLineItems[0].orderId, lineItem1.orderId);
Assert.AreEqual(localLineItems[0].costPerUnit.microAmount, lineItem1.costPerUnit.microAmount);
Assert.AreEqual(localLineItems[1].id, lineItem2.id);
Assert.AreEqual(localLineItems[1].name, lineItem2.name);
Assert.AreEqual(localLineItems[1].orderId, lineItem2.orderId);
Assert.AreEqual(localLineItems[1].costPerUnit.microAmount, lineItem2.costPerUnit.microAmount);
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Tests.LegacyTests
{
public class ContainsTests
{
// Class which is passed as an argument for EqualityComparer
public class AnagramEqualityComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return getCanonicalString(x) == getCanonicalString(y);
}
public int GetHashCode(string obj)
{
return getCanonicalString(obj).GetHashCode();
}
private string getCanonicalString(string word)
{
char[] wordChars = word.ToCharArray();
Array.Sort<char>(wordChars);
return new string(wordChars);
}
}
public class Helper
{
// Helper function for Test2f
public static IEnumerable<int?> NumList_Non_Null(int? start, int? count)
{
for (int? i = 0; i < count; i++)
yield return start + i;
}
// Helper function for Test 2g
public static IEnumerable<int?> NumList_Null(int count)
{
for (int i = 0; i < count; i++)
yield return null;
}
}
public class Contains003
{
private static int Contains001()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var rst1 = q.Contains(-1);
var rst2 = q.Contains(-1);
return ((rst1 == rst2) ? 0 : 1);
}
private static int Contains002()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x;
var rst1 = q.Contains("X");
var rst2 = q.Contains("X");
return ((rst1 == rst2) ? 0 : 1);
}
public static int Main()
{
int ret = RunTest(Contains001) + RunTest(Contains002);
if (0 != ret)
Console.Write(s_errorMessage);
return ret;
}
private static string s_errorMessage = String.Empty;
private delegate int D();
private static int RunTest(D m)
{
int n = m();
if (0 != n)
s_errorMessage += m.ToString() + " - FAILED!\r\n";
return n;
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains004
{
// DDB:171937
public static int Test004()
{
string[] source = { null };
string value = null;
bool expected = true;
// Check whether source is actually ICollection
ICollection<string> collection = source as ICollection<string>;
if (collection == null) return 1;
var actual = source.Contains(value, StringComparer.Ordinal);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test004();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains1a
{
// source implements ICollection, source is empty
public static int Test1a()
{
int[] source = { };
int value = 6;
bool expected = false;
// Check whether source is actually ICollection
ICollection<int> collection = source as ICollection<int>;
if (collection == null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains1b
{
// value does not occur in source
public static int Test1b()
{
int[] source = { 8, 10, 3, 0, -8 };
int value = 6;
bool expected = false;
// Check whether source is actually ICollection
ICollection<int> collection = source as ICollection<int>;
if (collection == null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains1c
{
// value is 1st element in source
public static int Test1c()
{
int[] source = { 8, 10, 3, 0, -8 };
int value = 8;
bool expected = true;
// Check whether source is actually ICollection
ICollection<int> collection = source as ICollection<int>;
if (collection == null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains1d
{
// value is last element in source
public static int Test1d()
{
int[] source = { 8, 10, 3, 0, -8 };
int value = -8;
bool expected = true;
// Check whether source is actually ICollection
ICollection<int> collection = source as ICollection<int>;
if (collection == null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains1e
{
// value is present more than once in source
public static int Test1e()
{
int[] source = { 8, 0, 10, 3, 0, -8, 0 };
int value = 0;
bool expected = true;
// Check whether source is actually ICollection
ICollection<int> collection = source as ICollection<int>;
if (collection == null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains1f
{
// value is null and source does not has null
public static int Test1f()
{
int?[] source = { 8, 0, 10, 3, 0, -8, 0 };
int? value = null;
bool expected = false;
// Check whether source is actually ICollection
ICollection<int?> collection = source as ICollection<int?>;
if (collection == null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1f();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains1g
{
// value is null and source has null
public static int Test1g()
{
int?[] source = { 8, 0, 10, null, 3, 0, -8, 0 };
int? value = null;
bool expected = true;
// Check whether source is actually ICollection
ICollection<int?> collection = source as ICollection<int?>;
if (collection == null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1g();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains1h
{
// Overload-2: Test when EqualityComparer is null
public static int Test1h()
{
string[] source = { "Bob", "Robert", "Tim" };
string value = "trboeR";
bool expected = false;
// Check whether source is actually ICollection
ICollection<string> collection = source as ICollection<string>;
if (collection == null) return 1;
var actual = source.Contains(value, null);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1h();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains1i
{
// Overload-2: Test when EqualityComparer is not null
public static int Test1i()
{
string[] source = { "Bob", "Robert", "Tim" };
string value = "trboeR";
bool expected = true;
// Check whether source is actually ICollection
ICollection<string> collection = source as ICollection<string>;
if (collection == null) return 1;
var actual = source.Contains(value, new AnagramEqualityComparer());
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1i();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains2a
{
// source does NOT implement ICollection, source is empty
public static int Test2a()
{
IEnumerable<int> source = Functions.NumList(0, 0);
int value = 0;
bool expected = false;
// Check whether source is actually ICollection
ICollection<int> collection = source as ICollection<int>;
if (collection != null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains2b
{
// value does not occur in source
public static int Test2b()
{
IEnumerable<int> source = Functions.NumList(4, 5);
int value = 3;
bool expected = false;
// Check whether source is actually ICollection
ICollection<int> collection = source as ICollection<int>;
if (collection != null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains2c
{
// value is 1st element in source
public static int Test2c()
{
IEnumerable<int> source = Functions.NumList(3, 5);
int value = 3;
bool expected = true;
// Check whether source is actually ICollection
ICollection<int> collection = source as ICollection<int>;
if (collection != null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains2d
{
// value is last element in source
public static int Test2d()
{
IEnumerable<int> source = Functions.NumList(3, 5);
int value = 7;
bool expected = true;
// Check whether source is actually ICollection
ICollection<int> collection = source as ICollection<int>;
if (collection != null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains2e
{
// value is present more than once in source
public static int Test2e()
{
IEnumerable<int> source = Functions.NumList(10, 3);
int value = 10;
bool expected = true;
// Check whether source is actually ICollection
ICollection<int> collection = source as ICollection<int>;
if (collection != null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains2f
{
// value is null and source does not has null
public static int Test2f()
{
IEnumerable<int?> source = Helper.NumList_Non_Null(3, 4);
int? value = null;
bool expected = false;
// Check whether source is actually ICollection
ICollection<int?> collection = source as ICollection<int?>;
if (collection != null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2f();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Contains2g
{
// value is null and source has null
public static int Test2g()
{
IEnumerable<int?> source = Helper.NumList_Null(5);
int? value = null;
bool expected = true;
// Check whether source is actually ICollection
ICollection<int?> collection = source as ICollection<int?>;
if (collection != null) return 1;
var actual = source.Contains(value);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2g();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Microsoft.Cci.Extensions.CSharp;
using Microsoft.Cci.Filters;
using Microsoft.Cci.Writers.Syntax;
namespace Microsoft.Cci.Writers.CSharp
{
public partial class CSDeclarationWriter : ICciDeclarationWriter
{
private readonly ISyntaxWriter _writer;
private readonly ICciFilter _filter;
private bool _forCompilation;
private bool _forCompilationIncludeGlobalprefix;
private bool _forCompilationThrowPlatformNotSupported;
private bool _includeFakeAttributes;
public CSDeclarationWriter(ISyntaxWriter writer)
: this(writer, new PublicOnlyCciFilter())
{
}
public CSDeclarationWriter(ISyntaxWriter writer, ICciFilter filter)
: this(writer, filter, true)
{
}
public CSDeclarationWriter(ISyntaxWriter writer, ICciFilter filter, bool forCompilation)
{
Contract.Requires(writer != null);
_writer = writer;
_filter = filter;
_forCompilation = forCompilation;
_forCompilationIncludeGlobalprefix = false;
_forCompilationThrowPlatformNotSupported = false;
_includeFakeAttributes = false;
}
public CSDeclarationWriter(ISyntaxWriter writer, ICciFilter filter, bool forCompilation, bool includePseudoCustomAttributes = false)
: this(writer, filter, forCompilation)
{
_includeFakeAttributes = includePseudoCustomAttributes;
}
public bool ForCompilation
{
get { return _forCompilation; }
set { _forCompilation = value; }
}
public bool ForCompilationIncludeGlobalPrefix
{
get { return _forCompilationIncludeGlobalprefix; }
set { _forCompilationIncludeGlobalprefix = value; }
}
public bool ForCompilationThrowPlatformNotSupported
{
get { return _forCompilationThrowPlatformNotSupported; }
set { _forCompilationThrowPlatformNotSupported = value; }
}
public ISyntaxWriter SyntaxtWriter { get { return _writer; } }
public ICciFilter Filter { get { return _filter; } }
public void WriteDeclaration(IDefinition definition)
{
if (definition == null)
return;
IAssembly assembly = definition as IAssembly;
if (assembly != null)
{
WriteAssemblyDeclaration(assembly);
return;
}
INamespaceDefinition ns = definition as INamespaceDefinition;
if (ns != null)
{
WriteNamespaceDeclaration(ns);
return;
}
ITypeDefinition type = definition as ITypeDefinition;
if (type != null)
{
WriteTypeDeclaration(type);
return;
}
ITypeDefinitionMember member = definition as ITypeDefinitionMember;
if (member != null)
{
WriteMemberDeclaration(member);
return;
}
DummyInternalConstructor ctor = definition as DummyInternalConstructor;
if (ctor != null)
{
WritePrivateConstructor(ctor.ContainingType);
return;
}
INamedEntity named = definition as INamedEntity;
if (named != null)
{
WriteIdentifier(named.Name);
return;
}
_writer.Write("Unknown definition type {0}", definition.ToString());
}
public void WriteAttribute(ICustomAttribute attribute)
{
WriteSymbol("[");
WriteAttribute(attribute, null);
WriteSymbol("]");
}
public void WriteAssemblyDeclaration(IAssembly assembly)
{
WriteAttributes(assembly.Attributes, prefix: "assembly");
WriteAttributes(assembly.SecurityAttributes, prefix: "assembly");
}
public void WriteMemberDeclaration(ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
{
WriteMethodDefinition(method);
return;
}
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
{
WritePropertyDefinition(property);
return;
}
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
{
WriteEventDefinition(evnt);
return;
}
IFieldDefinition field = member as IFieldDefinition;
if (field != null)
{
WriteFieldDefinition(field);
return;
}
_writer.Write("Unknown member definitions type {0}", member.ToString());
}
private void WriteVisibility(TypeMemberVisibility visibility)
{
switch (visibility)
{
case TypeMemberVisibility.Public:
WriteKeyword("public"); break;
case TypeMemberVisibility.Private:
WriteKeyword("private"); break;
case TypeMemberVisibility.Assembly:
WriteKeyword("internal"); break;
case TypeMemberVisibility.Family:
WriteKeyword("protected"); break;
case TypeMemberVisibility.FamilyOrAssembly:
WriteKeyword("protected"); WriteKeyword("internal"); break;
case TypeMemberVisibility.FamilyAndAssembly:
WriteKeyword("internal"); WriteKeyword("protected"); break; // Is this right?
default:
WriteKeyword("<Unknown-Visibility>"); break;
}
}
// Writer Helpers these are the only methods that should directly acess _writer
private void WriteKeyword(string keyword, bool noSpace = false)
{
_writer.WriteKeyword(keyword);
if (!noSpace) WriteSpace();
}
private void WriteSymbol(string symbol, bool addSpace = false)
{
_writer.WriteSymbol(symbol);
if (addSpace)
WriteSpace();
}
private void Write(string literal)
{
_writer.Write(literal);
}
private void WriteTypeName(ITypeReference type, bool noSpace = false, bool isDynamic = false, bool useTypeKeywords = true)
{
if (isDynamic)
{
WriteKeyword("dynamic", noSpace: noSpace);
return;
}
NameFormattingOptions namingOptions = NameFormattingOptions.TypeParameters;
if (useTypeKeywords)
namingOptions |= NameFormattingOptions.UseTypeKeywords;
if (_forCompilationIncludeGlobalprefix)
namingOptions |= NameFormattingOptions.UseGlobalPrefix;
if (!_forCompilation)
namingOptions |= NameFormattingOptions.OmitContainingNamespace;
string name = TypeHelper.GetTypeName(type, namingOptions);
if (CSharpCciExtensions.IsKeyword(name))
_writer.WriteKeyword(name);
else
_writer.WriteTypeName(name);
if (!noSpace) WriteSpace();
}
public void WriteIdentifier(string id)
{
WriteIdentifier(id, true);
}
public void WriteIdentifier(string id, bool escape)
{
// Escape keywords
if (escape && CSharpCciExtensions.IsKeyword(id))
id = "@" + id;
_writer.WriteIdentifier(id);
}
private void WriteIdentifier(IName name)
{
WriteIdentifier(name.Value);
}
private void WriteSpace()
{
_writer.Write(" ");
}
private void WriteList<T>(IEnumerable<T> list, Action<T> writeItem)
{
_writer.WriteList(list, writeItem);
}
}
}
| |
using eidss.model.Enums;
namespace eidss.model.Reports
{
public interface IReportFactory
{
void ResetLanguage();
#region Common Human Reports
void HumAggregateCase(AggregateReportParameters aggrParams);
void HumAggregateCaseSummary(AggregateSummaryReportParameters aggrParams);
void HumCaseInvestigation(long caseId, long epiId, long csId, long diagnosisId);
void HumUrgentyNotification(long caseId);
[MenuReportDescription(ReportSubMenu.Human, "ReportsHumDiagnosisToChangedDiagnosis", 400)]
[MenuReportCustomization(PresentInDtraCustomization = true, ForbiddenCountry = new[] {Country.Azerbaijan})]
void HumDiagnosisToChangedDiagnosis();
[MenuReportDescription(ReportSubMenu.Human, "ReportsHumMonthlyMorbidityAndMortality", 390)]
[MenuReportCustomization(PresentInDtraCustomization = true, ForbiddenCountry = new[] {Country.Azerbaijan})]
void HumMonthlyMorbidityAndMortality();
[MenuReportDescription(ReportSubMenu.Human, "ReportsHumSummaryOfInfectiousDiseases", 240)]
[MenuReportCustomization(ForbiddenCountry = new[] {Country.Georgia, Country.Azerbaijan})]
void HumSummaryOfInfectiousDiseases();
#endregion
#region Human GG reports
[MenuReportDescription(ReportSubMenu.Human, "ReportsJournal60BReportCard", 320)]
[MenuReportCustomization(Country.Georgia)]
void Hum60BJournal();
[MenuReportDescription(ReportSubMenu.Human, "ReportsHumInfectiousDiseaseMonth", 370)]
[MenuReportCustomization(Country.Georgia)]
void HumMonthInfectiousDisease();
[MenuReportDescription(ReportSubMenu.Human, "ReportsHumInfectiousDiseaseMonthNew", 330)]
[MenuReportCustomization(Country.Georgia)]
void HumMonthInfectiousDiseaseNew();
[MenuReportDescription(ReportSubMenu.Human, "HumInfectiousDiseaseIntermediateMonth", 380)]
[MenuReportCustomization(Country.Georgia)]
void HumIntermediateMonthInfectiousDisease();
[MenuReportDescription(ReportSubMenu.Human, "HumInfectiousDiseaseIntermediateMonthNew", 340)]
[MenuReportCustomization(Country.Georgia)]
void HumIntermediateMonthInfectiousDiseaseNew();
[MenuReportDescription(ReportSubMenu.Human, "ReportsHumInfectiousDiseaseYear", 350)]
[MenuReportCustomization(Country.Georgia)]
void HumAnnualInfectiousDisease();
[MenuReportDescription(ReportSubMenu.Human, "HumInfectiousDiseaseIntermediateYear", 360)]
[MenuReportCustomization(Country.Georgia)]
void HumIntermediateAnnualInfectiousDisease();
[MenuReportDescription(ReportSubMenu.Lab, "ReportsHumSerologyResearchCard", 410)]
[MenuReportCustomization(Country.Georgia)]
[ForbiddenDataGroup(PersonalDataGroup.Human_PersonName, PersonalDataGroup.Human_PersonAge)]
void HumSerologyResearchCard();
[MenuReportDescription(ReportSubMenu.Lab, "ReportsHumMicrobiologyResearchCard", 420)]
[MenuReportCustomization(Country.Georgia)]
[ForbiddenDataGroup(PersonalDataGroup.Human_PersonName, PersonalDataGroup.Human_PersonAge)]
void HumMicrobiologyResearchCard();
[MenuReportDescription(ReportSubMenu.Lab, "HumAntibioticResistanceCard", 430)]
[MenuReportCustomization(Country.Georgia)]
void HumAntibioticResistanceCard();
#endregion
#region Human AZ reports
[MenuReportDescription(ReportSubMenu.Human, "HumFormN1A3", 260)]
[MenuReportCustomization(Country.Azerbaijan)]
void HumFormN1A3();
[MenuReportDescription(ReportSubMenu.Human, "HumFormN1A4", 270)]
[MenuReportCustomization(Country.Azerbaijan)]
void HumFormN1A4();
//[MenuReportDescription(ReportSubMenu.Human, "HumDataQualityIndicators", 280, Permission = EIDSSPermissionObject.Report)]
[MenuReportCustomization(Country.Azerbaijan)]
// [MenuReportCustomization(PresentInDtraCustomization = true)]
[MenuReportDescription(ReportSubMenu.Human, "HumDataQualityIndicators", 280, Permission = EIDSSPermissionObject.CanSignReport)]
void HumDataQualityIndicators();
[MenuReportDescription(ReportSubMenu.Human, "HumDataQualityIndicatorsRayons", 285)]
[MenuReportCustomization(Country.Azerbaijan)]
void HumDataQualityIndicatorsRayons();
[MenuReportDescription(ReportSubMenu.Human, "HumComparativeReport", 290)]
[MenuReportCustomization(Country.Azerbaijan)]
void HumComparativeAZReport();
[MenuReportDescription(ReportSubMenu.Human, "HumSummaryByRayonDiagnosisAgeGroups", 300)]
[MenuReportCustomization(Country.Azerbaijan)]
void HumSummaryByRayonDiagnosisAgeGroups();
[MenuReportDescription(ReportSubMenu.Human, "HumExternalComparativeReport", 310)]
[MenuReportCustomization(Country.Azerbaijan)]
void HumExternalComparativeReport();
[MenuReportDescription(ReportSubMenu.Human, "HumMainIndicatorsOfAFPSurveillance", 320)]
[MenuReportCustomization(Country.Azerbaijan)]
void HumMainIndicatorsOfAFPSurveillance();
[MenuReportDescription(ReportSubMenu.Human, "HumAdditionalIndicatorsOfAFPSurveillance", 330)]
[MenuReportCustomization(Country.Azerbaijan)]
void HumAdditionalIndicatorsOfAFPSurveillance();
[MenuReportDescription(ReportSubMenu.Human, "HumWhoMeaslesRubellaReport", 340)]
[MenuReportCustomization(Country.Azerbaijan)]
void HumWhoMeaslesRubellaReport();
// todo: [ivan] uncomment after testing patch
[MenuReportDescription(ReportSubMenu.Human, "HumComparativeReportOfTwoYears", 350)]
[MenuReportCustomization(Country.Azerbaijan)]
void HumComparativeReportOfTwoYears();
#endregion
#region Veterinary AZ reports
[MenuReportDescription(ReportSubMenu.Vet, "VeterinaryCasesReport", 440)]
[MenuReportCustomization(Country.Azerbaijan)]
void VeterinaryCasesReportAZ();
[MenuReportDescription(ReportSubMenu.Vet, "VeterinaryLaboratoriesAZ", 450)]
[MenuReportCustomization(Country.Azerbaijan)]
void VeterinaryLaboratoriesAZ();
#endregion
#region ARM reports
[MenuReportDescription(ReportSubMenu.Human, "HumFormN85Annual", 500)]
[MenuReportCustomization(Country.Armenia)]
void HumFormN85Annual();
[MenuReportDescription(ReportSubMenu.Human, "HumFormN85Monthly", 510)]
[MenuReportCustomization(Country.Armenia)]
void HumFormN85Monthly();
#endregion
#region IQ reports
[MenuReportDescription(ReportSubMenu.Human, "WeeklySituationDiseasesByDistricts", 610)]
[MenuReportCustomization(Country.Iraq)]
void WeeklySituationDiseasesByDistricts();
[MenuReportDescription(ReportSubMenu.Human, "WeeklySituationDiseasesByAgeGroupAndSex", 620)]
[MenuReportCustomization(Country.Iraq)]
void WeeklySituationDiseasesByAgeGroupAndSex();
[MenuReportDescription(ReportSubMenu.Human, "HumComparativeIQReport", 630)]
[MenuReportCustomization(Country.Iraq)]
void HumComparativeIQReport();
#endregion
#region Veterinary reports
void VetAggregateCase(AggregateReportParameters aggrParams);
void VetAggregateCaseSummary(AggregateSummaryReportParameters aggrParams);
void VetAggregateCaseActions(AggregateActionsParameters aggrParams);
void VetAggregateCaseActionsSummary(AggregateActionsSummaryParameters aggrParams);
void VetAvianInvestigation(long caseId, long diagnosisId);
void VetLivestockInvestigation(long caseId, long diagnosisId);
void VetActiveSurveillanceSampleCollected(long id);
[MenuReportDescription(ReportSubMenu.Vet, "ReportsVetSamplesCount", 1310)]
[MenuReportCustomization(ForbiddenCountry = new[] {Country.Georgia, Country.Azerbaijan})]
void VetSamplesCount();
[MenuReportDescription(ReportSubMenu.Vet, "ReportsVetSamplesReportBySampleType", 1320)]
[MenuReportCustomization(ForbiddenCountry = new[] {Country.Georgia, Country.Azerbaijan})]
void VetSamplesBySampleType();
[MenuReportDescription(ReportSubMenu.Vet, "ReportsVetSamplesReportBySampleTypesWithinRegions", 1330)]
[MenuReportCustomization(ForbiddenCountry = new[] {Country.Georgia, Country.Azerbaijan})]
void VetSamplesBySampleTypesWithinRegions();
[MenuReportDescription(ReportSubMenu.Vet, "ReportsVetYearlySituation", 1340)]
[MenuReportCustomization(PresentInDtraCustomization = true, ForbiddenCountry = new[] { Country.Azerbaijan })]
void VetYearlySituation();
[MenuReportDescription(ReportSubMenu.Vet, "ReportsActiveSurveillance", 1350)]
[MenuReportCustomization(PresentInDtraCustomization = true, ForbiddenCountry = new[] { Country.Azerbaijan })]
void VetActiveSurveillance();
#endregion
#region Veterinary KZ reports
[MenuReportDescription(ReportSubMenu.Vet, "VetCountryPlannedDiagnosticTestsReport", 450)]
[MenuReportCustomization(Country.Kazakhstan)]
void VetCountryPlannedDiagnosticTests();
[MenuReportDescription(ReportSubMenu.Vet, "VetRegionPlannedDiagnosticTestsReport", 460)]
[MenuReportCustomization(Country.Kazakhstan)]
void VetOblastPlannedDiagnosticTests();
[MenuReportDescription(ReportSubMenu.Vet, "VetCountryPreventiveMeasuresReport", 470)]
[MenuReportCustomization(Country.Kazakhstan)]
void VetCountryPreventiveMeasures();
[MenuReportDescription(ReportSubMenu.Vet, "VetRegionPreventiveMeasuresReport", 480)]
[MenuReportCustomization(Country.Kazakhstan)]
void VetOblastPreventiveMeasures();
[MenuReportDescription(ReportSubMenu.Vet, "VetCountryProphilacticMeasuresReport", 490)]
[MenuReportCustomization(Country.Kazakhstan)]
void VetCountrySanitaryMeasures();
[MenuReportDescription(ReportSubMenu.Vet, "VetRegionProphilacticMeasuresReport", 500)]
[MenuReportCustomization(Country.Kazakhstan)]
void VetOblastSanitaryMeasures();
#endregion
#region Lab module reports
void LimSampleTransfer(long id);
void LimTestResult(long id, long csId, long typeId);
void LimTest(long id, bool isHuman);
void LimBatchTest(long id, long typeId);
void LimContainerDetails(long id);
void LimContainerContent(long? contId, long? freeserId);
void LimAccessionIn(long caseId);
#endregion
void Outbreak(long id);
void VectorSurveillanceSessionSummary(long id);
[MenuReportCustomization(PresentInDtraCustomization = true)]
[MenuReportDescription(ReportSubMenu.Admin, "ReportsAdmEventLog", 100)]
void AdmEventLog();
}
}
| |
#define SQLITE_ASCII
#define SQLITE_DISABLE_LFS
#define SQLITE_ENABLE_OVERSIZE_CELL_CHECK
#define SQLITE_MUTEX_OMIT
#define SQLITE_OMIT_AUTHORIZATION
#define SQLITE_OMIT_DEPRECATED
#define SQLITE_OMIT_GET_TABLE
#define SQLITE_OMIT_INCRBLOB
#define SQLITE_OMIT_LOOKASIDE
#define SQLITE_OMIT_SHARED_CACHE
#define SQLITE_OMIT_UTF16
#define SQLITE_OMIT_WAL
#define SQLITE_OS_WIN
#define SQLITE_SYSTEM_MALLOC
#define VDBE_PROFILE_OFF
#define WINDOWS_MOBILE
#define NDEBUG
#define _MSC_VER
#define YYFALLBACK
//#define SQLITE_HAS_CODEC
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
using u32 = System.UInt32;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2003 April 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the ATTACH and DETACH commands.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
#if !SQLITE_OMIT_ATTACH
/*
** Resolve an expression that was part of an ATTACH or DETACH statement. This
** is slightly different from resolving a normal SQL expression, because simple
** identifiers are treated as strings, not possible column names or aliases.
**
** i.e. if the parser sees:
**
** ATTACH DATABASE abc AS def
**
** it treats the two expressions as literal strings 'abc' and 'def' instead of
** looking for columns of the same name.
**
** This only applies to the root node of pExpr, so the statement:
**
** ATTACH DATABASE abc||def AS 'db2'
**
** will fail because neither abc or def can be resolved.
*/
static int resolveAttachExpr( NameContext pName, Expr pExpr )
{
int rc = SQLITE_OK;
if ( pExpr != null )
{
if ( pExpr.op != TK_ID )
{
rc = sqlite3ResolveExprNames( pName, ref pExpr );
if ( rc == SQLITE_OK && sqlite3ExprIsConstant( pExpr ) == 0 )
{
sqlite3ErrorMsg( pName.pParse, "invalid name: \"%s\"", pExpr.u.zToken );
return SQLITE_ERROR;
}
}
else
{
pExpr.op = TK_STRING;
}
}
return rc;
}
/*
** An SQL user-function registered to do the work of an ATTACH statement. The
** three arguments to the function come directly from an attach statement:
**
** ATTACH DATABASE x AS y KEY z
**
** SELECT sqlite_attach(x, y, z)
**
** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
** third argument.
*/
static void attachFunc(
sqlite3_context context,
int NotUsed,
sqlite3_value[] argv
)
{
int i;
int rc = 0;
sqlite3 db = sqlite3_context_db_handle( context );
string zName;
string zFile;
string zPath = "";
string zErr = "";
int flags;
Db aNew = null;
string zErrDyn = "";
sqlite3_vfs pVfs = null;
UNUSED_PARAMETER( NotUsed );
zFile = argv[0].z != null && ( argv[0].z.Length > 0 ) && argv[0].flags != MEM_Null ? sqlite3_value_text( argv[0] ) : "";
zName = argv[1].z != null && ( argv[1].z.Length > 0 ) && argv[1].flags != MEM_Null ? sqlite3_value_text( argv[1] ) : "";
//if( zFile==null ) zFile = "";
//if ( zName == null ) zName = "";
/* Check for the following errors:
**
** * Too many attached databases,
** * Transaction currently open
** * Specified database name already being used.
*/
if ( db.nDb >= db.aLimit[SQLITE_LIMIT_ATTACHED] + 2 )
{
zErrDyn = sqlite3MPrintf( db, "too many attached databases - max %d",
db.aLimit[SQLITE_LIMIT_ATTACHED]
);
goto attach_error;
}
if ( 0 == db.autoCommit )
{
zErrDyn = sqlite3MPrintf( db, "cannot ATTACH database within transaction" );
goto attach_error;
}
for ( i = 0; i < db.nDb; i++ )
{
string z = db.aDb[i].zName;
Debug.Assert( z != null && zName != null );
if ( z.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) )
{
zErrDyn = sqlite3MPrintf( db, "database %s is already in use", zName );
goto attach_error;
}
}
/* Allocate the new entry in the db.aDb[] array and initialise the schema
** hash tables.
*/
/* Allocate the new entry in the db.aDb[] array and initialise the schema
** hash tables.
*/
//if( db.aDb==db.aDbStatic ){
// aNew = sqlite3DbMallocRaw(db, sizeof(db.aDb[0])*3 );
// if( aNew==0 ) return;
// memcpy(aNew, db.aDb, sizeof(db.aDb[0])*2);
//}else {
if ( db.aDb.Length <= db.nDb )
Array.Resize( ref db.aDb, db.nDb + 1 );//aNew = sqlite3DbRealloc(db, db.aDb, sizeof(db.aDb[0])*(db.nDb+1) );
if ( db.aDb == null )
return; // if( aNew==0 ) return;
//}
db.aDb[db.nDb] = new Db();//db.aDb = aNew;
aNew = db.aDb[db.nDb];//memset(aNew, 0, sizeof(*aNew));
// memset(aNew, 0, sizeof(*aNew));
/* Open the database file. If the btree is successfully opened, use
** it to obtain the database schema. At this point the schema may
** or may not be initialised.
*/
flags = (int)db.openFlags;
rc = sqlite3ParseUri( db.pVfs.zName, zFile, ref flags, ref pVfs, ref zPath, ref zErr );
if ( rc != SQLITE_OK )
{
//if ( rc == SQLITE_NOMEM )
//db.mallocFailed = 1;
sqlite3_result_error( context, zErr, -1 );
//sqlite3_free( zErr );
return;
}
Debug.Assert( pVfs != null);
flags |= SQLITE_OPEN_MAIN_DB;
rc = sqlite3BtreeOpen( pVfs, zPath, db, ref aNew.pBt, 0, (int)flags );
//sqlite3_free( zPath );
db.nDb++;
if ( rc == SQLITE_CONSTRAINT )
{
rc = SQLITE_ERROR;
zErrDyn = sqlite3MPrintf( db, "database is already attached" );
}
else if ( rc == SQLITE_OK )
{
Pager pPager;
aNew.pSchema = sqlite3SchemaGet( db, aNew.pBt );
//if ( aNew.pSchema == null )
//{
// rc = SQLITE_NOMEM;
//}
//else
if ( aNew.pSchema.file_format != 0 && aNew.pSchema.enc != ENC( db ) )
{
zErrDyn = sqlite3MPrintf( db,
"attached databases must use the same text encoding as main database" );
rc = SQLITE_ERROR;
}
pPager = sqlite3BtreePager( aNew.pBt );
sqlite3PagerLockingMode( pPager, db.dfltLockMode );
sqlite3BtreeSecureDelete( aNew.pBt,
sqlite3BtreeSecureDelete( db.aDb[0].pBt, -1 ) );
}
aNew.safety_level = 3;
aNew.zName = zName;//sqlite3DbStrDup(db, zName);
//if( rc==SQLITE_OK && aNew.zName==0 ){
// rc = SQLITE_NOMEM;
//}
#if SQLITE_HAS_CODEC
if ( rc == SQLITE_OK )
{
//extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
//extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
int nKey;
string zKey;
int t = sqlite3_value_type( argv[2] );
switch ( t )
{
case SQLITE_INTEGER:
case SQLITE_FLOAT:
zErrDyn = "Invalid key value"; //sqlite3DbStrDup( db, "Invalid key value" );
rc = SQLITE_ERROR;
break;
case SQLITE_TEXT:
case SQLITE_BLOB:
nKey = sqlite3_value_bytes( argv[2] );
zKey = sqlite3_value_blob( argv[2] ).ToString(); // (char *)sqlite3_value_blob(argv[2]);
rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey );
break;
case SQLITE_NULL:
/* No key specified. Use the key from the main database */
sqlite3CodecGetKey( db, 0, out zKey, out nKey ); //sqlite3CodecGetKey(db, 0, (void**)&zKey, nKey);
if ( nKey > 0 || sqlite3BtreeGetReserve( db.aDb[0].pBt ) > 0 )
{
rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey );
}
break;
}
}
#endif
/* If the file was opened successfully, read the schema for the new database.
** If this fails, or if opening the file failed, then close the file and
** remove the entry from the db.aDb[] array. i.e. put everything back the way
** we found it.
*/
if ( rc == SQLITE_OK )
{
sqlite3BtreeEnterAll( db );
rc = sqlite3Init( db, ref zErrDyn );
sqlite3BtreeLeaveAll( db );
}
if ( rc != 0 )
{
int iDb = db.nDb - 1;
Debug.Assert( iDb >= 2 );
if ( db.aDb[iDb].pBt != null )
{
sqlite3BtreeClose( ref db.aDb[iDb].pBt );
db.aDb[iDb].pBt = null;
db.aDb[iDb].pSchema = null;
}
sqlite3ResetInternalSchema( db, -1 );
db.nDb = iDb;
if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM )
{
//// db.mallocFailed = 1;
sqlite3DbFree( db, ref zErrDyn );
zErrDyn = sqlite3MPrintf( db, "out of memory" );
}
else if ( zErrDyn == "" )
{
zErrDyn = sqlite3MPrintf( db, "unable to open database: %s", zFile );
}
goto attach_error;
}
return;
attach_error:
/* Return an error if we get here */
if ( zErrDyn != "" )
{
sqlite3_result_error( context, zErrDyn, -1 );
sqlite3DbFree( db, ref zErrDyn );
}
if ( rc != 0 )
sqlite3_result_error_code( context, rc );
}
/*
** An SQL user-function registered to do the work of an DETACH statement. The
** three arguments to the function come directly from a detach statement:
**
** DETACH DATABASE x
**
** SELECT sqlite_detach(x)
*/
static void detachFunc(
sqlite3_context context,
int NotUsed,
sqlite3_value[] argv
)
{
string zName = argv[0].z != null && ( argv[0].z.Length > 0 ) ? sqlite3_value_text( argv[0] ) : "";//(sqlite3_value_text(argv[0]);
sqlite3 db = sqlite3_context_db_handle( context );
int i;
Db pDb = null;
StringBuilder zErr = new StringBuilder( 200 );
UNUSED_PARAMETER( NotUsed );
if ( zName == null )
zName = "";
for ( i = 0; i < db.nDb; i++ )
{
pDb = db.aDb[i];
if ( pDb.pBt == null )
continue;
if ( pDb.zName.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) )
break;
}
if ( i >= db.nDb )
{
sqlite3_snprintf( 200, zErr, "no such database: %s", zName );
goto detach_error;
}
if ( i < 2 )
{
sqlite3_snprintf( 200, zErr, "cannot detach database %s", zName );
goto detach_error;
}
if ( 0 == db.autoCommit )
{
sqlite3_snprintf( 200, zErr,
"cannot DETACH database within transaction" );
goto detach_error;
}
if ( sqlite3BtreeIsInReadTrans( pDb.pBt ) || sqlite3BtreeIsInBackup( pDb.pBt ) )
{
sqlite3_snprintf( 200, zErr, "database %s is locked", zName );
goto detach_error;
}
sqlite3BtreeClose( ref pDb.pBt );
pDb.pBt = null;
pDb.pSchema = null;
sqlite3ResetInternalSchema( db, -1 );
return;
detach_error:
sqlite3_result_error( context, zErr.ToString(), -1 );
}
/*
** This procedure generates VDBE code for a single invocation of either the
** sqlite_detach() or sqlite_attach() SQL user functions.
*/
static void codeAttach(
Parse pParse, /* The parser context */
int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
FuncDef pFunc, /* FuncDef wrapper for detachFunc() or attachFunc() */
Expr pAuthArg, /* Expression to pass to authorization callback */
Expr pFilename, /* Name of database file */
Expr pDbname, /* Name of the database to use internally */
Expr pKey /* Database key for encryption extension */
)
{
NameContext sName;
Vdbe v;
sqlite3 db = pParse.db;
int regArgs;
sName = new NameContext();// memset( &sName, 0, sizeof(NameContext));
sName.pParse = pParse;
if (
SQLITE_OK != resolveAttachExpr( sName, pFilename ) ||
SQLITE_OK != resolveAttachExpr( sName, pDbname ) ||
SQLITE_OK != resolveAttachExpr( sName, pKey )
)
{
pParse.nErr++;
goto attach_end;
}
#if !SQLITE_OMIT_AUTHORIZATION
if( pAuthArg ){
char *zAuthArg;
if( pAuthArg->op==TK_STRING ){
zAuthArg = pAuthArg->u.zToken;
}else{
zAuthArg = 0;
}
int rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
if(rc!=SQLITE_OK ){
goto attach_end;
}
}
#endif //* SQLITE_OMIT_AUTHORIZATION */
v = sqlite3GetVdbe( pParse );
regArgs = sqlite3GetTempRange( pParse, 4 );
sqlite3ExprCode( pParse, pFilename, regArgs );
sqlite3ExprCode( pParse, pDbname, regArgs + 1 );
sqlite3ExprCode( pParse, pKey, regArgs + 2 );
Debug.Assert( v != null /*|| db.mallocFailed != 0 */ );
if ( v != null )
{
sqlite3VdbeAddOp3( v, OP_Function, 0, regArgs + 3 - pFunc.nArg, regArgs + 3 );
Debug.Assert( pFunc.nArg == -1 || ( pFunc.nArg & 0xff ) == pFunc.nArg );
sqlite3VdbeChangeP5( v, (u8)( pFunc.nArg ) );
sqlite3VdbeChangeP4( v, -1, pFunc, P4_FUNCDEF );
/* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
** statement only). For DETACH, set it to false (expire all existing
** statements).
*/
sqlite3VdbeAddOp1( v, OP_Expire, ( type == SQLITE_ATTACH ) ? 1 : 0 );
}
attach_end:
sqlite3ExprDelete( db, ref pFilename );
sqlite3ExprDelete( db, ref pDbname );
sqlite3ExprDelete( db, ref pKey );
}
/*
** Called by the parser to compile a DETACH statement.
**
** DETACH pDbname
*/
static FuncDef detach_func = new FuncDef(
1, /* nArg */
SQLITE_UTF8, /* iPrefEnc */
0, /* flags */
null, /* pUserData */
null, /* pNext */
detachFunc, /* xFunc */
null, /* xStep */
null, /* xFinalize */
"sqlite_detach", /* zName */
null, /* pHash */
null /* pDestructor */
);
static void sqlite3Detach( Parse pParse, Expr pDbname )
{
codeAttach( pParse, SQLITE_DETACH, detach_func, pDbname, null, null, pDbname );
}
/*
** Called by the parser to compile an ATTACH statement.
**
** ATTACH p AS pDbname KEY pKey
*/
static FuncDef attach_func = new FuncDef(
3, /* nArg */
SQLITE_UTF8, /* iPrefEnc */
0, /* flags */
null, /* pUserData */
null, /* pNext */
attachFunc, /* xFunc */
null, /* xStep */
null, /* xFinalize */
"sqlite_attach", /* zName */
null, /* pHash */
null /* pDestructor */
);
static void sqlite3Attach( Parse pParse, Expr p, Expr pDbname, Expr pKey )
{
codeAttach( pParse, SQLITE_ATTACH, attach_func, p, p, pDbname, pKey );
}
#endif // * SQLITE_OMIT_ATTACH */
/*
** Initialize a DbFixer structure. This routine must be called prior
** to passing the structure to one of the sqliteFixAAAA() routines below.
**
** The return value indicates whether or not fixation is required. TRUE
** means we do need to fix the database references, FALSE means we do not.
*/
static int sqlite3FixInit(
DbFixer pFix, /* The fixer to be initialized */
Parse pParse, /* Error messages will be written here */
int iDb, /* This is the database that must be used */
string zType, /* "view", "trigger", or "index" */
Token pName /* Name of the view, trigger, or index */
)
{
sqlite3 db;
if ( NEVER( iDb < 0 ) || iDb == 1 )
return 0;
db = pParse.db;
Debug.Assert( db.nDb > iDb );
pFix.pParse = pParse;
pFix.zDb = db.aDb[iDb].zName;
pFix.zType = zType;
pFix.pName = pName;
return 1;
}
/*
** The following set of routines walk through the parse tree and assign
** a specific database to all table references where the database name
** was left unspecified in the original SQL statement. The pFix structure
** must have been initialized by a prior call to sqlite3FixInit().
**
** These routines are used to make sure that an index, trigger, or
** view in one database does not refer to objects in a different database.
** (Exception: indices, triggers, and views in the TEMP database are
** allowed to refer to anything.) If a reference is explicitly made
** to an object in a different database, an error message is added to
** pParse.zErrMsg and these routines return non-zero. If everything
** checks out, these routines return 0.
*/
static int sqlite3FixSrcList(
DbFixer pFix, /* Context of the fixation */
SrcList pList /* The Source list to check and modify */
)
{
int i;
string zDb;
SrcList_item pItem;
if ( NEVER( pList == null ) )
return 0;
zDb = pFix.zDb;
for ( i = 0; i < pList.nSrc; i++ )
{//, pItem++){
pItem = pList.a[i];
if ( pItem.zDatabase == null )
{
pItem.zDatabase = zDb;// sqlite3DbStrDup( pFix.pParse.db, zDb );
}
else if ( !pItem.zDatabase.Equals( zDb ,StringComparison.InvariantCultureIgnoreCase ) )
{
sqlite3ErrorMsg( pFix.pParse,
"%s %T cannot reference objects in database %s",
pFix.zType, pFix.pName, pItem.zDatabase );
return 1;
}
#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER
if ( sqlite3FixSelect( pFix, pItem.pSelect ) != 0 )
return 1;
if ( sqlite3FixExpr( pFix, pItem.pOn ) != 0 )
return 1;
#endif
}
return 0;
}
#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER
static int sqlite3FixSelect(
DbFixer pFix, /* Context of the fixation */
Select pSelect /* The SELECT statement to be fixed to one database */
)
{
while ( pSelect != null )
{
if ( sqlite3FixExprList( pFix, pSelect.pEList ) != 0 )
{
return 1;
}
if ( sqlite3FixSrcList( pFix, pSelect.pSrc ) != 0 )
{
return 1;
}
if ( sqlite3FixExpr( pFix, pSelect.pWhere ) != 0 )
{
return 1;
}
if ( sqlite3FixExpr( pFix, pSelect.pHaving ) != 0 )
{
return 1;
}
pSelect = pSelect.pPrior;
}
return 0;
}
static int sqlite3FixExpr(
DbFixer pFix, /* Context of the fixation */
Expr pExpr /* The expression to be fixed to one database */
)
{
while ( pExpr != null )
{
if ( ExprHasAnyProperty( pExpr, EP_TokenOnly ) )
break;
if ( ExprHasProperty( pExpr, EP_xIsSelect ) )
{
if ( sqlite3FixSelect( pFix, pExpr.x.pSelect ) != 0 )
return 1;
}
else
{
if ( sqlite3FixExprList( pFix, pExpr.x.pList ) != 0 )
return 1;
}
if ( sqlite3FixExpr( pFix, pExpr.pRight ) != 0 )
{
return 1;
}
pExpr = pExpr.pLeft;
}
return 0;
}
static int sqlite3FixExprList(
DbFixer pFix, /* Context of the fixation */
ExprList pList /* The expression to be fixed to one database */
)
{
int i;
ExprList_item pItem;
if ( pList == null )
return 0;
for ( i = 0; i < pList.nExpr; i++ )//, pItem++ )
{
pItem = pList.a[i];
if ( sqlite3FixExpr( pFix, pItem.pExpr ) != 0 )
{
return 1;
}
}
return 0;
}
#endif
#if !SQLITE_OMIT_TRIGGER
static int sqlite3FixTriggerStep(
DbFixer pFix, /* Context of the fixation */
TriggerStep pStep /* The trigger step be fixed to one database */
)
{
while ( pStep != null )
{
if ( sqlite3FixSelect( pFix, pStep.pSelect ) != 0 )
{
return 1;
}
if ( sqlite3FixExpr( pFix, pStep.pWhere ) != 0 )
{
return 1;
}
if ( sqlite3FixExprList( pFix, pStep.pExprList ) != 0 )
{
return 1;
}
pStep = pStep.pNext;
}
return 0;
}
#endif
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="FlatDirectoryTransfer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.DataMovement
{
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.DataMovement.TransferEnumerators;
using Microsoft.Azure.Storage.File;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Represents a flat directory transfer operation.
/// In a flat directory transfer, the enumeration only returns file entries and it only transfers files under the directory.
///
/// In a hierarchy directory transfer, the enumeration also returns directory entries,
/// it transfers files under the directory and also handles opertions on directories.
/// </summary>
#if BINARY_SERIALIZATION
[Serializable]
#else
[DataContract]
#endif
internal class FlatDirectoryTransfer : DirectoryTransfer
{
/// <summary>
/// Serialization field name for transfer enumerator list continuation token.
/// </summary>
private const string ListContinuationTokenName = "ListContinuationToken";
/// <summary>
/// Serialization field name for sub transfers.
/// </summary>
private const string SubTransfersName = "SubTransfers";
/// <summary>
/// List continuation token from which enumeration begins.
/// </summary>
#if !BINARY_SERIALIZATION
[DataMember]
#endif
protected SerializableListContinuationToken enumerateContinuationToken;
/// <summary>
/// Lock object for enumeration continuation token.
/// </summary>
private object lockEnumerateContinuationToken = new object();
/// <summary>
/// Timeout used in reset event waiting.
/// </summary>
private TimeSpan EnumerationWaitTimeOut = TimeSpan.FromSeconds(10);
/// <summary>
/// Used to block enumeration when have enumerated enough transfer entries.
/// </summary>
private AutoResetEvent enumerationResetEvent;
/// <summary>
/// Stores enumerate exception.
/// </summary>
private Exception enumerateException;
/// <summary>
/// Number of outstandings tasks started by this transfer.
/// </summary>
private long outstandingTasks;
private ReaderWriterLockSlim progressUpdateLock = new ReaderWriterLockSlim();
/// <summary>
/// Job queue to invoke ShouldTransferCallback.
/// </summary>
private TaskQueue<Tuple<SingleObjectTransfer, TransferEntry>> shouldTransferQueue
= new TaskQueue<Tuple<SingleObjectTransfer, TransferEntry>>(TransferManager.Configurations.ParallelOperations * Constants.ListSegmentLengthMultiplier);
/// <summary>
/// Storres sub transfers.
/// </summary>
#if !BINARY_SERIALIZATION
[DataMember]
private TransferCollection<SingleObjectTransfer> serializeSubTransfers;
#endif
private TransferCollection<SingleObjectTransfer> subTransfers;
private TaskCompletionSource<object> allTransfersCompleteSource;
/// <summary>
/// Initializes a new instance of the <see cref="FlatDirectoryTransfer"/> class.
/// </summary>
/// <param name="source">Transfer source.</param>
/// <param name="dest">Transfer destination.</param>
/// <param name="transferMethod">Transfer method, see <see cref="TransferMethod"/> for detail available methods.</param>
public FlatDirectoryTransfer(TransferLocation source, TransferLocation dest, TransferMethod transferMethod)
: base(source, dest, transferMethod)
{
this.subTransfers = new TransferCollection<SingleObjectTransfer>();
this.subTransfers.OverallProgressTracker.Parent = this.ProgressTracker;
}
#if BINARY_SERIALIZATION
/// <summary>
/// Initializes a new instance of the <see cref="FlatDirectoryTransfer"/> class.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected FlatDirectoryTransfer(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.enumerateContinuationToken = (SerializableListContinuationToken)info.GetValue(ListContinuationTokenName, typeof(SerializableListContinuationToken));
if (context.Context is StreamJournal)
{
this.subTransfers = new TransferCollection<SingleObjectTransfer>();
}
else
{
this.subTransfers = (TransferCollection<SingleObjectTransfer>)info.GetValue(SubTransfersName, typeof(TransferCollection<SingleObjectTransfer>));
}
this.subTransfers.OverallProgressTracker.Parent = this.ProgressTracker;
}
#endif // BINARY_SERIALIZATION
#if !BINARY_SERIALIZATION
[OnSerializing]
private void OnSerializingCallback(StreamingContext context)
{
if (!IsStreamJournal)
{
this.serializeSubTransfers = this.subTransfers;
}
}
// Initialize a new MultipleObjectsTransfer object after deserialization
[OnDeserialized]
private void OnDeserializedCallback(StreamingContext context)
{
// Constructors and field initializers are not called by DCS, so initialize things here
progressUpdateLock = new ReaderWriterLockSlim();
lockEnumerateContinuationToken = new object();
EnumerationWaitTimeOut = TimeSpan.FromSeconds(10);
if (!IsStreamJournal)
{
this.subTransfers = this.serializeSubTransfers;
}
else
{
this.subTransfers = new TransferCollection<SingleObjectTransfer>();
}
this.subTransfers.OverallProgressTracker.Parent = this.ProgressTracker;
// DataContractSerializer doesn't invoke object's constructor, we should initialize member variables here.
shouldTransferQueue
= new TaskQueue<Tuple<SingleObjectTransfer, TransferEntry>>(TransferManager.Configurations.ParallelOperations * Constants.ListSegmentLengthMultiplier);
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="FlatDirectoryTransfer"/> class.
/// </summary>
/// <param name="other">Another <see cref="FlatDirectoryTransfer"/> object.</param>
private FlatDirectoryTransfer(FlatDirectoryTransfer other)
:base(other)
{
other.progressUpdateLock?.EnterWriteLock();
this.ProgressTracker = other.ProgressTracker.Copy();
lock (other.lockEnumerateContinuationToken)
{
// copy enumerator
this.enumerateContinuationToken = other.enumerateContinuationToken;
// copy transfers
this.subTransfers = other.subTransfers.Copy();
}
this.subTransfers.OverallProgressTracker.Parent = this.ProgressTracker;
other.progressUpdateLock?.ExitWriteLock();
}
#if BINARY_SERIALIZATION
/// <summary>
/// Serializes the object.
/// </summary>
/// <param name="info">Serialization info object.</param>
/// <param name="context">Streaming context.</param>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
// serialize enumerator
info.AddValue(ListContinuationTokenName, this.enumerateContinuationToken, typeof(SerializableListContinuationToken));
if (!(context.Context is StreamJournal))
{
// serialize sub transfers
info.AddValue(SubTransfersName, this.subTransfers, typeof(TransferCollection<SingleObjectTransfer>));
}
}
#endif // BINARY_SERIALIZATION
public override Transfer Copy()
{
return new FlatDirectoryTransfer(this);
}
public override async Task ExecuteInternalAsync(TransferScheduler scheduler, CancellationToken cancellationToken)
{
this.ResetExecutionStatus();
try
{
Task listTask = Task.Run(() => this.ListNewTransfers(cancellationToken));
await Task.Run(() => { this.EnumerateAndTransfer(scheduler, cancellationToken); });
await listTask;
}
finally
{
// wait for outstanding transfers to complete
await allTransfersCompleteSource.Task;
}
if (this.enumerateException != null)
{
throw this.enumerateException;
}
this.ProgressTracker.AddBytesTransferred(0);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
SpinWait sw = new SpinWait();
while (Interlocked.Read(ref this.outstandingTasks) != 0)
{
sw.SpinOnce();
}
if (this.enumerationResetEvent != null)
{
this.enumerationResetEvent.Dispose();
this.enumerationResetEvent = null;
}
if (this.shouldTransferQueue != null)
{
this.shouldTransferQueue.Dispose();
this.shouldTransferQueue = null;
}
if (null != this.progressUpdateLock)
{
this.progressUpdateLock.Dispose();
this.progressUpdateLock = null;
}
}
base.Dispose(disposing);
}
private void ListNewTransfers(CancellationToken cancellationToken)
{
// list new transfers
if (this.enumerateContinuationToken != null)
{
this.SourceEnumerator.EnumerateContinuationToken = this.enumerateContinuationToken.ListContinuationToken;
}
ShouldTransferCallbackAsync shouldTransferCallback = this.DirectoryContext?.ShouldTransferCallbackAsync;
try
{
var enumerator = this.SourceEnumerator.EnumerateLocation(cancellationToken).GetEnumerator();
while (true)
{
Utils.CheckCancellation(cancellationToken);
if (!enumerator.MoveNext())
{
break;
}
TransferEntry entry = enumerator.Current;
ErrorEntry errorEntry = entry as ErrorEntry;
if (errorEntry != null)
{
TransferException exception = errorEntry.Exception as TransferException;
if (null != exception)
{
throw exception;
}
else
{
throw new TransferException(
TransferErrorCode.FailToEnumerateDirectory,
errorEntry.Exception.GetExceptionMessage(),
errorEntry.Exception);
}
}
this.shouldTransferQueue.EnqueueJob(async () =>
{
try
{
SingleObjectTransfer candidate = this.CreateTransfer(entry);
bool shouldTransfer = shouldTransferCallback == null || await shouldTransferCallback(candidate.Source.Instance, candidate.Destination.Instance);
return new Tuple<SingleObjectTransfer, TransferEntry>(shouldTransfer ? candidate : null, entry);
}
catch (Exception ex)
{
throw new TransferException(TransferErrorCode.FailToEnumerateDirectory, string.Format(CultureInfo.CurrentCulture, "Error happens when handling entry {0}: {1}", entry.ToString(), ex.Message), ex);
}
});
}
}
finally
{
this.shouldTransferQueue.CompleteAdding();
}
}
private IEnumerable<SingleObjectTransfer> AllTransfers(CancellationToken cancellationToken)
{
if (null == this.Journal)
{
// return all existing transfers in subTransfers
foreach (var transfer in this.subTransfers.GetEnumerator())
{
Utils.CheckCancellation(cancellationToken);
transfer.Context = this.Context;
this.UpdateTransfer(transfer);
yield return transfer as SingleObjectTransfer;
}
}
else
{
foreach (var transfer in this.Journal.ListSubTransfers())
{
Utils.CheckCancellation(cancellationToken);
transfer.Context = this.Context;
this.UpdateTransfer(transfer);
this.subTransfers.AddTransfer(transfer, false);
yield return transfer;
}
}
while (true)
{
Utils.CheckCancellation(cancellationToken);
Tuple<SingleObjectTransfer, TransferEntry> pair;
try
{
pair = this.shouldTransferQueue.DequeueResult();
}
catch (InvalidOperationException)
{
// Task queue is empty and CompleteAdding. No more transfer to dequeue.
break;
}
catch (AggregateException aggregateException)
{
// Unwrap the AggregateException.
ExceptionDispatchInfo.Capture(aggregateException.Flatten().InnerExceptions[0]).Throw();
break;
}
SingleObjectTransfer transfer = pair.Item1;
TransferEntry entry = pair.Item2;
lock (this.lockEnumerateContinuationToken)
{
if (null != transfer)
{
this.subTransfers.AddTransfer(transfer);
}
this.enumerateContinuationToken = new SerializableListContinuationToken(entry.ContinuationToken);
}
if (null != transfer)
{
this.Journal?.AddSubtransfer(transfer);
}
this.Journal?.UpdateJournalItem(this);
if (null == transfer)
{
continue;
}
try
{
this.CreateParentDirectory(transfer);
}
catch (Exception ex)
{
transfer.OnTransferFailed(ex);
// Don't keep failed transfers in memory if they can be persisted to a journal.
if (null != this.Journal)
{
this.subTransfers.RemoveTransfer(transfer);
}
continue;
}
#if DEBUG
Utils.HandleFaultInjection(entry.RelativePath, transfer);
#endif
yield return transfer;
}
}
private void EnumerateAndTransfer(TransferScheduler scheduler, CancellationToken cancellationToken)
{
Interlocked.Increment(ref this.outstandingTasks);
try
{
foreach (var transfer in this.AllTransfers(cancellationToken))
{
this.CheckAndPauseEnumeration(cancellationToken);
transfer.UpdateProgressLock(this.progressUpdateLock);
transfer.ShouldTransferChecked = true;
this.DoTransfer(transfer, scheduler, cancellationToken);
}
}
catch (StorageException e)
{
throw new TransferException(TransferErrorCode.FailToEnumerateDirectory, e.GetExceptionMessage(), e);
}
finally
{
if (Interlocked.Decrement(ref this.outstandingTasks) == 0)
{
// make sure transfer terminiate when there is no subtransfer.
this.allTransfersCompleteSource.SetResult(null);
}
}
}
private void CheckAndPauseEnumeration(CancellationToken cancellationToken)
{
// -1 because there's one outstanding task for list while this method is called.
if ((this.outstandingTasks - 1) > this.MaxTransferConcurrency)
{
while (!this.enumerationResetEvent.WaitOne(EnumerationWaitTimeOut)
&& !cancellationToken.IsCancellationRequested)
{
}
}
}
private void ResetExecutionStatus()
{
if (this.enumerationResetEvent != null)
{
this.enumerationResetEvent.Dispose();
}
this.enumerationResetEvent = new AutoResetEvent(true);
this.enumerateException = null;
this.allTransfersCompleteSource = new TaskCompletionSource<object>();
this.outstandingTasks = 0;
}
private async void DoTransfer(Transfer transfer, TransferScheduler scheduler, CancellationToken cancellationToken)
{
using (transfer)
{
bool hasError = false;
Interlocked.Increment(ref this.outstandingTasks);
try
{
await transfer.ExecuteAsync(scheduler, cancellationToken);
}
catch
{
// catch exception thrown from sub-transfer as it's already recorded
hasError = true;
}
finally
{
// Don't keep the failed transferring in memory, if the checkpoint is persist to a streamed journal,
// instead, should only keep them in the streamed journal.
if ((!hasError)
|| (null != this.Journal))
{
this.subTransfers.RemoveTransfer(transfer);
}
this.enumerationResetEvent.Set();
if (Interlocked.Decrement(ref this.outstandingTasks) == 0)
{
// all transfers are done
this.allTransfersCompleteSource.SetResult(null);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void RoundToNearestIntegerScalarSingle()
{
var test = new SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle testClass)
{
var result = Sse41.RoundToNearestIntegerScalar(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
{
var result = Sse41.RoundToNearestIntegerScalar(
Sse.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar1;
private Vector128<Single> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.RoundToNearestIntegerScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.RoundToNearestIntegerScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.RoundToNearestIntegerScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.RoundToNearestIntegerScalar(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
{
var result = Sse41.RoundToNearestIntegerScalar(
Sse.LoadVector128((Single*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var result = Sse41.RoundToNearestIntegerScalar(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var result = Sse41.RoundToNearestIntegerScalar(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var result = Sse41.RoundToNearestIntegerScalar(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle();
var result = Sse41.RoundToNearestIntegerScalar(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
{
var result = Sse41.RoundToNearestIntegerScalar(
Sse.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.RoundToNearestIntegerScalar(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
{
var result = Sse41.RoundToNearestIntegerScalar(
Sse.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.RoundToNearestIntegerScalar(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.RoundToNearestIntegerScalar(
Sse.LoadVector128((Single*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[0], MidpointRounding.AwayFromZero)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(firstOp[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToNearestIntegerScalar)}<Single>(Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
namespace NVerify
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using NVerify.Core;
public static class CollectionExtensions
{
public static IVerifiable<IEnumerable<T>> IsEmpty<T>(this IAssertion<IEnumerable<T>> collection, string message = "")
{
return new Verifiable<IEnumerable<T>>(collection, target =>
NVerify.Verify.That(target).IsNotNull(message)
.And()
.ItsTrueThat(col => col.Count() == 0,
String.Format("The collection was not empty. It has {0} elements.\n{0}", target.Count(), message))
.Now());
}
public static IVerifiable<IEnumerable<T>> IsNotEmpty<T>(this IAssertion<IEnumerable<T>> collection, string message = "")
{
return new Verifiable<IEnumerable<T>>(collection, target =>
NVerify.Verify.That(target).IsNotNull(message)
.And()
.ItsTrueThat(col => col.Count() > 0, message)
.Now());
}
public static IVerifiable<IEnumerable<T>> ContainsAll<T>(this IAssertion<IEnumerable<T>> assertion, IEnumerable<T> expected, string message = "")
{
T[] localExpected = expected.ToArray();
return new Verifiable<IEnumerable<T>>(assertion, target =>
{
if (assertion != null)
{
foreach (T expectedItem in localExpected)
{
NVerify.Verify.That(target)
.DoesContain(expectedItem, message)
.Now();
}
}
else
{
throw new ArgumentNullException("Called with a null assertion!");
}
});
}
public static IVerifiable<IEnumerable> DoesContain(this IAssertion<IEnumerable> list, object expected, string message = "")
{
return new Verifiable<IEnumerable>(list, target =>
{
bool found = false;
if (list != null)
{
foreach (object o in target)
{
if (o == expected)
{
found = true;
break;
}
}
}
NVerify.Verify.That(found)
.IsTrue(string.Format("The <{0}> should have contained: <{1}>. {2}",
(target ?? "NULL"),
(expected ?? "NULL"),
(message ?? string.Empty)))
.Now();
});
}
public static IVerifiable<IEnumerable<T>> DoesContain<T>(this IAssertion<IEnumerable<T>> assertion, T expected, string message = "")
{
return new Verifiable<IEnumerable<T>>(assertion,
target => NVerify.Verify.That(target.Contains(expected))
.IsTrue(string.Format("The <{0}> should have contained: <{1}>. {2}",
(target != null ? target.ToString() : "NULL"),
(expected != null ? expected.ToString() : "NULL"),
(message ?? string.Empty)))
.Now());
}
public static IVerifiable<IEnumerable> DoesNotContain(this IAssertion<IEnumerable> assertion, object expected, string message = "")
{
return new Verifiable<IEnumerable>(assertion,
target =>
{
bool found = false;
if (assertion != null)
{
foreach (var o in target)
{
if (o == expected)
{
found = true;
}
}
}
NVerify.Verify.That(found)
.IsFalse(string.Format("The <{0}> should not have contained: <{1}>. {2}",
(target ?? "NULL"),
(expected ?? "NULL"),
(message ?? string.Empty)))
.Now();
});
}
public static IVerifiable<IEnumerable<T>> DoesNotContain<T>(this IAssertion<IEnumerable<T>> list, T expected, string message = "")
{
return new Verifiable<IEnumerable<T>>(list, target =>
NVerify.Verify.That(target.Contains(expected))
.IsFalse(string.Format(
"The <{0}> should not have contained: <{1}>. {2}",
(list != null ? list.ToString() : "NULL"),
(expected != null ? expected.ToString() : "NULL"),
(message ?? string.Empty)))
.Now());
}
/// <summary>
/// Asserts that all elements comply with a Predicate
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list.</param>
/// <param name="evaluator">The evaluator.</param>
public static IVerifiable<IEnumerable<T>> IsTrueForAll<T>(this IAssertion<IEnumerable<T>> list, Predicate<T> evaluator, string message = "")
{
return new Verifiable<IEnumerable<T>>(list, target =>
{
bool result = false;
int index = 0;
foreach (T item in target)
{
result = evaluator(item);
if (!result)
{
message = String.Format("Item <{2}>, at index: {0} did not comply with condition.\n{1}",
index,
message,
item == null ? "NULL" : item.ToString());
break;
}
index++;
}
NVerify.Verify.That(result)
.IsTrue(message)
.Now();
});
}
/// <summary>
/// Asserts that all elements DO NOT comply with a Predicate
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list.</param>
/// <param name="evaluator">The evaluator.</param>
public static IVerifiable<IEnumerable<T>> IsFalseForAll<T>(this IAssertion<IEnumerable<T>> list, Predicate<T> evaluator, string message = "")
{
return list.IsTrueForAll(value => !evaluator(value), message);
}
/// <summary>
/// Asserts that at least one element complies with a Predicate
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list.</param>
/// <param name="evaluator">The evaluator.</param>
public static IVerifiable<IEnumerable<T>> IsTrueForAny<T>(this IAssertion<IEnumerable<T>> list, Predicate<T> evaluator, string message = "")
{
return new Verifiable<IEnumerable<T>>(list, target =>
NVerify.Verify.That(
target.Any(t => evaluator(t)))
.IsTrue(message)
.Now());
}
/// <summary>
/// Asserts that at least one element complies with a Predicate
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list.</param>
/// <param name="evaluator">The evaluator.</param>
public static IVerifiable<IEnumerable<T>> IsFalseForAny<T>(this IAssertion<IEnumerable<T>> list, Predicate<T> evaluator, string message = "")
{
return list.IsTrueForAny(value => !evaluator(value), message);
}
/// <summary>
/// Determines whether [the specified list] [is of the specified size].
/// </summary>
/// <typeparam name="T">Type of elements in the list.</typeparam>
/// <param name="list">The list.</param>
/// <param name="elementCount">The element count.</param>
public static IVerifiable<IEnumerable<T>> IsOfSize<T>(this IAssertion<IEnumerable<T>> list, int elementCount)
{
return new Verifiable<IEnumerable<T>>(list, target =>
Assert.AreEqual(elementCount, target.Count(), string.Format("Number of elements should be: {0}", elementCount)));
}
public static IVerifiable<IEnumerable<T>> HasLessThan<T>(this IAssertion<IEnumerable<T>> list, int elementCount)
{
int listCount = list.Target.Count();
return new Verifiable<IEnumerable<T>>(list, target =>
NVerify.Verify.That(listCount < elementCount)
.IsTrue(
string.Format("Number of elements should be less than: {0} but was {1}",
elementCount,
listCount))
.Now());
}
/// <summary>
/// Verify that a collection should have more than a certain amount of elements
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list.</param>
/// <param name="elementCount">The count.</param>
public static IVerifiable<IEnumerable<T>> HasMoreThan<T>(this IAssertion<IEnumerable<T>> list, int elementCount)
{
int listCount = list.Target.Count();
return new Verifiable<IEnumerable<T>>(list, target =>
NVerify.Verify.That(listCount > elementCount)
.IsTrue(
string.Format("Number of elements should be more than: {0} but was {1}",
elementCount,
listCount))
.Now());
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Common;
using Mosa.Compiler.Framework;
using Mosa.Compiler.Linker;
using System;
using System.Diagnostics;
namespace Mosa.Platform.x86
{
/// <summary>
/// An x86 machine code emitter.
/// </summary>
public sealed class MachineCodeEmitter : BaseCodeEmitter
{
#region Code Generation
/// <summary>
/// Calls the specified target.
/// </summary>
/// <param name="symbolOperand">The symbol operand.</param>
public void EmitCallSite(Operand symbolOperand)
{
linker.Link(
LinkType.RelativeOffset,
PatchType.I4,
MethodName,
SectionKind.Text,
(int)codeStream.Position,
-4,
symbolOperand.Name,
SectionKind.Text,
0
);
codeStream.WriteZeroBytes(4);
}
/// <summary>
/// Emits relative branch code.
/// </summary>
/// <param name="code">The branch instruction code.</param>
/// <param name="dest">The destination label.</param>
public void EmitRelativeBranch(byte[] code, int dest)
{
codeStream.Write(code, 0, code.Length);
EmitRelativeBranchTarget(dest);
}
/// <summary>
/// Emits the specified op code.
/// </summary>
/// <param name="opCode">The op code.</param>
/// <param name="dest">The dest.</param>
public void Emit(OpCode opCode, Operand dest)
{
// Write the opcode
codeStream.Write(opCode.Code, 0, opCode.Code.Length);
byte? sib = null, modRM = null;
Operand displacement = null;
// Write the mod R/M byte
modRM = CalculateModRM(opCode.RegField, dest, null, out sib, out displacement);
if (modRM != null)
{
codeStream.WriteByte(modRM.Value);
if (sib.HasValue)
codeStream.WriteByte(sib.Value);
}
// Add displacement to the code
if (displacement != null)
WriteDisplacement(displacement);
}
/// <summary>
/// Emits the given code.
/// </summary>
/// <param name="opCode">The op code.</param>
/// <param name="dest">The destination operand.</param>
/// <param name="src">The source operand.</param>
public void Emit(OpCode opCode, Operand dest, Operand src)
{
// Write the opcode
codeStream.Write(opCode.Code, 0, opCode.Code.Length);
if (dest == null && src == null)
return;
byte? sib = null, modRM = null;
Operand displacement = null;
// Write the mod R/M byte
modRM = CalculateModRM(opCode.RegField, dest, src, out sib, out displacement);
if (modRM != null)
{
codeStream.WriteByte(modRM.Value);
if (sib.HasValue)
codeStream.WriteByte(sib.Value);
}
// Add displacement to the code
if (displacement != null)
WriteDisplacement(displacement);
// Add immediate bytes
if (dest.IsConstant)
WriteImmediate(dest);
else if (dest.IsSymbol)
WriteDisplacement(dest);
else if (src != null && src.IsConstant)
WriteImmediate(src);
else if (src != null && src.IsSymbol)
WriteDisplacement(src);
}
/// <summary>
/// Emits the given code.
/// </summary>
/// <param name="opCode">The op code.</param>
/// <param name="dest">The dest.</param>
/// <param name="src">The source.</param>
/// <param name="third">The third.</param>
public void Emit(OpCode opCode, Operand dest, Operand src, Operand third)
{
// Write the opcode
codeStream.Write(opCode.Code, 0, opCode.Code.Length);
if (dest == null && src == null)
return;
byte? sib = null, modRM = null;
Operand displacement = null;
// Write the mod R/M byte
modRM = CalculateModRM(opCode.RegField, dest, src, out sib, out displacement);
if (modRM != null)
{
codeStream.WriteByte(modRM.Value);
if (sib.HasValue)
codeStream.WriteByte(sib.Value);
}
// Add displacement to the code
if (displacement != null)
WriteDisplacement(displacement);
// Add immediate bytes
if (third != null && third.IsConstant)
WriteImmediate(third);
}
/// <summary>
/// Emits the displacement operand.
/// </summary>
/// <param name="displacement">The displacement operand.</param>
private void WriteDisplacement(Operand displacement)
{
if (displacement.IsLabel)
{
// FIXME! remove assertion
Debug.Assert(displacement.Displacement == 0);
linker.Link(LinkType.AbsoluteAddress, PatchType.I4, MethodName, SectionKind.Text, (int)codeStream.Position, 0, displacement.Name, SectionKind.ROData, 0);
codeStream.WriteZeroBytes(4);
}
else if (displacement.IsField)
{
var section = displacement.Field.Data != null ? SectionKind.ROData : SectionKind.BSS;
linker.Link(LinkType.AbsoluteAddress, PatchType.I4, MethodName, SectionKind.Text, (int)codeStream.Position, 0, displacement.Field.FullName, section, (int)displacement.Displacement);
codeStream.WriteZeroBytes(4);
}
else if (displacement.IsSymbol)
{
// FIXME! remove assertion
Debug.Assert(displacement.Displacement == 0);
var section = (displacement.Method != null) ? SectionKind.Text : SectionKind.ROData;
var symbol = linker.GetSymbol(displacement.Name, section);
if (symbol == null)
{
symbol = linker.FindSymbol(displacement.Name);
}
linker.Link(LinkType.AbsoluteAddress, PatchType.I4, MethodName, SectionKind.Text, (int)codeStream.Position, 0, symbol, 0);
codeStream.WriteZeroBytes(4);
}
else if (displacement.IsMemoryAddress && displacement.OffsetBase != null && displacement.OffsetBase.IsConstant)
{
codeStream.Write((int)(displacement.OffsetBase.ConstantSignedLongInteger + displacement.Displacement), Endianness.Little);
}
else
{
codeStream.Write((int)displacement.Displacement, Endianness.Little);
}
}
/// <summary>
/// Emits an immediate operand.
/// </summary>
/// <param name="op">The immediate operand to emit.</param>
private void WriteImmediate(Operand op)
{
if (op.IsRegister)
return; // nothing to do.
if (op.IsStackLocal || op.IsMemoryAddress)
{
codeStream.Write((int)op.Displacement, Endianness.Little);
return;
}
if (!op.IsConstant)
{
throw new InvalidCompilerException();
}
if (op.IsI1)
codeStream.WriteByte((byte)op.ConstantSignedInteger);
else if (op.IsU1 || op.IsBoolean)
codeStream.WriteByte(Convert.ToByte(op.ConstantUnsignedInteger));
else if (op.IsU2 || op.IsChar)
codeStream.Write(Convert.ToUInt16(op.ConstantUnsignedInteger), Endianness.Little);
else if (op.IsI2)
codeStream.Write(Convert.ToInt16(op.ConstantSignedInteger), Endianness.Little);
else if (op.IsI4 || op.IsI)
codeStream.Write(Convert.ToInt32(op.ConstantSignedInteger), Endianness.Little);
else if (op.IsU4 || op.IsPointer || op.IsU || !op.IsValueType)
codeStream.Write(Convert.ToUInt32(op.ConstantUnsignedInteger), Endianness.Little);
else
throw new InvalidCompilerException();
}
/// <summary>
/// Emits the relative branch target.
/// </summary>
/// <param name="label">The label.</param>
private void EmitRelativeBranchTarget(int label)
{
// The relative offset of the label
int relOffset = 0;
// The position in the code stream of the label
int position;
// Did we see the label?
if (TryGetLabel(label, out position))
{
// Yes, calculate the relative offset
relOffset = position - ((int)codeStream.Position + 4);
}
else
{
// Forward jump, we can't resolve yet - store a patch
AddPatch(label, (int)codeStream.Position);
}
// Emit the relative jump offset (zero if we don't know it yet!)
codeStream.Write(relOffset, Endianness.Little);
}
public override void ResolvePatches()
{
// Save the current position
long currentPosition = codeStream.Position;
foreach (var p in patches)
{
int labelPosition;
if (!TryGetLabel(p.Label, out labelPosition))
{
throw new ArgumentException("Missing label while resolving patches.", "label=" + labelPosition.ToString());
}
codeStream.Position = p.Position;
// Compute relative branch offset
int relOffset = labelPosition - ((int)p.Position + 4);
// Write relative offset to stream
var bytes = BitConverter.GetBytes(relOffset);
codeStream.Write(bytes, 0, bytes.Length);
}
// Reset the position
codeStream.Position = currentPosition;
}
/// <summary>
/// Emits a far jump to next instruction.
/// </summary>
public void EmitFarJumpToNextInstruction()
{
codeStream.WriteByte(0xEA);
linker.Link(LinkType.AbsoluteAddress, PatchType.I4, MethodName, SectionKind.Text, (int)codeStream.Position, 6, MethodName, SectionKind.Text, (int)codeStream.Position);
codeStream.WriteZeroBytes(4);
codeStream.WriteByte(0x08);
codeStream.WriteByte(0x00);
}
/// <summary>
/// Calculates the value of the modR/M byte and SIB bytes.
/// </summary>
/// <param name="regField">The modR/M regfield value.</param>
/// <param name="op1">The destination operand.</param>
/// <param name="op2">The source operand.</param>
/// <param name="sib">A potential SIB byte to emit.</param>
/// <param name="displacement">An immediate displacement to emit.</param>
/// <returns>The value of the modR/M byte.</returns>
private static byte? CalculateModRM(byte? regField, Operand op1, Operand op2, out byte? sib, out Operand displacement)
{
byte? modRM = null;
displacement = null;
// FIXME: Handle the SIB byte
sib = null;
Operand mop1 = op1 != null && op1.IsMemoryAddress ? op1 : null;
Operand mop2 = op2 != null && op2.IsMemoryAddress ? op2 : null;
bool op1IsRegister = (op1 != null) && op1.IsRegister;
bool op2IsRegister = (op2 != null) && op2.IsRegister;
// Normalize the operand order
if (!op1IsRegister && op2IsRegister)
{
// Swap the memory operands
op1 = op2;
op2 = null;
mop2 = mop1;
mop1 = null;
op1IsRegister = op2IsRegister;
op2IsRegister = false;
}
if (regField != null)
modRM = (byte)(regField.Value << 3);
if (op1IsRegister && op2IsRegister)
{
// mod = 11b, reg = rop1, r/m = rop2
modRM = (byte)((3 << 6) | (op1.Register.RegisterCode << 3) | op2.Register.RegisterCode);
}
// Check for register/memory combinations
else if (mop2 != null && mop2.EffectiveOffsetBase != null)
{
// mod = 10b, reg = rop1, r/m = mop2
modRM = (byte)(modRM.GetValueOrDefault() | (2 << 6) | (byte)mop2.EffectiveOffsetBase.RegisterCode);
if (op1 != null)
modRM |= (byte)(op1.Register.RegisterCode << 3);
displacement = mop2;
if (mop2.EffectiveOffsetBase.RegisterCode == 4)
sib = 0x24;
}
else if (mop2 != null)
{
// mod = 10b, r/m = mop1, reg = rop2
modRM = (byte)(modRM.GetValueOrDefault() | 5);
if (op1IsRegister)
modRM |= (byte)(op1.Register.RegisterCode << 3);
displacement = mop2;
}
else if (mop1 != null && mop1.EffectiveOffsetBase != null)
{
// mod = 10b, r/m = mop1, reg = rop2
modRM = (byte)(modRM.GetValueOrDefault() | (2 << 6) | mop1.EffectiveOffsetBase.RegisterCode);
if (op2IsRegister)
modRM |= (byte)(op2.Register.RegisterCode << 3);
displacement = mop1;
if (mop1.EffectiveOffsetBase.RegisterCode == 4)
sib = 0xA4;
}
else if (mop1 != null)
{
// mod = 10b, r/m = mop1, reg = rop2
modRM = (byte)(modRM.GetValueOrDefault() | 5);
if (op2IsRegister)
modRM |= (byte)(op2.Register.RegisterCode << 3);
displacement = mop1;
}
else if (op1IsRegister)
{
modRM = (byte)(modRM.GetValueOrDefault() | (3 << 6) | op1.Register.RegisterCode);
}
return modRM;
}
#endregion Code Generation
}
}
| |
// 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.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
/// <summary>The class that contains the unit tests of the ThreadLocal.</summary>
public static class ThreadLocalTests
{
/// <summary>Tests for the Ctor.</summary>
/// <returns>True if the tests succeeds, false otherwise.</returns>
[Fact]
public static void RunThreadLocalTest1_Ctor()
{
ThreadLocal<object> testObject;
testObject = new ThreadLocal<object>();
testObject = new ThreadLocal<object>(true);
testObject = new ThreadLocal<object>(() => new object());
testObject = new ThreadLocal<object>(() => new object(), true);
}
[Fact]
public static void RunThreadLocalTest1_Ctor_Negative()
{
try
{
new ThreadLocal<object>(null);
}
catch (ArgumentNullException)
{
// No other exception should be thrown.
// With a previous issue, if the constructor threw an exception, the finalizer would throw an exception as well.
}
}
/// <summary>Tests for the ToString.</summary>
/// <returns>True if the tests succeeds, false otherwise.</returns>
[Fact]
public static void RunThreadLocalTest2_ToString()
{
ThreadLocal<object> tlocal = new ThreadLocal<object>(() => (object)1);
Assert.Equal(1.ToString(), tlocal.ToString());
}
/// <summary>Tests for the Initialized property.</summary>
/// <returns>True if the tests succeeds, false otherwise.</returns>
[Fact]
public static void RunThreadLocalTest3_IsValueCreated()
{
ThreadLocal<string> tlocal = new ThreadLocal<string>(() => "Test");
Assert.False(tlocal.IsValueCreated);
string temp = tlocal.Value;
Assert.True(tlocal.IsValueCreated);
}
[Fact]
public static void RunThreadLocalTest4_Value()
{
ThreadLocal<string> tlocal = null;
// different threads call Value
int numOfThreads = 10;
Task[] threads = new Task[numOfThreads];
object alock = new object();
List<string> seenValuesFromAllThreads = new List<string>();
int counter = 0;
tlocal = new ThreadLocal<string>(() => (++counter).ToString());
//CancellationToken ct = new CancellationToken();
for (int i = 0; i < threads.Length; ++i)
{
// We are creating the task using TaskCreationOptions.LongRunning because...
// there is no guarantee that the Task will be created on another thread.
// There is also no guarantee that using this TaskCreationOption will force
// it to be run on another thread.
threads[i] = new Task(() =>
{
string value = tlocal.Value;
Debug.WriteLine("Val: " + value);
seenValuesFromAllThreads.Add(value);
}, TaskCreationOptions.LongRunning);
threads[i].Start(TaskScheduler.Default);
threads[i].Wait();
}
Assert.Equal(Enumerable.Range(1, threads.Length).Select(x => x.ToString()), seenValuesFromAllThreads);
}
[Fact]
public static void RunThreadLocalTest4_Value_NegativeCases()
{
ThreadLocal<string> tlocal = null;
Assert.Throws<InvalidOperationException>(() =>
{
int x = 0;
tlocal = new ThreadLocal<string>(delegate
{
if (x++ < 5)
return tlocal.Value;
else
return "Test";
});
string str = tlocal.Value;
});
}
[Fact]
public static void RunThreadLocalTest5_Dispose()
{
// test recycling the combination index;
ThreadLocal<string> tl = new ThreadLocal<string>(() => null);
Assert.False(tl.IsValueCreated);
Assert.Null(tl.Value);
// Test that a value is not kept alive by a departed thread
var threadLocal = new ThreadLocal<SetMreOnFinalize>();
var mres = new ManualResetEventSlim(false);
// (Careful when editing this test: saving the created thread into a local variable would likely break the
// test in Debug build.)
// We are creating the task using TaskCreationOptions.LongRunning because...
// there is no guarantee that the Task will be created on another thread.
// There is also no guarantee that using this TaskCreationOption will force
// it to be run on another thread.
new Task(() => { threadLocal.Value = new SetMreOnFinalize(mres); }, TaskCreationOptions.LongRunning).Start(TaskScheduler.Default);
SpinWait.SpinUntil(() =>
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
return mres.IsSet;
}, 500);
Assert.True(mres.IsSet);
}
[Fact]
public static void RunThreadLocalTest5_Dispose_Negative()
{
ThreadLocal<string> tl = new ThreadLocal<string>(() => "dispose test");
string value = tl.Value;
tl.Dispose();
Assert.Throws<ObjectDisposedException>(() => { string tmp = tl.Value; });
// Failure Case: The Value property of the disposed ThreadLocal object should throw ODE
Assert.Throws<ObjectDisposedException>(() => { bool tmp = tl.IsValueCreated; });
// Failure Case: The IsValueCreated property of the disposed ThreadLocal object should throw ODE
Assert.Throws<ObjectDisposedException>(() => { string tmp = tl.ToString(); });
// Failure Case: The ToString method of the disposed ThreadLocal object should throw ODE
}
[Fact]
public static void RunThreadLocalTest6_SlowPath()
{
// the maximum fast path instances for each type is 16 ^ 3 = 4096, when this number changes in the product code, it should be changed here as well
int MaximumFastPathPerInstance = 4096;
ThreadLocal<int>[] locals_int = new ThreadLocal<int>[MaximumFastPathPerInstance + 10];
for (int i = 0; i < locals_int.Length; i++)
{
locals_int[i] = new ThreadLocal<int>(() => i);
var val = locals_int[i].Value;
}
Assert.Equal(Enumerable.Range(0, locals_int.Length), locals_int.Select(x => x.Value));
// The maximum slowpath for all Ts is MaximumFastPathPerInstance * 4;
locals_int = new ThreadLocal<int>[4096];
ThreadLocal<long>[] locals_long = new ThreadLocal<long>[4096];
ThreadLocal<float>[] locals_float = new ThreadLocal<float>[4096];
ThreadLocal<double>[] locals_double = new ThreadLocal<double>[4096];
for (int i = 0; i < locals_int.Length; i++)
{
locals_int[i] = new ThreadLocal<int>(() => i);
locals_long[i] = new ThreadLocal<long>(() => i);
locals_float[i] = new ThreadLocal<float>(() => i);
locals_double[i] = new ThreadLocal<double>(() => i);
}
ThreadLocal<string> local = new ThreadLocal<string>(() => "slow path");
Assert.Equal("slow path", local.Value);
}
private class ThreadLocalWeakReferenceTest
{
private object _foo;
private WeakReference _wFoo;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private void Method()
{
_foo = new Object();
_wFoo = new WeakReference(_foo);
new ThreadLocal<object>() { Value = _foo }.Dispose();
}
public void Run()
{
Method();
_foo = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
// s_foo should have been garbage collected
Assert.False(_wFoo.IsAlive);
}
}
[Fact]
public static void RunThreadLocalTest7_WeakReference()
{
var threadLocalWeakReferenceTest = new ThreadLocalWeakReferenceTest();
threadLocalWeakReferenceTest.Run();
}
[Fact]
public static void RunThreadLocalTest8_Values()
{
// Test adding values and updating values
{
var threadLocal = new ThreadLocal<int>(true);
Assert.True(threadLocal.Values.Count == 0, "RunThreadLocalTest8_Values: Expected thread local to initially have 0 values");
Assert.True(threadLocal.Value == 0, "RunThreadLocalTest8_Values: Expected initial value of 0");
Assert.True(threadLocal.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to now be 1 from initialized value");
Assert.True(threadLocal.Values[0] == 0, "RunThreadLocalTest8_Values: Expected values to contain initialized value");
threadLocal.Value = 1000;
Assert.True(threadLocal.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to still be 1 after updating existing value");
Assert.True(threadLocal.Values[0] == 1000, "RunThreadLocalTest8_Values: Expected values to contain updated value");
((IAsyncResult)Task.Run(() => threadLocal.Value = 1001)).AsyncWaitHandle.WaitOne();
Assert.True(threadLocal.Values.Count == 2, "RunThreadLocalTest8_Values: Expected values count to be 2 now that another thread stored a value");
Assert.True(threadLocal.Values.Contains(1000) && threadLocal.Values.Contains(1001), "RunThreadLocalTest8_Values: Expected values to contain both thread's values");
int numTasks = 1000;
Task[] allTasks = new Task[numTasks];
for (int i = 0; i < numTasks; i++)
{
// We are creating the task using TaskCreationOptions.LongRunning because...
// there is no guarantee that the Task will be created on another thread.
// There is also no guarantee that using this TaskCreationOption will force
// it to be run on another thread.
var task = Task.Factory.StartNew(() => threadLocal.Value = i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
task.Wait();
}
var values = threadLocal.Values;
if (values.Count != 1002)
{
string message =
"RunThreadLocalTest8_Values: Expected values to contain both previous values and 1000 new values. Actual count: " +
values.Count +
'.';
if (values.Count != 0)
{
message += " Missing items:";
for (int i = 0; i < 1002; i++)
{
if (!values.Contains(i))
{
message += " " + i;
}
}
}
Assert.True(false, message);
}
for (int i = 0; i < 1000; i++)
{
Assert.True(values.Contains(i), "RunThreadLocalTest8_Values: Expected values to contain value for thread #: " + i);
}
threadLocal.Dispose();
}
// Test that thread values remain after threads depart
{
var tl = new ThreadLocal<string>(true);
var t = Task.Run(() => tl.Value = "Parallel");
t.Wait();
t = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.True(tl.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to be 1 from other thread's initialization");
Assert.True(tl.Values.Contains("Parallel"), "RunThreadLocalTest8_Values: Expected values to contain 'Parallel'");
}
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void RunThreadLocalTest8Helper(ManualResetEventSlim mres)
{
var tl = new ThreadLocal<object>(true);
var t = Task.Run(() => tl.Value = new SetMreOnFinalize(mres));
t.Wait();
t = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.True(tl.Values.Count == 1, "RunThreadLocalTest8_Values: Expected other thread to have set value");
Assert.True(tl.Values[0] is SetMreOnFinalize, "RunThreadLocalTest8_Values: Expected other thread's value to be of the right type");
tl.Dispose();
object values;
Assert.Throws<ObjectDisposedException>(() => values = tl.Values);
}
[Fact]
public static void RunThreadLocalTest8_Values_NegativeCases()
{
// Test that Dispose works and that objects are released on dispose
{
var mres = new ManualResetEventSlim();
RunThreadLocalTest8Helper(mres);
SpinWait.SpinUntil(() =>
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
return mres.IsSet;
}, 1000);
Assert.True(mres.IsSet, "RunThreadLocalTest8_Values: Expected thread local to release the object and for it to be finalized");
}
// Test that Values property throws an exception unless true was passed into the constructor
{
ThreadLocal<int> t = new ThreadLocal<int>();
t.Value = 5;
Exception exceptionCaught = null;
try
{
var randomValue = t.Values.Count;
}
catch (Exception ex)
{
exceptionCaught = ex;
}
Assert.True(exceptionCaught != null, "RunThreadLocalTest8_Values: Expected Values to throw an InvalidOperationException. No exception was thrown.");
Assert.True(
exceptionCaught != null && exceptionCaught is InvalidOperationException,
"RunThreadLocalTest8_Values: Expected Values to throw an InvalidOperationException. Wrong exception was thrown: " + exceptionCaught.GetType().ToString());
}
}
[Fact]
public static void RunThreadLocalTest9_Uninitialized()
{
for (int iter = 0; iter < 10; iter++)
{
ThreadLocal<int> t1 = new ThreadLocal<int>();
t1.Value = 177;
ThreadLocal<int> t2 = new ThreadLocal<int>();
Assert.True(!t2.IsValueCreated, "RunThreadLocalTest9_Uninitialized: The ThreadLocal instance should have been uninitialized.");
}
}
private class SetMreOnFinalize
{
private ManualResetEventSlim _mres;
public SetMreOnFinalize(ManualResetEventSlim mres)
{
_mres = mres;
}
~SetMreOnFinalize()
{
_mres.Set();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace Lucene.Net.Search
{
using NUnit.Framework;
using Similarities;
using System.IO;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/// <summary>
/// Utility class for asserting expected hits in tests.
/// </summary>
public class CheckHits
{
/// <summary>
/// Some explains methods calculate their values though a slightly
/// different order of operations from the actual scoring method ...
/// this allows for a small amount of relative variation
/// </summary>
public static float EXPLAIN_SCORE_TOLERANCE_DELTA = 0.001f;
/// <summary>
/// In general we use a relative epsilon, but some tests do crazy things
/// like boost documents with 0, creating tiny tiny scores where the
/// relative difference is large but the absolute difference is tiny.
/// we ensure the the epsilon is always at least this big.
/// </summary>
public static float EXPLAIN_SCORE_TOLERANCE_MINIMUM = 1e-6f;
/// <summary>
/// Tests that all documents up to maxDoc which are *not* in the
/// expected result set, have an explanation which indicates that
/// the document does not match
/// </summary>
public static void CheckNoMatchExplanations(Query q, string defaultFieldName, IndexSearcher searcher, int[] results)
{
string d = q.ToString(defaultFieldName);
SortedSet<int?> ignore = new SortedSet<int?>();
for (int i = 0; i < results.Length; i++)
{
ignore.Add(Convert.ToInt32(results[i], CultureInfo.InvariantCulture));
}
int maxDoc = searcher.IndexReader.MaxDoc;
for (int doc = 0; doc < maxDoc; doc++)
{
if (ignore.Contains(Convert.ToInt32(doc, CultureInfo.InvariantCulture)))
{
continue;
}
Explanation exp = searcher.Explain(q, doc);
Assert.IsNotNull(exp, "Explanation of [[" + d + "]] for #" + doc + " is null");
Assert.IsFalse(exp.IsMatch, "Explanation of [[" + d + "]] for #" + doc + " doesn't indicate non-match: " + exp.ToString());
}
}
/// <summary>
/// Tests that a query matches the an expected set of documents using a
/// HitCollector.
///
/// <p>
/// Note that when using the HitCollector API, documents will be collected
/// if they "match" regardless of what their score is.
/// </p> </summary>
/// <param name="query"> the query to test </param>
/// <param name="searcher"> the searcher to test the query against </param>
/// <param name="defaultFieldName"> used for displaying the query in assertion messages </param>
/// <param name="results"> a list of documentIds that must match the query </param>
/// <param name="similarity">
/// LUCENENET specific
/// Removes dependency on <see cref="LuceneTestCase.ClassEnv.Similarity"/>
/// </param>
/// <seealso cref=#checkHits </seealso>
public static void CheckHitCollector(Random random, Query query, string defaultFieldName, IndexSearcher searcher, int[] results, Similarity similarity)
{
QueryUtils.Check(random, query, searcher, similarity);
Trace.TraceInformation("Checked");
SortedSet<int?> correct = new SortedSet<int?>();
for (int i = 0; i < results.Length; i++)
{
correct.Add(Convert.ToInt32(results[i], CultureInfo.InvariantCulture));
}
SortedSet<int?> actual = new SortedSet<int?>();
ICollector c = new SetCollector(actual);
searcher.Search(query, c);
Assert.AreEqual(correct, actual, "Simple: " + query.ToString(defaultFieldName));
for (int i = -1; i < 2; i++)
{
actual.Clear();
IndexSearcher s = QueryUtils.WrapUnderlyingReader(random, searcher, i, similarity);
s.Search(query, c);
Assert.AreEqual(correct, actual, "Wrap Reader " + i + ": " + query.ToString(defaultFieldName));
}
}
/// <summary>
/// Just collects document ids into a set.
/// </summary>
public class SetCollector : ICollector
{
internal readonly ISet<int?> Bag;
public SetCollector(ISet<int?> bag)
{
this.Bag = bag;
}
internal int @base = 0;
public virtual void SetScorer(Scorer scorer)
{
}
public virtual void Collect(int doc)
{
Bag.Add(Convert.ToInt32(doc + @base, CultureInfo.InvariantCulture));
}
public virtual void SetNextReader(AtomicReaderContext context)
{
@base = context.DocBase;
}
public virtual bool AcceptsDocsOutOfOrder
{
get { return true; }
}
}
/// <summary>
/// Tests that a query matches the an expected set of documents using Hits.
///
/// <p>
/// Note that when using the Hits API, documents will only be returned
/// if they have a positive normalized score.
/// </p> </summary>
/// <param name="query"> the query to test </param>
/// <param name="searcher"> the searcher to test the query against </param>
/// <param name="defaultFieldName"> used for displaing the query in assertion messages </param>
/// <param name="results"> a list of documentIds that must match the query </param>
/// <param name="similarity">
/// LUCENENET specific
/// Removes dependency on <see cref="LuceneTestCase.ClassEnv.Similarity"/>
/// </param>
/// <seealso cref= #checkHitCollector </seealso>
public static void DoCheckHits(Random random, Query query, string defaultFieldName, IndexSearcher searcher, int[] results, Similarity similarity)
{
ScoreDoc[] hits = searcher.Search(query, 1000).ScoreDocs;
SortedSet<int?> correct = new SortedSet<int?>();
for (int i = 0; i < results.Length; i++)
{
correct.Add(Convert.ToInt32(results[i], CultureInfo.InvariantCulture));
}
SortedSet<int?> actual = new SortedSet<int?>();
for (int i = 0; i < hits.Length; i++)
{
actual.Add(Convert.ToInt32(hits[i].Doc, CultureInfo.InvariantCulture));
}
Assert.AreEqual(correct, actual, query.ToString(defaultFieldName));
QueryUtils.Check(random, query, searcher, LuceneTestCase.Rarely(random), similarity);
}
/// <summary>
/// Tests that a Hits has an expected order of documents </summary>
public static void CheckDocIds(string mes, int[] results, ScoreDoc[] hits)
{
Assert.AreEqual(hits.Length, results.Length, mes + " nr of hits");
for (int i = 0; i < results.Length; i++)
{
Assert.AreEqual(results[i], hits[i].Doc, mes + " doc nrs for hit " + i);
}
}
/// <summary>
/// Tests that two queries have an expected order of documents,
/// and that the two queries have the same score values.
/// </summary>
public static void CheckHitsQuery(Query query, ScoreDoc[] hits1, ScoreDoc[] hits2, int[] results)
{
CheckDocIds("hits1", results, hits1);
CheckDocIds("hits2", results, hits2);
CheckEqual(query, hits1, hits2);
}
public static void CheckEqual(Query query, ScoreDoc[] hits1, ScoreDoc[] hits2)
{
const float scoreTolerance = 1.0e-6f;
if (hits1.Length != hits2.Length)
{
Assert.Fail("Unequal lengths: hits1=" + hits1.Length + ",hits2=" + hits2.Length);
}
for (int i = 0; i < hits1.Length; i++)
{
if (hits1[i].Doc != hits2[i].Doc)
{
Assert.Fail("Hit " + i + " docnumbers don't match\n" + Hits2str(hits1, hits2, 0, 0) + "for query:" + query.ToString());
}
if ((hits1[i].Doc != hits2[i].Doc) || Math.Abs(hits1[i].Score - hits2[i].Score) > scoreTolerance)
{
Assert.Fail("Hit " + i + ", doc nrs " + hits1[i].Doc + " and " + hits2[i].Doc + "\nunequal : " + hits1[i].Score + "\n and: " + hits2[i].Score + "\nfor query:" + query.ToString());
}
}
}
public static string Hits2str(ScoreDoc[] hits1, ScoreDoc[] hits2, int start, int end)
{
StringBuilder sb = new StringBuilder();
int len1 = hits1 == null ? 0 : hits1.Length;
int len2 = hits2 == null ? 0 : hits2.Length;
if (end <= 0)
{
end = Math.Max(len1, len2);
}
sb.Append("Hits length1=").Append(len1).Append("\tlength2=").Append(len2);
sb.Append('\n');
for (int i = start; i < end; i++)
{
sb.Append("hit=").Append(i).Append(':');
if (i < len1)
{
sb.Append(" doc").Append(hits1[i].Doc).Append('=').Append(hits1[i].Score);
}
else
{
sb.Append(" ");
}
sb.Append(",\t");
if (i < len2)
{
sb.Append(" doc").Append(hits2[i].Doc).Append('=').Append(hits2[i].Score);
}
sb.Append('\n');
}
return sb.ToString();
}
public static string TopdocsString(TopDocs docs, int start, int end)
{
StringBuilder sb = new StringBuilder();
sb.Append("TopDocs totalHits=").Append(docs.TotalHits).Append(" top=").Append(docs.ScoreDocs.Length).Append('\n');
if (end <= 0)
{
end = docs.ScoreDocs.Length;
}
else
{
end = Math.Min(end, docs.ScoreDocs.Length);
}
for (int i = start; i < end; i++)
{
sb.Append('\t');
sb.Append(i);
sb.Append(") doc=");
sb.Append(docs.ScoreDocs[i].Doc);
sb.Append("\tscore=");
sb.Append(docs.ScoreDocs[i].Score);
sb.Append('\n');
}
return sb.ToString();
}
/// <summary>
/// Asserts that the explanation value for every document matching a
/// query corresponds with the true score.
/// </summary>
/// <seealso cref= ExplanationAsserter </seealso>
/// <seealso cref= #checkExplanations(Query, String, IndexSearcher, boolean) for a
/// "deep" testing of the explanation details.
/// </seealso>
/// <param name="query"> the query to test </param>
/// <param name="searcher"> the searcher to test the query against </param>
/// <param name="defaultFieldName"> used for displaing the query in assertion messages </param>
public static void CheckExplanations(Query query, string defaultFieldName, IndexSearcher searcher)
{
CheckExplanations(query, defaultFieldName, searcher, false);
}
/// <summary>
/// Asserts that the explanation value for every document matching a
/// query corresponds with the true score. Optionally does "deep"
/// testing of the explanation details.
/// </summary>
/// <seealso cref= ExplanationAsserter </seealso>
/// <param name="query"> the query to test </param>
/// <param name="searcher"> the searcher to test the query against </param>
/// <param name="defaultFieldName"> used for displaing the query in assertion messages </param>
/// <param name="deep"> indicates whether a deep comparison of sub-Explanation details should be executed </param>
public static void CheckExplanations(Query query, string defaultFieldName, IndexSearcher searcher, bool deep)
{
searcher.Search(query, new ExplanationAsserter(query, defaultFieldName, searcher, deep));
}
/// <summary>
/// returns a reasonable epsilon for comparing two floats,
/// where minor differences are acceptable such as score vs. explain
/// </summary>
public static float ExplainToleranceDelta(float f1, float f2)
{
return Math.Max(EXPLAIN_SCORE_TOLERANCE_MINIMUM, Math.Max(Math.Abs(f1), Math.Abs(f2)) * EXPLAIN_SCORE_TOLERANCE_DELTA);
}
/// <summary>
/// Assert that an explanation has the expected score, and optionally that its
/// sub-details max/sum/factor match to that score.
/// </summary>
/// <param name="q"> String representation of the query for assertion messages </param>
/// <param name="doc"> Document ID for assertion messages </param>
/// <param name="score"> Real score value of doc with query q </param>
/// <param name="deep"> indicates whether a deep comparison of sub-Explanation details should be executed </param>
/// <param name="expl"> The Explanation to match against score </param>
public static void VerifyExplanation(string q, int doc, float score, bool deep, Explanation expl)
{
float value = expl.Value;
Assert.AreEqual(score, value, ExplainToleranceDelta(score, value), q + ": score(doc=" + doc + ")=" + score + " != explanationScore=" + value + " Explanation: " + expl);
if (!deep)
{
return;
}
Explanation[] detail = expl.GetDetails();
// TODO: can we improve this entire method? its really geared to work only with TF/IDF
if (expl.Description.EndsWith("computed from:", StringComparison.Ordinal))
{
return; // something more complicated.
}
if (detail != null)
{
if (detail.Length == 1)
{
// simple containment, unless its a freq of: (which lets a query explain how the freq is calculated),
// just verify contained expl has same score
if (!expl.Description.EndsWith("with freq of:", StringComparison.Ordinal))
{
VerifyExplanation(q, doc, score, deep, detail[0]);
}
}
else
{
// explanation must either:
// - end with one of: "product of:", "sum of:", "max of:", or
// - have "max plus <x> times others" (where <x> is float).
float x = 0;
string descr = CultureInfo.InvariantCulture.TextInfo.ToLower(expl.Description);
bool productOf = descr.EndsWith("product of:", StringComparison.Ordinal);
bool sumOf = descr.EndsWith("sum of:", StringComparison.Ordinal);
bool maxOf = descr.EndsWith("max of:", StringComparison.Ordinal);
bool maxTimesOthers = false;
if (!(productOf || sumOf || maxOf))
{
// maybe 'max plus x times others'
int k1 = descr.IndexOf("max plus ");
if (k1 >= 0)
{
k1 += "max plus ".Length;
int k2 = descr.IndexOf(" ", k1);
try
{
// LUCENENET NOTE: Using current culture here is intentional because
// we are parsing from text that was made using the current culture.
x = Convert.ToSingle(descr.Substring(k1, k2 - k1).Trim());
if (descr.Substring(k2).Trim().Equals("times others of:", StringComparison.Ordinal))
{
maxTimesOthers = true;
}
}
#pragma warning disable 168
catch (FormatException e)
#pragma warning restore 168
{
}
}
}
// TODO: this is a TERRIBLE assertion!!!!
Assert.IsTrue(productOf || sumOf || maxOf || maxTimesOthers, q + ": multi valued explanation description=\"" + descr + "\" must be 'max of plus x times others' or end with 'product of'" + " or 'sum of:' or 'max of:' - " + expl);
float sum = 0;
float product = 1;
float max = 0;
for (int i = 0; i < detail.Length; i++)
{
float dval = detail[i].Value;
VerifyExplanation(q, doc, dval, deep, detail[i]);
product *= dval;
sum += dval;
max = Math.Max(max, dval);
}
float combined = 0;
if (productOf)
{
combined = product;
}
else if (sumOf)
{
combined = sum;
}
else if (maxOf)
{
combined = max;
}
else if (maxTimesOthers)
{
combined = max + x * (sum - max);
}
else
{
Assert.IsTrue(false, "should never get here!");
}
Assert.AreEqual(combined, value, ExplainToleranceDelta(combined, value), q + ": actual subDetails combined==" + combined + " != value=" + value + " Explanation: " + expl);
}
}
}
/// <summary>
/// an IndexSearcher that implicitly checks hte explanation of every match
/// whenever it executes a search.
/// </summary>
/// <seealso cref= ExplanationAsserter </seealso>
public class ExplanationAssertingSearcher : IndexSearcher
{
public ExplanationAssertingSearcher(IndexReader r)
: base(r)
{
}
protected internal virtual void CheckExplanations(Query q)
{
base.Search(q, null, new ExplanationAsserter(q, null, this));
}
public override TopFieldDocs Search(Query query, Filter filter, int n, Sort sort)
{
CheckExplanations(query);
return base.Search(query, filter, n, sort);
}
public override void Search(Query query, ICollector results)
{
CheckExplanations(query);
base.Search(query, results);
}
public override void Search(Query query, Filter filter, ICollector results)
{
CheckExplanations(query);
base.Search(query, filter, results);
}
public override TopDocs Search(Query query, Filter filter, int n)
{
CheckExplanations(query);
return base.Search(query, filter, n);
}
}
/// <summary>
/// Asserts that the score explanation for every document matching a
/// query corresponds with the true score.
///
/// NOTE: this HitCollector should only be used with the Query and Searcher
/// specified at when it is constructed.
/// </summary>
/// <seealso cref= CheckHits#verifyExplanation </seealso>
public class ExplanationAsserter : ICollector
{
internal Query q;
internal IndexSearcher s;
internal string d;
internal bool Deep;
internal Scorer Scorer_Renamed;
internal int @base = 0;
/// <summary>
/// Constructs an instance which does shallow tests on the Explanation </summary>
public ExplanationAsserter(Query q, string defaultFieldName, IndexSearcher s)
: this(q, defaultFieldName, s, false)
{
}
public ExplanationAsserter(Query q, string defaultFieldName, IndexSearcher s, bool deep)
{
this.q = q;
this.s = s;
this.d = q.ToString(defaultFieldName);
this.Deep = deep;
}
public virtual void SetScorer(Scorer scorer)
{
this.Scorer_Renamed = scorer;
}
public virtual void Collect(int doc)
{
Explanation exp = null;
doc = doc + @base;
try
{
exp = s.Explain(q, doc);
}
catch (IOException e)
{
throw new Exception("exception in hitcollector of [[" + d + "]] for #" + doc, e);
}
Assert.IsNotNull(exp, "Explanation of [[" + d + "]] for #" + doc + " is null");
VerifyExplanation(d, doc, Scorer_Renamed.GetScore(), Deep, exp);
Assert.IsTrue(exp.IsMatch, "Explanation of [[" + d + "]] for #" + doc + " does not indicate match: " + exp.ToString());
}
public virtual void SetNextReader(AtomicReaderContext context)
{
@base = context.DocBase;
}
public virtual bool AcceptsDocsOutOfOrder
{
get { return true; }
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Data.Linq;
using System.Linq;
using System.Data.Linq.Mapping;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Reflection;
using Dg.Deblazer;
using Dg.Deblazer.Validation;
using Dg.Deblazer.CodeAnnotation;
using Dg.Deblazer.Api;
using Dg.Deblazer.Visitors;
using Dg.Deblazer.Cache;
using Dg.Deblazer.SqlGeneration;
using Deblazer.WideWorldImporter.DbLayer.Queries;
using Deblazer.WideWorldImporter.DbLayer.Wrappers;
using Dg.Deblazer.Read;
namespace Deblazer.WideWorldImporter.DbLayer
{
public partial class Application_DeliveryMethod : DbEntity, IId
{
private DbValue<System.Int32> _DeliveryMethodID = new DbValue<System.Int32>();
private DbValue<System.String> _DeliveryMethodName = new DbValue<System.String>();
private DbValue<System.Int32> _LastEditedBy = new DbValue<System.Int32>();
private DbValue<System.DateTime> _ValidFrom = new DbValue<System.DateTime>();
private DbValue<System.DateTime> _ValidTo = new DbValue<System.DateTime>();
private IDbEntityRef<Application_People> _Application_People;
private IDbEntitySet<Purchasing_PurchaseOrder> _Purchasing_PurchaseOrders;
private IDbEntitySet<Purchasing_Supplier> _Purchasing_Suppliers;
private IDbEntitySet<Sales_Customer> _Sales_Customers;
private IDbEntitySet<Sales_Invoice> _Sales_Invoices;
public int Id => DeliveryMethodID;
long ILongId.Id => DeliveryMethodID;
[Validate]
public System.Int32 DeliveryMethodID
{
get
{
return _DeliveryMethodID.Entity;
}
set
{
_DeliveryMethodID.Entity = value;
}
}
[StringColumn(50, false)]
[Validate]
public System.String DeliveryMethodName
{
get
{
return _DeliveryMethodName.Entity;
}
set
{
_DeliveryMethodName.Entity = value;
}
}
[Validate]
public System.Int32 LastEditedBy
{
get
{
return _LastEditedBy.Entity;
}
set
{
_LastEditedBy.Entity = value;
}
}
[StringColumn(7, false)]
[Validate]
public System.DateTime ValidFrom
{
get
{
return _ValidFrom.Entity;
}
set
{
_ValidFrom.Entity = value;
}
}
[StringColumn(7, false)]
[Validate]
public System.DateTime ValidTo
{
get
{
return _ValidTo.Entity;
}
set
{
_ValidTo.Entity = value;
}
}
[Validate]
public Application_People Application_People
{
get
{
Action<Application_People> beforeRightsCheckAction = e => e.Application_DeliveryMethods.Add(this);
if (_Application_People != null)
{
return _Application_People.GetEntity(beforeRightsCheckAction);
}
_Application_People = GetDbEntityRef(true, new[]{"[LastEditedBy]"}, new Func<long ? >[]{() => _LastEditedBy.Entity}, beforeRightsCheckAction);
return (Application_People != null) ? _Application_People.GetEntity(beforeRightsCheckAction) : null;
}
set
{
if (_Application_People == null)
{
_Application_People = new DbEntityRef<Application_People>(_db, true, new[]{"[LastEditedBy]"}, new Func<long ? >[]{() => _LastEditedBy.Entity}, _lazyLoadChildren, _getChildrenFromCache);
}
AssignDbEntity<Application_People, Application_DeliveryMethod>(value, value == null ? new long ? [0] : new long ? []{(long ? )value.PersonID}, _Application_People, new long ? []{_LastEditedBy.Entity}, new Action<long ? >[]{x => LastEditedBy = (int ? )x ?? default (int)}, x => x.Application_DeliveryMethods, null, LastEditedByChanged);
}
}
void LastEditedByChanged(object sender, EventArgs eventArgs)
{
if (sender is Application_People)
_LastEditedBy.Entity = (int)((Application_People)sender).Id;
}
[Validate]
public IDbEntitySet<Purchasing_PurchaseOrder> Purchasing_PurchaseOrders
{
get
{
if (_Purchasing_PurchaseOrders == null)
{
if (_getChildrenFromCache)
{
_Purchasing_PurchaseOrders = new DbEntitySetCached<Application_DeliveryMethod, Purchasing_PurchaseOrder>(() => _DeliveryMethodID.Entity);
}
}
else
_Purchasing_PurchaseOrders = new DbEntitySet<Purchasing_PurchaseOrder>(_db, false, new Func<long ? >[]{() => _DeliveryMethodID.Entity}, new[]{"[DeliveryMethodID]"}, (member, root) => member.Application_DeliveryMethod = root as Application_DeliveryMethod, this, _lazyLoadChildren, e => e.Application_DeliveryMethod = this, e =>
{
var x = e.Application_DeliveryMethod;
e.Application_DeliveryMethod = null;
new UpdateSetVisitor(true, new[]{"DeliveryMethodID"}, false).Process(x);
}
);
return _Purchasing_PurchaseOrders;
}
}
[Validate]
public IDbEntitySet<Purchasing_Supplier> Purchasing_Suppliers
{
get
{
if (_Purchasing_Suppliers == null)
{
if (_getChildrenFromCache)
{
_Purchasing_Suppliers = new DbEntitySetCached<Application_DeliveryMethod, Purchasing_Supplier>(() => _DeliveryMethodID.Entity);
}
}
else
_Purchasing_Suppliers = new DbEntitySet<Purchasing_Supplier>(_db, false, new Func<long ? >[]{() => _DeliveryMethodID.Entity}, new[]{"[DeliveryMethodID]"}, (member, root) => member.Application_DeliveryMethod = root as Application_DeliveryMethod, this, _lazyLoadChildren, e => e.Application_DeliveryMethod = this, e =>
{
var x = e.Application_DeliveryMethod;
e.Application_DeliveryMethod = null;
new UpdateSetVisitor(true, new[]{"DeliveryMethodID"}, false).Process(x);
}
);
return _Purchasing_Suppliers;
}
}
[Validate]
public IDbEntitySet<Sales_Customer> Sales_Customers
{
get
{
if (_Sales_Customers == null)
{
if (_getChildrenFromCache)
{
_Sales_Customers = new DbEntitySetCached<Application_DeliveryMethod, Sales_Customer>(() => _DeliveryMethodID.Entity);
}
}
else
_Sales_Customers = new DbEntitySet<Sales_Customer>(_db, false, new Func<long ? >[]{() => _DeliveryMethodID.Entity}, new[]{"[DeliveryMethodID]"}, (member, root) => member.Application_DeliveryMethod = root as Application_DeliveryMethod, this, _lazyLoadChildren, e => e.Application_DeliveryMethod = this, e =>
{
var x = e.Application_DeliveryMethod;
e.Application_DeliveryMethod = null;
new UpdateSetVisitor(true, new[]{"DeliveryMethodID"}, false).Process(x);
}
);
return _Sales_Customers;
}
}
[Validate]
public IDbEntitySet<Sales_Invoice> Sales_Invoices
{
get
{
if (_Sales_Invoices == null)
{
if (_getChildrenFromCache)
{
_Sales_Invoices = new DbEntitySetCached<Application_DeliveryMethod, Sales_Invoice>(() => _DeliveryMethodID.Entity);
}
}
else
_Sales_Invoices = new DbEntitySet<Sales_Invoice>(_db, false, new Func<long ? >[]{() => _DeliveryMethodID.Entity}, new[]{"[DeliveryMethodID]"}, (member, root) => member.Application_DeliveryMethod = root as Application_DeliveryMethod, this, _lazyLoadChildren, e => e.Application_DeliveryMethod = this, e =>
{
var x = e.Application_DeliveryMethod;
e.Application_DeliveryMethod = null;
new UpdateSetVisitor(true, new[]{"DeliveryMethodID"}, false).Process(x);
}
);
return _Sales_Invoices;
}
}
protected override void ModifyInternalState(FillVisitor visitor)
{
SendIdChanging();
_DeliveryMethodID.Load(visitor.GetInt32());
SendIdChanged();
_DeliveryMethodName.Load(visitor.GetValue<System.String>());
_LastEditedBy.Load(visitor.GetInt32());
_ValidFrom.Load(visitor.GetDateTime());
_ValidTo.Load(visitor.GetDateTime());
this._db = visitor.Db;
isLoaded = true;
}
protected sealed override void CheckProperties(IUpdateVisitor visitor)
{
_DeliveryMethodID.Welcome(visitor, "DeliveryMethodID", "Int NOT NULL", false);
_DeliveryMethodName.Welcome(visitor, "DeliveryMethodName", "NVarChar(50) NOT NULL", false);
_LastEditedBy.Welcome(visitor, "LastEditedBy", "Int NOT NULL", false);
_ValidFrom.Welcome(visitor, "ValidFrom", "DateTime2(7) NOT NULL", false);
_ValidTo.Welcome(visitor, "ValidTo", "DateTime2(7) NOT NULL", false);
}
protected override void HandleChildren(DbEntityVisitorBase visitor)
{
visitor.ProcessAssociation(this, _Application_People);
visitor.ProcessAssociation(this, _Purchasing_PurchaseOrders);
visitor.ProcessAssociation(this, _Purchasing_Suppliers);
visitor.ProcessAssociation(this, _Sales_Customers);
visitor.ProcessAssociation(this, _Sales_Invoices);
}
}
public static class Db_Application_DeliveryMethodQueryGetterExtensions
{
public static Application_DeliveryMethodTableQuery<Application_DeliveryMethod> Application_DeliveryMethods(this IDb db)
{
var query = new Application_DeliveryMethodTableQuery<Application_DeliveryMethod>(db as IDb);
return query;
}
}
}
namespace Deblazer.WideWorldImporter.DbLayer.Queries
{
public class Application_DeliveryMethodQuery<K, T> : Query<K, T, Application_DeliveryMethod, Application_DeliveryMethodWrapper, Application_DeliveryMethodQuery<K, T>> where K : QueryBase where T : DbEntity, ILongId
{
public Application_DeliveryMethodQuery(IDb db): base (db)
{
}
protected sealed override Application_DeliveryMethodWrapper GetWrapper()
{
return Application_DeliveryMethodWrapper.Instance;
}
public Application_PeopleQuery<Application_DeliveryMethodQuery<K, T>, T> JoinApplication_People(JoinType joinType = JoinType.Inner, bool preloadEntities = false)
{
var joinedQuery = new Application_PeopleQuery<Application_DeliveryMethodQuery<K, T>, T>(Db);
return Join(joinedQuery, string.Concat(joinType.GetJoinString(), " [Application].[People] AS {1} {0} ON", "{2}.[LastEditedBy] = {1}.[PersonID]"), o => ((Application_DeliveryMethod)o)?.Application_People, (e, fv, ppe) =>
{
var child = (Application_People)ppe(QueryHelpers.Fill<Application_People>(null, fv));
if (e != null)
{
((Application_DeliveryMethod)e).Application_People = child;
}
return child;
}
, typeof (Application_People), preloadEntities);
}
public Purchasing_PurchaseOrderQuery<Application_DeliveryMethodQuery<K, T>, T> JoinPurchasing_PurchaseOrders(JoinType joinType = JoinType.Inner, bool attach = false)
{
var joinedQuery = new Purchasing_PurchaseOrderQuery<Application_DeliveryMethodQuery<K, T>, T>(Db);
return JoinSet(() => new Purchasing_PurchaseOrderTableQuery<Purchasing_PurchaseOrder>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Purchasing].[PurchaseOrders] AS {1} {0} ON", "{2}.[DeliveryMethodID] = {1}.[DeliveryMethodID]"), (p, ids) => ((Purchasing_PurchaseOrderWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Application_DeliveryMethod)o).Purchasing_PurchaseOrders.Attach(v.Cast<Purchasing_PurchaseOrder>()), p => (long)((Purchasing_PurchaseOrder)p).DeliveryMethodID, attach);
}
public Purchasing_SupplierQuery<Application_DeliveryMethodQuery<K, T>, T> JoinPurchasing_Suppliers(JoinType joinType = JoinType.Inner, bool attach = false)
{
var joinedQuery = new Purchasing_SupplierQuery<Application_DeliveryMethodQuery<K, T>, T>(Db);
return JoinSet(() => new Purchasing_SupplierTableQuery<Purchasing_Supplier>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Purchasing].[Suppliers] AS {1} {0} ON", "{2}.[DeliveryMethodID] = {1}.[DeliveryMethodID]"), (p, ids) => ((Purchasing_SupplierWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Application_DeliveryMethod)o).Purchasing_Suppliers.Attach(v.Cast<Purchasing_Supplier>()), p => (long)((Purchasing_Supplier)p).DeliveryMethodID, attach);
}
public Sales_CustomerQuery<Application_DeliveryMethodQuery<K, T>, T> JoinSales_Customers(JoinType joinType = JoinType.Inner, bool attach = false)
{
var joinedQuery = new Sales_CustomerQuery<Application_DeliveryMethodQuery<K, T>, T>(Db);
return JoinSet(() => new Sales_CustomerTableQuery<Sales_Customer>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Sales].[Customers] AS {1} {0} ON", "{2}.[DeliveryMethodID] = {1}.[DeliveryMethodID]"), (p, ids) => ((Sales_CustomerWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Application_DeliveryMethod)o).Sales_Customers.Attach(v.Cast<Sales_Customer>()), p => (long)((Sales_Customer)p).DeliveryMethodID, attach);
}
public Sales_InvoiceQuery<Application_DeliveryMethodQuery<K, T>, T> JoinSales_Invoices(JoinType joinType = JoinType.Inner, bool attach = false)
{
var joinedQuery = new Sales_InvoiceQuery<Application_DeliveryMethodQuery<K, T>, T>(Db);
return JoinSet(() => new Sales_InvoiceTableQuery<Sales_Invoice>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Sales].[Invoices] AS {1} {0} ON", "{2}.[DeliveryMethodID] = {1}.[DeliveryMethodID]"), (p, ids) => ((Sales_InvoiceWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Application_DeliveryMethod)o).Sales_Invoices.Attach(v.Cast<Sales_Invoice>()), p => (long)((Sales_Invoice)p).DeliveryMethodID, attach);
}
}
public class Application_DeliveryMethodTableQuery<T> : Application_DeliveryMethodQuery<Application_DeliveryMethodTableQuery<T>, T> where T : DbEntity, ILongId
{
public Application_DeliveryMethodTableQuery(IDb db): base (db)
{
}
}
}
namespace Deblazer.WideWorldImporter.DbLayer.Helpers
{
public class Application_DeliveryMethodHelper : QueryHelper<Application_DeliveryMethod>, IHelper<Application_DeliveryMethod>
{
string[] columnsInSelectStatement = new[]{"{0}.DeliveryMethodID", "{0}.DeliveryMethodName", "{0}.LastEditedBy", "{0}.ValidFrom", "{0}.ValidTo"};
public sealed override string[] ColumnsInSelectStatement => columnsInSelectStatement;
string[] columnsInInsertStatement = new[]{"{0}.DeliveryMethodID", "{0}.DeliveryMethodName", "{0}.LastEditedBy", "{0}.ValidFrom", "{0}.ValidTo"};
public sealed override string[] ColumnsInInsertStatement => columnsInInsertStatement;
private static readonly string createTempTableCommand = "CREATE TABLE #Application_DeliveryMethod ([DeliveryMethodID] Int NOT NULL,[DeliveryMethodName] NVarChar(50) NOT NULL,[LastEditedBy] Int NOT NULL,[ValidFrom] DateTime2(7) NOT NULL,[ValidTo] DateTime2(7) NOT NULL, [RowIndexForSqlBulkCopy] INT NOT NULL)";
public sealed override string CreateTempTableCommand => createTempTableCommand;
public sealed override string FullTableName => "[Application].[DeliveryMethods]";
public sealed override bool IsForeignKeyTo(Type other)
{
return other == typeof (Purchasing_PurchaseOrder) || other == typeof (Purchasing_Supplier) || other == typeof (Sales_Customer) || other == typeof (Sales_Invoice);
}
private const string insertCommand = "INSERT INTO [Application].[DeliveryMethods] ([{TableName = \"Application].[DeliveryMethods\";}].[DeliveryMethodID], [{TableName = \"Application].[DeliveryMethods\";}].[DeliveryMethodName], [{TableName = \"Application].[DeliveryMethods\";}].[LastEditedBy], [{TableName = \"Application].[DeliveryMethods\";}].[ValidFrom], [{TableName = \"Application].[DeliveryMethods\";}].[ValidTo]) VALUES ([@DeliveryMethodID],[@DeliveryMethodName],[@LastEditedBy],[@ValidFrom],[@ValidTo]); SELECT SCOPE_IDENTITY()";
public sealed override void FillInsertCommand(SqlCommand sqlCommand, Application_DeliveryMethod _Application_DeliveryMethod)
{
sqlCommand.CommandText = insertCommand;
sqlCommand.Parameters.AddWithValue("@DeliveryMethodID", _Application_DeliveryMethod.DeliveryMethodID);
sqlCommand.Parameters.AddWithValue("@DeliveryMethodName", _Application_DeliveryMethod.DeliveryMethodName ?? (object)DBNull.Value);
sqlCommand.Parameters.AddWithValue("@LastEditedBy", _Application_DeliveryMethod.LastEditedBy);
sqlCommand.Parameters.AddWithValue("@ValidFrom", _Application_DeliveryMethod.ValidFrom);
sqlCommand.Parameters.AddWithValue("@ValidTo", _Application_DeliveryMethod.ValidTo);
}
public sealed override void ExecuteInsertCommand(SqlCommand sqlCommand, Application_DeliveryMethod _Application_DeliveryMethod)
{
using (var sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.SequentialAccess))
{
sqlDataReader.Read();
_Application_DeliveryMethod.DeliveryMethodID = Convert.ToInt32(sqlDataReader.GetValue(0));
}
}
private static Application_DeliveryMethodWrapper _wrapper = Application_DeliveryMethodWrapper.Instance;
public QueryWrapper Wrapper
{
get
{
return _wrapper;
}
}
}
}
namespace Deblazer.WideWorldImporter.DbLayer.Wrappers
{
public class Application_DeliveryMethodWrapper : QueryWrapper<Application_DeliveryMethod>
{
public readonly QueryElMemberId<Application_People> LastEditedBy = new QueryElMemberId<Application_People>("LastEditedBy");
public readonly QueryElMember<System.String> DeliveryMethodName = new QueryElMember<System.String>("DeliveryMethodName");
public readonly QueryElMemberStruct<System.DateTime> ValidFrom = new QueryElMemberStruct<System.DateTime>("ValidFrom");
public readonly QueryElMemberStruct<System.DateTime> ValidTo = new QueryElMemberStruct<System.DateTime>("ValidTo");
public static readonly Application_DeliveryMethodWrapper Instance = new Application_DeliveryMethodWrapper();
private Application_DeliveryMethodWrapper(): base ("[Application].[DeliveryMethods]", "Application_DeliveryMethod")
{
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using log4net;
namespace OpenSim.Region.Physics.Manager
{
/// <summary>
/// Description of MyClass.
/// </summary>
public class PhysicsPluginManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<string, IPhysicsPlugin> _PhysPlugins = new Dictionary<string, IPhysicsPlugin>();
private Dictionary<string, IMeshingPlugin> _MeshPlugins = new Dictionary<string, IMeshingPlugin>();
/// <summary>
/// Constructor.
/// </summary>
public PhysicsPluginManager()
{
// Load "plugins", that are hard coded and not existing in form of an external lib, and hence always
// available
IMeshingPlugin plugHard;
plugHard = new ZeroMesherPlugin();
_MeshPlugins.Add(plugHard.GetName(), plugHard);
m_log.Info("[PHYSICS]: Added meshing engine: " + plugHard.GetName());
}
/// <summary>
/// Get a physics scene for the given physics engine and mesher.
/// </summary>
/// <param name="physEngineName"></param>
/// <param name="meshEngineName"></param>
/// <param name="config"></param>
/// <returns></returns>
public PhysicsScene GetPhysicsScene(string physEngineName, string meshEngineName, IConfigSource config, string regionName)
{
if (String.IsNullOrEmpty(physEngineName))
{
return PhysicsScene.Null;
}
if (String.IsNullOrEmpty(meshEngineName))
{
return PhysicsScene.Null;
}
IMesher meshEngine = null;
if (_MeshPlugins.ContainsKey(meshEngineName))
{
m_log.Info("[PHYSICS]: creating meshing engine " + meshEngineName);
meshEngine = _MeshPlugins[meshEngineName].GetMesher();
}
else
{
m_log.WarnFormat("[PHYSICS]: couldn't find meshingEngine: {0}", meshEngineName);
throw new ArgumentException(String.Format("couldn't find meshingEngine: {0}", meshEngineName));
}
if (_PhysPlugins.ContainsKey(physEngineName))
{
m_log.Info("[PHYSICS]: creating " + physEngineName);
PhysicsScene result = _PhysPlugins[physEngineName].GetScene(regionName);
result.Initialise(meshEngine, config);
return result;
}
else
{
m_log.WarnFormat("[PHYSICS]: couldn't find physicsEngine: {0}", physEngineName);
throw new ArgumentException(String.Format("couldn't find physicsEngine: {0}", physEngineName));
}
}
/// <summary>
/// Load all plugins in assemblies at the given path
/// </summary>
/// <param name="pluginsPath"></param>
public void LoadPluginsFromAssemblies(string assembliesPath)
{
// Walk all assemblies (DLLs effectively) and see if they are home
// of a plugin that is of interest for us
string[] pluginFiles = Directory.GetFiles(assembliesPath, "*.dll");
for (int i = 0; i < pluginFiles.Length; i++)
{
LoadPluginsFromAssembly(pluginFiles[i]);
}
}
/// <summary>
/// Load plugins from an assembly at the given path
/// </summary>
/// <param name="assemblyPath"></param>
public void LoadPluginsFromAssembly(string assemblyPath)
{
// TODO / NOTE
// The assembly named 'OpenSim.Region.Physics.BasicPhysicsPlugin' was loaded from
// 'file:///C:/OpenSim/trunk2/bin/Physics/OpenSim.Region.Physics.BasicPhysicsPlugin.dll'
// using the LoadFrom context. The use of this context can result in unexpected behavior
// for serialization, casting and dependency resolution. In almost all cases, it is recommended
// that the LoadFrom context be avoided. This can be done by installing assemblies in the
// Global Assembly Cache or in the ApplicationBase directory and using Assembly.
// Load when explicitly loading assemblies.
Assembly pluginAssembly = null;
Type[] types = null;
try
{
pluginAssembly = Assembly.LoadFrom(assemblyPath);
}
catch (Exception ex)
{
m_log.Error("[PHYSICS]: Failed to load plugin from " + assemblyPath, ex);
}
if (pluginAssembly != null)
{
try
{
types = pluginAssembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
m_log.Error("[PHYSICS]: Failed to enumerate types in plugin from " + assemblyPath + ": " +
ex.LoaderExceptions[0].Message, ex);
}
catch (Exception ex)
{
m_log.Error("[PHYSICS]: Failed to enumerate types in plugin from " + assemblyPath, ex);
}
if (types != null)
{
foreach (Type pluginType in types)
{
if (pluginType.IsPublic)
{
if (!pluginType.IsAbstract)
{
Type physTypeInterface = pluginType.GetInterface("IPhysicsPlugin", true);
if (physTypeInterface != null)
{
IPhysicsPlugin plug =
(IPhysicsPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
plug.Init();
if (!_PhysPlugins.ContainsKey(plug.GetName()))
{
_PhysPlugins.Add(plug.GetName(), plug);
m_log.Info("[PHYSICS]: Added physics engine: " + plug.GetName());
}
}
Type meshTypeInterface = pluginType.GetInterface("IMeshingPlugin", true);
if (meshTypeInterface != null)
{
IMeshingPlugin plug =
(IMeshingPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
if (!_MeshPlugins.ContainsKey(plug.GetName()))
{
_MeshPlugins.Add(plug.GetName(), plug);
m_log.Info("[PHYSICS]: Added meshing engine: " + plug.GetName());
}
}
physTypeInterface = null;
meshTypeInterface = null;
}
}
}
}
}
pluginAssembly = null;
}
//---
public static void PhysicsPluginMessage(string message, bool isWarning)
{
if (isWarning)
{
m_log.Warn("[PHYSICS]: " + message);
}
else
{
m_log.Info("[PHYSICS]: " + message);
}
}
//---
}
public interface IPhysicsPlugin
{
bool Init();
PhysicsScene GetScene(String sceneIdentifier);
string GetName();
void Dispose();
}
public interface IMeshingPlugin
{
string GetName();
IMesher GetMesher();
}
}
| |
#region License
//
// Command Line Library: CommandLineText.cs
//
// Author:
// Giacomo Stelluti Scala (gsscoder@gmail.com)
// Contributor(s):
// Steven Evans
//
// Copyright (C) 2005 - 2012 Giacomo Stelluti Scala
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#endregion
#region Using Directives
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
#endregion
namespace CommandLine.Text
{
#region *SentenceBuilder
/// <summary>
/// Models an abstract sentence builder.
/// </summary>
public abstract class BaseSentenceBuilder
{
/// <summary>
/// Creates the built in sentence builder.
/// </summary>
/// <returns>
/// The built in sentence builder.
/// </returns>
public static BaseSentenceBuilder CreateBuiltIn()
{
return new EnglishSentenceBuilder();
}
/// <summary>
/// Gets a string containing word 'option'.
/// </summary>
/// <value>
/// The word 'option'.
/// </value>
public abstract string OptionWord { get; }
/// <summary>
/// Gets a string containing the word 'and'.
/// </summary>
/// <value>
/// The word 'and'.
/// </value>
public abstract string AndWord { get; }
/// <summary>
/// Gets a string containing the sentence 'required option missing'.
/// </summary>
/// <value>
/// The sentence 'required option missing'.
/// </value>
public abstract string RequiredOptionMissingText { get; }
/// <summary>
/// Gets a string containing the sentence 'violates format'.
/// </summary>
/// <value>
/// The sentence 'violates format'.
/// </value>
public abstract string ViolatesFormatText { get; }
/// <summary>
/// Gets a string containing the sentence 'violates mutual exclusiveness'.
/// </summary>
/// <value>
/// The sentence 'violates mutual exclusiveness'.
/// </value>
public abstract string ViolatesMutualExclusivenessText { get; }
/// <summary>
/// Gets a string containing the error heading text.
/// </summary>
/// <value>
/// The error heading text.
/// </value>
public abstract string ErrorsHeadingText { get; }
}
/// <summary>
/// Models an english sentence builder, currently the default one.
/// </summary>
public class EnglishSentenceBuilder : BaseSentenceBuilder
{
/// <summary>
/// Gets a string containing word 'option' in english.
/// </summary>
/// <value>
/// The word 'option' in english.
/// </value>
public override string OptionWord { get { return "option"; } }
/// <summary>
/// Gets a string containing the word 'and' in english.
/// </summary>
/// <value>
/// The word 'and' in english.
/// </value>
public override string AndWord { get { return "and"; } }
/// <summary>
/// Gets a string containing the sentence 'required option missing' in english.
/// </summary>
/// <value>
/// The sentence 'required option missing' in english.
/// </value>
public override string RequiredOptionMissingText { get { return "required option is missing"; } }
/// <summary>
/// Gets a string containing the sentence 'violates format' in english.
/// </summary>
/// <value>
/// The sentence 'violates format' in english.
/// </value>
public override string ViolatesFormatText { get { return "violates format"; } }
/// <summary>
/// Gets a string containing the sentence 'violates mutual exclusiveness' in english.
/// </summary>
/// <value>
/// The sentence 'violates mutual exclusiveness' in english.
/// </value>
public override string ViolatesMutualExclusivenessText { get { return "violates mutual exclusiveness"; } }
/// <summary>
/// Gets a string containing the error heading text in english.
/// </summary>
/// <value>
/// The error heading text in english.
/// </value>
public override string ErrorsHeadingText { get { return "ERROR(S):"; } }
}
#endregion
#region Secondary Helpers
/// <summary>
/// Models the copyright informations part of an help text.
/// You can assign it where you assign any <see cref="System.String"/> instance.
/// </summary>
public class CopyrightInfo
{
private readonly bool _isSymbolUpper;
private readonly int[] _years;
private readonly string _author;
private static readonly string _defaultCopyrightWord = "Copyright";
private static readonly string _symbolLower = "(c)";
private static readonly string _symbolUpper = "(C)";
private StringBuilder _builder;
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.CopyrightInfo"/> class.
/// </summary>
protected CopyrightInfo()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.CopyrightInfo"/> class
/// specifying author and year.
/// </summary>
/// <param name="author">The company or person holding the copyright.</param>
/// <param name="year">The year of coverage of copyright.</param>
/// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="author"/> is null or empty string.</exception>
public CopyrightInfo(string author, int year)
: this(true, author, new int[] { year })
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.CopyrightInfo"/> class
/// specifying author and years.
/// </summary>
/// <param name="author">The company or person holding the copyright.</param>
/// <param name="years">The years of coverage of copyright.</param>
/// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="author"/> is null or empty string.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">Thrown when parameter <paramref name="years"/> is not supplied.</exception>
public CopyrightInfo(string author, params int[] years)
: this(true, author, years)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.CopyrightInfo"/> class
/// specifying symbol case, author and years.
/// </summary>
/// <param name="isSymbolUpper">The case of the copyright symbol.</param>
/// <param name="author">The company or person holding the copyright.</param>
/// <param name="years">The years of coverage of copyright.</param>
/// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="author"/> is null or empty string.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">Thrown when parameter <paramref name="years"/> is not supplied.</exception>
public CopyrightInfo(bool isSymbolUpper, string author, params int[] years)
{
Assumes.NotNullOrEmpty(author, "author");
Assumes.NotZeroLength(years, "years");
const int extraLength = 10;
_isSymbolUpper = isSymbolUpper;
_author = author;
_years = years;
_builder = new StringBuilder
(CopyrightWord.Length + author.Length + (4 * years.Length) + extraLength);
}
/// <summary>
/// Returns the copyright informations as a <see cref="System.String"/>.
/// </summary>
/// <returns>The <see cref="System.String"/> that contains the copyright informations.</returns>
public override string ToString()
{
_builder.Append(CopyrightWord);
_builder.Append(' ');
if (_isSymbolUpper)
_builder.Append(_symbolUpper);
else
_builder.Append(_symbolLower);
_builder.Append(' ');
_builder.Append(FormatYears(_years));
_builder.Append(' ');
_builder.Append(_author);
return _builder.ToString();
}
/// <summary>
/// Converts the copyright informations to a <see cref="System.String"/>.
/// </summary>
/// <param name="info">This <see cref="CommandLine.Text.CopyrightInfo"/> instance.</param>
/// <returns>The <see cref="System.String"/> that contains the copyright informations.</returns>
public static implicit operator string(CopyrightInfo info)
{
return info.ToString();
}
/// <summary>
/// When overridden in a derived class, allows to specify a different copyright word.
/// </summary>
protected virtual string CopyrightWord
{
get { return _defaultCopyrightWord; }
}
/// <summary>
/// When overridden in a derived class, allows to specify a new algorithm to render copyright years
/// as a <see cref="System.String"/> instance.
/// </summary>
/// <param name="years">A <see cref="System.Int32"/> array of years.</param>
/// <returns>A <see cref="System.String"/> instance with copyright years.</returns>
protected virtual string FormatYears(int[] years)
{
if (years.Length == 1)
return years[0].ToString(CultureInfo.InvariantCulture);
var yearsPart = new StringBuilder(years.Length * 6);
for (int i = 0; i < years.Length; i++)
{
yearsPart.Append(years[i].ToString(CultureInfo.InvariantCulture));
int next = i + 1;
if (next < years.Length)
{
if (years[next] - years[i] > 1)
yearsPart.Append(" - ");
else
yearsPart.Append(", ");
}
}
return yearsPart.ToString();
}
}
/// <summary>
/// Models the heading informations part of an help text.
/// You can assign it where you assign any <see cref="System.String"/> instance.
/// </summary>
public class HeadingInfo
{
private readonly string _programName;
private readonly string _version;
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HeadingInfo"/> class
/// specifying program name.
/// </summary>
/// <param name="programName">The name of the program.</param>
/// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="programName"/> is null or empty string.</exception>
public HeadingInfo(string programName)
: this(programName, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HeadingInfo"/> class
/// specifying program name and version.
/// </summary>
/// <param name="programName">The name of the program.</param>
/// <param name="version">The version of the program.</param>
/// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="programName"/> is null or empty string.</exception>
public HeadingInfo(string programName, string version)
{
Assumes.NotNullOrEmpty(programName, "programName");
_programName = programName;
_version = version;
}
/// <summary>
/// Returns the heading informations as a <see cref="System.String"/>.
/// </summary>
/// <returns>The <see cref="System.String"/> that contains the heading informations.</returns>
public override string ToString()
{
bool isVersionNull = string.IsNullOrEmpty(_version);
var builder = new StringBuilder(_programName.Length +
(!isVersionNull ? _version.Length + 1 : 0)
);
builder.Append(_programName);
if (!isVersionNull)
{
builder.Append(' ');
builder.Append(_version);
}
return builder.ToString();
}
/// <summary>
/// Converts the heading informations to a <see cref="System.String"/>.
/// </summary>
/// <param name="info">This <see cref="CommandLine.Text.HeadingInfo"/> instance.</param>
/// <returns>The <see cref="System.String"/> that contains the heading informations.</returns>
public static implicit operator string(HeadingInfo info)
{
return info.ToString();
}
/// <summary>
/// Writes out a string and a new line using the program name specified in the constructor
/// and <paramref name="message"/> parameter.
/// </summary>
/// <param name="message">The <see cref="System.String"/> message to write.</param>
/// <param name="writer">The target <see cref="System.IO.TextWriter"/> derived type.</param>
/// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="message"/> is null or empty string.</exception>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="writer"/> is null.</exception>
public void WriteMessage(string message, TextWriter writer)
{
Assumes.NotNullOrEmpty(message, "message");
Assumes.NotNull(writer, "writer");
var builder = new StringBuilder(_programName.Length + message.Length + 2);
builder.Append(_programName);
builder.Append(": ");
builder.Append(message);
writer.WriteLine(builder.ToString());
}
/// <summary>
/// Writes out a string and a new line using the program name specified in the constructor
/// and <paramref name="message"/> parameter to standard output stream.
/// </summary>
/// <param name="message">The <see cref="System.String"/> message to write.</param>
/// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="message"/> is null or empty string.</exception>
public void WriteMessage(string message)
{
WriteMessage(message, Console.Out);
}
/// <summary>
/// Writes out a string and a new line using the program name specified in the constructor
/// and <paramref name="message"/> parameter to standard error stream.
/// </summary>
/// <param name="message">The <see cref="System.String"/> message to write.</param>
/// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="message"/> is null or empty string.</exception>
public void WriteError(string message)
{
WriteMessage(message, Console.Error);
}
}
/*
internal static class AssemblyVersionAttributeUtil
{
public static string GetInformationalVersion(this AssemblyVersionAttribute attr)
{
var parts = attr.Version.Split('.');
if (parts.Length > 2)
{
return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", parts[0], parts[1]);
}
return attr.Version;
}
}
*/
/*
internal static class StringBuilderUtil
{
public static void AppendLineIfNotNullOrEmpty(this StringBuilder bldr, string value)
{
if (!string.IsNullOrEmpty(value))
{
bldr.AppendLine(value);
}
}
}
*/
#endregion
#region Attributes
public abstract class MultiLineTextAttribute : Attribute
{
//string _fullText;
string _line1;
string _line2;
string _line3;
string _line4;
string _line5;
//public MultiLineTextAttribute(object fullText)
//{
// var realFullText = fullText as string;
// Assumes.NotNullOrEmpty(realFullText, "fullText");
// _fullText = realFullText;
//}
public MultiLineTextAttribute(string line1)
{
Assumes.NotNullOrEmpty(line1, "line1");
_line1 = line1;
}
public MultiLineTextAttribute(string line1, string line2)
: this(line1)
{
Assumes.NotNullOrEmpty(line2, "line2");
_line2 = line2;
}
public MultiLineTextAttribute(string line1, string line2, string line3)
: this(line1, line2)
{
Assumes.NotNullOrEmpty(line3, "line3");
_line3 = line3;
}
public MultiLineTextAttribute(string line1, string line2, string line3, string line4)
: this(line1, line2, line3)
{
Assumes.NotNullOrEmpty(line4, "line4");
_line4 = line4;
}
public MultiLineTextAttribute(string line1, string line2, string line3, string line4, string line5)
: this(line1, line2, line3, line4)
{
Assumes.NotNullOrEmpty(line5, "line5");
_line5 = line5;
}
/*
public string FullText
{
get
{
if (string.IsNullOrEmpty(_fullText))
{
if (!string.IsNullOrEmpty(_line1))
{
var builder = new StringBuilder(_line1);
builder.AppendLineIfNotNullOrEmpty(_line2);
builder.AppendLineIfNotNullOrEmpty(_line3);
builder.AppendLineIfNotNullOrEmpty(_line4);
builder.AppendLineIfNotNullOrEmpty(_line5);
_fullText = builder.ToString();
}
}
return _fullText;
}
}
*/
internal void AddToHelpText(HelpText helpText, bool before)
{
if (before)
{
if (!string.IsNullOrEmpty(_line1)) helpText.AddPreOptionsLine(_line1);
if (!string.IsNullOrEmpty(_line2)) helpText.AddPreOptionsLine(_line2);
if (!string.IsNullOrEmpty(_line3)) helpText.AddPreOptionsLine(_line3);
if (!string.IsNullOrEmpty(_line4)) helpText.AddPreOptionsLine(_line4);
if (!string.IsNullOrEmpty(_line5)) helpText.AddPreOptionsLine(_line5);
}
else
{
if (!string.IsNullOrEmpty(_line1)) helpText.AddPostOptionsLine(_line1);
if (!string.IsNullOrEmpty(_line2)) helpText.AddPostOptionsLine(_line2);
if (!string.IsNullOrEmpty(_line3)) helpText.AddPostOptionsLine(_line3);
if (!string.IsNullOrEmpty(_line4)) helpText.AddPostOptionsLine(_line4);
if (!string.IsNullOrEmpty(_line5)) helpText.AddPostOptionsLine(_line5);
}
}
}
[AttributeUsage(AttributeTargets.Assembly, Inherited = false), ComVisible(true)]
public sealed class AssemblyLicenseAttribute : MultiLineTextAttribute
{
//public AssemblyLicenseAttribute(object fullText)
// : base(fullText)
//{
//}
public AssemblyLicenseAttribute(string line1)
: base(line1)
{
}
public AssemblyLicenseAttribute(string line1, string line2)
: base(line1, line2)
{
}
public AssemblyLicenseAttribute(string line1, string line2, string line3)
: base(line1, line2, line3)
{
}
public AssemblyLicenseAttribute(string line1, string line2, string line3, string line4)
: base(line1, line2, line3, line4)
{
}
public AssemblyLicenseAttribute(string line1, string line2, string line3, string line4, string line5)
: base(line1, line2, line3, line4, line5)
{
}
}
[AttributeUsage(AttributeTargets.Assembly, Inherited = false), ComVisible(true)]
public sealed class AssemblyUsageAttribute : MultiLineTextAttribute
{
//public AssemblyUsageAttribute(object fullText)
// : base(fullText)
//{
//}
public AssemblyUsageAttribute(string line1)
: base(line1)
{
}
public AssemblyUsageAttribute(string line1, string line2)
: base(line1, line2)
{
}
public AssemblyUsageAttribute(string line1, string line2, string line3)
: base(line1, line2, line3)
{
}
public AssemblyUsageAttribute(string line1, string line2, string line3, string line4)
: base(line1, line2, line3, line4)
{
}
public AssemblyUsageAttribute(string line1, string line2, string line3, string line4, string line5)
: base(line1, line2, line3, line4, line5)
{
}
}
/*[AttributeUsage(AttributeTargets.Assembly, Inherited=false), ComVisible(true)]
public sealed class AssemblyInformationalVersionAttribute : Attribute
{
public string Version { get; private set; }
public AssemblyInformationalVersionAttribute (string version)
{
this.Version = version;
}
}*/
#endregion
#region HelpText
/// <summary>
/// Handle parsing errors delegate.
/// </summary>
public delegate void HandleParsingErrorsDelegate(HelpText current);
/// <summary>
/// Provides data for the FormatOptionHelpText event.
/// </summary>
public class FormatOptionHelpTextEventArgs : EventArgs
{
private readonly BaseOptionAttribute _option;
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.FormatOptionHelpTextEventArgs"/> class.
/// </summary>
/// <param name="option">Option to format.</param>
public FormatOptionHelpTextEventArgs(BaseOptionAttribute option)
{
_option = option;
}
/// <summary>
/// Gets the option to format.
/// </summary>
public BaseOptionAttribute Option
{
get
{
return _option;
}
}
}
/// <summary>
/// Models an help text and collects related informations.
/// You can assign it in place of a <see cref="System.String"/> instance.
/// </summary>
public class HelpText
{
private const int _builderCapacity = 128;
private const int _defaultMaximumLength = 80; // default console width
private int? _maximumDisplayWidth;
private string _heading;
private string _copyright;
private bool _additionalNewLineAfterOption;
private StringBuilder _preOptionsHelp;
private StringBuilder _optionsHelp;
private StringBuilder _postOptionsHelp;
private BaseSentenceBuilder _sentenceBuilder;
private static readonly string _defaultRequiredWord = "Required.";
private bool _addDashesToOption = false;
/// <summary>
/// Occurs when an option help text is formatted.
/// </summary>
public event EventHandler<FormatOptionHelpTextEventArgs> FormatOptionHelpText;
/// <summary>
/// Message type enumeration.
/// </summary>
public enum MessageEnum : short
{
/// <summary>
/// Parsing error due to a violation of the format of an option value.
/// </summary>
ParsingErrorViolatesFormat,
/// <summary>
/// Parsing error due to a violation of mandatory option.
/// </summary>
ParsingErrorViolatesRequired,
/// <summary>
/// Parsing error due to a violation of the mutual exclusiveness of two or more option.
/// </summary>
ParsingErrorViolatesExclusiveness
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class.
/// </summary>
public HelpText()
{
_preOptionsHelp = new StringBuilder(_builderCapacity);
_postOptionsHelp = new StringBuilder(_builderCapacity);
_sentenceBuilder = BaseSentenceBuilder.CreateBuiltIn();
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying the sentence builder.
/// </summary>
/// <param name="sentenceBuilder">
/// A <see cref="BaseSentenceBuilder"/> instance.
/// </param>
public HelpText(BaseSentenceBuilder sentenceBuilder)
: this()
{
Assumes.NotNull(sentenceBuilder, "sentenceBuilder");
_sentenceBuilder = sentenceBuilder;
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying heading informations.
/// </summary>
/// <param name="heading">A string with heading information or
/// an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
/// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="heading"/> is null or empty string.</exception>
public HelpText(string heading)
: this()
{
Assumes.NotNullOrEmpty(heading, "heading");
_heading = heading;
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying the sentence builder and heading informations.
/// </summary>
/// <param name="sentenceBuilder">
/// A <see cref="BaseSentenceBuilder"/> instance.
/// </param>
/// <param name="heading">
/// A string with heading information or
/// an instance of <see cref="CommandLine.Text.HeadingInfo"/>.
/// </param>
public HelpText(BaseSentenceBuilder sentenceBuilder, string heading)
: this(heading)
{
Assumes.NotNull(sentenceBuilder, "sentenceBuilder");
_sentenceBuilder = sentenceBuilder;
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying heading and copyright informations.
/// </summary>
/// <param name="heading">A string with heading information or
/// an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
/// <param name="copyright">A string with copyright information or
/// an instance of <see cref="CommandLine.Text.CopyrightInfo"/>.</param>
/// <exception cref="System.ArgumentException">Thrown when one or more parameters <paramref name="heading"/> are null or empty strings.</exception>
public HelpText(string heading, string copyright)
: this()
{
Assumes.NotNullOrEmpty(heading, "heading");
Assumes.NotNullOrEmpty(copyright, "copyright");
_heading = heading;
_copyright = copyright;
}
public HelpText(BaseSentenceBuilder sentenceBuilder, string heading, string copyright)
: this(heading, copyright)
{
Assumes.NotNull(sentenceBuilder, "sentenceBuilder");
_sentenceBuilder = sentenceBuilder;
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying heading and copyright informations.
/// </summary>
/// <param name="heading">A string with heading information or
/// an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
/// <param name="copyright">A string with copyright information or
/// an instance of <see cref="CommandLine.Text.CopyrightInfo"/>.</param>
/// <param name="options">The instance that collected command line arguments parsed with <see cref="CommandLine.CommandLineParser"/> class.</param>
/// <exception cref="System.ArgumentException">Thrown when one or more parameters <paramref name="heading"/> are null or empty strings.</exception>
public HelpText(string heading, string copyright, object options)
: this()
{
Assumes.NotNullOrEmpty(heading, "heading");
Assumes.NotNullOrEmpty(copyright, "copyright");
Assumes.NotNull(options, "options");
_heading = heading;
_copyright = copyright;
AddOptions(options);
}
public HelpText(BaseSentenceBuilder sentenceBuilder, string heading, string copyright, object options)
: this(heading, copyright, options)
{
Assumes.NotNull(sentenceBuilder, "sentenceBuilder");
_sentenceBuilder = sentenceBuilder;
}
/// <summary>
/// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class using common defaults.
/// </summary>
/// <returns>
/// An instance of <see cref="CommandLine.Text.HelpText"/> class.
/// </returns>
/// <param name='options'>
/// The instance that collected command line arguments parsed with <see cref="CommandLine.CommandLineParser"/> class.
/// </param>
public static HelpText AutoBuild(object options)
{
return AutoBuild(options, null);
}
/// <summary>
/// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class using common defaults.
/// </summary>
/// <returns>
/// An instance of <see cref="CommandLine.Text.HelpText"/> class.
/// </returns>
/// <param name='options'>
/// The instance that collected command line arguments parsed with <see cref="CommandLine.CommandLineParser"/> class.
/// </param>
/// <param name='errDelegate'>
/// A delegate used to customize the text block for reporting parsing errors.
/// </param>
public static HelpText AutoBuild(object options, HandleParsingErrorsDelegate errDelegate)
{
var title = ReflectionUtil.GetAttribute<AssemblyTitleAttribute>();
if (title == null) throw new InvalidOperationException("HelpText::AutoBuild() requires that you define AssemblyTitleAttribute.");
var version = ReflectionUtil.GetAttribute<AssemblyInformationalVersionAttribute>();
if (version == null) throw new InvalidOperationException("HelpText::AutoBuild() requires that you define AssemblyInformationalVersionAttribute.");
var copyright = ReflectionUtil.GetAttribute<AssemblyCopyrightAttribute>();
if (copyright == null) throw new InvalidOperationException("HelpText::AutoBuild() requires that you define AssemblyCopyrightAttribute.");
var auto = new HelpText
{
Heading = new HeadingInfo(Path.GetFileNameWithoutExtension(title.Title), version.InformationalVersion),
Copyright = copyright.Copyright,
AdditionalNewLineAfterOption = true,
AddDashesToOption = true
};
if (errDelegate != null)
{
var typedTarget = options as CommandLineOptionsBase;
if (typedTarget != null)
{
errDelegate(auto);
}
}
var license = ReflectionUtil.GetAttribute<AssemblyLicenseAttribute>();
if (license != null)
{
//auto.AddPreOptionsLine(license.FullText);
license.AddToHelpText(auto, true);
}
var usage = ReflectionUtil.GetAttribute<AssemblyUsageAttribute>();
if (usage != null)
{
//auto.AddPreOptionsLine(usage.FullText);
usage.AddToHelpText(auto, true);
}
auto.AddOptions(options);
return auto;
}
public static void DefaultParsingErrorsHandler(CommandLineOptionsBase options, HelpText current)
{
if (options.InternalLastPostParsingState.Errors.Count > 0)
{
var errors = current.RenderParsingErrorsText(options, 2); // indent with two spaces
if (!string.IsNullOrEmpty(errors))
{
current.AddPreOptionsLine(string.Concat(Environment.NewLine, current.SentenceBuilder.ErrorsHeadingText));
//current.AddPreOptionsLine(errors);
var lines = errors.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
foreach (var line in lines) { current.AddPreOptionsLine(line); }
}
}
}
/// <summary>
/// Sets the heading information string.
/// You can directly assign a <see cref="CommandLine.Text.HeadingInfo"/> instance.
/// </summary>
public string Heading
{
set
{
Assumes.NotNullOrEmpty(value, "value");
_heading = value;
}
}
/// <summary>
/// Sets the copyright information string.
/// You can directly assign a <see cref="CommandLine.Text.CopyrightInfo"/> instance.
/// </summary>
public string Copyright
{
set
{
Assumes.NotNullOrEmpty(value, "value");
_copyright = value;
}
}
/// <summary>
/// Gets or sets the maximum width of the display. This determines word wrap when displaying the text.
/// </summary>
/// <value>The maximum width of the display.</value>
public int MaximumDisplayWidth
{
get { return _maximumDisplayWidth.HasValue ? _maximumDisplayWidth.Value : _defaultMaximumLength; }
set { _maximumDisplayWidth = value; }
}
/// <summary>
/// Gets or sets the format of options for adding or removing dashes.
/// It modifies behavior of <see cref="AddOptions"/> method.
/// </summary>
public bool AddDashesToOption
{
get { return _addDashesToOption; }
set { _addDashesToOption = value; }
}
/// <summary>
/// Gets or sets whether to add an additional line after the description of the option.
/// </summary>
public bool AdditionalNewLineAfterOption
{
get { return _additionalNewLineAfterOption; }
set { _additionalNewLineAfterOption = value; }
}
public BaseSentenceBuilder SentenceBuilder
{
get { return _sentenceBuilder; }
}
/// <summary>
/// Adds a text line after copyright and before options usage informations.
/// </summary>
/// <param name="value">A <see cref="System.String"/> instance.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="value"/> is null or empty string.</exception>
public void AddPreOptionsLine(string value)
{
AddPreOptionsLine(value, MaximumDisplayWidth);
}
private void AddPreOptionsLine(string value, int maximumLength)
{
AddLine(_preOptionsHelp, value, maximumLength);
}
/// <summary>
/// Adds a text line at the bottom, after options usage informations.
/// </summary>
/// <param name="value">A <see cref="System.String"/> instance.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="value"/> is null or empty string.</exception>
public void AddPostOptionsLine(string value)
{
AddLine(_postOptionsHelp, value);
}
/// <summary>
/// Adds a text block with options usage informations.
/// </summary>
/// <param name="options">The instance that collected command line arguments parsed with <see cref="CommandLine.CommandLineParser"/> class.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="options"/> is null.</exception>
public void AddOptions(object options)
{
AddOptions(options, _defaultRequiredWord);
}
/// <summary>
/// Adds a text block with options usage informations.
/// </summary>
/// <param name="options">The instance that collected command line arguments parsed with the <see cref="CommandLine.CommandLineParser"/> class.</param>
/// <param name="requiredWord">The word to use when the option is required.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="options"/> is null.</exception>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="requiredWord"/> is null or empty string.</exception>
public void AddOptions(object options, string requiredWord)
{
Assumes.NotNull(options, "options");
Assumes.NotNullOrEmpty(requiredWord, "requiredWord");
AddOptions(options, requiredWord, MaximumDisplayWidth);
}
/// <summary>
/// Adds a text block with options usage informations.
/// </summary>
/// <param name="options">The instance that collected command line arguments parsed with the <see cref="CommandLine.CommandLineParser"/> class.</param>
/// <param name="requiredWord">The word to use when the option is required.</param>
/// <param name="maximumLength">The maximum length of the help documentation.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="options"/> is null.</exception>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="requiredWord"/> is null or empty string.</exception>
public void AddOptions(object options, string requiredWord, int maximumLength)
{
Assumes.NotNull(options, "options");
Assumes.NotNullOrEmpty(requiredWord, "requiredWord");
var optionList = ReflectionUtil.RetrievePropertyAttributeList<BaseOptionAttribute>(options);
var optionHelp = ReflectionUtil.RetrieveMethodAttributeOnly<HelpOptionAttribute>(options);
if (optionHelp != null)
{
optionList.Add(optionHelp);
}
if (optionList.Count == 0)
{
return;
}
int maxLength = GetMaxLength(optionList);
_optionsHelp = new StringBuilder(_builderCapacity);
int remainingSpace = maximumLength - (maxLength + 6);
foreach (BaseOptionAttribute option in optionList)
{
AddOption(requiredWord, maxLength, option, remainingSpace);
}
}
/// <summary>
/// Builds a string that contains a parsing error message.
/// </summary>
/// <param name="options">
/// An options target <see cref="CommandLineOptionsBase"/> instance that collected command line arguments parsed with the <see cref="CommandLine.CommandLineParser"/> class.
/// </param>
/// <returns>
/// The <see cref="System.String"/> that contains the parsing error message.
/// </returns>
public string RenderParsingErrorsText(CommandLineOptionsBase options, int indent)
{
if (options.InternalLastPostParsingState.Errors.Count == 0)
{
return string.Empty;
}
var text = new StringBuilder();
foreach (var e in options.InternalLastPostParsingState.Errors)
{
var line = new StringBuilder();
line.Append(StringUtil.Spaces(indent));
if (!string.IsNullOrEmpty(e.BadOption.ShortName))
{
line.Append('-');
line.Append(e.BadOption.ShortName);
if (!string.IsNullOrEmpty(e.BadOption.LongName)) line.Append('/');
}
if (!string.IsNullOrEmpty(e.BadOption.LongName))
{
line.Append("--");
line.Append(e.BadOption.LongName);
}
line.Append(" ");
if (e.ViolatesRequired)
{
line.Append(_sentenceBuilder.RequiredOptionMissingText);
}
else
{
line.Append(_sentenceBuilder.OptionWord);
}
if (e.ViolatesFormat)
{
line.Append(" ");
line.Append(_sentenceBuilder.ViolatesFormatText);
}
if (e.ViolatesMutualExclusiveness)
{
if (e.ViolatesFormat || e.ViolatesRequired)
{
line.Append(" ");
line.Append(_sentenceBuilder.AndWord);
}
line.Append(" ");
line.Append(_sentenceBuilder.ViolatesMutualExclusivenessText);
}
line.Append('.');
text.AppendLine(line.ToString());
}
return text.ToString();
}
private void AddOption(string requiredWord, int maxLength, BaseOptionAttribute option, int widthOfHelpText)
{
_optionsHelp.Append(" ");
StringBuilder optionName = new StringBuilder(maxLength);
if (option.HasShortName)
{
if (_addDashesToOption)
{
optionName.Append('-');
}
optionName.AppendFormat("{0}", option.ShortName);
if (option.HasLongName)
{
optionName.Append(", ");
}
}
if (option.HasLongName)
{
if (_addDashesToOption)
{
optionName.Append("--");
}
optionName.AppendFormat("{0}", option.LongName);
}
if (optionName.Length < maxLength)
{
_optionsHelp.Append(optionName.ToString().PadRight(maxLength));
}
else
{
_optionsHelp.Append(optionName.ToString());
}
_optionsHelp.Append(" ");
if (option.Required)
{
option.HelpText = String.Format("{0} ", requiredWord) + option.HelpText;
}
FormatOptionHelpTextEventArgs e = new FormatOptionHelpTextEventArgs(option);
OnFormatOptionHelpText(e);
option.HelpText = e.Option.HelpText;
if (!string.IsNullOrEmpty(option.HelpText))
{
do
{
int wordBuffer = 0;
var words = option.HelpText.Split(new[] { ' ' });
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length < (widthOfHelpText - wordBuffer))
{
_optionsHelp.Append(words[i]);
wordBuffer += words[i].Length;
if ((widthOfHelpText - wordBuffer) > 1 && i != words.Length - 1)
{
_optionsHelp.Append(" ");
wordBuffer++;
}
}
else if (words[i].Length >= widthOfHelpText && wordBuffer == 0)
{
_optionsHelp.Append(words[i].Substring(
0,
widthOfHelpText
));
wordBuffer = widthOfHelpText;
break;
}
else
{
break;
}
}
option.HelpText = option.HelpText.Substring(Math.Min(
wordBuffer,
option.HelpText.Length
))
.Trim();
if (option.HelpText.Length > 0)
{
_optionsHelp.Append(Environment.NewLine);
_optionsHelp.Append(new string(' ', maxLength + 6));
}
} while (option.HelpText.Length > widthOfHelpText);
}
_optionsHelp.Append(option.HelpText);
_optionsHelp.Append(Environment.NewLine);
if (_additionalNewLineAfterOption)
_optionsHelp.Append(Environment.NewLine);
}
/// <summary>
/// Returns the help informations as a <see cref="System.String"/>.
/// </summary>
/// <returns>The <see cref="System.String"/> that contains the help informations.</returns>
public override string ToString()
{
const int extraLength = 10;
var builder = new StringBuilder(GetLength(_heading) + GetLength(_copyright) +
GetLength(_preOptionsHelp) + GetLength(_optionsHelp) + extraLength
);
builder.Append(_heading);
if (!string.IsNullOrEmpty(_copyright))
{
builder.Append(Environment.NewLine);
builder.Append(_copyright);
}
if (_preOptionsHelp.Length > 0)
{
builder.Append(Environment.NewLine);
builder.Append(_preOptionsHelp.ToString());
}
if (_optionsHelp != null && _optionsHelp.Length > 0)
{
builder.Append(Environment.NewLine);
builder.Append(Environment.NewLine);
builder.Append(_optionsHelp.ToString());
}
if (_postOptionsHelp.Length > 0)
{
builder.Append(Environment.NewLine);
builder.Append(_postOptionsHelp.ToString());
}
return builder.ToString();
}
/// <summary>
/// Converts the help informations to a <see cref="System.String"/>.
/// </summary>
/// <param name="info">This <see cref="CommandLine.Text.HelpText"/> instance.</param>
/// <returns>The <see cref="System.String"/> that contains the help informations.</returns>
public static implicit operator string(HelpText info)
{
return info.ToString();
}
private void AddLine(StringBuilder builder, string value)
{
Assumes.NotNull(value, "value");
AddLine(builder, value, MaximumDisplayWidth);
}
private static void AddLine(StringBuilder builder, string value, int maximumLength)
{
Assumes.NotNull(value, "value");
if (builder.Length > 0)
{
builder.Append(Environment.NewLine);
}
do
{
int wordBuffer = 0;
string[] words = value.Split(new[] { ' ' });
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length < (maximumLength - wordBuffer))
{
builder.Append(words[i]);
wordBuffer += words[i].Length;
if ((maximumLength - wordBuffer) > 1 && i != words.Length - 1)
{
builder.Append(" ");
wordBuffer++;
}
}
else if (words[i].Length >= maximumLength && wordBuffer == 0)
{
builder.Append(words[i].Substring(0, maximumLength));
wordBuffer = maximumLength;
break;
}
else
{
break;
}
}
value = value.Substring(Math.Min(wordBuffer, value.Length));
if (value.Length > 0)
{
builder.Append(Environment.NewLine);
}
} while (value.Length > maximumLength);
builder.Append(value);
}
private static int GetLength(string value)
{
if (value == null)
{
return 0;
}
return value.Length;
}
private static int GetLength(StringBuilder value)
{
if (value == null)
{
return 0;
}
return value.Length;
}
//ex static
private int GetMaxLength(IList<BaseOptionAttribute> optionList)
{
int length = 0;
foreach (BaseOptionAttribute option in optionList)
{
int optionLength = 0;
bool hasShort = option.HasShortName;
bool hasLong = option.HasLongName;
if (hasShort)
{
optionLength += option.ShortName.Length;
if (AddDashesToOption)
++optionLength;
}
if (hasLong)
{
optionLength += option.LongName.Length;
if (AddDashesToOption)
optionLength += 2;
}
if (hasShort && hasLong)
{
optionLength += 2; // ", "
}
length = Math.Max(length, optionLength);
}
return length;
}
protected virtual void OnFormatOptionHelpText(FormatOptionHelpTextEventArgs e)
{
EventHandler<FormatOptionHelpTextEventArgs> handler = FormatOptionHelpText;
if (handler != null)
handler(this, e);
}
}
#endregion
}
| |
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace FlatBuffers
{
/// <summary>
/// All tables in the generated code derive from this struct, and add their own accessors.
/// </summary>
public struct Table
{
public int bb_pos { get; private set; }
public ByteBuffer bb { get; private set; }
public ByteBuffer ByteBuffer { get { return bb; } }
// Re-init the internal state with an external buffer {@code ByteBuffer} and an offset within.
public Table(int _i, ByteBuffer _bb) : this()
{
bb = _bb;
bb_pos = _i;
}
// Look up a field in the vtable, return an offset into the object, or 0 if the field is not
// present.
public int __offset(int vtableOffset)
{
int vtable = bb_pos - bb.GetInt(bb_pos);
return vtableOffset < bb.GetShort(vtable) ? (int)bb.GetShort(vtable + vtableOffset) : 0;
}
public static int __offset(int vtableOffset, int offset, ByteBuffer bb)
{
int vtable = bb.Length - offset;
return (int)bb.GetShort(vtable + vtableOffset - bb.GetInt(vtable)) + vtable;
}
// Retrieve the relative offset stored at "offset"
public int __indirect(int offset)
{
return offset + bb.GetInt(offset);
}
public static int __indirect(int offset, ByteBuffer bb)
{
return offset + bb.GetInt(offset);
}
// Create a .NET String from UTF-8 data stored inside the flatbuffer.
public string __string(int offset)
{
offset += bb.GetInt(offset);
var len = bb.GetInt(offset);
var startPos = offset + sizeof(int);
return bb.GetStringUTF8(startPos, len);
}
// Get the length of a vector whose offset is stored at "offset" in this object.
public int __vector_len(int offset)
{
offset += bb_pos;
offset += bb.GetInt(offset);
return bb.GetInt(offset);
}
// Get the start of data of a vector whose offset is stored at "offset" in this object.
public int __vector(int offset)
{
offset += bb_pos;
return offset + bb.GetInt(offset) + sizeof(int); // data starts after the length
}
#if ENABLE_SPAN_T && (UNSAFE_BYTEBUFFER || NETSTANDARD2_1)
// Get the data of a vector whoses offset is stored at "offset" in this object as an
// Spant<byte>. If the vector is not present in the ByteBuffer,
// then an empty span will be returned.
public Span<T> __vector_as_span<T>(int offset, int elementSize) where T : struct
{
if (!BitConverter.IsLittleEndian)
{
throw new NotSupportedException("Getting typed span on a Big Endian " +
"system is not support");
}
var o = this.__offset(offset);
if (0 == o)
{
return new Span<T>();
}
var pos = this.__vector(o);
var len = this.__vector_len(o);
return MemoryMarshal.Cast<byte, T>(bb.ToSpan(pos, len * elementSize));
}
#else
// Get the data of a vector whoses offset is stored at "offset" in this object as an
// ArraySegment<byte>. If the vector is not present in the ByteBuffer,
// then a null value will be returned.
public ArraySegment<byte>? __vector_as_arraysegment(int offset)
{
var o = this.__offset(offset);
if (0 == o)
{
return null;
}
var pos = this.__vector(o);
var len = this.__vector_len(o);
return bb.ToArraySegment(pos, len);
}
#endif
// Get the data of a vector whoses offset is stored at "offset" in this object as an
// T[]. If the vector is not present in the ByteBuffer, then a null value will be
// returned.
public T[] __vector_as_array<T>(int offset)
where T : struct
{
if(!BitConverter.IsLittleEndian)
{
throw new NotSupportedException("Getting typed arrays on a Big Endian " +
"system is not support");
}
var o = this.__offset(offset);
if (0 == o)
{
return null;
}
var pos = this.__vector(o);
var len = this.__vector_len(o);
return bb.ToArray<T>(pos, len);
}
// Initialize any Table-derived type to point to the union at the given offset.
public T __union<T>(int offset) where T : struct, IFlatbufferObject
{
T t = new T();
t.__init(__indirect(offset), bb);
return t;
}
public static bool __has_identifier(ByteBuffer bb, string ident)
{
if (ident.Length != FlatBufferConstants.FileIdentifierLength)
throw new ArgumentException("FlatBuffers: file identifier must be length " + FlatBufferConstants.FileIdentifierLength, "ident");
for (var i = 0; i < FlatBufferConstants.FileIdentifierLength; i++)
{
if (ident[i] != (char)bb.Get(bb.Position + sizeof(int) + i)) return false;
}
return true;
}
// Compare strings in the ByteBuffer.
public static int CompareStrings(int offset_1, int offset_2, ByteBuffer bb)
{
offset_1 += bb.GetInt(offset_1);
offset_2 += bb.GetInt(offset_2);
var len_1 = bb.GetInt(offset_1);
var len_2 = bb.GetInt(offset_2);
var startPos_1 = offset_1 + sizeof(int);
var startPos_2 = offset_2 + sizeof(int);
var len = Math.Min(len_1, len_2);
for(int i = 0; i < len; i++) {
byte b1 = bb.Get(i + startPos_1);
byte b2 = bb.Get(i + startPos_2);
if (b1 != b2)
return b1 - b2;
}
return len_1 - len_2;
}
// Compare string from the ByteBuffer with the string object
public static int CompareStrings(int offset_1, byte[] key, ByteBuffer bb)
{
offset_1 += bb.GetInt(offset_1);
var len_1 = bb.GetInt(offset_1);
var len_2 = key.Length;
var startPos_1 = offset_1 + sizeof(int);
var len = Math.Min(len_1, len_2);
for (int i = 0; i < len; i++) {
byte b = bb.Get(i + startPos_1);
if (b != key[i])
return b - key[i];
}
return len_1 - len_2;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void RoundToZeroSingle()
{
var test = new SimpleUnaryOpTest__RoundToZeroSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__RoundToZeroSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__RoundToZeroSingle testClass)
{
var result = Avx.RoundToZero(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToZeroSingle testClass)
{
fixed (Vector256<Single>* pFld1 = &_fld1)
{
var result = Avx.RoundToZero(
Avx.LoadVector256((Single*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Vector256<Single> _clsVar1;
private Vector256<Single> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__RoundToZeroSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public SimpleUnaryOpTest__RoundToZeroSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.RoundToZero(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.RoundToZero(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.RoundToZero(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.RoundToZero), new Type[] { typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.RoundToZero), new Type[] { typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.RoundToZero), new Type[] { typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.RoundToZero(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Single>* pClsVar1 = &_clsVar1)
{
var result = Avx.RoundToZero(
Avx.LoadVector256((Single*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var result = Avx.RoundToZero(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var result = Avx.RoundToZero(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var result = Avx.RoundToZero(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__RoundToZeroSingle();
var result = Avx.RoundToZero(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__RoundToZeroSingle();
fixed (Vector256<Single>* pFld1 = &test._fld1)
{
var result = Avx.RoundToZero(
Avx.LoadVector256((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.RoundToZero(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Single>* pFld1 = &_fld1)
{
var result = Avx.RoundToZero(
Avx.LoadVector256((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.RoundToZero(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.RoundToZero(
Avx.LoadVector256((Single*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Single> op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits((firstOp[0] > 0) ? MathF.Floor(firstOp[0]) : MathF.Ceiling(firstOp[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits((firstOp[i] > 0) ? MathF.Floor(firstOp[i]) : MathF.Ceiling(firstOp[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.RoundToZero)}<Single>(Vector256<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Core.Vertex;
using SlimDX;
using SlimDX.Direct3D9;
namespace Core.Model {
/// <summary>
/// Refer to https://dxut.codeplex.com/SourceControl/latest#Optional/SDKmesh.h
/// and https://dxut.codeplex.com/SourceControl/latest#Optional/SDKmesh.cpp
/// </summary>
internal class SdkMesh {
private SdkMeshHeader _header;
internal readonly List<SdkMeshVertexBuffer> VertexBuffers = new List<SdkMeshVertexBuffer>();
internal readonly List<SdkMeshIndexBuffer> IndexBuffers = new List<SdkMeshIndexBuffer>();
internal readonly List<SdkMeshMesh> Meshes = new List<SdkMeshMesh>();
internal readonly List<SdkMeshSubset> Subsets = new List<SdkMeshSubset>();
internal readonly List<SdkMeshFrame> Frames = new List<SdkMeshFrame>();
internal readonly List<SdkMeshMaterial> Materials = new List<SdkMeshMaterial>();
public override string ToString() {
var sb = new StringBuilder();
sb.AppendLine(_header.ToString());
foreach (var vertexBuffer in VertexBuffers) {
sb.AppendLine(vertexBuffer.ToString());
}
foreach (var indexBuffer in IndexBuffers) {
sb.AppendLine(indexBuffer.ToString());
}
foreach (var mesh in Meshes) {
sb.AppendLine(mesh.ToString());
}
foreach (var subset in Subsets) {
sb.AppendLine(subset.ToString());
}
foreach (var frame in Frames) {
sb.AppendLine(frame.ToString());
}
foreach (var material in Materials) {
sb.AppendLine(material.ToString());
}
return sb.ToString();
}
public SdkMesh(string filename) {
using (var reader = new BinaryReader(new FileStream(filename, FileMode.Open))) {
_header = new SdkMeshHeader(reader);
for (int i = 0; i < _header.NumVertexBuffers; i++) {
VertexBuffers.Add(new SdkMeshVertexBuffer(reader));
}
for (int i = 0; i < _header.NumIndexBuffers; i++) {
IndexBuffers.Add(new SdkMeshIndexBuffer(reader));
}
for (int i = 0; i < _header.NumMeshes; i++) {
Meshes.Add(new SdkMeshMesh(reader));
}
for (int i = 0; i < _header.NumTotalSubsets; i++) {
Subsets.Add(new SdkMeshSubset(reader));
}
for (int i = 0; i < _header.NumFrames; i++) {
Frames.Add(new SdkMeshFrame(reader));
}
for (int i = 0; i < _header.NumMaterials; i++) {
Materials.Add(new SdkMeshMaterial(reader));
}
}
}
[StructLayout(LayoutKind.Sequential)]
public struct SdkMeshHeader {
public readonly uint Version;
public readonly byte IsBigEndian;
public readonly UInt64 HeaderSize;
public readonly UInt64 NonBufferDataSize;
public readonly UInt64 BufferDataSize;
public readonly uint NumVertexBuffers;
public readonly uint NumIndexBuffers;
public readonly uint NumMeshes;
public readonly uint NumTotalSubsets;
public readonly uint NumFrames;
public readonly uint NumMaterials;
public readonly UInt64 VertexStreamHeaderOffset;
public readonly UInt64 IndexStreamHeaderOffset;
public readonly UInt64 MeshDataOffset;
public readonly UInt64 SubsetDataOffset;
public readonly UInt64 FrameDataOffset;
public readonly UInt64 MaterialDataOffset;
public override string ToString() {
var sb = new StringBuilder();
foreach (var fieldInfo in GetType().GetFields()) {
sb.AppendLine(fieldInfo.Name + ": " + fieldInfo.GetValue(this));
}
return sb.ToString();
}
public SdkMeshHeader(BinaryReader reader) {
Version = reader.ReadUInt32();
IsBigEndian = reader.ReadByte();
reader.ReadBytes(3); // allow for padding
HeaderSize = reader.ReadUInt64();
NonBufferDataSize = reader.ReadUInt64();
BufferDataSize = reader.ReadUInt64();
NumVertexBuffers = reader.ReadUInt32();
NumIndexBuffers = reader.ReadUInt32();
NumMeshes = reader.ReadUInt32();
NumTotalSubsets = reader.ReadUInt32();
NumFrames = reader.ReadUInt32();
NumMaterials = reader.ReadUInt32();
VertexStreamHeaderOffset = reader.ReadUInt64();
IndexStreamHeaderOffset = reader.ReadUInt64();
MeshDataOffset = reader.ReadUInt64();
SubsetDataOffset = reader.ReadUInt64();
FrameDataOffset = reader.ReadUInt64();
MaterialDataOffset = reader.ReadUInt64();
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct SdkMeshVertexBuffer {
private const int MaxVertexElements = 32;
public readonly UInt64 NumVertices;
public readonly UInt64 SizeBytes;
public readonly UInt64 StrideBytes;
public readonly List<VertexElement> Decl;
public readonly UInt64 DataOffset;
public readonly List<PosNormalTexTan> Vertices;
public override string ToString() {
var sb = new StringBuilder();
sb.AppendLine("NumVertices: " + NumVertices);
sb.AppendLine("SizeBytes: " + SizeBytes);
sb.AppendLine("StrideBytes: " + StrideBytes);
sb.AppendLine("Decl: ");
foreach (var elem in Decl) {
sb.AppendLine("\tVertexElement(Stream: " + elem.Stream + " Offset: " + elem.Offset + " Type: " + elem.Type + " Method: " + elem.Method + " Usage: " + elem.Usage + " UsageIndex: " + elem.UsageIndex + ")");
}
sb.AppendLine("DataOffset: " + DataOffset);
sb.AppendLine("Vertices in vertex buffer: " + Vertices.Count);
return sb.ToString();
}
public SdkMeshVertexBuffer(BinaryReader reader) {
NumVertices = reader.ReadUInt64();
SizeBytes = reader.ReadUInt64();
StrideBytes = reader.ReadUInt64();
Decl = new List<VertexElement>();
var processElem = true;
for (int j = 0; j < MaxVertexElements; j++) {
var stream = reader.ReadUInt16();
var offset = reader.ReadUInt16();
var type = reader.ReadByte();
var method = reader.ReadByte();
var usage = reader.ReadByte();
var usageIndex = reader.ReadByte();
if (stream < 16 && processElem) {
var element = new VertexElement((short)stream, (short)offset, (DeclarationType)type, (DeclarationMethod)method, (DeclarationUsage)usage, usageIndex);
Decl.Add(element);
} else {
processElem = false;
}
}
DataOffset = reader.ReadUInt64();
Vertices = new List<PosNormalTexTan>();
if (SizeBytes > 0) {
ReadVertices(reader);
}
}
private void ReadVertices(BinaryReader reader) {
var curPos = reader.BaseStream.Position;
reader.BaseStream.Seek((long)DataOffset, SeekOrigin.Begin);
//var data = reader.ReadBytes((int) vbHeader.SizeBytes);
for (ulong i = 0; i < NumVertices; i++) {
var vertex = new PosNormalTexTan();
foreach (var element in Decl) {
switch (element.Type) {
case DeclarationType.Float3:
var v3 = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
switch (element.Usage) {
case DeclarationUsage.Position:
vertex.Pos = v3;
break;
case DeclarationUsage.Normal:
vertex.Normal = v3;
break;
case DeclarationUsage.Tangent:
vertex.Tan = v3;
break;
}
//Console.WriteLine("{0} - {1}", element.Usage, v3);
break;
case DeclarationType.Float2:
var v2 = new Vector2(reader.ReadSingle(), reader.ReadSingle());
switch (element.Usage) {
case DeclarationUsage.TextureCoordinate:
vertex.Tex = v2;
break;
}
//Console.WriteLine("{0} - {1}", element.Usage, v2);
break;
}
}
Vertices.Add(vertex);
}
reader.BaseStream.Position = curPos;
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct SdkMeshIndexBuffer {
public readonly UInt64 NumIndices;
public readonly UInt64 SizeBytes;
public readonly uint IndexType;
public readonly UInt64 DataOffset;
public readonly List<int> Indices;
public override string ToString() {
var sb = new StringBuilder();
sb.AppendLine("NumIndices: " + NumIndices);
sb.AppendLine("SizeBytes: " + SizeBytes);
sb.AppendLine("IndexType: " + IndexType);
sb.AppendLine("DataOffset: " + DataOffset);
sb.AppendLine("Number of indices in buffer: " + Indices.Count);
return sb.ToString();
}
public SdkMeshIndexBuffer(BinaryReader reader) {
NumIndices = reader.ReadUInt64();
SizeBytes = reader.ReadUInt64();
IndexType = reader.ReadUInt32();
reader.ReadUInt32(); // padding
DataOffset = reader.ReadUInt64();
Indices = new List<int>();
if (SizeBytes > 0) {
ReadIndices(reader);
}
}
private void ReadIndices(BinaryReader reader) {
var curPos = reader.BaseStream.Position;
reader.BaseStream.Seek((long)DataOffset, SeekOrigin.Begin);
for (ulong i = 0; i < NumIndices; i++) {
int idx;
if (IndexType == 0) {
idx = reader.ReadUInt16();
Indices.Add(idx);
} else {
idx = reader.ReadInt32();
Indices.Add(idx);
}
}
reader.BaseStream.Position = curPos;
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct SdkMeshMesh {
public readonly string Name;
public readonly byte NumVertexBuffers;
public readonly List<uint> VertexBuffers;
public readonly uint IndexBuffer;
public readonly uint NumSubsets;
public readonly uint NumFrameInfluences; // bones
public readonly Vector3 BoundingBoxCenter;
public readonly Vector3 BoundingBoxExtents;
public readonly UInt64 SubsetOffset;
public readonly UInt64 FrameInfluenceOffset; // offset to bone data
public readonly List<int> SubsetData;
private const int MaxMeshName = 100;
private const int MaxVertexStreams = 16;
public override string ToString() {
var sb = new StringBuilder();
sb.AppendLine("Name: " + Name);
sb.AppendLine("NumVertexBuffers: " + NumVertexBuffers);
sb.Append("VertexBuffers: ");
foreach (var vertexBuffer in VertexBuffers) {
sb.Append(vertexBuffer + ", ");
}
sb.AppendLine();
sb.AppendLine("IndexBuffer: " + IndexBuffer);
sb.AppendLine("NumSubsets: " + NumSubsets);
sb.AppendLine("NumFrameInfluences: " + NumFrameInfluences);
sb.AppendLine("BoundingBoxCenter: " + BoundingBoxCenter);
sb.AppendLine("BoundingBoxExtents: " + BoundingBoxExtents);
sb.AppendLine("SubsetOffset: " + SubsetOffset);
sb.AppendLine("FrameInfluenceOffset: " + SubsetOffset);
sb.Append("Subsets: ");
foreach (var i in SubsetData) {
sb.Append(i + ", ");
}
sb.AppendLine();
return sb.ToString();
}
public SdkMeshMesh(BinaryReader reader) {
Name = Encoding.Default.GetString(reader.ReadBytes(MaxMeshName));
NumVertexBuffers = reader.ReadByte();
reader.ReadBytes(3);
VertexBuffers = new List<uint>();
for (int j = 0; j < MaxVertexStreams; j++) {
VertexBuffers.Add(reader.ReadUInt32());
}
IndexBuffer = reader.ReadUInt32();
NumSubsets = reader.ReadUInt32();
NumFrameInfluences = reader.ReadUInt32();
BoundingBoxCenter = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
BoundingBoxExtents = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
reader.ReadUInt32();
SubsetOffset = reader.ReadUInt64();
FrameInfluenceOffset = reader.ReadUInt64();
SubsetData = new List<int>();
if (NumSubsets > 0) {
ReadSubsets(reader);
}
// NOTE: not bothering with bone data now
}
private void ReadSubsets(BinaryReader reader) {
var curPos = reader.BaseStream.Position;
reader.BaseStream.Seek((long)SubsetOffset, SeekOrigin.Begin);
for (int i = 0; i < NumSubsets; i++) {
var subsetId = reader.ReadInt32();
SubsetData.Add(subsetId);
}
reader.BaseStream.Position = curPos;
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct SdkMeshSubset {
private const int MaxSubsetName = 100;
public readonly string Name;
public readonly uint MaterialID;
public readonly uint PrimitiveType;
public readonly UInt64 IndexStart;
public readonly UInt64 IndexCount;
public readonly UInt64 VertexStart;
public readonly UInt64 VertexCount;
public override string ToString() {
var sb = new StringBuilder();
foreach (var fieldInfo in GetType().GetFields().Where(fi => !fi.IsLiteral)) {
sb.AppendLine(fieldInfo.Name + ": " + fieldInfo.GetValue(this));
}
return sb.ToString();
}
public SdkMeshSubset(BinaryReader reader) {
Name = Encoding.Default.GetString(reader.ReadBytes(MaxSubsetName));
if (Name[0] == '\0') {
Name = "";
}
MaterialID = reader.ReadUInt32();
PrimitiveType = reader.ReadUInt32();
reader.ReadUInt32();
IndexStart = reader.ReadUInt64();
IndexCount = reader.ReadUInt64();
VertexStart = reader.ReadUInt64();
VertexCount = reader.ReadUInt64();
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct SdkMeshFrame {
private const int MaxFrameName = 100;
public readonly string Name;
public readonly uint Mesh;
public readonly int ParentFrame;
public readonly int ChildFrame;
public readonly int SiblingFrame;
public readonly Matrix Matrix;
public readonly int AnimationDataIndex;
public override string ToString() {
var sb = new StringBuilder();
foreach (var fieldInfo in GetType().GetFields().Where(fi => !fi.IsLiteral)) {
sb.AppendLine(fieldInfo.Name + ": " + fieldInfo.GetValue(this));
}
return sb.ToString();
}
public SdkMeshFrame(BinaryReader reader) {
Name = Encoding.Default.GetString(reader.ReadBytes(MaxFrameName));
if (Name[0] == '\0') {
Name = "";
}
Mesh = reader.ReadUInt32();
ParentFrame = reader.ReadInt32();
ChildFrame = reader.ReadInt32();
SiblingFrame = reader.ReadInt32();
Matrix = new Matrix();
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
Matrix[k, j] = reader.ReadSingle();
}
}
AnimationDataIndex = reader.ReadInt32();
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct SdkMeshMaterial {
private const int MaxMaterialName = 100;
private const int MaxMaterialPath = 260;
private const int MaxTextureName = 260;
public readonly string Name;
public readonly string MaterialInstancePath;
public readonly string DiffuseTexture;
public readonly string NormalTexture;
public readonly string SpecularTexture;
public readonly Color4 Diffuse;
public readonly Color4 Ambient;
public readonly Color4 Specular;
public readonly Color4 Emissive;
public readonly float Power;
public override string ToString() {
var sb = new StringBuilder();
foreach (var fieldInfo in GetType().GetFields().Where(fi => !fi.IsLiteral)) {
sb.AppendLine(fieldInfo.Name + ": " + fieldInfo.GetValue(this));
}
return sb.ToString();
}
public SdkMeshMaterial(BinaryReader reader) {
Name = Encoding.Default.GetString(reader.ReadBytes(MaxMaterialName));
if (Name[0] == '\0') {
Name = "";
}
MaterialInstancePath = Encoding.Default.GetString(reader.ReadBytes(MaxMaterialPath)).Trim(new[] { ' ', '\0' });
DiffuseTexture = Encoding.Default.GetString(reader.ReadBytes(MaxTextureName)).Trim(new[] { ' ', '\0' });
NormalTexture = Encoding.Default.GetString(reader.ReadBytes(MaxTextureName)).Trim(new[] { ' ', '\0' });
SpecularTexture = Encoding.Default.GetString(reader.ReadBytes(MaxTextureName)).Trim(new[] { ' ', '\0' });
Diffuse = new Color4 {
Red = reader.ReadSingle(),
Green = reader.ReadSingle(),
Blue = reader.ReadSingle(),
Alpha = reader.ReadSingle()
};
Ambient = new Color4 {
Red = reader.ReadSingle(),
Green = reader.ReadSingle(),
Blue = reader.ReadSingle(),
Alpha = reader.ReadSingle()
};
Specular = new Color4 {
Red = reader.ReadSingle(),
Green = reader.ReadSingle(),
Blue = reader.ReadSingle(),
Alpha = reader.ReadSingle()
};
Emissive = new Color4 {
Red = reader.ReadSingle(),
Green = reader.ReadSingle(),
Blue = reader.ReadSingle(),
Alpha = reader.ReadSingle()
};
Power = reader.ReadSingle();
// Padding...
reader.ReadUInt64();
reader.ReadUInt64();
reader.ReadUInt64();
reader.ReadUInt64();
reader.ReadUInt64();
reader.ReadUInt64();
}
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Text;
using Alachisoft.NCache.Runtime.Exceptions;
using Alachisoft.NCache.SocketServer.Statistics;
using Alachisoft.NCache.Common.DataStructures.Clustered;
using System.Collections;
using System.Threading;
using Alachisoft.NCache.Client;
using System.Diagnostics;
using Alachisoft.NCache.Common.Monitoring;
using Alachisoft.NCache.Common.Pooling.Lease;
using Alachisoft.NCache.Caching.Pooling;
using Alachisoft.NCache.Common.Pooling;
using System.Collections.Generic;
namespace Alachisoft.NCache.SocketServer.Command
{
abstract class CommandBase : SimpleLease, IDisposable,ICancellableRequest
{
Stopwatch _watch = new Stopwatch();
protected string immatureId = "-2";
protected object _userData;
protected long _requestTimeout;
protected int forcedViewId = -5;
protected CancellationTokenSource _cancellationTokenSource;
internal virtual OperationResult OperationResult{get {return OperationResult.Failure;}}
public virtual int Operations { get { return 1; } }
protected IList _serializedResponsePackets = new List<object>();
//Usefull for debugging (Dump analysis)
private TimeSpan _elapsedTime;
internal const string oldClientsGroupType = "$OldClients$"; //Group Type for client before NCache 5.0
public virtual IList SerializedResponsePackets
{
get { return _serializedResponsePackets; }
}
public virtual bool CanHaveLargedata { get { return false; } }
public virtual bool IsBulkOperation { get { return false; } }
public virtual object UserData
{
get { return _userData; }
set { _userData = value; }
}
public long RequestTimeout { get { return _requestTimeout; } set { _requestTimeout = value; } }
public bool IsCancelled
{
get
{
return _cancellationTokenSource != null? _cancellationTokenSource.IsCancellationRequested: false;
}
}
public bool HasTimedout
{
get
{
_elapsedTime = _watch != null ? _watch.Elapsed : TimeSpan.Zero;
return _elapsedTime.TotalMilliseconds > _requestTimeout;
}
}
//PROTOBUF
abstract public void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command);
// For Counters
public virtual void IncrementCounter(StatisticsCounter collector, long value)
{
}
public virtual string GetCommandParameters(out string commandName)
{
StringBuilder details = new StringBuilder();
commandName = this.GetType().Name;
details.Append("Command Type: " + this.GetType().Name);
return details.ToString();
}
/// <summary>
/// Update the indexes passed to the next and current delimiter
/// </summary>
/// <param name="command">source string</param>
/// <param name="delim">dlimiter</param>
/// <param name="beginQuoteIndex">current delimiter index</param>
/// <param name="endQuoteIndex">next delimiters index</param>
protected void UpdateDelimIndexes(ref string command, char delim, ref int beginQuoteIndex, ref int endQuoteIndex)
{
beginQuoteIndex = endQuoteIndex;
endQuoteIndex = command.IndexOf(delim, beginQuoteIndex + 1);
}
protected string ExceptionPacket(Exception exc, string requestId)
{
byte exceptionId = 0;
if (exc is OperationFailedException) exceptionId = (int)ExceptionType.OPERATIONFAILED;
else if (exc is Runtime.Exceptions.AggregateException) exceptionId = (int)ExceptionType.AGGREGATE;
else if (exc is ConfigurationException) exceptionId = (int)ExceptionType.CONFIGURATION;
else if (exc is SecurityException) exceptionId = (int)ExceptionType.SECURITY;
else if (exc is OperationNotSupportedException) exceptionId = (int)ExceptionType.NOTSUPPORTED;
else exceptionId = (int)ExceptionType.GENERALFAILURE;
return "EXCEPTION \"" + requestId + "\"" + exceptionId + "\"";
}
protected byte[] ExceptionMessage(Exception exc)
{
if (exc is Runtime.Exceptions.AggregateException)
{
Exception[] innerExceptions = ((Runtime.Exceptions.AggregateException)exc).InnerExceptions;
if (innerExceptions[0] != null)
return Util.HelperFxn.ToBytes(innerExceptions[0].ToString());
}
return Util.HelperFxn.ToBytes(exc.ToString());
}
protected byte[] ParsingExceptionMessage(Exception exc)
{
return Util.HelperFxn.ToBytes("ParsingException: " + exc.ToString());
}
public CancellationToken CancellationToken
{
get
{
if (_cancellationTokenSource == null)
_cancellationTokenSource = new CancellationTokenSource();
return _cancellationTokenSource.Token;
}
}
public void StartWatch ()
{
if (!_watch.IsRunning)
{
_watch.Start();
}
}
public long ElapsedTIme()
{
return _watch.ElapsedMilliseconds;
}
public void Dispose()
{
if (_cancellationTokenSource != null)
_cancellationTokenSource.Dispose();
if (_watch != null)
_watch.Stop();
}
public bool Cancel()
{
if (_cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested)
{
_cancellationTokenSource.Cancel();
return true;
}
return false;
}
#region ILeasable
public override void ResetLeasable()
{
_watch.Reset();
_userData = null;
immatureId = "-2";
forcedViewId = -5;
_elapsedTime = default;
_requestTimeout = default;
_cancellationTokenSource = default;
_serializedResponsePackets.Clear();
}
public override void ReturnLeasableToPool()
{
throw new NotImplementedException();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Drawing.Printing
{
/// <summary>
/// Controls how a document is printed.
/// </summary>
public abstract class PrintController
{
// DEVMODEs are pretty expensive, so we cache one here and share it with the
// Standard and Preview print controllers. If it weren't for all the rules about API changes,
// I'd consider making this protected.
#region SafeDeviceModeHandle Class
/// <summary>
/// Represents a SafeHandle for a Printer's Device Mode struct handle (DEVMODE)
/// </summary>
internal sealed class SafeDeviceModeHandle : SafeHandle
{
// This constructor is used by the P/Invoke marshaling layer
// to allocate a SafeHandle instance. P/Invoke then does the
// appropriate method call, storing the handle in this class.
private SafeDeviceModeHandle() : base(IntPtr.Zero, true) { return; }
internal SafeDeviceModeHandle(IntPtr handle)
: base(IntPtr.Zero, true) // "true" means "owns the handle"
{
SetHandle(handle);
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
// Specifies how to free the handle.
// The boolean returned should be true for success and false if the runtime
// should fire a SafeHandleCriticalFailure MDA (CustomerDebugProbe) if that
// MDA is enabled.
protected override bool ReleaseHandle()
{
if (!IsInvalid)
{
SafeNativeMethods.GlobalFree(new HandleRef(this, handle));
}
handle = IntPtr.Zero;
return true;
}
public static implicit operator IntPtr(SafeDeviceModeHandle handle)
{
return (handle == null) ? IntPtr.Zero : handle.handle;
}
public static explicit operator SafeDeviceModeHandle(IntPtr handle)
{
return new SafeDeviceModeHandle(handle);
}
}
#endregion
internal SafeDeviceModeHandle modeHandle = null;
/// <summary>
/// Initializes a new instance of the <see cref='PrintController'/> class.
/// </summary>
protected PrintController()
{
}
/// <summary>
/// This is new public property which notifies if this controller is used for PrintPreview.
/// </summary>
public virtual bool IsPreview
{
get
{
return false;
}
}
// WARNING: if you have nested PrintControllers, this method won't get called on the inner one.
// Add initialization code to StartPrint or StartPage instead.
internal void Print(PrintDocument document)
{
//
// Get the PrintAction for this event
PrintAction printAction;
if (IsPreview)
{
printAction = PrintAction.PrintToPreview;
}
else
{
printAction = document.PrinterSettings.PrintToFile ? PrintAction.PrintToFile : PrintAction.PrintToPrinter;
}
// Check that user has permission to print to this particular printer
PrintEventArgs printEvent = new PrintEventArgs(printAction);
document._OnBeginPrint(printEvent);
if (printEvent.Cancel)
{
document._OnEndPrint(printEvent);
return;
}
OnStartPrint(document, printEvent);
if (printEvent.Cancel)
{
document._OnEndPrint(printEvent);
OnEndPrint(document, printEvent);
return;
}
bool canceled = true;
try
{
// To enable optimization of the preview dialog, add the following to the config file:
// <runtime >
// <!-- AppContextSwitchOverrides values are in the form of 'key1=true|false;key2=true|false -->
// <AppContextSwitchOverrides value = "Switch.System.Drawing.Printing.OptimizePrintPreview=true" />
// </runtime >
canceled = LocalAppContextSwitches.OptimizePrintPreview ? PrintLoopOptimized(document) : PrintLoop(document);
}
finally
{
try
{
document._OnEndPrint(printEvent);
printEvent.Cancel = canceled | printEvent.Cancel;
}
finally
{
OnEndPrint(document, printEvent);
}
}
}
// Returns true if print was aborted.
// WARNING: if you have nested PrintControllers, this method won't get called on the inner one
// Add initialization code to StartPrint or StartPage instead.
private bool PrintLoop(PrintDocument document)
{
QueryPageSettingsEventArgs queryEvent = new QueryPageSettingsEventArgs((PageSettings)document.DefaultPageSettings.Clone());
for (;;)
{
document._OnQueryPageSettings(queryEvent);
if (queryEvent.Cancel)
{
return true;
}
PrintPageEventArgs pageEvent = CreatePrintPageEvent(queryEvent.PageSettings);
Graphics graphics = OnStartPage(document, pageEvent);
pageEvent.SetGraphics(graphics);
try
{
document._OnPrintPage(pageEvent);
OnEndPage(document, pageEvent);
}
finally
{
pageEvent.Dispose();
}
if (pageEvent.Cancel)
{
return true;
}
else if (!pageEvent.HasMorePages)
{
return false;
}
else
{
// loop
}
}
}
private bool PrintLoopOptimized(PrintDocument document)
{
PrintPageEventArgs pageEvent = null;
PageSettings documentPageSettings = (PageSettings)document.DefaultPageSettings.Clone();
QueryPageSettingsEventArgs queryEvent = new QueryPageSettingsEventArgs(documentPageSettings);
for (;;)
{
queryEvent.PageSettingsChanged = false;
document._OnQueryPageSettings(queryEvent);
if (queryEvent.Cancel)
{
return true;
}
if (!queryEvent.PageSettingsChanged)
{
// QueryPageSettings event handler did not change the page settings,
// thus we use default page settings from the document object.
if (pageEvent == null)
{
pageEvent = CreatePrintPageEvent(queryEvent.PageSettings);
}
else
{
// This is not the first page and the settings had not changed since the previous page,
// thus don't re-apply them.
pageEvent.CopySettingsToDevMode = false;
}
Graphics graphics = OnStartPage(document, pageEvent);
pageEvent.SetGraphics(graphics);
}
else
{
// Page settings were customized, so use the customized ones in the start page event.
pageEvent = CreatePrintPageEvent(queryEvent.PageSettings);
Graphics graphics = OnStartPage(document, pageEvent);
pageEvent.SetGraphics(graphics);
}
try
{
document._OnPrintPage(pageEvent);
OnEndPage(document, pageEvent);
}
finally
{
pageEvent.Graphics.Dispose();
pageEvent.SetGraphics(null);
}
if (pageEvent.Cancel)
{
return true;
}
else if (!pageEvent.HasMorePages)
{
return false;
}
}
}
private PrintPageEventArgs CreatePrintPageEvent(PageSettings pageSettings)
{
Debug.Assert((modeHandle != null), "modeHandle is null. Someone must have forgot to call base.StartPrint");
Rectangle pageBounds = pageSettings.GetBounds(modeHandle);
Rectangle marginBounds = new Rectangle(pageSettings.Margins.Left,
pageSettings.Margins.Top,
pageBounds.Width - (pageSettings.Margins.Left + pageSettings.Margins.Right),
pageBounds.Height - (pageSettings.Margins.Top + pageSettings.Margins.Bottom));
PrintPageEventArgs pageEvent = new PrintPageEventArgs(null, marginBounds, pageBounds, pageSettings);
return pageEvent;
}
/// <summary>
/// When overridden in a derived class, begins the control sequence of when and how to print a document.
/// </summary>
public virtual void OnStartPrint(PrintDocument document, PrintEventArgs e)
{
modeHandle = (SafeDeviceModeHandle)document.PrinterSettings.GetHdevmode(document.DefaultPageSettings);
}
/// <summary>
/// When overridden in a derived class, begins the control sequence of when and how to print a page in a document.
/// </summary>
public virtual Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e)
{
return null;
}
/// <summary>
/// When overridden in a derived class, completes the control sequence of when and how to print a page in a document.
/// </summary>
public virtual void OnEndPage(PrintDocument document, PrintPageEventArgs e)
{
}
/// <summary>
/// When overridden in a derived class, completes the control sequence of when and how to print a document.
/// </summary>
public virtual void OnEndPrint(PrintDocument document, PrintEventArgs e)
{
Debug.Assert((modeHandle != null), "modeHandle is null. Someone must have forgot to call base.StartPrint");
if (modeHandle != null)
{
modeHandle.Close();
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using SimpleJSON;
using System;
using System.Text;
namespace Xsolla
{
public class XsollaPaymentImpl : MonoBehaviour, IXsollaPayment {
private string DOMAIN = "https://secure.xsolla.com";
private const string SDK_VERSION = "1.4.2";
private const int TRANSLATIONS = 0;
private const int DIRECTPAYMENT_FORM = 1;
private const int DIRECTPAYMENT_STATUS = 2;
private const int PRICEPOINTS = 3;
private const int GOODS = 5;
private const int GOODS_GROUPS = 51;
private const int GOODS_ITEMS = 52;
private const int PAYMENT_LIST = 6;
private const int SAVED_PAYMENT_LIST = 61;
private const int QUICK_PAYMENT_LIST = 7;
private const int COUNTRIES = 8;
private const int VIRTUAL_STATUS = 11;
private const int APPLY_PROMO_COUPONE = 12;
private const int COUPON_PROCEED = 13;
private const int HISTORY = 22;
private const int PAYMENT_MANAGER_LIST = 15;
private const int CALCULATE_CUSTOM_AMOUNT = 14;
private const int ACTIVE_SUBS = 16;
private const int DELETE_SAVED_METHOD = 17;
private const int SUBSCRIPTIONS_MANAGER_LIST = 18;
public Action<XsollaUtils> UtilsRecieved;
public Action<XsollaTranslations> TranslationRecieved;
public Action<XsollaPricepointsManager> PricepointsRecieved;
public Action<XsollaGroupsManager> GoodsGroupsRecieved;
public Action<XsollaGoodsManager> GoodsRecieved;
public Action<XsollaPaymentMethods> PaymentMethodsRecieved;
public Action<XsollaSavedPaymentMethods> SavedPaymentMethodsRecieved;
public Action<XsollaQuickPayments> QuickPaymentMethodsRecieved;
public Action<XsollaQuickPayments> QuickPaymentMethodsRecievedNew;
public Action<XsollaCountries> CountriesRecieved;
public Action<XsollaForm> FormReceived;
public Action<XsollaStatus, XsollaForm> StatusReceived;
public Action<XsollaForm> ApplyCouponeCodeReceived;
public Action<XsollaStatusPing> StatusChecked;
public Action<XsollaError> ErrorReceived;
public Action<XsollaCouponProceedResult> CouponProceedErrorRecived;
public Action<CustomVirtCurrAmountController.CustomAmountCalcRes> CustomAmountCalcRecieved;
public Action<XsollaSummaryRecived> VirtualPaymentSummaryRecieved;
public Action<string> VirtualPaymentProceedError;
public Action<XVPStatus> VirtualPaymentStatusRecieved;
public Action<XsollaSavedPaymentMethods, bool> PaymentManagerMethods;
public Action DeleteSavedPaymentMethodRespond;
public Action WaitChangeSavedMethods;
public Action<XsollaManagerSubscriptions> SubsManagerListRecived;
//TODO CHANGE PARAMS
protected string _accessToken;
protected Dictionary<string, object> baseParams;
protected HttpTlsRequest httpreq;
public XsollaPaymentImpl(){
}
public XsollaPaymentImpl(string accessToken){
this._accessToken = accessToken;
}
public void InitPaystation(XsollaWallet xsollaWallet)
{
this._accessToken = xsollaWallet.GetToken ();
GetUtils (null);
}
public void InitPaystation(string accessToken)
{
this._accessToken = accessToken;
GetUtils (null);
}
public void InitPaystation(Dictionary<string, object> pararams)
{
baseParams = new Dictionary<string, object> (pararams);
GetUtils (pararams);
}
public void StartPaymentWithoutUtils(XsollaWallet xsollaWallet)
{
this._accessToken = xsollaWallet.GetToken ();
GetNextStep (new Dictionary<string, object> ());
}
public void NextStep(Dictionary<string, object> xpsMap)
{
GetNextStep (xpsMap);
}
public void Status(string token, long invoice)
{
}
public void SetModeSandbox(bool isSandbox)
{
if (!isSandbox) {
DOMAIN = "https://secure.xsolla.com";
} else {
DOMAIN = "https://sandbox-secure.xsolla.com";
}
}
public void SetDomain(string domain)
{
DOMAIN = domain;
}
public void SetToken (string token)
{
this._accessToken = token;
}
// ---------------------------------------------------------------------------
private void OnUtilsRecieved(XsollaUtils utils)
{
if(UtilsRecieved != null)
UtilsRecieved(utils);
}
private void OnPricepointsRecieved(XsollaPricepointsManager pricepoints)
{
if(PricepointsRecieved != null)
PricepointsRecieved(pricepoints);
}
private void OnGoodsRecieved(XsollaGoodsManager goods)
{
if(GoodsRecieved != null)
GoodsRecieved(goods);
}
private void OnGoodsGroupsRecieved(XsollaGroupsManager groups)
{
if(GoodsGroupsRecieved != null)
GoodsGroupsRecieved(groups);
}
// ---------------------------------------------------------------------------
private void OnVPSummaryRecieved(XsollaSummaryRecived summary)
{
if(VirtualPaymentSummaryRecieved != null)
VirtualPaymentSummaryRecieved(summary);
}
private void OnVPProceedError(string error)
{
if(VirtualPaymentProceedError != null)
VirtualPaymentProceedError(error);
}
private void OnVPStatusRecieved(XVPStatus status)
{
if (VirtualPaymentStatusRecieved != null)
VirtualPaymentStatusRecieved (status);
}
private void OnPaymentMethodsRecieved(XsollaPaymentMethods paymentMethods)
{
if(PaymentMethodsRecieved != null)
PaymentMethodsRecieved(paymentMethods);
}
private void OnSavedPaymentMethodsRecieved(XsollaSavedPaymentMethods pMethods)
{
if (SavedPaymentMethodsRecieved != null)
SavedPaymentMethodsRecieved(pMethods);
}
private void OnQuickPaymentMethodsRecieved(XsollaQuickPayments quickPayments)
{
if(QuickPaymentMethodsRecieved != null)
QuickPaymentMethodsRecieved(quickPayments);
}
private void OnQuickPaymentMethodsRecievedNew(XsollaQuickPayments quickPayments)
{
if(QuickPaymentMethodsRecievedNew != null)
QuickPaymentMethodsRecievedNew(quickPayments);
}
private void OnCountriesRecieved(XsollaCountries countries)
{
if(CountriesRecieved != null)
CountriesRecieved(countries);
}
protected virtual void OnTranslationRecieved(XsollaTranslations translations)
{
if (TranslationRecieved != null)
TranslationRecieved(translations);
}
// ---------------------------------------------------------------------------
protected virtual void OnFormReceived(XsollaForm form)
{
if (FormReceived != null)
FormReceived(form);
}
protected virtual void OnStatusReceived(XsollaStatus status, XsollaForm form)
{
if (StatusReceived != null)
StatusReceived(status, form);
}
protected virtual void OnApplyCouponeReceived(XsollaForm pForm)
{
if (ApplyCouponeCodeReceived != null)
ApplyCouponeCodeReceived(pForm);
}
protected virtual void OnStatusChecked(XsollaStatusPing pStatus)
{
if (StatusChecked != null)
StatusChecked(pStatus);
}
protected virtual void OnErrorReceived(XsollaError error)
{
if (ErrorReceived != null)
ErrorReceived(error);
}
protected virtual void OnCouponProceedErrorRecived(XsollaCouponProceedResult pCouponObj)
{
if (CouponProceedErrorRecived != null)
CouponProceedErrorRecived(pCouponObj);
}
protected virtual void OnCustomAmountResRecieved(CustomVirtCurrAmountController.CustomAmountCalcRes pRes)
{
if (CustomAmountCalcRecieved != null)
CustomAmountCalcRecieved(pRes);
}
protected virtual void OnPaymentManagerMethod(XsollaSavedPaymentMethods pRes, bool pAddState)
{
if (PaymentManagerMethods != null)
PaymentManagerMethods(pRes, pAddState);
}
protected virtual void OnManageSubsListrecived(XsollaManagerSubscriptions pListSubs)
{
if (SubsManagerListRecived != null)
SubsManagerListRecived(pListSubs);
}
protected virtual void OnDeleteSavedPaymentMethod()
{
if (DeleteSavedPaymentMethodRespond != null)
DeleteSavedPaymentMethodRespond();
}
private void OnWaitPaymentChange()
{
if(WaitChangeSavedMethods != null)
WaitChangeSavedMethods();
}
// ---------------------------------------------------------------------------
public void VPaymentStatus(Dictionary<string, object> pararams) {
StartCoroutine(POST (VIRTUAL_STATUS, GetVirtualPaymentStatusLink (), pararams));
}
void GetUtils(Dictionary<string, object> pararams)
{
StartCoroutine(POST (TRANSLATIONS, GetUtilsLink(), pararams));
}
void GetNextStep(Dictionary<string, object> nextStepParams)
{
if (nextStepParams.Count == 0) {
nextStepParams.Add ("pid", 26);
}
if (!nextStepParams.ContainsKey ("paymentWithSavedMethod")) {
nextStepParams.Add ("paymentWithSavedMethod", 0);
}
StartCoroutine(POST (DIRECTPAYMENT_FORM, GetDirectpaymentLink(), nextStepParams));
}
public void GetStatus(Dictionary<string, object> statusParams)
{
StartCoroutine(POST (DIRECTPAYMENT_STATUS, GetStatusLink(), statusParams));
}
public void GetPricePoints(Dictionary<string, object> requestParams)
{
StartCoroutine(POST (PRICEPOINTS, GetPricepointsUrl(), requestParams));
}
public void GetGoods(Dictionary<string, object> requestParams)
{
StartCoroutine(POST (GOODS, GetGoodsUrl(), requestParams));
}
public void GetItemsGroups(Dictionary<string, object> requestParams)
{
StartCoroutine(POST (GOODS_GROUPS, GetItemsGroupsUrl(), requestParams));
}
public void GetItems(long groupId, Dictionary<string, object> requestParams)
{
requestParams.Add ("group_id", groupId );//group_id <- NEW | OLD -> requestParams.Add ("id_group",groupId );
StartCoroutine(POST (GOODS_ITEMS, GetItemsUrl(), requestParams));
}
public void GetFavorites(Dictionary<string, object> requestParams)
{
StartCoroutine(POST (GOODS_ITEMS, GetFavoritsUrl(), requestParams));
}
public void GetCouponProceed(Dictionary<string, object> pParams)
{
if (!pParams.ContainsKey(XsollaApiConst.ACCESS_TOKEN) && (baseParams.ContainsKey(XsollaApiConst.ACCESS_TOKEN)))
pParams.Add(XsollaApiConst.ACCESS_TOKEN, baseParams[XsollaApiConst.ACCESS_TOKEN]);
StartCoroutine(POST(COUPON_PROCEED, GetCouponProceed(), pParams));
}
public void SetFavorite(Dictionary<string, object> requestParams)
{
StartCoroutine(POST (999, SetFavoritsUrl(), requestParams));
}
public void GetPaymentsInfo(Dictionary<string, object> requestParams)
{
StartCoroutine(POST (QUICK_PAYMENT_LIST, GetQuickPaymentsUrl(), requestParams));
StartCoroutine(POST (PAYMENT_LIST, GetPaymentListUrl(), requestParams));
StartCoroutine(POST (COUNTRIES, GetCountriesListUrl(), requestParams));
}
public void GetQuickPayments(string countryIso, Dictionary<string, object> requestParams)
{
if (countryIso != null && !"".Equals (countryIso)) {
requestParams["country"] = countryIso;
}
StartCoroutine(POST (QUICK_PAYMENT_LIST, GetQuickPaymentsUrl(), requestParams));
}
public void GetPayments(string countryIso, Dictionary<string, object> requestParams)
{
if (countryIso != null && !"".Equals (countryIso)) {
requestParams["country"] = countryIso;
}
StartCoroutine(POST (PAYMENT_LIST, GetPaymentListUrl(), requestParams));
}
public void GetSavedPayments(Dictionary<string, object> requestParams)
{
StartCoroutine(POST(SAVED_PAYMENT_LIST, GetSavedPaymentListUrl(), requestParams));
}
public void GetSavedPaymentsForManager(Dictionary<string, object> pParams)
{
StartCoroutine(POST(PAYMENT_MANAGER_LIST, GetSavedPaymentListUrl(), pParams));
}
public void GetSubscriptionForManager(Dictionary<string, object> pParams)
{
StartCoroutine(POST(SUBSCRIPTIONS_MANAGER_LIST, GetSubscriptionsList(), pParams));
}
public void GetCountries(Dictionary<string, object> requestParams)
{
StartCoroutine(POST (COUNTRIES, GetCountriesListUrl(), requestParams));
}
public void ApplyPromoCoupone(Dictionary<string, object> pParams)
{
StartCoroutine(POST(APPLY_PROMO_COUPONE, GetDirectpaymentLink(), pParams));
}
public void CalculateCustomAmount(Dictionary<string, object> pParams)
{
if (!pParams.ContainsKey(XsollaApiConst.ACCESS_TOKEN))
pParams.Add(XsollaApiConst.ACCESS_TOKEN, baseParams[XsollaApiConst.ACCESS_TOKEN]);
StartCoroutine(POST(CALCULATE_CUSTOM_AMOUNT, GetCalculateCustomAmountUrl(), pParams));
}
public void DeleteSavedMethod(Dictionary<string, object> pParam)
{
if (!pParam.ContainsKey(XsollaApiConst.ACCESS_TOKEN))
pParam.Add(XsollaApiConst.ACCESS_TOKEN, baseParams[XsollaApiConst.ACCESS_TOKEN]);
StartCoroutine(POST(DELETE_SAVED_METHOD, GetDeleteSavedPaymentMethodUrl(), pParam));
}
public IEnumerator POST(int type, string url, Dictionary<string, object> post)
{
WWWForm form = new WWWForm();
StringBuilder sb = new StringBuilder ();
if (!post.ContainsKey (XsollaApiConst.ACCESS_TOKEN) && !post.ContainsKey ("project") && !post.ContainsKey ("access_data") && baseParams != null)
{
foreach (KeyValuePair<string, object> kv in baseParams)
post.Add (kv.Key, kv.Value);
if (!post.ContainsKey(XsollaApiConst.ACCESS_TOKEN) && !baseParams.ContainsKey(XsollaApiConst.ACCESS_TOKEN) && (_accessToken != ""))
post.Add(XsollaApiConst.ACCESS_TOKEN, _accessToken);
}
if (type == DIRECTPAYMENT_STATUS)
TransactionHelper.SaveRequest (post);
if(!post.ContainsKey("alternative_platform"))
post.Add ("alternative_platform", "unity/" + SDK_VERSION);
foreach(KeyValuePair<string,object> post_arg in post)
{
string argValue = post_arg.Value != null ? post_arg.Value.ToString() : "";
sb.Append(post_arg.Key).Append("=").Append(argValue).Append("&");
form.AddField(post_arg.Key, argValue);
}
Debug.Log (url);
Debug.Log (sb.ToString());
WWW www = new WWW(url, form);
yield return StartCoroutine(WaitForRequest(type, www, post));
}
private IEnumerator WaitForRequest(int pType, WWW www, Dictionary<string, object> post)
{
Logger.Log("Start get www");
yield return www;
// check for errors
if (www.error == null || www.error == "")
{
Debug.Log("Type -> " + pType);
Debug.Log("WWW_request -> " + www.text);
string data = www.text;
JSONNode rootNode = JSON.Parse(www.text);
if(rootNode != null && rootNode.Count > 2 || rootNode["error"] == null) {
switch(pType)
{
case TRANSLATIONS:
{
if(rootNode.Count > 2){
XsollaUtils utils = new XsollaUtils().Parse(rootNode) as XsollaUtils;
projectId = utils.GetProject().id.ToString();
if (baseParams.ContainsKey(XsollaApiConst.ACCESS_TOKEN))
utils.SetAccessToken(baseParams[XsollaApiConst.ACCESS_TOKEN].ToString());
OnUtilsRecieved(utils);
OnTranslationRecieved(utils.GetTranslations());
} else {
XsollaError error = new XsollaError();
error.Parse(rootNode);
OnErrorReceived(error);
}
break;
}
case DIRECTPAYMENT_FORM:
{
if(rootNode.Count > 8) {
XsollaForm form = new XsollaForm();
form.Parse(rootNode);
switch (form.GetCurrentCommand()) {
case XsollaForm.CurrentCommand.STATUS:
// if we replaced or add saved account, we must start loop on get list saved account
if (post.ContainsKey("save_payment_account_only") || (post.ContainsKey("replace_payment_account")))
{
if (!form.IsCardPayment() && !(post.ContainsKey("replace_payment_account")))
{
OnWaitPaymentChange();
break;
}
else
{
OnPaymentManagerMethod(null, post.ContainsKey("replace_payment_account")?false:true);
break;
}
}
GetStatus(form.GetXpsMap());
break;
case XsollaForm.CurrentCommand.CHECKOUT:
case XsollaForm.CurrentCommand.CHECK:
case XsollaForm.CurrentCommand.FORM:
case XsollaForm.CurrentCommand.CREATE:
case XsollaForm.CurrentCommand.ACCOUNT:
OnFormReceived(form);
break;
case XsollaForm.CurrentCommand.UNKNOWN:
if(rootNode.Count > 10)
{
OnFormReceived(form);
} else {
XsollaError error = new XsollaError();
error.Parse(rootNode);
OnErrorReceived(error);
}
break;
default:
break;
}
} else {
XsollaStatusPing statusPing = new XsollaStatusPing();
statusPing.Parse(rootNode);
OnStatusChecked(statusPing);
}
break;
}
case DIRECTPAYMENT_STATUS:
{
XsollaForm form = new XsollaForm();
form.Parse(rootNode);
XsollaStatus status = new XsollaStatus();
status.Parse(rootNode);
OnStatusReceived(status, form);
break;
}
case PRICEPOINTS:
{
XsollaPricepointsManager pricepoints = new XsollaPricepointsManager();
pricepoints.Parse(rootNode);
OnPricepointsRecieved(pricepoints);
break;
}
case GOODS:
{
XsollaGoodsManager goods = new XsollaGoodsManager();
goods.Parse(rootNode);
OnGoodsRecieved(goods);
break;
}
case GOODS_GROUPS:
{
XsollaGroupsManager groups = new XsollaGroupsManager();
groups.Parse(rootNode);
OnGoodsGroupsRecieved(groups);
break;
}
case GOODS_ITEMS:
{
XsollaGoodsManager goods = new XsollaGoodsManager();
goods.Parse(rootNode);
OnGoodsRecieved(goods);
break;
}
case PAYMENT_LIST:
{
XsollaPaymentMethods paymentMethods = new XsollaPaymentMethods();
paymentMethods.Parse(rootNode);
OnPaymentMethodsRecieved(paymentMethods);
break;
}
case SAVED_PAYMENT_LIST:
{
XsollaSavedPaymentMethods savedPaymentsMethods = new XsollaSavedPaymentMethods();
savedPaymentsMethods.Parse(rootNode);
OnSavedPaymentMethodsRecieved(savedPaymentsMethods);
break;
}
case QUICK_PAYMENT_LIST:
{
XsollaQuickPayments quickPayments = new XsollaQuickPayments();
quickPayments.Parse(rootNode);
OnQuickPaymentMethodsRecieved(quickPayments);
break;
}
case COUNTRIES:
{
XsollaCountries countries = new XsollaCountries();
countries.Parse(rootNode);
OnCountriesRecieved(countries);
break;
}
case VIRTUAL_STATUS:
{
XVPStatus vpStatus = new XVPStatus();
vpStatus.Parse(rootNode);
Logger.Log ("VIRTUAL_STATUS" + vpStatus.ToString());
OnVPStatusRecieved(vpStatus);
break;
}
case APPLY_PROMO_COUPONE:
{
XsollaForm form = new XsollaForm();
form.Parse(rootNode);
OnApplyCouponeReceived(form);
break;
}
case COUPON_PROCEED:
{
XsollaCouponProceedResult couponProceed = new XsollaCouponProceedResult();
couponProceed.Parse(rootNode);
if (couponProceed._error != null)
{
Logger.Log("COUPON_PROCEED ERROR: " + couponProceed._error);
OnCouponProceedErrorRecived(couponProceed);
}
else
{
long operationId = couponProceed._operationId;
if (post.ContainsKey("coupon_code"))
post.Remove("coupon_code");
post.Add("operation_id", operationId);
VPaymentStatus(post);
}
break;
}
case CALCULATE_CUSTOM_AMOUNT:
{
CustomVirtCurrAmountController.CustomAmountCalcRes res = new CustomVirtCurrAmountController.CustomAmountCalcRes().Parse(rootNode["calculation"]) as CustomVirtCurrAmountController.CustomAmountCalcRes;
OnCustomAmountResRecieved(res);
break;
}
case PAYMENT_MANAGER_LIST:
{
XsollaSavedPaymentMethods res = new XsollaSavedPaymentMethods().Parse(rootNode) as XsollaSavedPaymentMethods;
OnPaymentManagerMethod(res, false);
break;
}
case DELETE_SAVED_METHOD:
{
OnDeleteSavedPaymentMethod();
break;
}
case SUBSCRIPTIONS_MANAGER_LIST:
{
XsollaManagerSubscriptions lSubsList = new XsollaManagerSubscriptions().Parse(rootNode["subscriptions"]) as XsollaManagerSubscriptions;
OnManageSubsListrecived(lSubsList);
break;
}
default:
break;
}
}
else
{
XsollaError error = new XsollaError();
error.Parse(rootNode);
OnErrorReceived(error);
}
}
else
{
JSONNode errorNode = JSON.Parse(www.text);
string errorMsg = errorNode["errors"].AsArray[0]["message"].Value
+ ". Support code " + errorNode["errors"].AsArray[0]["support_code"].Value;
int errorCode = 0;
if(www.error.Length > 3)
errorCode = int.Parse(www.error.Substring(0, 3));
else
errorCode = int.Parse(www.error);
OnErrorReceived(new XsollaError(errorCode, errorMsg));
}
if(projectId != null && !"".Equals(projectId))
LogEvent ("UNITY " + SDK_VERSION + " REQUEST", projectId, www.url);
else
LogEvent ("UNITY " + SDK_VERSION + " REQUEST", "undefined", www.url);
}
private string GetUtilsLink(){
return DOMAIN + "/paystation2/api/utils";
}
private string GetDirectpaymentLink(){
return DOMAIN + "/paystation2/api/directpayment";
}
private string GetStatusLink(){
return DOMAIN + "/paystation2/api/directpayment";
}
/* PAYMENT METHODS LINKS */
private string GetPricepointsUrl(){
return DOMAIN + "/paystation2/api/pricepoints";
}
private string GetGoodsUrl(){
return DOMAIN + "/paystation2/api/digitalgoods";
}
private string GetFavoritsUrl(){
return DOMAIN + "/paystation2/api/virtualitems/favorite";
}
private string SetFavoritsUrl(){
return DOMAIN + "/paystation2/api/virtualitems/setfavorite";
}
private string GetItemsGroupsUrl(){
return DOMAIN + "/paystation2/api/virtualitems/groups";
}
private string GetCouponProceed()
{
return DOMAIN + "/paystation2/api/coupons/proceed";
}
private string GetItemsUrl(){
return DOMAIN + "/paystation2/api/virtualitems/items";
}
/* PAYMENT METHODS LINKS */
private string GetPaymentListUrl()
{
return DOMAIN + "/paystation2/api/paymentlist/payment_methods";
}
private string GetSavedPaymentListUrl(){
return DOMAIN + "/paystation2/api/savedmethods";
}
private string GetQuickPaymentsUrl(){
return DOMAIN + "/paystation2/api/paymentlist/quick_payments";
}
private string GetCountriesListUrl(){
return DOMAIN + "/paystation2/api/country";
}
private string GetSubsUrl()
{
return DOMAIN + "/paystation2/api/recurring/active";
}
/* BUY WITH VIRTUAL CURERENCY */
private string GetCartSummary() {
return DOMAIN + "/paystation2/api/cart/summary";
}
private string ProceedVirtualPaymentLink() {
return DOMAIN + "/paystation2/api/virtualpayment/proceed";
}
private string GetVirtualPaymentStatusLink() {
return DOMAIN + "/paystation2/api/virtualstatus";
}
private string GetCalculateCustomAmountUrl()
{
return DOMAIN + "/paystation2/api/pricepoints/calculate";
}
private string GetDeleteSavedPaymentMethodUrl()
{
return DOMAIN + "/paystation2/api/savedmethods/delete";
}
private string GetSubscriptionsList()
{
return DOMAIN + "/paystation2/api/useraccount/subscriptions";
}
//*** GA SECTION START ***
private string propertyID = "UA-62372273-1";
private static XsollaPaymentImpl instance;
private string bundleID = "Unity";
private string appName;
private string projectId = "";
private string screenRes;
private string clientID;
// void Awake()
// {
// if(instance)
// DestroyImmediate(gameObject);
// else
// {
// DontDestroyOnLoad(gameObject);
// instance = this;
// }
// }
void Start()
{
appName = GetProjectName ();
screenRes = Screen.width + "x" + Screen.height;
#if UNITY_IPHONE
clientID = SystemInfo.deviceUniqueIdentifier;// iPhoneSettings.uniqueIdentifier;
#else
clientID = SystemInfo.deviceUniqueIdentifier;
#endif
}
public void LogScreen(string title)
{
// Debug.Log ("Google Analytics - Screen --> " + title);
title = WWW.EscapeURL(title);
var url = "https://www.google-analytics.com/collect?v=1&ul=en-us&t=appview&sr="+screenRes+"&an="+WWW.EscapeURL(appName)+"&a=448166238&tid="+propertyID+"&aid="+bundleID+"&cid="+WWW.EscapeURL(clientID)+"&_u=.sB&av="+SDK_VERSION+"&_v=ma1b3&cd="+title+"&qt=2500&z=185";
StartCoroutine( Process(new WWW(url)) );
}
/* MOBILE EVENT TRACKING: https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide */
public void LogEvent(string titleCat, string titleAction, string actionLable)
{
titleCat = WWW.EscapeURL(titleCat);
titleAction = WWW.EscapeURL(titleAction);
actionLable = WWW.EscapeURL (actionLable);
//LOG Google analitic
//Debug.Log ("Google Analytics - Event --> " + titleAction + " -->" + titleCat + " -->" + actionLable);
var url = "https://www.google-analytics.com/collect?v=1&ul=en-us&t=event&sr="+screenRes+"&an="+WWW.EscapeURL(appName)+"&a=448166238&tid="+propertyID+"&aid="+bundleID+"&cid="+WWW.EscapeURL(clientID)+"&_u=.sB&av="+SDK_VERSION+"&_v=ma1b3&ec="+titleCat+"&ea="+titleAction+"&el"+actionLable+"&qt=2500&z=185";
StartCoroutine( Process(new WWW(url)) );
}
public void LogEvent(string titleCat, string actionLable)
{
//LOG Google analitic
//Debug.Log ("Google Analytics - Event --> " + actionLable);
titleCat = WWW.EscapeURL(titleCat);
if (projectId == null) {
projectId = GetProjectName();//PlayerSettings.companyName + " | " + PlayerSettings.productName;
projectId = WWW.EscapeURL (projectId);
}
actionLable = WWW.EscapeURL (actionLable);
var url = "https://www.google-analytics.com/collect?v=1&ul=en-us&t=event&sr="+screenRes+"&an="+WWW.EscapeURL(appName)+"&a=448166238&tid="+propertyID+"&aid="+bundleID+"&cid="+WWW.EscapeURL(clientID)+"&_u=.sB&av="+SDK_VERSION+"&_v=ma1b3&ec="+titleCat+"&ea="+projectId+"&el="+actionLable+"&qt=2500&z=185";
StartCoroutine( Process(new WWW(url)) );
}
private IEnumerator Process(WWW www)
{
yield return www;
if(www.error == null || www.error == "")
{
if (www.responseHeaders.ContainsKey("STATUS"))
{
//LOG Google analitic
if (www.responseHeaders["STATUS"] == "HTTP/1.1 200 OK")
{
//Debug.Log ("GA Success");
} else {
//Debug.LogWarning(www.responseHeaders["STATUS"]);
}
}else{
Debug.LogWarning("Event failed to send to Google");
}
}else{
Debug.LogWarning(www.error.ToString());
}
www.Dispose();
}
//*** GA SECTION END ***
public string GetProjectName()
{
string[] s = Application.dataPath.Split('/');
string projectName = s[s.Length - 2];
// Debug.Log("project = " + projectName);
return projectName;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Cci.Extensions;
using Microsoft.Cci.Extensions.CSharp;
using Microsoft.Cci.Filters;
using Microsoft.Cci.Traversers;
using Microsoft.Cci.Writers.CSharp;
using Microsoft.Cci.Writers.Syntax;
namespace Microsoft.Cci.Writers
{
public class CSharpWriter : SimpleTypeMemberTraverser, ICciWriter
{
private readonly ISyntaxWriter _syntaxWriter;
private readonly IStyleSyntaxWriter _styleWriter;
private readonly CSDeclarationWriter _declarationWriter;
private readonly bool _writeAssemblyAttributes;
private readonly bool _apiOnly;
private readonly ICciFilter _cciFilter;
private bool _firstMemberGroup;
public CSharpWriter(ISyntaxWriter writer, ICciFilter filter, bool apiOnly, bool writeAssemblyAttributes = false)
: base(filter)
{
_syntaxWriter = writer;
_styleWriter = writer as IStyleSyntaxWriter;
_apiOnly = apiOnly;
_cciFilter = filter;
_declarationWriter = new CSDeclarationWriter(_syntaxWriter, filter, !apiOnly);
_writeAssemblyAttributes = writeAssemblyAttributes;
}
public ISyntaxWriter SyntaxWriter { get { return _syntaxWriter; } }
public ICciDeclarationWriter DeclarationWriter { get { return _declarationWriter; } }
public bool IncludeSpaceBetweenMemberGroups { get; set; }
public bool IncludeMemberGroupHeadings { get; set; }
public bool HighlightBaseMembers { get; set; }
public bool HighlightInterfaceMembers { get; set; }
public bool PutBraceOnNewLine { get; set; }
public bool IncludeGlobalPrefixForCompilation
{
get { return _declarationWriter.ForCompilationIncludeGlobalPrefix; }
set { _declarationWriter.ForCompilationIncludeGlobalPrefix = value; }
}
public string PlatformNotSupportedExceptionMessage
{
get { return _declarationWriter.PlatformNotSupportedExceptionMessage; }
set { _declarationWriter.PlatformNotSupportedExceptionMessage = value; }
}
public bool AlwaysIncludeBase
{
get { return _declarationWriter.AlwaysIncludeBase; }
set { _declarationWriter.AlwaysIncludeBase = value; }
}
public void WriteAssemblies(IEnumerable<IAssembly> assemblies)
{
foreach (var assembly in assemblies)
Visit(assembly);
}
public override void Visit(IAssembly assembly)
{
if (_writeAssemblyAttributes)
{
_declarationWriter.WriteDeclaration(assembly);
}
base.Visit(assembly);
}
public override void Visit(INamespaceDefinition ns)
{
if (ns != null && string.IsNullOrEmpty(ns.Name.Value))
{
base.Visit(ns);
}
else
{
_declarationWriter.WriteDeclaration(ns);
using (_syntaxWriter.StartBraceBlock(PutBraceOnNewLine))
{
base.Visit(ns);
}
}
_syntaxWriter.WriteLine();
}
public override void Visit(IEnumerable<ITypeDefinition> types)
{
WriteMemberGroupHeader(types.FirstOrDefault(Filter.Include) as ITypeDefinitionMember);
base.Visit(types);
}
public override void Visit(ITypeDefinition type)
{
_declarationWriter.WriteDeclaration(type);
if (!type.IsDelegate)
{
using (_syntaxWriter.StartBraceBlock(PutBraceOnNewLine))
{
// If we have no constructors then output a private one this
// prevents the C# compiler from creating a default public one.
var constructors = type.Methods.Where(m => m.IsConstructor && Filter.Include(m));
if (!type.IsStatic && !constructors.Any())
{
// HACK... this will likely not work for any thing other than CSDeclarationWriter
_declarationWriter.WriteDeclaration(CSDeclarationWriter.GetDummyConstructor(type));
_syntaxWriter.WriteLine();
}
_firstMemberGroup = true;
base.Visit(type);
}
}
_syntaxWriter.WriteLine();
}
public override void Visit(IEnumerable<ITypeDefinitionMember> members)
{
WriteMemberGroupHeader(members.FirstOrDefault(Filter.Include));
base.Visit(members);
}
public override void Visit(ITypeDefinition parentType, IEnumerable<IFieldDefinition> fields)
{
if (parentType.IsStruct && !_apiOnly)
{
// For compile-time compat, the following rules should work for producing a reference assembly. We drop all private fields, but add back certain synthesized private fields for a value type (struct) as follows:
// - If there are any private fields that are or contain any value type members, add a single private field of type int.
// - And, if there are any private fields that are or contain any reference type members, add a single private field of type object.
// - And, if the type is generic, then for every type parameter of the type, if there are any private fields that are or contain any members whose type is that type parameter, we add a direct private field of that type.
// Note: By "private", we mean not visible outside the assembly.
// For more details see issue https://github.com/dotnet/corefx/issues/6185
// this blog is helpful as well http://blog.paranoidcoding.com/2016/02/15/are-private-members-api-surface.html
List<IFieldDefinition> newFields = new List<IFieldDefinition>();
var includedVisibleFields = fields.Where(f => f.IsVisibleOutsideAssembly()).Where(_cciFilter.Include);
includedVisibleFields = includedVisibleFields.OrderBy(GetMemberKey, StringComparer.OrdinalIgnoreCase);
var excludedFields = fields.Except(includedVisibleFields).Where(f => !f.IsStatic);
if (excludedFields.Any())
{
var genericTypedFields = excludedFields.Where(f => f.Type.UnWrap().IsGenericParameter());
// Compiler needs to see any fields, even private, that have generic arugments to be able
// to validate there aren't any struct layout cycles
foreach (var genericField in genericTypedFields)
newFields.Add(genericField);
// For definiteassignment checks the compiler needs to know there is a private field
// that has not been initialized so if there are any we need to add a dummy private
// field to help the compiler do its job and error about uninitialized structs
bool hasRefPrivateField = excludedFields.Any(f => f.Type.IsOrContainsReferenceType());
// If at least one of the private fields contains a reference type then we need to
// set this field type to object or reference field to inform the compiler to block
// taking pointers to this struct because the GC will not track updating those references
if (hasRefPrivateField)
{
IFieldDefinition fieldType = DummyFieldWriterHelper(parentType, excludedFields, parentType.PlatformType.SystemObject);
newFields.Add(fieldType);
}
bool hasValueTypePrivateField = excludedFields.Any(f => !f.Type.IsOrContainsReferenceType());
if (hasValueTypePrivateField)
{
IFieldDefinition fieldType = DummyFieldWriterHelper(parentType, excludedFields, parentType.PlatformType.SystemInt32, "_dummyPrimitive");
newFields.Add(fieldType);
}
}
foreach (var visibleField in includedVisibleFields)
newFields.Add(visibleField);
foreach (var field in newFields)
Visit(field);
}
else
{
base.Visit(parentType, fields);
}
}
private IFieldDefinition DummyFieldWriterHelper(ITypeDefinition parentType, IEnumerable<IFieldDefinition> excludedFields, ITypeReference fieldType, string fieldName = "_dummy")
{
// For primitive types that have a field of their type set the dummy field to that type
if (excludedFields.Count() == 1)
{
var onlyField = excludedFields.First();
if (TypeHelper.TypesAreEquivalent(onlyField.Type, parentType))
{
fieldType = parentType;
}
}
return new DummyPrivateField(parentType, fieldType, fieldName);
}
public override void Visit(ITypeDefinitionMember member)
{
IDisposable style = null;
if (_styleWriter != null)
{
// Favor overrides over interface implemenations (i.e. consider override Dispose() as an override and not an interface implementation)
if (this.HighlightBaseMembers && member.IsOverride())
style = _styleWriter.StartStyle(SyntaxStyle.InheritedMember);
else if (this.HighlightInterfaceMembers && member.IsInterfaceImplementation())
style = _styleWriter.StartStyle(SyntaxStyle.InterfaceMember);
}
_declarationWriter.WriteDeclaration(member);
if (style != null)
style.Dispose();
_syntaxWriter.WriteLine();
base.Visit(member);
}
private void WriteMemberGroupHeader(ITypeDefinitionMember member)
{
if (IncludeMemberGroupHeadings || IncludeSpaceBetweenMemberGroups)
{
string header = CSharpWriter.MemberGroupHeading(member);
if (header != null)
{
if (IncludeSpaceBetweenMemberGroups)
{
if (!_firstMemberGroup)
_syntaxWriter.WriteLine(true);
_firstMemberGroup = false;
}
if (IncludeMemberGroupHeadings)
{
IDisposable dispose = null;
if (_styleWriter != null)
dispose = _styleWriter.StartStyle(SyntaxStyle.Comment);
_syntaxWriter.Write("// {0}", header);
if (dispose != null)
dispose.Dispose();
_syntaxWriter.WriteLine();
}
}
}
}
public static string MemberGroupHeading(ITypeDefinitionMember member)
{
if (member == null)
return null;
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
{
if (method.IsConstructor)
return "Constructors";
return "Methods";
}
IFieldDefinition field = member as IFieldDefinition;
if (field != null)
return "Fields";
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return "Properties";
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return "Events";
INestedTypeDefinition nType = member as INestedTypeDefinition;
if (nType != null)
return "Nested Types";
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// MailAddressTest.cs - NUnit Test Cases for System.Net.MailAddress.MailAddress
//
// Authors:
// John Luke (john.luke@gmail.com)
//
// (C) 2005 John Luke
//
using Xunit;
namespace System.Net.Mail.Tests
{
public class MailAddressTest
{
MailAddress address;
public MailAddressTest()
{
address = new MailAddress("foo@example.com", "Mr. Foo Bar");
}
[Fact]
public void TestConstructorOverload1()
{
address = new MailAddress(" foo@example.com ");
Assert.Equal("foo@example.com", address.Address);
Assert.Equal(string.Empty, address.DisplayName);
Assert.Equal("example.com", address.Host);
Assert.Equal("foo@example.com", address.ToString());
Assert.Equal("foo", address.User);
address = new MailAddress("Mr. Foo Bar <foo@example.com>");
Assert.Equal("foo@example.com", address.Address);
Assert.Equal("Mr. Foo Bar", address.DisplayName);
Assert.Equal("example.com", address.Host);
Assert.Equal("\"Mr. Foo Bar\" <foo@example.com>", address.ToString());
Assert.Equal("foo", address.User);
address = new MailAddress("FooBar <foo@example.com>");
Assert.Equal("foo@example.com", address.Address);
Assert.Equal("FooBar", address.DisplayName);
Assert.Equal("example.com", address.Host);
Assert.Equal("\"FooBar\" <foo@example.com>", address.ToString());
Assert.Equal("foo", address.User);
address = new MailAddress("\"FooBar\"foo@example.com ");
Assert.Equal("foo@example.com", address.Address);
Assert.Equal("FooBar", address.DisplayName);
Assert.Equal("example.com", address.Host);
Assert.Equal("\"FooBar\" <foo@example.com>", address.ToString());
Assert.Equal("foo", address.User);
address = new MailAddress("\" FooBar \"< foo@example.com >");
Assert.Equal("foo@example.com", address.Address);
Assert.Equal(" FooBar ", address.DisplayName);
Assert.Equal("example.com", address.Host);
Assert.Equal("\" FooBar \" <foo@example.com>", address.ToString());
Assert.Equal("foo", address.User);
address = new MailAddress("<foo@example.com>");
Assert.Equal("foo@example.com", address.Address);
Assert.Equal(string.Empty, address.DisplayName);
Assert.Equal("example.com", address.Host);
Assert.Equal("foo@example.com", address.ToString());
Assert.Equal("foo", address.User);
address = new MailAddress(" < foo@example.com >");
Assert.Equal("foo@example.com", address.Address);
Assert.Equal(string.Empty, address.DisplayName);
Assert.Equal("example.com", address.Host);
Assert.Equal("foo@example.com", address.ToString());
Assert.Equal("foo", address.User);
}
[Fact]
public void TestConstructorWithNullString()
{
Assert.Throws<ArgumentNullException>(() => new MailAddress(null));
}
[Fact]
public void TestConstructorWithEmptyString()
{
AssertExtensions.Throws<ArgumentException>("address", () => new MailAddress(""));
}
[Fact]
public void TestInvalidAddressInConstructor()
{
Assert.Throws<FormatException>(() => new MailAddress("Mr. Foo Bar"));
Assert.Throws<FormatException>(() => new MailAddress("foo@b@ar"));
Assert.Throws<FormatException>(() => new MailAddress("Mr. Foo Bar <foo@exa<mple.com"));
Assert.Throws<FormatException>(() => new MailAddress("Mr. Foo Bar <foo@example.com"));
Assert.Throws<FormatException>(() => new MailAddress("Mr. \"F@@ Bar\" <foo@example.com> Whatever@You@Want"));
Assert.Throws<FormatException>(() => new MailAddress("Mr. F@@ Bar <foo@example.com> What\"ever@You@Want"));
Assert.Throws<FormatException>(() => new MailAddress("\"MrFo@Bar\""));
Assert.Throws<FormatException>(() => new MailAddress("\"MrFo@Bar\"<>"));
Assert.Throws<FormatException>(() => new MailAddress(" "));
Assert.Throws<FormatException>(() => new MailAddress("forbar"));
Assert.Throws<FormatException>(() => new MailAddress("<foo@example.com> WhatEver", " Mr. Foo Bar "));
Assert.Throws<FormatException>(() => new MailAddress("Mr. Far Bar <foo@example.com> Whatever", "BarFoo"));
}
[Fact]
public void TestConstructorOverload2()
{
address = new MailAddress(" foo@example.com ", null);
Assert.Equal("foo@example.com", address.Address);
Assert.Equal(string.Empty, address.DisplayName);
Assert.Equal("example.com", address.Host);
Assert.Equal("foo@example.com", address.ToString());
Assert.Equal("foo", address.User);
address = new MailAddress("Mr. Far Bar <foo@example.com>", "BarFoo");
Assert.Equal("foo@example.com", address.Address);
Assert.Equal("BarFoo", address.DisplayName);
Assert.Equal("example.com", address.Host);
Assert.Equal("\"BarFoo\" <foo@example.com>", address.ToString());
Assert.Equal("foo", address.User);
address = new MailAddress("Mr. Far Bar <foo@example.com> ", string.Empty);
Assert.Equal("foo@example.com", address.Address);
Assert.Equal("Mr. Far Bar", address.DisplayName);
Assert.Equal("example.com", address.Host);
Assert.Equal("\"Mr. Far Bar\" <foo@example.com>", address.ToString());
Assert.Equal("foo", address.User);
address = new MailAddress("Mr. Far Bar <foo@example.com>", null);
Assert.Equal("foo@example.com", address.Address);
Assert.Equal("Mr. Far Bar", address.DisplayName);
Assert.Equal("example.com", address.Host);
Assert.Equal("\"Mr. Far Bar\" <foo@example.com>", address.ToString());
Assert.Equal("foo", address.User);
address = new MailAddress("Mr. Far Bar <foo@example.com> ", " ");
Assert.Equal("foo@example.com", address.Address);
Assert.Equal(" ", address.DisplayName);
Assert.Equal("example.com", address.Host);
Assert.Equal("\" \" <foo@example.com>", address.ToString());
Assert.Equal("foo", address.User);
}
[Fact]
public void DisplayName_Precedence()
{
var ma = new MailAddress("Hola <foo@bar.com>");
Assert.Equal("Hola", ma.DisplayName);
ma = new MailAddress("Hola <foo@bar.com>", "Adios");
Assert.Equal("Adios", ma.DisplayName);
ma = new MailAddress("Hola <foo@bar.com>", "");
Assert.Equal("Hola", ma.DisplayName);
ma = new MailAddress("<foo@bar.com>", "");
Assert.Equal("", ma.DisplayName);
}
[Fact]
public void Address_QuoteFirst()
{
new MailAddress("\"Hola\" <foo@bar.com>");
}
[Fact]
public void Address_QuoteNotFirst()
{
Assert.Throws<FormatException>(() => new MailAddress("H\"ola\" <foo@bar.com>"));
}
[Fact]
public void Address_NoClosingQuote()
{
Assert.Throws<FormatException>(() => new MailAddress("\"Hola <foo@bar.com>"));
}
[Fact]
public void Address_NoUser()
{
Assert.Throws<FormatException>(() => new MailAddress("Hola <@bar.com>"));
}
[Fact]
public void Address_NoUserNoHost()
{
Assert.Throws<FormatException>(() => new MailAddress("Hola <@>"));
}
[Fact]
public void Address()
{
Assert.Equal("foo@example.com", address.Address);
}
[Fact]
public void DisplayName()
{
Assert.Equal("Mr. Foo Bar", address.DisplayName);
}
[Fact]
public void Host()
{
Assert.Equal("example.com", address.Host);
}
[Fact]
public void User()
{
Assert.Equal("foo", address.User);
}
[Fact]
public void ToStringTest()
{
Assert.Equal("\"Mr. Foo Bar\" <foo@example.com>", address.ToString());
}
[Fact]
public void EqualsTest()
{
var n = new MailAddress("Mr. Bar <a@example.com>");
var n2 = new MailAddress("a@example.com", "Mr. Bar");
Assert.Equal(n, n2);
}
[Fact]
public void EqualsTest2()
{
var n = new MailAddress("Mr. Bar <a@example.com>");
var n2 = new MailAddress("MR. BAR <a@EXAMPLE.com>");
Assert.Equal(n, n2);
}
}
}
| |
using System;
using System.Xml;
using System.Reflection;
using System.Collections;
namespace Platform.Xml.Serialization
{
/// <summary>
///
/// </summary>
public class AnyTypeTypeSerializer
: TypeSerializer
{
private sealed class LightSerializationMember
{
public MemberGetter Getter;
public MemberSetter Setter;
public TypeSerializer Serializer;
public bool SerializeAsCData;
public MemberInfo MemberInfo;
public string SerializedName;
public bool XmlTreatAsNullIfEmpty;
public Type LogicalType;
public LightSerializationMember(SerializationMemberInfo memberInfo)
{
this.Getter = memberInfo.Getter;
this.Setter = memberInfo.Setter;
this.Serializer = memberInfo.Serializer;
this.MemberInfo = memberInfo.MemberInfo;
this.SerializedName = memberInfo.GetSerializedName();
this.SerializeAsCData = memberInfo.SerializeAsCData;
this.XmlTreatAsNullIfEmpty = memberInfo.HasApplicableAttribute(typeof(XmlTreatAsNullIfEmptyAttribute));
this.LogicalType = memberInfo.LogicalType;
}
public object GetValue(object obj)
{
return Getter(MemberInfo, obj);
}
public void SetValue(object obj, object value)
{
Setter(MemberInfo, obj, value);
}
}
/// <summary>
///
/// </summary>
protected IDictionary m_ElementMembersMap;
/// <summary>
///
/// </summary>
protected IDictionary m_AttributeMembersMap;
/// <summary>
///
/// </summary>
public override Type SupportedType
{
get
{
return m_Type;
}
}
private Type m_Type;
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="cache"></param>
/// <param name="options"></param>
public AnyTypeTypeSerializer(Type type, TypeSerializerCache cache, SerializerOptions options)
{
m_Type = type;
m_ElementMembersMap = new SortedList(0x10);
m_AttributeMembersMap = new SortedList(0x10);
cache.Add(this);
Scan(cache, options);
}
/// <summary>
///
/// </summary>
/// <param name="cache"></param>
/// <param name="options"></param>
private void Scan(TypeSerializerCache cache, SerializerOptions options)
{
Type type;
FieldInfo[] fields;
PropertyInfo[] properties;
type = m_Type;
while (type != typeof(object) && type != null)
{
fields = m_Type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
properties = m_Type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
foreach (FieldInfo field in fields)
{
AddMember(field, cache, options);
}
foreach (PropertyInfo property in properties)
{
AddMember(property, cache, options);
}
object[] attribs;
bool serializeBase = true;
attribs = type.GetCustomAttributes(typeof(XmlSerializeBaseAttribute), false);
foreach (XmlSerializeBaseAttribute attrib in attribs)
{
if (attrib.Applies(options))
{
if (attrib.SerializeBase)
{
serializeBase = true;
}
}
}
if (!serializeBase)
{
break;
}
type = type.BaseType;
}
}
/// <summary>
///
/// </summary>
/// <param name="memberInfo"></param>
/// <param name="cache"></param>
/// <param name="options"></param>
private void AddMember(MemberInfo memberInfo, TypeSerializerCache cache, SerializerOptions options)
{
SerializationMemberInfo serializationMemberInfo;
serializationMemberInfo = new SerializationMemberInfo(memberInfo, options, cache);
if (serializationMemberInfo.SerializedNodeType == XmlNodeType.Element)
{
m_ElementMembersMap[serializationMemberInfo.GetSerializedName()] = new LightSerializationMember(serializationMemberInfo);
return;
}
else if (serializationMemberInfo.SerializedNodeType == XmlNodeType.Attribute)
{
if (!(serializationMemberInfo.Serializer is TypeSerializerWithSimpleTextSupport))
{
throw new InvalidOperationException("Serializer for member doesn't support serializing to an attribute.");
}
m_AttributeMembersMap[serializationMemberInfo.GetSerializedName()] = new LightSerializationMember(serializationMemberInfo);
}
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <param name="writer"></param>
/// <param name="state"></param>
public override void Serialize(object obj, XmlWriter writer, SerializationState state)
{
TypeSerializerWithSimpleTextSupport simpleSerializer;
state.SerializationStart(obj);
try
{
// Serialize attributes...
foreach (LightSerializationMember smi in m_AttributeMembersMap.Values)
{
object val;
val = smi.GetValue(obj);
if (smi.XmlTreatAsNullIfEmpty)
{
if (smi.LogicalType.IsValueType)
{
if (Activator.CreateInstance(smi.LogicalType).Equals(obj))
{
val = null;
}
}
}
if (state.ShouldSerialize(val))
{
simpleSerializer = (TypeSerializerWithSimpleTextSupport)smi.Serializer;
writer.WriteStartAttribute(smi.SerializedName, "");
writer.WriteString(simpleSerializer.Serialize(val, state));
writer.WriteEndAttribute();
}
}
// Serialize elements...
foreach (LightSerializationMember smi in m_ElementMembersMap.Values)
{
object val;
val = smi.GetValue(obj);
if (smi.XmlTreatAsNullIfEmpty)
{
if (smi.LogicalType.IsValueType)
{
if (Activator.CreateInstance(smi.LogicalType).Equals(val))
{
val = null;
}
}
}
if (smi.SerializeAsCData)
{
simpleSerializer = smi.Serializer as TypeSerializerWithSimpleTextSupport;
}
else
{
simpleSerializer = null;
}
if (state.ShouldSerialize(val))
{
writer.WriteStartElement(smi.SerializedName, "");
if (simpleSerializer != null)
{
writer.WriteCData(simpleSerializer.Serialize(val, state));
}
else
{
smi.Serializer.Serialize(val, writer, state);
}
writer.WriteEndElement();
}
}
}
finally
{
state.SerializationEnd(obj);
}
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="state"></param>
/// <returns></returns>
public override object Deserialize(XmlReader reader, SerializationState state)
{
object retval;
LightSerializationMember serializationMember;
ISerializationUnhandledMarkupListener uhm;
retval = Activator.CreateInstance(m_Type);
state.DeserializationStart(retval);
uhm = retval as ISerializationUnhandledMarkupListener;
if (reader.AttributeCount > 0)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
serializationMember = (LightSerializationMember)m_AttributeMembersMap[reader.Name];
if (serializationMember == null)
{
// Unknown attribute.
if (uhm != null)
{
uhm.UnhandledAttribute(reader.Name, reader.Value);
}
}
else
{
serializationMember.SetValue(retval, serializationMember.Serializer.Deserialize(reader, state));
}
}
reader.MoveToElement();
}
if (reader.IsEmptyElement)
{
reader.ReadStartElement();
return retval;
}
reader.ReadStartElement();
// Read elements
while (true)
{
XmlReaderHelper.ReadUntilAnyTypesReached(reader,
new XmlNodeType[] { XmlNodeType.Element, XmlNodeType.EndElement});
if (reader.NodeType == XmlNodeType.Element)
{
serializationMember = (LightSerializationMember)m_ElementMembersMap[reader.Name];
if (serializationMember == null)
{
// Unknown element.
}
else
{
serializationMember.SetValue(retval, serializationMember.Serializer.Deserialize(reader, state));
}
}
else
{
if (reader.NodeType == XmlNodeType.EndElement)
{
reader.ReadEndElement();
}
else
{
if (uhm != null)
{
uhm.UnhandledOther(reader.ReadOuterXml());
}
}
break;
}
}
state.DeserializationEnd(retval);
return retval;
}
}
}
| |
namespace android.preference
{
[global::MonoJavaBridge.JavaClass()]
public partial class PreferenceManager : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected PreferenceManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.preference.PreferenceManager.OnActivityDestroyListener_))]
public partial interface OnActivityDestroyListener : global::MonoJavaBridge.IJavaObject
{
void onActivityDestroy();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.preference.PreferenceManager.OnActivityDestroyListener))]
internal sealed partial class OnActivityDestroyListener_ : java.lang.Object, OnActivityDestroyListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnActivityDestroyListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.preference.PreferenceManager.OnActivityDestroyListener.onActivityDestroy()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.PreferenceManager.OnActivityDestroyListener_.staticClass, "onActivityDestroy", "()V", ref global::android.preference.PreferenceManager.OnActivityDestroyListener_._m0);
}
static OnActivityDestroyListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.preference.PreferenceManager.OnActivityDestroyListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/PreferenceManager$OnActivityDestroyListener"));
}
}
public delegate void OnActivityDestroyListenerDelegate();
internal partial class OnActivityDestroyListenerDelegateWrapper : java.lang.Object, OnActivityDestroyListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected OnActivityDestroyListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public OnActivityDestroyListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.preference.PreferenceManager.OnActivityDestroyListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.preference.PreferenceManager.OnActivityDestroyListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.OnActivityDestroyListenerDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.PreferenceManager.OnActivityDestroyListenerDelegateWrapper.staticClass, global::android.preference.PreferenceManager.OnActivityDestroyListenerDelegateWrapper._m0);
Init(@__env, handle);
}
static OnActivityDestroyListenerDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.preference.PreferenceManager.OnActivityDestroyListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/PreferenceManager_OnActivityDestroyListenerDelegateWrapper"));
}
}
internal partial class OnActivityDestroyListenerDelegateWrapper
{
private OnActivityDestroyListenerDelegate myDelegate;
public void onActivityDestroy()
{
myDelegate();
}
public static implicit operator OnActivityDestroyListenerDelegateWrapper(OnActivityDestroyListenerDelegate d)
{
global::android.preference.PreferenceManager.OnActivityDestroyListenerDelegateWrapper ret = new global::android.preference.PreferenceManager.OnActivityDestroyListenerDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.preference.PreferenceManager.OnActivityResultListener_))]
public partial interface OnActivityResultListener : global::MonoJavaBridge.IJavaObject
{
bool onActivityResult(int arg0, int arg1, android.content.Intent arg2);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.preference.PreferenceManager.OnActivityResultListener))]
internal sealed partial class OnActivityResultListener_ : java.lang.Object, OnActivityResultListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnActivityResultListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
bool android.preference.PreferenceManager.OnActivityResultListener.onActivityResult(int arg0, int arg1, android.content.Intent arg2)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.PreferenceManager.OnActivityResultListener_.staticClass, "onActivityResult", "(IILandroid/content/Intent;)Z", ref global::android.preference.PreferenceManager.OnActivityResultListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
static OnActivityResultListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.preference.PreferenceManager.OnActivityResultListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/PreferenceManager$OnActivityResultListener"));
}
}
public delegate bool OnActivityResultListenerDelegate(int arg0, int arg1, android.content.Intent arg2);
internal partial class OnActivityResultListenerDelegateWrapper : java.lang.Object, OnActivityResultListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected OnActivityResultListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public OnActivityResultListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.preference.PreferenceManager.OnActivityResultListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.preference.PreferenceManager.OnActivityResultListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.OnActivityResultListenerDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.PreferenceManager.OnActivityResultListenerDelegateWrapper.staticClass, global::android.preference.PreferenceManager.OnActivityResultListenerDelegateWrapper._m0);
Init(@__env, handle);
}
static OnActivityResultListenerDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.preference.PreferenceManager.OnActivityResultListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/PreferenceManager_OnActivityResultListenerDelegateWrapper"));
}
}
internal partial class OnActivityResultListenerDelegateWrapper
{
private OnActivityResultListenerDelegate myDelegate;
public bool onActivityResult(int arg0, int arg1, android.content.Intent arg2)
{
return myDelegate(arg0, arg1, arg2);
}
public static implicit operator OnActivityResultListenerDelegateWrapper(OnActivityResultListenerDelegate d)
{
global::android.preference.PreferenceManager.OnActivityResultListenerDelegateWrapper ret = new global::android.preference.PreferenceManager.OnActivityResultListenerDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.preference.PreferenceManager.OnActivityStopListener_))]
public partial interface OnActivityStopListener : global::MonoJavaBridge.IJavaObject
{
void onActivityStop();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.preference.PreferenceManager.OnActivityStopListener))]
internal sealed partial class OnActivityStopListener_ : java.lang.Object, OnActivityStopListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnActivityStopListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.preference.PreferenceManager.OnActivityStopListener.onActivityStop()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.PreferenceManager.OnActivityStopListener_.staticClass, "onActivityStop", "()V", ref global::android.preference.PreferenceManager.OnActivityStopListener_._m0);
}
static OnActivityStopListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.preference.PreferenceManager.OnActivityStopListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/PreferenceManager$OnActivityStopListener"));
}
}
public delegate void OnActivityStopListenerDelegate();
internal partial class OnActivityStopListenerDelegateWrapper : java.lang.Object, OnActivityStopListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected OnActivityStopListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public OnActivityStopListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.preference.PreferenceManager.OnActivityStopListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.preference.PreferenceManager.OnActivityStopListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.OnActivityStopListenerDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.PreferenceManager.OnActivityStopListenerDelegateWrapper.staticClass, global::android.preference.PreferenceManager.OnActivityStopListenerDelegateWrapper._m0);
Init(@__env, handle);
}
static OnActivityStopListenerDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.preference.PreferenceManager.OnActivityStopListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/PreferenceManager_OnActivityStopListenerDelegateWrapper"));
}
}
internal partial class OnActivityStopListenerDelegateWrapper
{
private OnActivityStopListenerDelegate myDelegate;
public void onActivityStop()
{
myDelegate();
}
public static implicit operator OnActivityStopListenerDelegateWrapper(OnActivityStopListenerDelegate d)
{
global::android.preference.PreferenceManager.OnActivityStopListenerDelegateWrapper ret = new global::android.preference.PreferenceManager.OnActivityStopListenerDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
public new global::android.content.SharedPreferences SharedPreferences
{
get
{
return getSharedPreferences();
}
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual global::android.content.SharedPreferences getSharedPreferences()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.content.SharedPreferences>(this, global::android.preference.PreferenceManager.staticClass, "getSharedPreferences", "()Landroid/content/SharedPreferences;", ref global::android.preference.PreferenceManager._m0) as android.content.SharedPreferences;
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual global::android.preference.PreferenceScreen createPreferenceScreen(android.content.Context arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.preference.PreferenceScreen>(this, global::android.preference.PreferenceManager.staticClass, "createPreferenceScreen", "(Landroid/content/Context;)Landroid/preference/PreferenceScreen;", ref global::android.preference.PreferenceManager._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.preference.PreferenceScreen;
}
public new global::java.lang.String SharedPreferencesName
{
get
{
return getSharedPreferencesName();
}
set
{
setSharedPreferencesName(value);
}
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual global::java.lang.String getSharedPreferencesName()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.preference.PreferenceManager.staticClass, "getSharedPreferencesName", "()Ljava/lang/String;", ref global::android.preference.PreferenceManager._m2) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual void setSharedPreferencesName(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.PreferenceManager.staticClass, "setSharedPreferencesName", "(Ljava/lang/String;)V", ref global::android.preference.PreferenceManager._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int SharedPreferencesMode
{
get
{
return getSharedPreferencesMode();
}
set
{
setSharedPreferencesMode(value);
}
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual int getSharedPreferencesMode()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.preference.PreferenceManager.staticClass, "getSharedPreferencesMode", "()I", ref global::android.preference.PreferenceManager._m4);
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual void setSharedPreferencesMode(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.PreferenceManager.staticClass, "setSharedPreferencesMode", "(I)V", ref global::android.preference.PreferenceManager._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public static global::android.content.SharedPreferences getDefaultSharedPreferences(android.content.Context arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.preference.PreferenceManager._m6.native == global::System.IntPtr.Zero)
global::android.preference.PreferenceManager._m6 = @__env.GetStaticMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "getDefaultSharedPreferences", "(Landroid/content/Context;)Landroid/content/SharedPreferences;");
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.SharedPreferences>(@__env.CallStaticObjectMethod(android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.SharedPreferences;
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual global::android.preference.Preference findPreference(java.lang.CharSequence arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.preference.PreferenceManager.staticClass, "findPreference", "(Ljava/lang/CharSequence;)Landroid/preference/Preference;", ref global::android.preference.PreferenceManager._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.preference.Preference;
}
public android.preference.Preference findPreference(string arg0)
{
return findPreference((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
private static global::MonoJavaBridge.MethodId _m8;
public static void setDefaultValues(android.content.Context arg0, int arg1, bool arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.preference.PreferenceManager._m8.native == global::System.IntPtr.Zero)
global::android.preference.PreferenceManager._m8 = @__env.GetStaticMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "setDefaultValues", "(Landroid/content/Context;IZ)V");
@__env.CallStaticVoidMethod(android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m9;
public static void setDefaultValues(android.content.Context arg0, java.lang.String arg1, int arg2, int arg3, bool arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.preference.PreferenceManager._m9.native == global::System.IntPtr.Zero)
global::android.preference.PreferenceManager._m9 = @__env.GetStaticMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "setDefaultValues", "(Landroid/content/Context;Ljava/lang/String;IIZ)V");
@__env.CallStaticVoidMethod(android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._m9, 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));
}
public static global::java.lang.String METADATA_KEY_PREFERENCES
{
get
{
return "android.preference";
}
}
public static global::java.lang.String KEY_HAS_SET_DEFAULT_VALUES
{
get
{
return "_has_set_default_values";
}
}
static PreferenceManager()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.preference.PreferenceManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/PreferenceManager"));
}
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Reflection;
using Boo.Lang.Compiler.TypeSystem.Core;
using Boo.Lang.Compiler.TypeSystem.Services;
using Boo.Lang.Compiler.Util;
using Boo.Lang.Environments;
namespace Boo.Lang.Compiler.TypeSystem.Reflection
{
public class ExternalType : IType
{
protected IReflectionTypeSystemProvider _provider;
private readonly Type _type;
private IType[] _interfaces;
private IEntity[] _members;
private Dictionary<string, List<IEntity>> _cache;
private int _typeDepth = -1;
private string _primitiveName;
private string _fullName;
private string _name;
public ExternalType(IReflectionTypeSystemProvider tss, Type type)
{
if (null == type) throw new ArgumentException("type");
_provider = tss;
_type = type;
}
public virtual string FullName
{
get
{
if (null != _fullName) return _fullName;
return _fullName = BuildFullName();
}
}
internal string PrimitiveName
{
get { return _primitiveName; }
set { _primitiveName = value; }
}
public virtual string Name
{
get
{
if (null != _name) return _name;
return _name = TypeUtilities.TypeName(_type);
}
}
public EntityType EntityType
{
get { return EntityType.Type; }
}
public IType Type
{
get { return this; }
}
public virtual bool IsFinal
{
get { return _type.IsSealed; }
}
public bool IsByRef
{
get { return _type.IsByRef; }
}
public virtual IEntity DeclaringEntity
{
get { return DeclaringType; }
}
public IType DeclaringType
{
get
{
var declaringType = _type.DeclaringType;
return null != declaringType
? _provider.Map(declaringType)
: null;
}
}
public bool IsDefined(IType attributeType)
{
var type = attributeType as ExternalType;
if (type == null) return false;
return MetadataUtil.IsAttributeDefined(_type, type.ActualType);
}
public virtual IType ElementType
{
get { return _provider.Map(_type.GetElementType() ?? _type); }
}
public virtual bool IsClass
{
get { return _type.IsClass; }
}
public bool IsAbstract
{
get { return _type.IsAbstract; }
}
public bool IsInterface
{
get { return _type.IsInterface; }
}
public bool IsEnum
{
get { return _type.IsEnum; }
}
public virtual bool IsValueType
{
get { return _type.IsValueType; }
}
public bool IsArray
{
get { return false; }
}
public bool IsPointer
{
get { return _type.IsPointer; }
}
public virtual bool IsVoid
{
get { return false; }
}
public virtual IType BaseType
{
get
{
var baseType = _type.BaseType;
return baseType == null ? null : _provider.Map(baseType);
}
}
protected virtual MemberInfo[] GetDefaultMembers()
{
return ActualType.GetDefaultMembers();
}
public IEntity GetDefaultMember()
{
return _provider.Map(GetDefaultMembers());
}
public Type ActualType
{
get { return _type; }
}
public virtual bool IsSubclassOf(IType other)
{
var external = other as ExternalType;
if (external == null)
return false;
return _type.IsSubclassOf(external._type)
|| (external.IsInterface && external._type.IsAssignableFrom(_type));
}
public virtual bool IsAssignableFrom(IType other)
{
var external = other as ExternalType;
if (null == external)
{
if (EntityType.Null == other.EntityType)
{
return !IsValueType;
}
if (other.ConstructedInfo != null && this.ConstructedInfo != null
&& ConstructedInfo.GenericDefinition == other.ConstructedInfo.GenericDefinition)
{
for (int i = 0; i < ConstructedInfo.GenericArguments.Length; ++i)
{
if (!ConstructedInfo.GenericArguments[i].IsAssignableFrom(other.ConstructedInfo.GenericArguments[i]))
return false;
}
return true;
}
return other.IsSubclassOf(this);
}
if (other == _provider.Map(Types.Void))
{
return false;
}
return _type.IsAssignableFrom(external._type);
}
public virtual IType[] GetInterfaces()
{
if (null == _interfaces)
{
Type[] interfaces = _type.GetInterfaces();
_interfaces = new IType[interfaces.Length];
for (int i=0; i<_interfaces.Length; ++i)
{
_interfaces[i] = _provider.Map(interfaces[i]);
}
}
return _interfaces;
}
private void BuildCache()
{
_cache = new Dictionary<string, List<IEntity>>();
}
public virtual IEnumerable<IEntity> GetMembers()
{
if (_members == null)
{
IEntity[] members = CreateMembers();
_members = members;
BuildCache();
}
return _members;
}
protected virtual IEntity[] CreateMembers()
{
var result = new List<IEntity>();
foreach (var member in DeclaredMembers())
result.Add(_provider.Map(member));
return result.ToArray();
}
private MemberInfo[] DeclaredMembers()
{
return _type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
}
public int GetTypeDepth()
{
if (-1 == _typeDepth)
{
_typeDepth = GetTypeDepth(_type);
}
return _typeDepth;
}
public virtual INamespace ParentNamespace
{
get { return null; }
}
private bool CachedResolve(string name, EntityType typesToConsider, ICollection<IEntity> resultingSet)
{
if (_cache == null)
{
GetMembers();
}
if (!_cache.ContainsKey(name))
LoadCache(name);
var list = _cache[name];
if (list != null)
{
var result = false;
foreach (var entity in list)
{
if (Entities.IsFlagSet(typesToConsider, entity.EntityType))
{
result = true;
resultingSet.Add(entity);
}
}
return result;
}
return false;
}
private void LoadCache(string name)
{
var matches = My<NameResolutionService>.Instance.EntityNameMatcher;
var list = new List<IEntity>();
foreach (var member in _members)
if (matches(member, name))
list.Add(member);
if (list.Count == 0)
list = null;
_cache.Add(name, list);
}
public virtual bool Resolve(ICollection<IEntity> resultingSet, string name, EntityType typesToConsider)
{
bool found = CachedResolve(name, typesToConsider, resultingSet);
//bool found = My<NameResolutionService>.Instance.Resolve(name, GetMembers(), typesToConsider, resultingSet);
if (IsInterface)
{
if (_provider.Map(typeof(object)).Resolve(resultingSet, name, typesToConsider))
found = true;
foreach (IType baseInterface in GetInterfaces())
found |= baseInterface.Resolve(resultingSet, name, typesToConsider);
}
else
{
if (!found || TypeSystemServices.ContainsMethodsOnly(resultingSet))
{
IType baseType = BaseType;
if (null != baseType)
found |= baseType.Resolve(resultingSet, name, typesToConsider);
}
}
return found;
}
public override string ToString()
{
return this.DisplayName();
}
static int GetTypeDepth(Type type)
{
if (type.IsByRef)
{
return GetTypeDepth(type.GetElementType());
}
if (type.IsInterface)
{
return GetInterfaceDepth(type);
}
return GetClassDepth(type);
}
static int GetClassDepth(Type type)
{
int depth = 0;
Type objectType = Types.Object;
while (type != null && type != objectType)
{
type = type.BaseType;
++depth;
}
return depth;
}
static int GetInterfaceDepth(Type type)
{
Type[] interfaces = type.GetInterfaces();
if (interfaces.Length > 0)
{
int current = 0;
foreach (Type i in interfaces)
{
int depth = GetInterfaceDepth(i);
if (depth > current)
{
current = depth;
}
}
return 1+current;
}
return 1;
}
protected virtual string BuildFullName()
{
if (_primitiveName != null) return _primitiveName;
// keep builtin names pretty ('ref int' instead of 'ref System.Int32')
if (_type.IsByRef) return "ref " + ElementType.FullName;
return TypeUtilities.GetFullName(_type);
}
ExternalGenericTypeInfo _genericTypeDefinitionInfo;
public virtual IGenericTypeInfo GenericInfo
{
get
{
if (ActualType.IsGenericTypeDefinition)
return _genericTypeDefinitionInfo ?? (_genericTypeDefinitionInfo = new ExternalGenericTypeInfo(_provider, this));
return null;
}
}
ExternalConstructedTypeInfo _genericTypeInfo;
public virtual IConstructedTypeInfo ConstructedInfo
{
get
{
if (ActualType.IsGenericType && !ActualType.IsGenericTypeDefinition)
return _genericTypeInfo ?? (_genericTypeInfo = new ExternalConstructedTypeInfo(_provider, this));
return null;
}
}
private ArrayTypeCache _arrayTypes;
public IArrayType MakeArrayType(int rank)
{
if (null == _arrayTypes)
_arrayTypes = new ArrayTypeCache(this);
return _arrayTypes.MakeArrayType(rank);
}
public IType MakePointerType()
{
return _provider.Map(_type.MakePointerType());
}
}
}
| |
/*
* 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 CSJ2K;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Assets;
using OpenMetaverse.Imaging;
using OpenMetaverse.Rendering;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Rednettle.Warp3D;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using WarpRenderer = global::Warp3D.Warp3D;
namespace OpenSim.Region.CoreModules.World.Warp3DMap
{
public static class ImageUtils
{
/// <summary>
/// Performs bilinear interpolation between four values
/// </summary>
/// <param name="v00">First, or top left value</param>
/// <param name="v01">Second, or top right value</param>
/// <param name="v10">Third, or bottom left value</param>
/// <param name="v11">Fourth, or bottom right value</param>
/// <param name="xPercent">Interpolation value on the X axis, between 0.0 and 1.0</param>
/// <param name="yPercent">Interpolation value on fht Y axis, between 0.0 and 1.0</param>
/// <returns>The bilinearly interpolated result</returns>
public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent)
{
return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent);
}
/// <summary>
/// Performs a high quality image resize
/// </summary>
/// <param name="image">Image to resize</param>
/// <param name="width">New width</param>
/// <param name="height">New height</param>
/// <returns>Resized image</returns>
public static Bitmap ResizeImage(Image image, int width, int height)
{
Bitmap result = new Bitmap(width, height);
using (Graphics graphics = Graphics.FromImage(result))
{
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphics.DrawImage(image, 0, 0, result.Width, result.Height);
}
return result;
}
}
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Warp3DImageModule")]
public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3");
private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216);
#pragma warning disable 414
private static string LogHeader = "[WARP 3D IMAGE MODULE]";
#pragma warning restore 414
private Dictionary<UUID, Color4> m_colors = new Dictionary<UUID, Color4>();
private IConfigSource m_config;
private bool m_drawPrimVolume = true;
private bool m_Enabled = false;
private IRendering m_primMesher;
private bool m_renderMeshes = false;
private Scene m_scene;
private bool m_texturePrims = true;
// true if should texture the rendered prims
private float m_texturePrimSize = 48f;
// true if should render the prims on the tile
private bool m_textureTerrain = true; // true if to create terrain splatting texture
// size of prim before we consider texturing it
// true if to render meshes rather than just bounding boxes
private bool m_useAntiAliasing = false; // true if to anti-alias the rendered image
#region Region Module interface
public string Name
{
get { return "Warp3DImageModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_scene = scene;
List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
if (renderers.Count > 0)
{
m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
m_log.DebugFormat("[WARP 3D IMAGE MODULE]: Loaded prim mesher {0}", m_primMesher);
}
else
{
m_log.Debug("[WARP 3D IMAGE MODULE]: No prim mesher loaded, prim rendering will be disabled");
}
m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
}
public void Close()
{
}
public void Initialise(IConfigSource source)
{
m_config = source;
string[] configSections = new string[] { "Map", "Startup" };
if (Util.GetConfigVarFromSections<string>(
m_config, "MapImageModule", configSections, "MapImageModule") != "Warp3DImageModule")
return;
m_Enabled = true;
m_drawPrimVolume
= Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, m_drawPrimVolume);
m_textureTerrain
= Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, m_textureTerrain);
m_texturePrims
= Util.GetConfigVarFromSections<bool>(m_config, "TexturePrims", configSections, m_texturePrims);
m_texturePrimSize
= Util.GetConfigVarFromSections<float>(m_config, "TexturePrimSize", configSections, m_texturePrimSize);
m_renderMeshes
= Util.GetConfigVarFromSections<bool>(m_config, "RenderMeshes", configSections, m_renderMeshes);
m_useAntiAliasing
= Util.GetConfigVarFromSections<bool>(m_config, "UseAntiAliasing", configSections, m_useAntiAliasing);
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
}
#endregion Region Module interface
#region IMapImageGenerator Members
public Bitmap CreateMapTile()
{
// Vector3 camPos = new Vector3(127.5f, 127.5f, 221.7025033688163f);
// Camera above the middle of the region
Vector3 camPos = new Vector3(
m_scene.RegionInfo.RegionSizeX / 2 - 0.5f,
m_scene.RegionInfo.RegionSizeY / 2 - 0.5f,
221.7025033688163f);
// Viewport viewing down onto the region
Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f,
(int)m_scene.RegionInfo.RegionSizeX, (int)m_scene.RegionInfo.RegionSizeY,
(float)m_scene.RegionInfo.RegionSizeX, (float)m_scene.RegionInfo.RegionSizeY);
// Fill the viewport and return the image
return CreateMapTile(viewport, false);
}
public Bitmap CreateMapTile(Viewport viewport, bool useTextures)
{
m_colors.Clear();
int width = viewport.Width;
int height = viewport.Height;
if (m_useAntiAliasing)
{
width *= 2;
height *= 2;
}
WarpRenderer renderer = new WarpRenderer();
renderer.CreateScene(width, height);
renderer.Scene.autoCalcNormals = false;
#region Camera
warp_Vector pos = ConvertVector(viewport.Position);
pos.z -= 0.001f; // Works around an issue with the Warp3D camera
warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection));
renderer.Scene.defaultCamera.setPos(pos);
renderer.Scene.defaultCamera.lookAt(lookat);
if (viewport.Orthographic)
{
renderer.Scene.defaultCamera.isOrthographic = true;
renderer.Scene.defaultCamera.orthoViewWidth = viewport.OrthoWindowWidth;
renderer.Scene.defaultCamera.orthoViewHeight = viewport.OrthoWindowHeight;
}
else
{
float fov = viewport.FieldOfView;
fov *= 1.75f; // FIXME: ???
renderer.Scene.defaultCamera.setFov(fov);
}
#endregion Camera
renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(1.0f, 0.5f, 1f), 0xffffff, 0, 320, 40));
renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 0, 100, 40));
CreateWater(renderer);
CreateTerrain(renderer, m_textureTerrain);
if (m_drawPrimVolume)
CreateAllPrims(renderer, useTextures);
renderer.Render();
Bitmap bitmap = renderer.Scene.getImage();
if (m_useAntiAliasing)
{
using (Bitmap origBitmap = bitmap)
bitmap = ImageUtils.ResizeImage(origBitmap, viewport.Width, viewport.Height);
}
// XXX: It shouldn't really be necesary to force a GC here as one should occur anyway pretty shortly
// afterwards. It's generally regarded as a bad idea to manually GC. If Warp3D is using lots of memory
// then this may be some issue with the Warp3D code itself, though it's also quite possible that generating
// this map tile simply takes a lot of memory.
foreach (var o in renderer.Scene.objectData.Values)
{
warp_Object obj = (warp_Object)o;
obj.vertexData = null;
obj.triangleData = null;
}
renderer.Scene.removeAllObjects();
renderer = null;
viewport = null;
m_colors.Clear();
GC.Collect();
m_log.Debug("[WARP 3D IMAGE MODULE]: GC.Collect()");
return bitmap;
}
public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
{
Viewport viewport = new Viewport(camPos, camDir, fov, Constants.RegionSize, 0.1f, width, height);
return CreateMapTile(viewport, useTextures);
}
public byte[] WriteJpeg2000Image()
{
try
{
using (Bitmap mapbmp = CreateMapTile())
return OpenJPEG.EncodeFromImage(mapbmp, true);
}
catch (Exception e)
{
// JPEG2000 encoder failed
m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e);
}
return null;
}
#endregion IMapImageGenerator Members
#region Rendering Methods
public string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID)
{
string materialName = "Color-" + faceColor.ToString() + "-Texture-" + textureID.ToString();
if (renderer.Scene.material(materialName) == null)
{
renderer.AddMaterial(materialName, ConvertColor(faceColor));
if (faceColor.A < 1f)
{
renderer.Scene.material(materialName).setTransparency((byte)((1f - faceColor.A) * 255f));
}
warp_Texture texture = GetTexture(textureID);
if (texture != null)
renderer.Scene.material(materialName).setTexture(texture);
}
return materialName;
}
private void CreateAllPrims(WarpRenderer renderer, bool useTextures)
{
if (m_primMesher == null)
return;
m_scene.ForEachSOG(
delegate(SceneObjectGroup group)
{
CreatePrim(renderer, group.RootPart, useTextures);
foreach (SceneObjectPart child in group.Parts)
CreatePrim(renderer, child, useTextures);
}
);
}
private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim,
bool useTextures)
{
const float MIN_SIZE = 2f;
if ((PCode)prim.Shape.PCode != PCode.Prim)
return;
if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE)
return;
FacetedMesh renderMesh = null;
Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
if (m_renderMeshes)
{
if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero)
{
// Try fetchinng the asset
byte[] sculptAsset = m_scene.AssetService.GetData(omvPrim.Sculpt.SculptTexture.ToString());
if (sculptAsset != null)
{
// Is it a mesh?
if (omvPrim.Sculpt.Type == SculptType.Mesh)
{
AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset);
FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh);
meshAsset = null;
}
else // It's sculptie
{
IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
if (imgDecoder != null)
{
Image sculpt = imgDecoder.DecodeToImage(sculptAsset);
if (sculpt != null)
{
renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt,
DetailLevel.Medium);
sculpt.Dispose();
}
}
}
}
}
}
// If not a mesh or sculptie, try the regular mesher
if (renderMesh == null)
{
renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
}
if (renderMesh == null)
return;
warp_Vector primPos = ConvertVector(prim.GetWorldPosition());
warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset);
warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
if (prim.ParentID != 0)
{
SceneObjectGroup group = m_scene.SceneGraph.GetGroupByPrim(prim.LocalId);
if (group != null)
m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootPart.RotationOffset)));
}
warp_Vector primScale = ConvertVector(prim.Scale);
string primID = prim.UUID.ToString();
// Create the prim faces
// TODO: Implement the useTextures flag behavior
for (int i = 0; i < renderMesh.Faces.Count; i++)
{
Face face = renderMesh.Faces[i];
string meshName = primID + "-Face-" + i.ToString();
// Avoid adding duplicate meshes to the scene
if (renderer.Scene.objectData.ContainsKey(meshName))
{
continue;
}
warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3);
for (int j = 0; j < face.Vertices.Count; j++)
{
Vertex v = face.Vertices[j];
warp_Vector pos = ConvertVector(v.Position);
warp_Vector norm = ConvertVector(v.Normal);
if (prim.Shape.SculptTexture == UUID.Zero)
norm = norm.reverse();
warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y);
faceObj.addVertex(vert);
}
for (int j = 0; j < face.Indices.Count; j += 3)
{
faceObj.addTriangle(
face.Indices[j + 0],
face.Indices[j + 1],
face.Indices[j + 2]);
}
Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
Color4 faceColor = GetFaceColor(teFace);
string materialName = String.Empty;
if (m_texturePrims && prim.Scale.LengthSquared() > m_texturePrimSize * m_texturePrimSize)
materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID);
else
materialName = GetOrCreateMaterial(renderer, faceColor);
faceObj.transform(m);
faceObj.setPos(primPos);
faceObj.scaleSelf(primScale.x, primScale.y, primScale.z);
renderer.Scene.addObject(meshName, faceObj);
renderer.SetObjectMaterial(meshName, materialName);
}
}
// Add a terrain to the renderer.
// Note that we create a 'low resolution' 256x256 vertex terrain rather than trying for
// full resolution. This saves a lot of memory especially for very large regions.
private void CreateTerrain(WarpRenderer renderer, bool textureTerrain)
{
ITerrainChannel terrain = m_scene.Heightmap;
// 'diff' is the difference in scale between the real region size and the size of terrain we're buiding
float diff = (float)m_scene.RegionInfo.RegionSizeX / 256f;
warp_Object obj = new warp_Object(256 * 256, 255 * 255 * 2);
// Create all the vertices for the terrain
for (float y = 0; y < m_scene.RegionInfo.RegionSizeY; y += diff)
{
for (float x = 0; x < m_scene.RegionInfo.RegionSizeX; x += diff)
{
warp_Vector pos = ConvertVector(x, y, (float)terrain[(int)x, (int)y]);
obj.addVertex(new warp_Vertex(pos,
x / (float)m_scene.RegionInfo.RegionSizeX,
(((float)m_scene.RegionInfo.RegionSizeY) - y) / m_scene.RegionInfo.RegionSizeY));
}
}
// Now that we have all the vertices, make another pass and create
// the normals for each of the surface triangles and
// create the list of triangle indices.
for (float y = 0; y < m_scene.RegionInfo.RegionSizeY; y += diff)
{
for (float x = 0; x < m_scene.RegionInfo.RegionSizeX; x += diff)
{
float newX = x / diff;
float newY = y / diff;
if (newX < 255 && newY < 255)
{
int v = (int)newY * 256 + (int)newX;
// Normal for a triangle made up of three adjacent vertices
Vector3 v1 = new Vector3(newX, newY, (float)terrain[(int)x, (int)y]);
Vector3 v2 = new Vector3(newX + 1, newY, (float)terrain[(int)(x + 1), (int)y]);
Vector3 v3 = new Vector3(newX, newY + 1, (float)terrain[(int)x, ((int)(y + 1))]);
warp_Vector norm = ConvertVector(SurfaceNormal(v1, v2, v3));
norm = norm.reverse();
obj.vertex(v).n = norm;
// Make two triangles for each of the squares in the grid of vertices
obj.addTriangle(
v,
v + 1,
v + 256);
obj.addTriangle(
v + 256 + 1,
v + 256,
v + 1);
}
}
}
renderer.Scene.addObject("Terrain", obj);
UUID[] textureIDs = new UUID[4];
float[] startHeights = new float[4];
float[] heightRanges = new float[4];
OpenSim.Framework.RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings;
textureIDs[0] = regionInfo.TerrainTexture1;
textureIDs[1] = regionInfo.TerrainTexture2;
textureIDs[2] = regionInfo.TerrainTexture3;
textureIDs[3] = regionInfo.TerrainTexture4;
startHeights[0] = (float)regionInfo.Elevation1SW;
startHeights[1] = (float)regionInfo.Elevation1NW;
startHeights[2] = (float)regionInfo.Elevation1SE;
startHeights[3] = (float)regionInfo.Elevation1NE;
heightRanges[0] = (float)regionInfo.Elevation2SW;
heightRanges[1] = (float)regionInfo.Elevation2NW;
heightRanges[2] = (float)regionInfo.Elevation2SE;
heightRanges[3] = (float)regionInfo.Elevation2NE;
uint globalX, globalY;
Util.RegionHandleToWorldLoc(m_scene.RegionInfo.RegionHandle, out globalX, out globalY);
warp_Texture texture;
using (
Bitmap image
= TerrainSplat.Splat(terrain, textureIDs, startHeights, heightRanges,
new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain))
{
texture = new warp_Texture(image);
}
warp_Material material = new warp_Material(texture);
material.setReflectivity(50);
renderer.Scene.addMaterial("TerrainColor", material);
renderer.Scene.material("TerrainColor").setReflectivity(0); // reduces tile seams a bit thanks lkalif
renderer.SetObjectMaterial("Terrain", "TerrainColor");
}
// Add a water plane to the renderer.
private void CreateWater(WarpRenderer renderer)
{
float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
renderer.AddPlane("Water", m_scene.RegionInfo.RegionSizeX * 0.5f);
renderer.Scene.sceneobject("Water").setPos(m_scene.RegionInfo.RegionSizeX / 2 - 0.5f,
waterHeight,
m_scene.RegionInfo.RegionSizeY / 2 - 0.5f);
warp_Material waterColorMaterial = new warp_Material(ConvertColor(WATER_COLOR));
waterColorMaterial.setReflectivity(0); // match water color with standard map module thanks lkalif
waterColorMaterial.setTransparency((byte)((1f - WATER_COLOR.A) * 255f));
renderer.Scene.addMaterial("WaterColor", waterColorMaterial);
renderer.SetObjectMaterial("Water", "WaterColor");
}
private Color4 GetFaceColor(Primitive.TextureEntryFace face)
{
Color4 color;
if (face.TextureID == UUID.Zero)
return face.RGBA;
if (!m_colors.TryGetValue(face.TextureID, out color))
{
bool fetched = false;
// Attempt to fetch the texture metadata
UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString());
if (metadata != null)
{
OSDMap map = null;
try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; }
catch { }
if (map != null)
{
color = map["X-JPEG2000-RGBA"].AsColor4();
fetched = true;
}
}
if (!fetched)
{
// Fetch the texture, decode and get the average color,
// then save it to a temporary metadata asset
AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
if (textureAsset != null)
{
int width, height;
color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);
OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } };
metadata = new AssetBase
{
Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
Flags = AssetFlags.Collectable,
FullID = metadataID,
ID = metadataID.ToString(),
Local = true,
Temporary = true,
Name = String.Empty,
Type = (sbyte)AssetType.Unknown
};
m_scene.AssetService.Store(metadata);
}
else
{
color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
}
}
m_colors[face.TextureID] = color;
}
return color * face.RGBA;
}
private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color)
{
string name = color.ToString();
warp_Material material = renderer.Scene.material(name);
if (material != null)
return name;
renderer.AddMaterial(name, ConvertColor(color));
if (color.A < 1f)
renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f));
return name;
}
private warp_Texture GetTexture(UUID id)
{
warp_Texture ret = null;
byte[] asset = m_scene.AssetService.GetData(id.ToString());
if (asset != null)
{
IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
try
{
using (Bitmap img = (Bitmap)imgDecoder.DecodeToImage(asset))
ret = new warp_Texture(img);
}
catch (Exception e)
{
m_log.Warn(string.Format("[WARP 3D IMAGE MODULE]: Failed to decode asset {0}, exception ", id), e);
}
}
return ret;
}
#endregion Rendering Methods
#region Static Helpers
public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
{
ulong r = 0;
ulong g = 0;
ulong b = 0;
ulong a = 0;
using (MemoryStream stream = new MemoryStream(j2kData))
{
try
{
int pixelBytes;
using (Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream))
{
width = bitmap.Width;
height = bitmap.Height;
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
// Sum up the individual channels
unsafe
{
if (pixelBytes == 4)
{
for (int y = 0; y < height; y++)
{
byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
for (int x = 0; x < width; x++)
{
b += row[x * pixelBytes + 0];
g += row[x * pixelBytes + 1];
r += row[x * pixelBytes + 2];
a += row[x * pixelBytes + 3];
}
}
}
else
{
for (int y = 0; y < height; y++)
{
byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
for (int x = 0; x < width; x++)
{
b += row[x * pixelBytes + 0];
g += row[x * pixelBytes + 1];
r += row[x * pixelBytes + 2];
}
}
}
}
}
// Get the averages for each channel
const decimal OO_255 = 1m / 255m;
decimal totalPixels = (decimal)(width * height);
decimal rm = ((decimal)r / totalPixels) * OO_255;
decimal gm = ((decimal)g / totalPixels) * OO_255;
decimal bm = ((decimal)b / totalPixels) * OO_255;
decimal am = ((decimal)a / totalPixels) * OO_255;
if (pixelBytes == 3)
am = 1m;
return new Color4((float)rm, (float)gm, (float)bm, (float)am);
}
catch (Exception ex)
{
m_log.WarnFormat(
"[WARP 3D IMAGE MODULE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}",
textureID, j2kData.Length, ex.Message);
width = 0;
height = 0;
return new Color4(0.5f, 0.5f, 0.5f, 1.0f);
}
}
}
private static int ConvertColor(Color4 color)
{
int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f));
if (color.A < 1f)
c |= (byte)(color.A * 255f) << 24;
return c;
}
private static warp_Quaternion ConvertQuaternion(Quaternion quat)
{
return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W);
}
// Note: axis change.
private static warp_Vector ConvertVector(float x, float y, float z)
{
return new warp_Vector(x, z, y);
}
private static warp_Vector ConvertVector(Vector3 vector)
{
return new warp_Vector(vector.X, vector.Z, vector.Y);
}
private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3)
{
Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z);
Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z);
Vector3 normal = Vector3.Cross(edge1, edge2);
normal.Normalize();
return normal;
}
#endregion Static Helpers
}
}
| |
using UnityEngine;
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
public enum RuleResult { Done, Working }
namespace Casanova.Prelude
{
public class Tuple<T,E> {
public T Item1 { get; set;}
public E Item2 { get; set;}
public Tuple(T item1, E item2)
{
Item1 = item1;
Item2 = item2;
}
}
public static class MyExtensions
{
//public T this[List<T> list]
//{
// get { return list.ElementAt(0); }
//}
public static T Head<T>(this List<T> list) { return list.ElementAt(0); }
public static T Head<T>(this IEnumerable<T> list) { return list.ElementAt(0); }
public static int Length<T>(this List<T> list) { return list.Count; }
public static int Length<T>(this IEnumerable<T> list) { return list.ToList<T>().Count; }
}
public class Cons<T> : IEnumerable<T>
{
public class Enumerator : IEnumerator<T>
{
public Enumerator(Cons<T> parent)
{
firstEnumerated = 0;
this.parent = parent;
tailEnumerator = parent.tail.GetEnumerator();
}
byte firstEnumerated;
Cons<T> parent;
IEnumerator<T> tailEnumerator;
public T Current
{
get
{
if (firstEnumerated == 0) return default(T);
if (firstEnumerated == 1) return parent.head;
else return tailEnumerator.Current;
}
}
object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } }
public bool MoveNext()
{
if (firstEnumerated == 0)
{
if (parent.head == null) return false;
firstEnumerated++;
return true;
}
if (firstEnumerated == 1) firstEnumerated++;
return tailEnumerator.MoveNext();
}
public void Reset() { firstEnumerated = 0; tailEnumerator.Reset(); }
public void Dispose() { }
}
T head;
IEnumerable<T> tail;
public Cons(T head, IEnumerable<T> tail)
{
this.head = head;
this.tail = tail;
}
public IEnumerator<T> GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
}
public class Empty<T> : IEnumerable<T>
{
public Empty() { }
public class Enumerator : IEnumerator<T>
{
public T Current { get { throw new Exception("Empty sequence has no elements"); } }
object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } }
public bool MoveNext() { return false; }
public void Reset() { }
public void Dispose() { }
}
public IEnumerator<T> GetEnumerator()
{
return new Enumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator();
}
}
public abstract class Option<T> : IComparable, IEquatable<Option<T>>
{
public bool IsSome;
public bool IsNone { get { return !IsSome; } }
protected abstract Just<T> Some { get; }
public U Match<U>(Func<T,U> f, Func<U> g) {
if (this.IsSome)
return f(this.Some.Value);
else
return g();
}
public bool Equals(Option<T> b)
{
return this.Match(
x => b.Match(
y => x.Equals(y),
() => false),
() => b.Match(
y => false,
() => true));
}
public override bool Equals(System.Object other)
{
if (other == null) return false;
if (other is Option<T>)
{
var other1 = other as Option<T>;
return this.Equals(other1);
}
return false;
}
public override int GetHashCode() { return this.GetHashCode(); }
public static bool operator ==(Option<T> a, Option<T> b)
{
if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b);
return a.Equals(b);
}
public static bool operator !=(Option<T> a, Option<T> b)
{
if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b);
return !(a.Equals(b));
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
if (obj is Option<T>)
{
var obj1 = obj as Option<T>;
if (this.Equals(obj1)) return 0;
}
return -1;
}
abstract public T Value { get; }
public override string ToString()
{
return "Option<" + typeof(T).ToString() + ">";
}
}
public class Just<T> : Option<T>
{
T elem;
public Just(T elem) { this.elem = elem; this.IsSome = true; }
protected override Just<T> Some { get { return this; } }
public override T Value { get { return elem; } }
}
public class Nothing<T> : Option<T>
{
public Nothing() { this.IsSome = false; }
protected override Just<T> Some { get { return null; } }
public override T Value { get { throw new Exception("Cant get a value from a None object"); } }
}
public class Utils
{
public static T IfThenElse<T>(Func<bool> c, Func<T> t, Func<T> e)
{
if (c())
return t();
else
return e();
}
}
}
public class FastStack
{
public int[] Elements;
public int Top;
public FastStack(int elems)
{
Top = 0;
Elements = new int[elems];
}
public void Clear() { Top = 0; }
public void Push(int x) { Elements[Top++] = x; }
}
public class RuleTable
{
public RuleTable(int elems)
{
ActiveIndices = new FastStack(elems);
SupportStack = new FastStack(elems);
ActiveSlots = new bool[elems];
}
public FastStack ActiveIndices;
public FastStack SupportStack;
public bool[] ActiveSlots;
public void Add(int i)
{
if (!ActiveSlots[i])
{
ActiveSlots[i] = true;
ActiveIndices.Push(i);
}
}
}
public class World : MonoBehaviour{
void Update () { Update(Time.deltaTime, this); }
public void Start()
{ UnityCube = UnityCube.Find();
Velocity = new UnityEngine.Vector3(3f,0.5f,1f);
}
public UnityCube UnityCube;
public UnityEngine.Vector3 Velocity;
public void Update(float dt, World world) {
this.Rule0(dt, world);
}
public void Rule0(float dt, World world)
{
UnityCube.Position = (UnityCube.Position) + ((Velocity) * (dt));
}
}
| |
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
namespace System.Web.UI
{
/// <summary>
/// HtmlTextWriterEx
/// </summary>
public class HtmlTextWriterEx : HtmlTextWriter
{
//public static readonly string TofuUri = "/WebResource.axd?d=5n2TUlkoTdAS-KsOrl50eRfwyioj-rmID-zYEi3RUhcnLXiS2Mpbuuzm1Sc8arqCRn7QycAdJALOtf73b2HlzQ2&t=633426477648026143";
internal static readonly int HtmlAttributeSplit = (int)HtmlAttribute.__Undefined;
private HtmlBuilder _htmlBuilder;
static HtmlTextWriterEx() { FixHtmlTagTable(); }
private static void FixHtmlTagTable()
{
var htmlTextWriterType = Type.GetType("System.Web.UI.HtmlTextWriter, " + AssemblyRef.SystemWeb, true, true);
// remove br tag
var _tagKeyLookupTableField = htmlTextWriterType.GetField("_tagKeyLookupTable", BindingFlags.Static | BindingFlags.NonPublic);
var _tagKeyLookupTable = (Hashtable)_tagKeyLookupTableField.GetValue(null);
_tagKeyLookupTable.Remove("br");
// add br tag
var htmlTextWriter_TagTypeType = Type.GetType("System.Web.UI.HtmlTextWriter+TagType, " + AssemblyRef.SystemWeb, true, true);
var tagTypeNonClosing = (int)Enum.Parse(htmlTextWriter_TagTypeType, "NonClosing");
var registerTagMethod = htmlTextWriterType.GetMethod("RegisterTag", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { typeof(string), typeof(HtmlTextWriterTag), htmlTextWriter_TagTypeType }, null);
registerTagMethod.Invoke(null, BindingFlags.InvokeMethod, null, new object[] { "br", HtmlTextWriterTag.Br, tagTypeNonClosing }, CultureInfo.CurrentCulture);
}
/// <summary>
/// Initializes a new instance of the <see cref="HtmlTextWriterEx"/> class.
/// </summary>
public HtmlTextWriterEx()
: base(new StringWriter())
{
_htmlBuilder = CreateHtmlBuilder(this);
}
/// <summary>
/// Initializes a new instance of the <see cref="HtmlTextWriterEx"/> class.
/// </summary>
/// <param name="w">The w.</param>
public HtmlTextWriterEx(TextWriter w)
: base(w)
{
_htmlBuilder = CreateHtmlBuilder(this);
}
/// <summary>
/// Initializes a new instance of the <see cref="HtmlTextWriterEx"/> class.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="tabText">The tab text.</param>
public HtmlTextWriterEx(TextWriter w, string tabText)
: base(w, tabText)
{
_htmlBuilder = CreateHtmlBuilder(this);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="T:System.IO.TextWriter"/> and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
_htmlBuilder.Dispose();
base.Dispose(disposing);
}
/// <summary>
/// Adds the attribute if undefined.
/// </summary>
/// <param name="attribute">The attribute.</param>
/// <param name="value">The value.</param>
public void AddAttributeIfUndefined(HtmlAttribute attribute, string value)
{
var attribute2 = (int)attribute;
if (attribute2 < HtmlAttributeSplit)
AddAttributeIfUndefined((HtmlTextWriterAttribute)attribute2, value);
else if (attribute2 > HtmlAttributeSplit)
AddStyleAttributeIfUndefined((HtmlTextWriterStyle)attribute2 - HtmlAttributeSplit - 1, value);
else
throw new ArgumentException(string.Format("Local.InvalidHtmlAttribA", attribute.ToString()), "attribute");
}
/// <summary>
/// Adds the attribute if undefined.
/// </summary>
/// <param name="attribute">The attribute.</param>
/// <param name="value">The value.</param>
public void AddAttributeIfUndefined(HtmlTextWriterAttribute attribute, string value)
{
if (!IsAttributeDefined(attribute))
AddAttribute(attribute, value);
}
/// <summary>
/// Adds the style attribute if undefined.
/// </summary>
/// <param name="attribute">The attribute.</param>
/// <param name="value">The value.</param>
public void AddStyleAttributeIfUndefined(HtmlTextWriterStyle attribute, string value)
{
if (!IsStyleAttributeDefined(attribute))
AddStyleAttribute(attribute, value);
}
/// <summary>
/// Gets the HTML builder.
/// </summary>
public HtmlBuilder HtmlBuilder
{
get { return _htmlBuilder; }
}
/// <summary>
/// Gets the inner text.
/// </summary>
public string InnerText
{
get
{
var innerWriter = (InnerWriter as HtmlTextWriter);
if (innerWriter != null)
{
var innerStringWriter = (innerWriter.InnerWriter as StringWriter);
if (innerStringWriter != null)
return innerStringWriter.ToString();
}
return string.Empty;
}
}
/// <summary>
/// Tries the add attribute.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool TryAddAttribute(HtmlAttribute key, out string value)
{
var key2 = (int)key;
if (key2 < HtmlAttributeSplit)
return TryAddAttribute((HtmlTextWriterAttribute)key2, out value);
else if (key2 > HtmlAttributeSplit)
return TryAddStyleAttribute((HtmlTextWriterStyle)(key2 - HtmlAttributeSplit - 1), out value);
throw new ArgumentException(string.Format("Local.InvalidHtmlAttribA", key.ToString()), "key");
}
/// <summary>
/// Tries the add attribute.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool TryAddAttribute(HtmlTextWriterAttribute key, out string value)
{
if (!IsAttributeDefined(key, out value))
{
AddAttribute(key, value);
return true;
}
return false;
}
/// <summary>
/// Tries the add style attribute.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool TryAddStyleAttribute(HtmlTextWriterStyle key, out string value)
{
if (!IsStyleAttributeDefined(key, out value))
{
AddStyleAttribute(key, value);
return true;
}
return false;
}
/// <summary>
/// Renders the control.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="text">The text.</param>
public static void RenderControl(Control control, out string text)
{
if (control == null)
throw new ArgumentNullException("control");
using (var w = new StringWriter())
{
using (var w2 = new HtmlTextWriter(w))
control.RenderControl(w2);
text = w.ToString();
}
}
/// <summary>
/// Renders the control.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="b">The b.</param>
public static void RenderControl(Control control, StringBuilder b)
{
if (control == null)
throw new ArgumentNullException("control");
using (var w = new StringWriter(b))
using (var w2 = new HtmlTextWriter(w))
control.RenderControl(w2);
}
#region Class-Factory
/// <summary>
/// Creates the HTML builder.
/// </summary>
/// <param name="w">The w.</param>
/// <returns></returns>
public virtual HtmlBuilder CreateHtmlBuilder(HtmlTextWriterEx w) { return new HtmlBuilder(w); }
#endregion
}
}
| |
using System;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Xunit;
namespace k8s.Tests
{
/// <summary>
/// Tests the <see cref="ByteBuffer"/> class.
/// </summary>
public class ByteBufferTests
{
private readonly byte[] writeData = new byte[]
{
0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF,
};
/// <summary>
/// Tests a sequential read and write operation.
/// </summary>
[Fact]
public void LinearReadWriteTest()
{
var buffer = new ByteBuffer(0x10, 0x100);
// There's no real guarantee that this will be the case because the ArrayPool does not guarantee
// a specific buffer size. So let's assert this first to make sure the test fails should this
// assumption not hold.
Assert.Equal(0x10, buffer.Size);
// Assert the initial values.
Assert.Equal(0, buffer.AvailableReadableBytes);
Assert.Equal(0x10, buffer.AvailableWritableBytes);
Assert.Equal(0, buffer.ReadWaterMark);
Assert.Equal(0, buffer.WriteWaterMark);
// Write two bytes
buffer.Write(writeData, 0, 2);
Assert.Equal(2, buffer.AvailableReadableBytes);
Assert.Equal(0x0E, buffer.AvailableWritableBytes);
Assert.Equal(0, buffer.ReadWaterMark);
Assert.Equal(2, buffer.WriteWaterMark);
// Read two bytes, one byte at a time
var readData = new byte[0x10];
var read = buffer.Read(readData, 0, 1);
Assert.Equal(1, read);
// Verify the result of the read operation.
Assert.Equal(0xF0, readData[0]);
Assert.Equal(0, readData[1]); // Make sure no additional data was read
// Check the state of the buffer
Assert.Equal(1, buffer.AvailableReadableBytes);
Assert.Equal(0x0F, buffer.AvailableWritableBytes);
Assert.Equal(1, buffer.ReadWaterMark);
Assert.Equal(2, buffer.WriteWaterMark);
// Read another byte
read = buffer.Read(readData, 1, 1);
Assert.Equal(1, read);
// Verify the result of the read operation.
Assert.Equal(0xF1, readData[1]);
Assert.Equal(0, readData[2]); // Make sure no additional data was read
// Check the state of the buffer
Assert.Equal(0, buffer.AvailableReadableBytes);
Assert.Equal(0x10, buffer.AvailableWritableBytes);
Assert.Equal(2, buffer.ReadWaterMark);
Assert.Equal(2, buffer.WriteWaterMark);
}
/// <summary>
/// Tests reading a writing which crosses the boundary (end) of the circular buffer.
/// </summary>
[Fact]
public void BoundaryReadWriteTest()
{
var buffer = new ByteBuffer(0x10, 0x100);
// There's no real guarantee that this will be the case because the ArrayPool does not guarantee
// a specific buffer size. So let's assert this first to make sure the test fails should this
// assumption not hold.
Assert.Equal(0x10, buffer.Size);
// Write out 0x0A bytes to the buffer, to increase the high water level for writing bytes
buffer.Write(writeData, 0, 0x0A);
// Assert the initial values.
Assert.Equal(0x0A, buffer.AvailableReadableBytes);
Assert.Equal(0x06, buffer.AvailableWritableBytes);
Assert.Equal(0, buffer.ReadWaterMark);
Assert.Equal(0x0A, buffer.WriteWaterMark);
// Read 0x0A bytes, to increase the high water level for reading bytes
var readData = new byte[0x10];
var read = buffer.Read(readData, 0, 0x0A);
Assert.Equal(0x0A, read);
Assert.Equal(0x00, buffer.AvailableReadableBytes);
Assert.Equal(0x10, buffer.AvailableWritableBytes);
Assert.Equal(0x0A, buffer.ReadWaterMark);
Assert.Equal(0x0A, buffer.WriteWaterMark);
// Write an additional 0x0A bytes, but now in reverse order. This will cause the data
// to be wrapped.
Array.Reverse(writeData);
buffer.Write(writeData, 0, 0x0A);
// Assert the resulting state of the buffer.
Assert.Equal(0x0A, buffer.AvailableReadableBytes);
Assert.Equal(0x06, buffer.AvailableWritableBytes);
Assert.Equal(0x0A, buffer.ReadWaterMark);
Assert.Equal(0x04, buffer.WriteWaterMark);
// Read ten bytes, this will be a wrapped read
read = buffer.Read(readData, 0, 0x0A);
Assert.Equal(0x0A, read);
// Verify the result of the read operation.
Assert.Equal(0xFF, readData[0]);
Assert.Equal(0xFE, readData[1]);
Assert.Equal(0xFD, readData[2]);
Assert.Equal(0xFC, readData[3]);
Assert.Equal(0xFB, readData[4]);
Assert.Equal(0xFA, readData[5]);
Assert.Equal(0xF9, readData[6]);
Assert.Equal(0xF8, readData[7]);
Assert.Equal(0xF7, readData[8]);
Assert.Equal(0xF6, readData[9]);
Assert.Equal(0, readData[10]); // Make sure no additional data was read
// Check the state of the buffer
Assert.Equal(0, buffer.AvailableReadableBytes);
Assert.Equal(0x10, buffer.AvailableWritableBytes);
Assert.Equal(4, buffer.ReadWaterMark);
Assert.Equal(4, buffer.WriteWaterMark);
}
/// <summary>
/// Tests resizing of the <see cref="ByteBuffer"/> class.
/// </summary>
[Fact]
public void ResizeWriteTest()
{
var buffer = new ByteBuffer(0x10, 0x100);
// There's no real guarantee that this will be the case because the ArrayPool does not guarantee
// a specific buffer size. So let's assert this first to make sure the test fails should this
// assumption not hold.
Assert.Equal(0x10, buffer.Size);
// Write out 0x0A bytes to the buffer, to increase the high water level for writing bytes
buffer.Write(writeData, 0, 0x0A);
var readData = new byte[0x20];
// Read these 0x0A bytes.
var read = buffer.Read(readData, 0, 0x0A);
Assert.Equal(0x0A, read);
// Assert the initial state of the buffer
Assert.Equal(0x00, buffer.AvailableReadableBytes);
Assert.Equal(0x10, buffer.AvailableWritableBytes);
Assert.Equal(0x0A, buffer.ReadWaterMark);
Assert.Equal(0x0A, buffer.WriteWaterMark);
// Write out 0x0A bytes to the buffer, this will cause the buffer to wrap
buffer.Write(writeData, 0, 0x0A);
Assert.Equal(0x0A, buffer.AvailableReadableBytes);
Assert.Equal(0x06, buffer.AvailableWritableBytes);
Assert.Equal(0x0A, buffer.ReadWaterMark);
Assert.Equal(0x04, buffer.WriteWaterMark);
// Write an additional 0x0A bytes, but now in reverse order. This will cause the buffer to be resized.
Array.Reverse(writeData);
buffer.Write(writeData, 0, 0x0A);
// Make sure the buffer has been resized.
Assert.Equal(0x20, buffer.Size);
Assert.Equal(0x14, buffer.AvailableReadableBytes); // 2 * 0x0A = 0x14
Assert.Equal(0x0C, buffer.AvailableWritableBytes); // 0x20 - 0x14 = 0x0C
Assert.Equal(0x1A, buffer.ReadWaterMark);
Assert.Equal(0x0E, buffer.WriteWaterMark);
// Read data, and verify the read data
read = buffer.Read(readData, 0, 0x14);
Assert.Equal(0xF0, readData[0]);
Assert.Equal(0xF1, readData[1]);
Assert.Equal(0xF2, readData[2]);
Assert.Equal(0xF3, readData[3]);
Assert.Equal(0xF4, readData[4]);
Assert.Equal(0xF5, readData[5]);
Assert.Equal(0xF6, readData[6]);
Assert.Equal(0xF7, readData[7]);
Assert.Equal(0xF8, readData[8]);
Assert.Equal(0xF9, readData[9]);
Assert.Equal(0xFF, readData[10]);
Assert.Equal(0xFE, readData[11]);
Assert.Equal(0xFD, readData[12]);
Assert.Equal(0xFC, readData[13]);
Assert.Equal(0xFB, readData[14]);
Assert.Equal(0xFA, readData[15]);
Assert.Equal(0xF9, readData[16]);
Assert.Equal(0xF8, readData[17]);
Assert.Equal(0xF7, readData[18]);
Assert.Equal(0xF6, readData[19]);
}
/// <summary>
/// Tests a call to <see cref="ByteBuffer.Read(byte[], int, int)"/> which wants to read more data
/// than is available.
/// </summary>
[Fact]
public void ReadTooMuchDataTest()
{
var buffer = new ByteBuffer();
var readData = new byte[0x10];
// Read 0x010 bytes of data when only 0x06 are available
buffer.Write(writeData, 0, 0x06);
var read = buffer.Read(readData, 0, readData.Length);
Assert.Equal(0x06, read);
Assert.Equal(0xF0, readData[0]);
Assert.Equal(0xF1, readData[1]);
Assert.Equal(0xF2, readData[2]);
Assert.Equal(0xF3, readData[3]);
Assert.Equal(0xF4, readData[4]);
Assert.Equal(0xF5, readData[5]);
Assert.Equal(0x00, readData[6]);
}
/// <summary>
/// Tests a call to <see cref="ByteBuffer.Read(byte[], int, int)"/> when no data is available; and makes
/// sure the call blocks until data is available.
/// </summary>
/// <returns><placeholder>A <see cref="Task"/> representing the asynchronous unit test.</placeholder></returns>
/// <returns><placeholder>A <see cref="Task"/> representing the asynchronous unit test.</placeholder></returns>
[Fact]
public async Task ReadBlocksUntilDataAvailableTest()
{
// Makes sure that the Read method does not return until data is available.
var buffer = new ByteBuffer();
var readData = new byte[0x10];
var read = 0;
// Kick off a read operation
var readTask = Task.Run(() => read = buffer.Read(readData, 0, readData.Length));
await Task.Delay(250).ConfigureAwait(false);
Assert.False(readTask.IsCompleted, "Read task completed before data was available.");
// Write data to the buffer
buffer.Write(writeData, 0, 0x03);
await TaskAssert.Completed(
readTask,
TimeSpan.FromMilliseconds(1000),
"Timed out waiting for read task to complete.").ConfigureAwait(false);
Assert.Equal(3, read);
Assert.Equal(0xF0, readData[0]);
Assert.Equal(0xF1, readData[1]);
Assert.Equal(0xF2, readData[2]);
Assert.Equal(0x00, readData[3]);
}
/// <summary>
/// Tests reading until the end of the file.
/// </summary>
[Fact]
public void ReadUntilEndOfFileTest()
{
var buffer = new ByteBuffer(0x10, 0x100);
// There's no real guarantee that this will be the case because the ArrayPool does not guarantee
// a specific buffer size. So let's assert this first to make sure the test fails should this
// assumption not hold.
Assert.Equal(0x10, buffer.Size);
buffer.Write(writeData, 0, 2);
buffer.Write(writeData, 2, 2);
buffer.WriteEnd();
// Assert the initial state of the buffer
Assert.Equal(0x04, buffer.AvailableReadableBytes);
Assert.Equal(0x0C, buffer.AvailableWritableBytes);
Assert.Equal(0x00, buffer.ReadWaterMark);
Assert.Equal(0x04, buffer.WriteWaterMark);
// Read the data on a chunk-by-chunk basis
var readData = new byte[0x03];
var read = buffer.Read(readData, 0, 3);
Assert.Equal(3, read);
Assert.Equal(0xF0, readData[0]);
Assert.Equal(0xF1, readData[1]);
Assert.Equal(0xF2, readData[2]);
read = buffer.Read(readData, 0, 3);
Assert.Equal(1, read);
Assert.Equal(0xF3, readData[0]);
}
/// <summary>
/// Tests reading until the end of a file, piecemeal.
/// </summary>
[Fact]
public void ReadUntilEndOfFileTest2()
{
var buffer = new ByteBuffer(0x10, 0x100);
// There's no real guarantee that this will be the case because the ArrayPool does not guarantee
// a specific buffer size. So let's assert this first to make sure the test fails should this
// assumption not hold.
Assert.Equal(0x10, buffer.Size);
buffer.Write(writeData, 0, 2);
buffer.Write(writeData, 2, 2);
buffer.WriteEnd();
// Assert the initial state of the buffer
Assert.Equal(0x04, buffer.AvailableReadableBytes);
Assert.Equal(0x0C, buffer.AvailableWritableBytes);
Assert.Equal(0x00, buffer.ReadWaterMark);
Assert.Equal(0x04, buffer.WriteWaterMark);
// Read the data at once
var readData = new byte[0x10];
var read = buffer.Read(readData, 0, 0x10);
Assert.Equal(4, read);
Assert.Equal(0xF0, readData[0]);
Assert.Equal(0xF1, readData[1]);
Assert.Equal(0xF2, readData[2]);
Assert.Equal(0xF3, readData[3]);
Assert.Equal(0x00, readData[4]);
read = buffer.Read(readData, 0, 0x10);
Assert.Equal(0, read);
}
/// <summary>
/// Tests growing the byte buffer on the first write. This is a special case where
/// ReadWaterMark = WriteWaterMark = 0
/// </summary>
[Fact]
public void GrowOnFirstWriteTest()
{
// In the current implementation, the minimum size of the buffer will be 16 bytes,
// but that's not guaranteed.
var buffer = new ByteBuffer(1, 128);
var data = new byte[buffer.Size + 1];
RandomNumberGenerator.Create().GetBytes(data);
var output = new byte[buffer.Size + 1];
buffer.Write(data, 0, data.Length);
Assert.Equal(data.Length, buffer.AvailableReadableBytes);
buffer.Read(output, 0, output.Length);
Assert.Equal(data, output);
}
/// <summary>
/// Tests growing the byte buffer on the second write.
/// </summary>
[Fact]
public void GrowOnSecondFirstWriteTest()
{
// In the current implementation, the minimum size of the buffer will be 16 bytes,
// but that's not guaranteed.
var buffer = new ByteBuffer(1, 128);
var data = new byte[buffer.Size + 1];
RandomNumberGenerator.Create().GetBytes(data);
var output = new byte[buffer.Size + 1];
buffer.Write(data, 0, 1);
buffer.Write(data, 0, data.Length);
Assert.Equal(data.Length + 1, buffer.AvailableReadableBytes);
buffer.Read(output, 0, 1);
buffer.Read(output, 0, output.Length);
Assert.Equal(data, output);
}
/// <summary>
/// Tests reading from the buffer before data has been written, and makes sure
/// data is read correctly.
/// </summary>
/// <returns>
/// A <see cref="Task"/> which represents the asynchronous operation.
/// </returns>
[Fact]
public async Task ReadFirstTest()
{
var buffer = new ByteBuffer(1, 128);
var data = new byte[buffer.Size + 1];
RandomNumberGenerator.Create().GetBytes(data);
var output = new byte[buffer.Size + 1];
var readTask = Task.Run(() => buffer.Read(output, 0, output.Length));
await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
buffer.Write(data, 0, data.Length);
await readTask.ConfigureAwait(false);
}
#if NETCOREAPP2_0
/// <summary>
/// A simpel test which will use a random number generator to write lots of data to
/// the buffer, and read that data using another thread. Makes sure the hashes of the
/// data written and read matches.
/// </summary>
/// <returns>
/// A <see cref="Task"/> which represents the asynchronous operation.
/// </returns>
[Fact]
public async Task RandomReadWriteTest()
{
ByteBuffer buffer
= new ByteBuffer(1, 1024 * 1024);
var generatorTask
= Task.Run(() => this.Generate(buffer, SHA256.Create()));
var consumerTask
= Task.Run(() => this.Consume(buffer, SHA256.Create()));
await Task.WhenAll(generatorTask, consumerTask).ConfigureAwait(false);
var generatorHash
= await generatorTask.ConfigureAwait(false);
var consumerHash
= await consumerTask.ConfigureAwait(false);
Assert.Equal(generatorHash, consumerHash);
}
private byte[] Generate(ByteBuffer buffer, HashAlgorithm hash)
{
RandomNumberGenerator g
= RandomNumberGenerator.Create();
byte[] next
= new byte[32];
int iterations
= 0;
while (buffer.Size < buffer.MaximumSize)
{
iterations++;
g.GetBytes(next);
buffer.Write(next, 0, next.Length);
hash.TransformBlock(next, 0, next.Length, null, 0);
}
buffer.WriteEnd();
hash.TransformFinalBlock(next, 0, 0);
return hash.Hash;
}
private byte[] Consume(ByteBuffer buffer, HashAlgorithm hash)
{
byte[] data
= new byte[32];
AsyncAutoResetEvent onBufferResized
= new AsyncAutoResetEvent();
buffer.OnResize
+= (sender, e) => onBufferResized.Set();
int read;
int iterations
= 0;
while ((read
= buffer.Read(data, 0, data.Length)) > 0)
{
iterations++;
hash.TransformBlock(data, 0, read, null, 0);
// The reader task is probably much faster than the writer, as the writer should also generate
// random data. Wait at specific intervals for the writer to catch up and to force a resize
// of the buffer.
if (iterations % 1024 == 0 && buffer.Size < buffer.MaximumSize)
{
onBufferResized.Wait();
}
}
hash.TransformFinalBlock(data, 0, 0);
return hash.Hash;
}
#endif
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mono.Cecil.Rocks {
public class DocCommentId {
IMemberDefinition commentMember;
StringBuilder id;
DocCommentId (IMemberDefinition member)
{
commentMember = member;
id = new StringBuilder ();
}
void WriteField (FieldDefinition field)
{
WriteDefinition ('F', field);
}
void WriteEvent (EventDefinition @event)
{
WriteDefinition ('E', @event);
}
void WriteType (TypeDefinition type)
{
id.Append ('T').Append (':');
WriteTypeFullName (type);
}
void WriteMethod (MethodDefinition method)
{
WriteDefinition ('M', method);
if (method.HasGenericParameters) {
id.Append ('`').Append ('`');
id.Append (method.GenericParameters.Count);
}
if (method.HasParameters)
WriteParameters (method.Parameters);
if (IsConversionOperator (method))
WriteReturnType (method);
}
static bool IsConversionOperator (MethodDefinition self)
{
if (self == null)
throw new ArgumentNullException ("self");
return self.IsSpecialName
&& (self.Name == "op_Explicit" || self.Name == "op_Implicit");
}
void WriteReturnType (MethodDefinition method)
{
id.Append ('~');
WriteTypeSignature (method.ReturnType);
}
void WriteProperty (PropertyDefinition property)
{
WriteDefinition ('P', property);
if (property.HasParameters)
WriteParameters (property.Parameters);
}
void WriteParameters (IList<ParameterDefinition> parameters)
{
id.Append ('(');
WriteList (parameters, p => WriteTypeSignature (p.ParameterType));
id.Append (')');
}
void WriteTypeSignature (TypeReference type)
{
switch (type.MetadataType) {
case MetadataType.Array:
WriteArrayTypeSignature ((ArrayType)type);
break;
case MetadataType.ByReference:
WriteTypeSignature (((ByReferenceType)type).ElementType);
id.Append ('@');
break;
case MetadataType.FunctionPointer:
WriteFunctionPointerTypeSignature ((FunctionPointerType)type);
break;
case MetadataType.GenericInstance:
WriteGenericInstanceTypeSignature ((GenericInstanceType)type);
break;
case MetadataType.Var:
if (IsGenericMethodTypeParameter (type))
id.Append ('`');
id.Append ('`');
id.Append (((GenericParameter)type).Position);
break;
case MetadataType.MVar:
id.Append ('`').Append ('`');
id.Append (((GenericParameter)type).Position);
break;
case MetadataType.OptionalModifier:
WriteModiferTypeSignature ((OptionalModifierType)type, '!');
break;
case MetadataType.RequiredModifier:
WriteModiferTypeSignature ((RequiredModifierType)type, '|');
break;
case MetadataType.Pointer:
WriteTypeSignature (((PointerType)type).ElementType);
id.Append ('*');
break;
default:
WriteTypeFullName (type);
break;
}
}
bool IsGenericMethodTypeParameter (TypeReference type)
{
if (commentMember is MethodDefinition methodDefinition && type is GenericParameter genericParameter)
return methodDefinition.GenericParameters.Any (i => i.Name == genericParameter.Name);
return false;
}
void WriteGenericInstanceTypeSignature (GenericInstanceType type)
{
if (type.ElementType.IsTypeSpecification ())
throw new NotSupportedException ();
GenericTypeOptions options = new GenericTypeOptions {
IsArgument = true,
IsNestedType = type.IsNested,
Arguments = type.GenericArguments
};
WriteTypeFullName (type.ElementType, options);
}
void WriteList<T> (IList<T> list, Action<T> action)
{
for (int i = 0; i < list.Count; i++) {
if (i > 0)
id.Append (',');
action (list [i]);
}
}
void WriteModiferTypeSignature (IModifierType type, char id)
{
WriteTypeSignature (type.ElementType);
this.id.Append (id);
WriteTypeSignature (type.ModifierType);
}
void WriteFunctionPointerTypeSignature (FunctionPointerType type)
{
id.Append ("=FUNC:");
WriteTypeSignature (type.ReturnType);
if (type.HasParameters)
WriteParameters (type.Parameters);
}
void WriteArrayTypeSignature (ArrayType type)
{
WriteTypeSignature (type.ElementType);
if (type.IsVector) {
id.Append ("[]");
return;
}
id.Append ("[");
WriteList (type.Dimensions, dimension => {
if (dimension.LowerBound.HasValue)
id.Append (dimension.LowerBound.Value);
id.Append (':');
if (dimension.UpperBound.HasValue)
id.Append (dimension.UpperBound.Value - (dimension.LowerBound.GetValueOrDefault () + 1));
});
id.Append ("]");
}
void WriteDefinition (char id, IMemberDefinition member)
{
this.id.Append (id)
.Append (':');
WriteTypeFullName (member.DeclaringType);
this.id.Append ('.');
WriteItemName (member.Name);
}
void WriteTypeFullName (TypeReference type)
{
WriteTypeFullName (type, GenericTypeOptions.Empty ());
}
void WriteTypeFullName (TypeReference type, GenericTypeOptions options)
{
if (type.DeclaringType != null) {
WriteTypeFullName (type.DeclaringType, options);
id.Append ('.');
}
if (!string.IsNullOrEmpty (type.Namespace)) {
id.Append (type.Namespace);
id.Append ('.');
}
var name = type.Name;
if (options.IsArgument) {
var index = name.LastIndexOf ('`');
if (index > 0)
name = name.Substring (0, index);
}
id.Append (name);
WriteGenericTypeParameters (type, options);
}
void WriteGenericTypeParameters (TypeReference type, GenericTypeOptions options)
{
if (options.IsArgument && IsGenericType (type)) {
id.Append ('{');
WriteList (GetGenericTypeArguments (type, options), WriteTypeSignature);
id.Append ('}');
}
}
static bool IsGenericType (TypeReference type)
{
// When the type is a nested type and that is defined in a generic class,
// the nested type will have generic parameters but sometimes that is not a generic type.
if (type.HasGenericParameters) {
var name = string.Empty;
var index = type.Name.LastIndexOf ('`');
if (index >= 0)
name = type.Name.Substring (0, index);
return type.Name.LastIndexOf ('`') == name.Length;
}
return false;
}
IList<TypeReference> GetGenericTypeArguments (TypeReference type, GenericTypeOptions options)
{
if (options.IsNestedType) {
var typeParameterCount = type.GenericParameters.Count;
var typeGenericArguments = options.Arguments.Skip (options.ArgumentIndex).Take (typeParameterCount).ToList ();
options.ArgumentIndex += typeParameterCount;
return typeGenericArguments;
}
return options.Arguments;
}
//int GetGenericTypeParameterCount (TypeReference type)
//{
// var returnValue = 0;
// var index = type.Name.LastIndexOf ('`');
// if (index >= 0)
// returnValue = int.Parse (type.Name.Substring (index + 1));
// return returnValue;
//}
void WriteItemName (string name)
{
id.Append (name.Replace('.', '#').Replace('<', '{').Replace('>', '}'));
}
public override string ToString ()
{
return id.ToString ();
}
public static string GetDocCommentId (IMemberDefinition member)
{
if (member == null)
throw new ArgumentNullException ("member");
var documentId = new DocCommentId (member);
switch (member.MetadataToken.TokenType) {
case TokenType.Field:
documentId.WriteField ((FieldDefinition)member);
break;
case TokenType.Method:
documentId.WriteMethod ((MethodDefinition)member);
break;
case TokenType.TypeDef:
documentId.WriteType ((TypeDefinition)member);
break;
case TokenType.Event:
documentId.WriteEvent ((EventDefinition)member);
break;
case TokenType.Property:
documentId.WriteProperty ((PropertyDefinition)member);
break;
default:
throw new NotSupportedException (member.FullName);
}
return documentId.ToString ();
}
class GenericTypeOptions {
public bool IsArgument { get; set; }
public bool IsNestedType { get; set; }
public IList<TypeReference> Arguments { get; set; }
public int ArgumentIndex { get; set; }
public static GenericTypeOptions Empty ()
{
return new GenericTypeOptions ();
}
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// A stream implementing a block-oriented read cache.
/// </summary>
public sealed class BlockCacheStream : SparseStream
{
private SparseStream _wrappedStream;
private Ownership _ownWrapped;
private BlockCacheSettings _settings;
private BlockCacheStatistics _stats;
private long _position;
private bool _atEof;
private BlockCache<Block> _cache;
private byte[] _readBuffer;
private int _blocksInReadBuffer;
/// <summary>
/// Initializes a new instance of the BlockCacheStream class.
/// </summary>
/// <param name="toWrap">The stream to wrap</param>
/// <param name="ownership">Whether to assume ownership of <c>toWrap</c></param>
public BlockCacheStream(SparseStream toWrap, Ownership ownership)
: this(toWrap, ownership, new BlockCacheSettings())
{
}
/// <summary>
/// Initializes a new instance of the BlockCacheStream class.
/// </summary>
/// <param name="toWrap">The stream to wrap</param>
/// <param name="ownership">Whether to assume ownership of <c>toWrap</c></param>
/// <param name="settings">The cache settings</param>
public BlockCacheStream(SparseStream toWrap, Ownership ownership, BlockCacheSettings settings)
{
if (!toWrap.CanRead)
{
throw new ArgumentException("The wrapped stream does not support reading", "toWrap");
}
if (!toWrap.CanSeek)
{
throw new ArgumentException("The wrapped stream does not support seeking", "toWrap");
}
_wrappedStream = toWrap;
_ownWrapped = ownership;
_settings = new BlockCacheSettings(settings);
if (_settings.OptimumReadSize % _settings.BlockSize != 0)
{
throw new ArgumentException("Invalid settings, OptimumReadSize must be a multiple of BlockSize", "settings");
}
_readBuffer = new byte[_settings.OptimumReadSize];
_blocksInReadBuffer = _settings.OptimumReadSize / _settings.BlockSize;
int totalBlocks = (int)(_settings.ReadCacheSize / _settings.BlockSize);
_cache = new BlockCache<Block>(_settings.BlockSize, totalBlocks);
_stats = new BlockCacheStatistics();
_stats.FreeReadBlocks = totalBlocks;
}
/// <summary>
/// Gets the parts of the stream that are stored.
/// </summary>
/// <remarks>This may be an empty enumeration if all bytes are zero.</remarks>
public override IEnumerable<StreamExtent> Extents
{
get
{
CheckDisposed();
return _wrappedStream.Extents;
}
}
/// <summary>
/// Gets an indication as to whether the stream can be read.
/// </summary>
public override bool CanRead
{
get { return true; }
}
/// <summary>
/// Gets an indication as to whether the stream position can be changed.
/// </summary>
public override bool CanSeek
{
get { return true; }
}
/// <summary>
/// Gets an indication as to whether the stream can be written to.
/// </summary>
public override bool CanWrite
{
get { return _wrappedStream.CanWrite; }
}
/// <summary>
/// Gets the length of the stream.
/// </summary>
public override long Length
{
get
{
CheckDisposed();
return _wrappedStream.Length;
}
}
/// <summary>
/// Gets and sets the current stream position.
/// </summary>
public override long Position
{
get
{
CheckDisposed();
return _position;
}
set
{
CheckDisposed();
_position = value;
}
}
/// <summary>
/// Gets the performance statistics for this instance.
/// </summary>
public BlockCacheStatistics Statistics
{
get
{
_stats.FreeReadBlocks = _cache.FreeBlockCount;
return _stats;
}
}
/// <summary>
/// Gets the parts of a stream that are stored, within a specified range.
/// </summary>
/// <param name="start">The offset of the first byte of interest</param>
/// <param name="count">The number of bytes of interest</param>
/// <returns>An enumeration of stream extents, indicating stored bytes</returns>
public override IEnumerable<StreamExtent> GetExtentsInRange(long start, long count)
{
CheckDisposed();
return _wrappedStream.GetExtentsInRange(start, count);
}
/// <summary>
/// Reads data from the stream.
/// </summary>
/// <param name="buffer">The buffer to fill</param>
/// <param name="offset">The buffer offset to start from</param>
/// <param name="count">The number of bytes to read</param>
/// <returns>The number of bytes read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
CheckDisposed();
if (_position >= Length)
{
if (_atEof)
{
throw new IOException("Attempt to read beyond end of stream");
}
else
{
_atEof = true;
return 0;
}
}
_stats.TotalReadsIn++;
if (count > _settings.LargeReadSize)
{
_stats.LargeReadsIn++;
_stats.TotalReadsOut++;
_wrappedStream.Position = _position;
int numRead = _wrappedStream.Read(buffer, offset, count);
_position = _wrappedStream.Position;
if (_position >= Length)
{
_atEof = true;
}
return numRead;
}
int totalBytesRead = 0;
bool servicedFromCache = false;
bool servicedOutsideCache = false;
int blockSize = _settings.BlockSize;
long firstBlock = _position / blockSize;
int offsetInNextBlock = (int)(_position % blockSize);
long endBlock = Utilities.Ceil(Math.Min(_position + count, Length), blockSize);
int numBlocks = (int)(endBlock - firstBlock);
if (offsetInNextBlock != 0)
{
_stats.UnalignedReadsIn++;
}
int blocksRead = 0;
while (blocksRead < numBlocks)
{
Block block;
// Read from the cache as much as possible
while (blocksRead < numBlocks && _cache.TryGetBlock(firstBlock + blocksRead, out block))
{
int bytesToRead = Math.Min(count - totalBytesRead, block.Available - offsetInNextBlock);
Array.Copy(block.Data, offsetInNextBlock, buffer, offset + totalBytesRead, bytesToRead);
offsetInNextBlock = 0;
totalBytesRead += bytesToRead;
_position += bytesToRead;
blocksRead++;
servicedFromCache = true;
}
// Now handle a sequence of (one or more) blocks that are not cached
if (blocksRead < numBlocks && !_cache.ContainsBlock(firstBlock + blocksRead))
{
servicedOutsideCache = true;
// Figure out how many blocks to read from the wrapped stream
int blocksToRead = 0;
while (blocksRead + blocksToRead < numBlocks
&& blocksToRead < _blocksInReadBuffer
&& !_cache.ContainsBlock(firstBlock + blocksRead + blocksToRead))
{
++blocksToRead;
}
// Allow for the end of the stream not being block-aligned
long readPosition = (firstBlock + blocksRead) * (long)blockSize;
int bytesToRead = (int)Math.Min(blocksToRead * (long)blockSize, Length - readPosition);
// Do the read
_stats.TotalReadsOut++;
_wrappedStream.Position = readPosition;
int bytesRead = Utilities.ReadFully(_wrappedStream, _readBuffer, 0, bytesToRead);
if (bytesRead != bytesToRead)
{
throw new IOException("Short read before end of stream");
}
// Cache the read blocks
for (int i = 0; i < blocksToRead; ++i)
{
int copyBytes = Math.Min(blockSize, bytesToRead - (i * blockSize));
block = _cache.GetBlock(firstBlock + blocksRead + i);
Array.Copy(_readBuffer, i * blockSize, block.Data, 0, copyBytes);
block.Available = copyBytes;
if (copyBytes < blockSize)
{
Array.Clear(_readBuffer, (i * blockSize) + copyBytes, blockSize - copyBytes);
}
}
blocksRead += blocksToRead;
// Propogate the data onto the caller
int bytesToCopy = Math.Min(count - totalBytesRead, bytesRead - offsetInNextBlock);
Array.Copy(_readBuffer, offsetInNextBlock, buffer, offset + totalBytesRead, bytesToCopy);
totalBytesRead += bytesToCopy;
_position += bytesToCopy;
offsetInNextBlock = 0;
}
}
if (_position >= Length && totalBytesRead == 0)
{
_atEof = true;
}
if (servicedFromCache)
{
_stats.ReadCacheHits++;
}
if (servicedOutsideCache)
{
_stats.ReadCacheMisses++;
}
return totalBytesRead;
}
/// <summary>
/// Flushes the stream.
/// </summary>
public override void Flush()
{
CheckDisposed();
_wrappedStream.Flush();
}
/// <summary>
/// Moves the stream position.
/// </summary>
/// <param name="offset">The origin-relative location</param>
/// <param name="origin">The base location</param>
/// <returns>The new absolute stream position</returns>
public override long Seek(long offset, SeekOrigin origin)
{
CheckDisposed();
long effectiveOffset = offset;
if (origin == SeekOrigin.Current)
{
effectiveOffset += _position;
}
else if (origin == SeekOrigin.End)
{
effectiveOffset += Length;
}
_atEof = false;
if (effectiveOffset < 0)
{
throw new IOException("Attempt to move before beginning of disk");
}
else
{
_position = effectiveOffset;
return _position;
}
}
/// <summary>
/// Sets the length of the stream.
/// </summary>
/// <param name="value">The new length</param>
public override void SetLength(long value)
{
CheckDisposed();
_wrappedStream.SetLength(value);
}
/// <summary>
/// Writes data to the stream at the current location.
/// </summary>
/// <param name="buffer">The data to write</param>
/// <param name="offset">The first byte to write from buffer</param>
/// <param name="count">The number of bytes to write</param>
public override void Write(byte[] buffer, int offset, int count)
{
CheckDisposed();
_stats.TotalWritesIn++;
int blockSize = _settings.BlockSize;
long firstBlock = _position / blockSize;
long endBlock = Utilities.Ceil(Math.Min(_position + count, Length), blockSize);
int numBlocks = (int)(endBlock - firstBlock);
try
{
_wrappedStream.Position = _position;
_wrappedStream.Write(buffer, offset, count);
}
catch
{
InvalidateBlocks(firstBlock, numBlocks);
throw;
}
int offsetInNextBlock = (int)(_position % blockSize);
if (offsetInNextBlock != 0)
{
_stats.UnalignedWritesIn++;
}
// For each block touched, if it's cached, update it
int bytesProcessed = 0;
for (int i = 0; i < numBlocks; ++i)
{
int bufferPos = offset + bytesProcessed;
int bytesThisBlock = Math.Min(count - bytesProcessed, blockSize - offsetInNextBlock);
Block block;
if (_cache.TryGetBlock(firstBlock + i, out block))
{
Array.Copy(buffer, bufferPos, block.Data, offsetInNextBlock, bytesThisBlock);
block.Available = Math.Max(block.Available, offsetInNextBlock + bytesThisBlock);
}
offsetInNextBlock = 0;
bytesProcessed += bytesThisBlock;
}
_position += count;
}
/// <summary>
/// Disposes of this instance, freeing up associated resources.
/// </summary>
/// <param name="disposing"><c>true</c> if invoked from <c>Dispose</c>, else <c>false</c>.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_wrappedStream != null && _ownWrapped == Ownership.Dispose)
{
_wrappedStream.Dispose();
}
_wrappedStream = null;
}
base.Dispose(disposing);
}
private void CheckDisposed()
{
if (_wrappedStream == null)
{
throw new ObjectDisposedException("BlockCacheStream");
}
}
private void InvalidateBlocks(long firstBlock, int numBlocks)
{
for (long i = firstBlock; i < (firstBlock + numBlocks); ++i)
{
_cache.ReleaseBlock(i);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using OpenSim.Services.Connectors.Hypergrid;
using OpenMetaverse;
using Nini.Config;
using log4net;
namespace OpenSim.Services.HypergridService
{
public class GatekeeperService : IGatekeeperService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private static bool m_Initialized = false;
private static IGridService m_GridService;
private static IPresenceService m_PresenceService;
private static IUserAccountService m_UserAccountService;
private static IUserAgentService m_UserAgentService;
private static ISimulationService m_SimulationService;
private static IGridUserService m_GridUserService;
private static IBansService m_BansService;
private static string m_AllowedClients = string.Empty;
private static string m_DeniedClients = string.Empty;
private static bool m_ForeignAgentsAllowed = true;
private static List<string> m_ForeignsAllowedExceptions = new List<string>();
private static List<string> m_ForeignsDisallowedExceptions = new List<string>();
private static UUID m_ScopeID;
private static bool m_AllowTeleportsToAnyRegion;
private static string m_ExternalName;
private static Uri m_Uri;
private static GridRegion m_DefaultGatewayRegion;
public GatekeeperService(IConfigSource config, ISimulationService simService)
{
if (!m_Initialized)
{
m_Initialized = true;
IConfig serverConfig = config.Configs["GatekeeperService"];
if (serverConfig == null)
throw new Exception(String.Format("No section GatekeeperService in config file"));
string accountService = serverConfig.GetString("UserAccountService", String.Empty);
string homeUsersService = serverConfig.GetString("UserAgentService", string.Empty);
string gridService = serverConfig.GetString("GridService", String.Empty);
string presenceService = serverConfig.GetString("PresenceService", String.Empty);
string simulationService = serverConfig.GetString("SimulationService", String.Empty);
string gridUserService = serverConfig.GetString("GridUserService", String.Empty);
string bansService = serverConfig.GetString("BansService", String.Empty);
// These are mandatory, the others aren't
if (gridService == string.Empty || presenceService == string.Empty)
throw new Exception("Incomplete specifications, Gatekeeper Service cannot function.");
string scope = serverConfig.GetString("ScopeID", UUID.Zero.ToString());
UUID.TryParse(scope, out m_ScopeID);
//m_WelcomeMessage = serverConfig.GetString("WelcomeMessage", "Welcome to OpenSim!");
m_AllowTeleportsToAnyRegion = serverConfig.GetBoolean("AllowTeleportsToAnyRegion", true);
m_ExternalName = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI",
new string[] { "Startup", "Hypergrid", "GatekeeperService" }, String.Empty);
m_ExternalName = serverConfig.GetString("ExternalName", m_ExternalName);
if (m_ExternalName != string.Empty && !m_ExternalName.EndsWith("/"))
m_ExternalName = m_ExternalName + "/";
try
{
m_Uri = new Uri(m_ExternalName);
}
catch
{
m_log.WarnFormat("[GATEKEEPER SERVICE]: Malformed gatekeeper address {0}", m_ExternalName);
}
Object[] args = new Object[] { config };
m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
if (accountService != string.Empty)
m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(accountService, args);
if (homeUsersService != string.Empty)
m_UserAgentService = ServerUtils.LoadPlugin<IUserAgentService>(homeUsersService, args);
if (gridUserService != string.Empty)
m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(gridUserService, args);
if (bansService != string.Empty)
m_BansService = ServerUtils.LoadPlugin<IBansService>(bansService, args);
if (simService != null)
m_SimulationService = simService;
else if (simulationService != string.Empty)
m_SimulationService = ServerUtils.LoadPlugin<ISimulationService>(simulationService, args);
string[] possibleAccessControlConfigSections = new string[] { "AccessControl", "GatekeeperService" };
m_AllowedClients = Util.GetConfigVarFromSections<string>(
config, "AllowedClients", possibleAccessControlConfigSections, string.Empty);
m_DeniedClients = Util.GetConfigVarFromSections<string>(
config, "DeniedClients", possibleAccessControlConfigSections, string.Empty);
m_ForeignAgentsAllowed = serverConfig.GetBoolean("ForeignAgentsAllowed", true);
LoadDomainExceptionsFromConfig(serverConfig, "AllowExcept", m_ForeignsAllowedExceptions);
LoadDomainExceptionsFromConfig(serverConfig, "DisallowExcept", m_ForeignsDisallowedExceptions);
if (m_GridService == null || m_PresenceService == null || m_SimulationService == null)
throw new Exception("Unable to load a required plugin, Gatekeeper Service cannot function.");
m_log.Debug("[GATEKEEPER SERVICE]: Starting...");
}
}
public GatekeeperService(IConfigSource config)
: this(config, null)
{
}
protected void LoadDomainExceptionsFromConfig(IConfig config, string variable, List<string> exceptions)
{
string value = config.GetString(variable, string.Empty);
string[] parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in parts)
exceptions.Add(s.Trim());
}
public bool LinkRegion(string regionName, out UUID regionID, out ulong regionHandle, out string externalName, out string imageURL, out string reason)
{
regionID = UUID.Zero;
regionHandle = 0;
externalName = m_ExternalName + ((regionName != string.Empty) ? " " + regionName : "");
imageURL = string.Empty;
reason = string.Empty;
GridRegion region = null;
m_log.DebugFormat("[GATEKEEPER SERVICE]: Request to link to {0}", (regionName == string.Empty)? "default region" : regionName);
if (!m_AllowTeleportsToAnyRegion || regionName == string.Empty)
{
List<GridRegion> defs = m_GridService.GetDefaultHypergridRegions(m_ScopeID);
if (defs != null && defs.Count > 0)
{
region = defs[0];
m_DefaultGatewayRegion = region;
}
else
{
reason = "Grid setup problem. Try specifying a particular region here.";
m_log.DebugFormat("[GATEKEEPER SERVICE]: Unable to send information. Please specify a default region for this grid!");
return false;
}
}
else
{
region = m_GridService.GetRegionByName(m_ScopeID, regionName);
if (region == null)
{
reason = "Region not found";
return false;
}
}
regionID = region.RegionID;
regionHandle = region.RegionHandle;
string regionimage = "regionImage" + regionID.ToString();
regionimage = regionimage.Replace("-", "");
imageURL = region.ServerURI + "index.php?method=" + regionimage;
return true;
}
public GridRegion GetHyperlinkRegion(UUID regionID, UUID agentID, string agentHomeURI, out string message)
{
message = null;
if (!m_AllowTeleportsToAnyRegion)
{
// Don't even check the given regionID
m_log.DebugFormat(
"[GATEKEEPER SERVICE]: Returning gateway region {0} {1} @ {2} to user {3}{4} as teleporting to arbitrary regions is not allowed.",
m_DefaultGatewayRegion.RegionName,
m_DefaultGatewayRegion.RegionID,
m_DefaultGatewayRegion.ServerURI,
agentID,
agentHomeURI == null ? "" : " @ " + agentHomeURI);
message = "Teleporting to the default region.";
return m_DefaultGatewayRegion;
}
GridRegion region = m_GridService.GetRegionByUUID(m_ScopeID, regionID);
if (region == null)
{
m_log.DebugFormat(
"[GATEKEEPER SERVICE]: Could not find region with ID {0} as requested by user {1}{2}. Returning null.",
regionID, agentID, (agentHomeURI == null) ? "" : " @ " + agentHomeURI);
message = "The teleport destination could not be found.";
return null;
}
m_log.DebugFormat(
"[GATEKEEPER SERVICE]: Returning region {0} {1} @ {2} to user {3}{4}.",
region.RegionName,
region.RegionID,
region.ServerURI,
agentID,
agentHomeURI == null ? "" : " @ " + agentHomeURI);
return region;
}
#region Login Agent
public bool LoginAgent(GridRegion source, AgentCircuitData aCircuit, GridRegion destination, out string reason)
{
reason = string.Empty;
string authURL = string.Empty;
if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
authURL = aCircuit.ServiceURLs["HomeURI"].ToString();
m_log.InfoFormat("[GATEKEEPER SERVICE]: Login request for {0} {1} @ {2} ({3}) at {4} using viewer {5}, channel {6}, IP {7}, Mac {8}, Id0 {9}, Teleport Flags: {10}. From region {11}",
aCircuit.firstname, aCircuit.lastname, authURL, aCircuit.AgentID, destination.RegionID,
aCircuit.Viewer, aCircuit.Channel, aCircuit.IPAddress, aCircuit.Mac, aCircuit.Id0, (TeleportFlags)aCircuit.teleportFlags,
(source == null) ? "Unknown" : string.Format("{0} ({1}){2}", source.RegionName, source.RegionID, (source.RawServerURI == null) ? "" : " @ " + source.ServerURI));
string curViewer = Util.GetViewerName(aCircuit);
//
// Check client
//
if (m_AllowedClients != string.Empty)
{
Regex arx = new Regex(m_AllowedClients);
Match am = arx.Match(curViewer);
if (!am.Success)
{
m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client {0} is not allowed", curViewer);
return false;
}
}
if (m_DeniedClients != string.Empty)
{
Regex drx = new Regex(m_DeniedClients);
Match dm = drx.Match(curViewer);
if (dm.Success)
{
m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client {0} is denied", curViewer);
return false;
}
}
//
// Authenticate the user
//
if (!Authenticate(aCircuit))
{
reason = "Unable to verify identity";
m_log.InfoFormat("[GATEKEEPER SERVICE]: Unable to verify identity of agent {0} {1}. Refusing service.", aCircuit.firstname, aCircuit.lastname);
return false;
}
m_log.DebugFormat("[GATEKEEPER SERVICE]: Identity verified for {0} {1} @ {2}", aCircuit.firstname, aCircuit.lastname, authURL);
//
// Check for impersonations
//
UserAccount account = null;
if (m_UserAccountService != null)
{
// Check to see if we have a local user with that UUID
account = m_UserAccountService.GetUserAccount(m_ScopeID, aCircuit.AgentID);
if (account != null)
{
// Make sure this is the user coming home, and not a foreign user with same UUID as a local user
if (m_UserAgentService != null)
{
if (!m_UserAgentService.IsAgentComingHome(aCircuit.SessionID, m_ExternalName))
{
// Can't do, sorry
reason = "Unauthorized";
m_log.InfoFormat("[GATEKEEPER SERVICE]: Foreign agent {0} {1} has same ID as local user. Refusing service.",
aCircuit.firstname, aCircuit.lastname);
return false;
}
}
}
}
//
// Foreign agents allowed? Exceptions?
//
if (account == null)
{
bool allowed = m_ForeignAgentsAllowed;
if (m_ForeignAgentsAllowed && IsException(aCircuit, m_ForeignsAllowedExceptions))
allowed = false;
if (!m_ForeignAgentsAllowed && IsException(aCircuit, m_ForeignsDisallowedExceptions))
allowed = true;
if (!allowed)
{
reason = "Destination does not allow visitors from your world";
m_log.InfoFormat("[GATEKEEPER SERVICE]: Foreign agents are not permitted {0} {1} @ {2}. Refusing service.",
aCircuit.firstname, aCircuit.lastname, aCircuit.ServiceURLs["HomeURI"]);
return false;
}
}
//
// Is the user banned?
// This uses a Ban service that's more powerful than the configs
//
string uui = (account != null ? aCircuit.AgentID.ToString() : Util.ProduceUserUniversalIdentifier(aCircuit));
if (m_BansService != null && m_BansService.IsBanned(uui, aCircuit.IPAddress, aCircuit.Id0, authURL))
{
reason = "You are banned from this world";
m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: user {0} is banned", uui);
return false;
}
m_log.DebugFormat("[GATEKEEPER SERVICE]: User {0} is ok", aCircuit.Name);
bool isFirstLogin = false;
//
// Login the presence, if it's not there yet (by the login service)
//
PresenceInfo presence = m_PresenceService.GetAgent(aCircuit.SessionID);
if (presence != null) // it has been placed there by the login service
isFirstLogin = true;
else
{
if (!m_PresenceService.LoginAgent(aCircuit.AgentID.ToString(), aCircuit.SessionID, aCircuit.SecureSessionID))
{
reason = "Unable to login presence";
m_log.InfoFormat("[GATEKEEPER SERVICE]: Presence login failed for foreign agent {0} {1}. Refusing service.",
aCircuit.firstname, aCircuit.lastname);
return false;
}
m_log.DebugFormat("[GATEKEEPER SERVICE]: Login presence {0} is ok", aCircuit.Name);
// Also login foreigners with GridUser service
if (m_GridUserService != null && account == null)
{
string userId = aCircuit.AgentID.ToString();
string first = aCircuit.firstname, last = aCircuit.lastname;
if (last.StartsWith("@"))
{
string[] parts = aCircuit.firstname.Split('.');
if (parts.Length >= 2)
{
first = parts[0];
last = parts[1];
}
}
userId += ";" + aCircuit.ServiceURLs["HomeURI"] + ";" + first + " " + last;
m_GridUserService.LoggedIn(userId);
}
}
//
// Get the region
//
destination = m_GridService.GetRegionByUUID(m_ScopeID, destination.RegionID);
if (destination == null)
{
reason = "Destination region not found";
return false;
}
m_log.DebugFormat(
"[GATEKEEPER SERVICE]: Destination {0} is ok for {1}", destination.RegionName, aCircuit.Name);
//
// Adjust the visible name
//
if (account != null)
{
aCircuit.firstname = account.FirstName;
aCircuit.lastname = account.LastName;
}
if (account == null)
{
if (!aCircuit.lastname.StartsWith("@"))
aCircuit.firstname = aCircuit.firstname + "." + aCircuit.lastname;
try
{
Uri uri = new Uri(aCircuit.ServiceURLs["HomeURI"].ToString());
aCircuit.lastname = "@" + uri.Authority;
}
catch
{
m_log.WarnFormat("[GATEKEEPER SERVICE]: Malformed HomeURI (this should never happen): {0}", aCircuit.ServiceURLs["HomeURI"]);
aCircuit.lastname = "@" + aCircuit.ServiceURLs["HomeURI"].ToString();
}
}
//
// Finally launch the agent at the destination
//
Constants.TeleportFlags loginFlag = isFirstLogin ? Constants.TeleportFlags.ViaLogin : Constants.TeleportFlags.ViaHGLogin;
// Preserve our TeleportFlags we have gathered so-far
loginFlag |= (Constants.TeleportFlags) aCircuit.teleportFlags;
m_log.DebugFormat("[GATEKEEPER SERVICE]: Launching {0}, Teleport Flags: {1}", aCircuit.Name, loginFlag);
EntityTransferContext ctx = new EntityTransferContext();
if (!m_SimulationService.QueryAccess(
destination, aCircuit.AgentID, aCircuit.ServiceURLs["HomeURI"].ToString(),
true, aCircuit.startpos, new List<UUID>(), ctx, out reason))
return false;
return m_SimulationService.CreateAgent(source, destination, aCircuit, (uint)loginFlag, ctx, out reason);
}
protected bool Authenticate(AgentCircuitData aCircuit)
{
if (!CheckAddress(aCircuit.ServiceSessionID))
return false;
if (string.IsNullOrEmpty(aCircuit.IPAddress))
{
m_log.DebugFormat("[GATEKEEPER SERVICE]: Agent did not provide a client IP address.");
return false;
}
string userURL = string.Empty;
if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
userURL = aCircuit.ServiceURLs["HomeURI"].ToString();
if (userURL == string.Empty)
{
m_log.DebugFormat("[GATEKEEPER SERVICE]: Agent did not provide an authentication server URL");
return false;
}
if (userURL == m_ExternalName)
{
return m_UserAgentService.VerifyAgent(aCircuit.SessionID, aCircuit.ServiceSessionID);
}
else
{
IUserAgentService userAgentService = new UserAgentServiceConnector(userURL);
try
{
return userAgentService.VerifyAgent(aCircuit.SessionID, aCircuit.ServiceSessionID);
}
catch
{
m_log.DebugFormat("[GATEKEEPER SERVICE]: Unable to contact authentication service at {0}", userURL);
return false;
}
}
}
// Check that the service token was generated for *this* grid.
// If it wasn't then that's a fake agent.
protected bool CheckAddress(string serviceToken)
{
string[] parts = serviceToken.Split(new char[] { ';' });
if (parts.Length < 2)
return false;
char[] trailing_slash = new char[] { '/' };
string addressee = parts[0].TrimEnd(trailing_slash);
string externalname = m_ExternalName.TrimEnd(trailing_slash);
m_log.DebugFormat("[GATEKEEPER SERVICE]: Verifying {0} against {1}", addressee, externalname);
Uri uri;
try
{
uri = new Uri(addressee);
}
catch
{
m_log.DebugFormat("[GATEKEEPER SERVICE]: Visitor provided malformed service address {0}", addressee);
return false;
}
return string.Equals(uri.GetLeftPart(UriPartial.Authority), m_Uri.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase) ;
}
#endregion
#region Misc
private bool IsException(AgentCircuitData aCircuit, List<string> exceptions)
{
bool exception = false;
if (exceptions.Count > 0) // we have exceptions
{
// Retrieve the visitor's origin
string userURL = aCircuit.ServiceURLs["HomeURI"].ToString();
if (!userURL.EndsWith("/"))
userURL += "/";
if (exceptions.Find(delegate(string s)
{
if (!s.EndsWith("/"))
s += "/";
return s == userURL;
}) != null)
exception = true;
}
return exception;
}
#endregion
}
}
| |
//
// Copyright (C) 2012-2016 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.Collections;
using Cassandra.Serialization;
using Cassandra.Tasks;
namespace Cassandra
{
/// <summary>
/// Represents a pool of connections to a host
/// </summary>
internal class HostConnectionPool : IDisposable
{
private static readonly Logger Logger = new Logger(typeof(HostConnectionPool));
private const int ConnectionIndexOverflow = int.MaxValue - 1000000;
private const long BetweenResizeDelay = 2000;
/// <summary>
/// Represents the possible states of the pool.
/// Possible state transitions:
/// - From Init to Closing: The pool must be closed because the host is ignored or because the pool should
/// not attempt more reconnections (another pool is trying to reconnect to a UP host).
/// - From Init to ShuttingDown: The pool is being shutdown as a result of a client shutdown.
/// - From Closing to Init: The pool finished closing connections (is now ignored) and it resets to
/// initial state in case the host is marked as local/remote in the future.
/// - From Closing to ShuttingDown (rare): It was marked as ignored, now the client is being shutdown.
/// - From ShuttingDown to Shutdown: Finished shutting down, the pool should not be reused.
/// </summary>
private static class PoolState
{
/// <summary>
/// Initial state: open / opening / ready to be opened
/// </summary>
public const int Init = 0;
/// <summary>
/// When the pool is being closed as part of a distance change
/// </summary>
public const int Closing = 1;
/// <summary>
/// When the pool is being shutdown for good
/// </summary>
public const int ShuttingDown = 2;
/// <summary>
/// When the pool has being shutdown
/// </summary>
public const int Shutdown = 3;
}
private readonly Host _host;
private readonly Configuration _config;
private readonly Serializer _serializer;
private readonly CopyOnWriteList<Connection> _connections = new CopyOnWriteList<Connection>();
private readonly HashedWheelTimer _timer;
private readonly object _allConnectionClosedEventLock = new object();
private volatile IReconnectionSchedule _reconnectionSchedule;
private volatile int _expectedConnectionLength;
private volatile int _maxInflightThreshold;
private volatile int _maxConnectionLength;
private volatile HashedWheelTimer.ITimeout _resizingEndTimeout;
private volatile bool _canCreateForeground = true;
private int _poolResizing;
private int _state = PoolState.Init;
private HashedWheelTimer.ITimeout _newConnectionTimeout;
private TaskCompletionSource<Connection> _connectionOpenTcs;
private int _connectionIndex;
public event Action<Host, HostConnectionPool> AllConnectionClosed;
public bool HasConnections
{
get { return _connections.Count > 0; }
}
public int OpenConnections
{
get { return _connections.Count; }
}
public bool IsClosing
{
get { return Volatile.Read(ref _state) != PoolState.Init; }
}
public HostConnectionPool(Host host, Configuration config, Serializer serializer)
{
_host = host;
_host.Down += OnHostDown;
_host.Up += OnHostUp;
_host.Remove += OnHostRemoved;
_host.DistanceChanged += OnDistanceChanged;
_config = config;
_serializer = serializer;
_timer = config.Timer;
_reconnectionSchedule = config.Policies.ReconnectionPolicy.NewSchedule();
_expectedConnectionLength = 1;
}
/// <summary>
/// Gets an open connection from the host pool (creating if necessary).
/// It returns null if the load balancing policy didn't allow connections to this host.
/// </summary>
public async Task<Connection> BorrowConnection()
{
var connections = await EnsureCreate().ConfigureAwait(false);
if (connections.Length == 0)
{
throw new DriverInternalError("No connection could be borrowed");
}
var c = MinInFlight(connections, ref _connectionIndex, _maxInflightThreshold);
ConsiderResizingPool(c.InFlight);
return c;
}
private void CancelNewConnectionTimeout(HashedWheelTimer.ITimeout newTimeout = null)
{
var previousTimeout = Interlocked.Exchange(ref _newConnectionTimeout, newTimeout);
if (previousTimeout != null)
{
// Clear previous reconnection attempt timeout
previousTimeout.Cancel();
}
if (newTimeout != null && IsClosing)
{
// It could have been the case the it was set after it was set as closed.
Interlocked.Exchange(ref _newConnectionTimeout, null);
}
}
public void CheckHealth(Connection c)
{
var timedOutOps = c.TimedOutOperations;
if (timedOutOps < _config.SocketOptions.DefunctReadTimeoutThreshold)
{
return;
}
Logger.Warning("Connection to {0} considered as unhealthy after {1} timed out operations",
_host.Address, timedOutOps);
//Defunct: close it and remove it from the pool
OnConnectionClosing(c);
c.Dispose();
}
public void ConsiderResizingPool(int inFlight)
{
if (inFlight < _maxInflightThreshold)
{
// The requests in-flight are normal
return;
}
if (_expectedConnectionLength >= _maxConnectionLength)
{
// We can not add more connections
return;
}
if (_connections.Count < _expectedConnectionLength)
{
// The pool is still trying to acquire the correct size
return;
}
var canResize = Interlocked.Exchange(ref _poolResizing, 1) == 0;
if (!canResize)
{
// There is already another thread resizing the pool
return;
}
if (IsClosing)
{
return;
}
_expectedConnectionLength++;
Logger.Info("Increasing pool #{0} size to {1}, as in-flight requests are above threshold ({2})",
GetHashCode(), _expectedConnectionLength, _maxInflightThreshold);
StartCreatingConnection(null);
_resizingEndTimeout = _timer.NewTimeout(_ => Interlocked.Exchange(ref _poolResizing, 0), null,
BetweenResizeDelay);
}
/// <summary>
/// Releases the resources associated with the pool.
/// </summary>
public void Dispose()
{
var markShuttingDown =
(Interlocked.CompareExchange(ref _state, PoolState.ShuttingDown, PoolState.Init) == PoolState.Init) ||
(Interlocked.CompareExchange(ref _state, PoolState.ShuttingDown, PoolState.Closing) ==
PoolState.Closing);
if (!markShuttingDown)
{
// The pool is already being shutdown, never mind
return;
}
Logger.Info("Disposing connection pool #{0} to {1}", GetHashCode(), _host.Address);
var connections = _connections.ClearAndGet();
foreach (var c in connections)
{
c.Dispose();
}
_host.Up -= OnHostUp;
_host.Down -= OnHostDown;
_host.Remove -= OnHostRemoved;
_host.DistanceChanged -= OnDistanceChanged;
var t = _resizingEndTimeout;
if (t != null)
{
t.Cancel();
}
CancelNewConnectionTimeout();
Interlocked.Exchange(ref _state, PoolState.Shutdown);
}
public virtual async Task<Connection> DoCreateAndOpen()
{
var c = new Connection(_serializer, _host.Address, _config);
try
{
await c.Open().ConfigureAwait(false);
}
catch
{
c.Dispose();
throw;
}
if (_config.GetPoolingOptions(_serializer.ProtocolVersion).GetHeartBeatInterval() > 0)
{
c.OnIdleRequestException += ex => OnIdleRequestException(c, ex);
}
c.Closing += OnConnectionClosing;
return c;
}
/// <summary>
/// Gets the connection with the minimum number of InFlight requests.
/// Only checks for index + 1 and index, to avoid a loop of all connections.
/// </summary>
/// <param name="connections">A snapshot of the pool of connections</param>
/// <param name="connectionIndex">Current round-robin index</param>
/// <param name="inFlightThreshold">
/// The max amount of in-flight requests that cause this method to continue
/// iterating until finding the connection with min number of in-flight requests.
/// </param>
public static Connection MinInFlight(Connection[] connections, ref int connectionIndex, int inFlightThreshold)
{
if (connections.Length == 1)
{
return connections[0];
}
//It is very likely that the amount of InFlight requests per connection is the same
//Do round robin between connections, skipping connections that have more in flight requests
var index = Interlocked.Increment(ref connectionIndex);
if (index > ConnectionIndexOverflow)
{
//Overflow protection, not exactly thread-safe but we can live with it
Interlocked.Exchange(ref connectionIndex, 0);
}
Connection c = null;
for (var i = index; i < index + connections.Length; i++)
{
c = connections[i % connections.Length];
var previousConnection = connections[(i - 1) % connections.Length];
// Avoid multiple volatile reads
var inFlight = c.InFlight;
var previousInFlight = previousConnection.InFlight;
if (previousInFlight < inFlight)
{
c = previousConnection;
inFlight = previousInFlight;
}
if (inFlight < inFlightThreshold)
{
// We should avoid traversing all the connections
// We have a connection with a decent amount of in-flight requests
break;
}
}
return c;
}
private void OnConnectionClosing(Connection c = null)
{
int currentLength;
if (c != null)
{
var removalInfo = _connections.RemoveAndCount(c);
currentLength = removalInfo.Item2;
var hasBeenRemoved = removalInfo.Item1;
if (!hasBeenRemoved)
{
// It has been already removed (via event or direct call)
// When it was removed, all the following checks have been made
// No point in doing them again
return;
}
Logger.Info("Pool #{0} for host {1} removed a connection, new length: {2}",
GetHashCode(), _host.Address, currentLength);
}
else
{
currentLength = _connections.Count;
}
if (IsClosing || currentLength >= _expectedConnectionLength)
{
// No need to reconnect
return;
}
// We are using an IO thread
Task.Run(() =>
{
// Use a lock for avoiding concurrent calls to SetNewConnectionTimeout()
lock (_allConnectionClosedEventLock)
{
if (currentLength == 0)
{
// All connections have been closed
// If the node is UP, we should stop attempting to reconnect
if (_host.IsUp && AllConnectionClosed != null)
{
// Raise the event and wait for a caller to decide
AllConnectionClosed(_host, this);
return;
}
}
SetNewConnectionTimeout(_reconnectionSchedule);
}
});
}
private void OnDistanceChanged(HostDistance previousDistance, HostDistance distance)
{
SetDistance(distance);
if (previousDistance == HostDistance.Ignored)
{
_canCreateForeground = true;
// Start immediate reconnection
ScheduleReconnection(true);
return;
}
if (distance != HostDistance.Ignored)
{
return;
}
// Host is now ignored
var isClosing = Interlocked.CompareExchange(ref _state, PoolState.Closing, PoolState.Init) ==
PoolState.Init;
if (!isClosing)
{
// Is already shutting down or shutdown, don't mind
return;
}
Logger.Info("Host ignored. Closing pool #{0} to {1}", GetHashCode(), _host.Address);
DrainConnections(() =>
{
// After draining, set the pool back to init state
Interlocked.CompareExchange(ref _state, PoolState.Init, PoolState.Closing);
});
CancelNewConnectionTimeout();
}
private void OnHostRemoved()
{
var previousState = Interlocked.Exchange(ref _state, PoolState.ShuttingDown);
if (previousState == PoolState.Shutdown)
{
// It was already shutdown
Interlocked.Exchange(ref _state, PoolState.Shutdown);
return;
}
Logger.Info("Host decommissioned. Closing pool #{0} to {1}", GetHashCode(), _host.Address);
DrainConnections(() => Interlocked.Exchange(ref _state, PoolState.Shutdown));
CancelNewConnectionTimeout();
var t = _resizingEndTimeout;
if (t != null)
{
t.Cancel();
}
}
/// <summary>
/// Removes the connections from the pool and defers the closing of the connections until twice the
/// readTimeout. The connection might be already selected and sending requests.
/// </summary>
private void DrainConnections(Action afterDrainHandler)
{
var connections = _connections.ClearAndGet();
if (connections.Length == 0)
{
Logger.Info("Pool #{0} to {1} had no connections", GetHashCode(), _host.Address);
return;
}
// The request handler might execute up to 2 queries with a single connection:
// Changing the keyspace + the actual query
var delay = _config.SocketOptions.ReadTimeoutMillis*2;
// Use a sane maximum of 5 mins
const int maxDelay = 5*60*1000;
if (delay <= 0 || delay > maxDelay)
{
delay = maxDelay;
}
DrainConnectionsTimer(connections, afterDrainHandler, delay/1000);
}
private void DrainConnectionsTimer(Connection[] connections, Action afterDrainHandler, int steps)
{
_timer.NewTimeout(_ =>
{
Task.Run(() =>
{
var drained = !connections.Any(c => c.HasPendingOperations);
if (!drained && --steps >= 0)
{
Logger.Info("Pool #{0} to {1} can not be closed yet",
GetHashCode(), _host.Address);
DrainConnectionsTimer(connections, afterDrainHandler, steps);
return;
}
Logger.Info("Pool #{0} to {1} closing {2} connections to after {3} draining",
GetHashCode(), _host.Address, connections.Length, drained ? "successful" : "unsuccessful");
foreach (var c in connections)
{
c.Dispose();
}
if (afterDrainHandler != null)
{
afterDrainHandler();
}
});
}, null, 1000);
}
public void OnHostUp(Host h)
{
// It can be awaited upon pool creation
_canCreateForeground = true;
if (_connections.Count > 0)
{
// This was the pool that was reconnecting, the pool is already getting the appropriate size
return;
}
Logger.Info("Pool #{0} for host {1} attempting to reconnect as host is UP", GetHashCode(), _host.Address);
// Schedule an immediate reconnection
ScheduleReconnection(true);
}
private void OnHostDown(Host h)
{
// Cancel the outstanding timeout (if any)
// If the timeout already elapsed, a connection could be been created anyway
CancelNewConnectionTimeout();
}
/// <summary>
/// Handler that gets invoked when if there is a socket exception when making a heartbeat/idle request
/// </summary>
private void OnIdleRequestException(Connection c, Exception ex)
{
Logger.Warning("Connection to {0} considered as unhealthy after idle timeout exception: {1}",
_host.Address, ex);
OnConnectionClosing(c);
c.Dispose();
}
/// <summary>
/// Adds a new reconnection timeout using a new schedule.
/// Resets the status of the pool to allow further reconnections.
/// </summary>
public void ScheduleReconnection(bool immediate = false)
{
var schedule = _config.Policies.ReconnectionPolicy.NewSchedule();
_reconnectionSchedule = schedule;
SetNewConnectionTimeout(immediate ? null : schedule);
}
private void SetNewConnectionTimeout(IReconnectionSchedule schedule)
{
if (schedule != null && _reconnectionSchedule != schedule)
{
// There's another reconnection schedule, leave it
return;
}
HashedWheelTimer.ITimeout timeout = null;
if (schedule != null)
{
// Schedule the creation
var delay = schedule.NextDelayMs();
Logger.Info("Scheduling reconnection from #{0} to {1} in {2}ms", GetHashCode(), _host.Address, delay);
timeout = _timer.NewTimeout(_ => Task.Run(() => StartCreatingConnection(schedule)), null, delay);
}
CancelNewConnectionTimeout(timeout);
if (schedule == null)
{
// Start creating immediately after de-scheduling the timer
Logger.Info("Starting reconnection from pool #{0} to {1}", GetHashCode(), _host.Address);
StartCreatingConnection(null);
}
}
/// <summary>
/// Asynchronously starts to create a new connection (if its not already being created).
/// A <c>null</c> schedule signals that the pool is not reconnecting but growing to the expected size.
/// </summary>
/// <param name="schedule"></param>
private void StartCreatingConnection(IReconnectionSchedule schedule)
{
var count = _connections.Count;
if (count >= _expectedConnectionLength)
{
return;
}
if (schedule != null && schedule != _reconnectionSchedule)
{
// There's another reconnection schedule, leave it
return;
}
CreateOpenConnection(false).ContinueWith(t =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
StartCreatingConnection(null);
_host.BringUpIfDown();
return;
}
// The connection could not be opened
if (IsClosing)
{
// don't mind, the pool is not supposed to be open
return;
}
if (schedule == null)
{
// As it failed, we need a new schedule for the following attempts
schedule = _config.Policies.ReconnectionPolicy.NewSchedule();
_reconnectionSchedule = schedule;
}
if (schedule != _reconnectionSchedule)
{
// There's another reconnection schedule, leave it
return;
}
OnConnectionClosing();
}, TaskContinuationOptions.ExecuteSynchronously);
}
/// <summary>
/// Opens one connection.
/// If a connection is being opened it yields the same task, preventing creation in parallel.
/// </summary>
/// <exception cref="SocketException">Throws a SocketException when the connection could not be established with the host</exception>
/// <exception cref="AuthenticationException" />
/// <exception cref="UnsupportedProtocolVersionException" />
private async Task<Connection> CreateOpenConnection(bool foreground)
{
var concurrentOpenTcs = Volatile.Read(ref _connectionOpenTcs);
// Try to exit early (cheap) as there could be another thread creating / finishing creating
if (concurrentOpenTcs != null)
{
// There is another thread opening a new connection
return await concurrentOpenTcs.Task.ConfigureAwait(false);
}
var tcs = new TaskCompletionSource<Connection>();
// Try to set the creation task source
concurrentOpenTcs = Interlocked.CompareExchange(ref _connectionOpenTcs, tcs, null);
if (concurrentOpenTcs != null)
{
// There is another thread opening a new connection
return await concurrentOpenTcs.Task.ConfigureAwait(false);
}
if (IsClosing)
{
return await FinishOpen(tcs, false, GetNotConnectedException()).ConfigureAwait(false);
}
// Before creating, make sure that its still needed
// This method is the only one that adds new connections
// But we don't control the removal, use snapshot
var connectionsSnapshot = _connections.GetSnapshot();
if (connectionsSnapshot.Length >= _expectedConnectionLength)
{
if (connectionsSnapshot.Length == 0)
{
// Avoid race condition while removing
return await FinishOpen(tcs, false, GetNotConnectedException()).ConfigureAwait(false);
}
return await FinishOpen(tcs, true, null, connectionsSnapshot[0]).ConfigureAwait(false);
}
if (foreground && !_canCreateForeground)
{
// Foreground creation only cares about one connection
// If its already there, yield it
connectionsSnapshot = _connections.GetSnapshot();
if (connectionsSnapshot.Length == 0)
{
// When creating in foreground, it failed
return await FinishOpen(tcs, false, GetNotConnectedException()).ConfigureAwait(false);
}
return await FinishOpen(tcs, false, null, connectionsSnapshot[0]).ConfigureAwait(false);
}
Logger.Info("Creating a new connection to {0}", _host.Address);
Connection c = null;
Exception creationEx = null;
try
{
c = await DoCreateAndOpen().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.Info("Connection to {0} could not be created: {1}", _host.Address, ex);
// Can not await on catch on C# 5...
creationEx = ex;
}
if (creationEx != null)
{
return await FinishOpen(tcs, true, creationEx).ConfigureAwait(false);
}
if (IsClosing)
{
Logger.Info("Connection to {0} opened successfully but pool #{1} was being closed",
_host.Address, GetHashCode());
c.Dispose();
return await FinishOpen(tcs, false, GetNotConnectedException()).ConfigureAwait(false);
}
var newLength = _connections.AddNew(c);
Logger.Info("Connection to {0} opened successfully, pool #{1} length: {2}",
_host.Address, GetHashCode(), newLength);
if (IsClosing)
{
// We haven't use a CAS operation, so it's possible that the pool is being closed while adding a new
// connection, we should remove it.
Logger.Info("Connection to {0} opened successfully and added to the pool #{1} but it was being closed",
_host.Address, GetHashCode());
_connections.Remove(c);
c.Dispose();
return await FinishOpen(tcs, false, GetNotConnectedException()).ConfigureAwait(false);
}
return await FinishOpen(tcs, true, null, c).ConfigureAwait(false);
}
private Task<Connection> FinishOpen(
TaskCompletionSource<Connection> tcs,
bool preventForeground,
Exception ex,
Connection c = null)
{
// Instruction ordering: canCreateForeground flag must be set before resetting of the tcs
if (preventForeground)
{
_canCreateForeground = false;
}
Interlocked.Exchange(ref _connectionOpenTcs, null);
tcs.TrySet(ex, c);
return tcs.Task;
}
private static SocketException GetNotConnectedException()
{
return new SocketException((int)SocketError.NotConnected);
}
/// <summary>
/// Ensures that the pool has at least contains 1 connection to the host.
/// </summary>
/// <returns>An Array of connections with 1 or more elements or throws an exception.</returns>
/// <exception cref="SocketException" />
/// <exception cref="AuthenticationException" />
/// <exception cref="UnsupportedProtocolVersionException" />
public async Task<Connection[]> EnsureCreate()
{
var connections = _connections.GetSnapshot();
if (connections.Length > 0)
{
// Use snapshot to return as early as possible
return connections;
}
if (IsClosing || !_host.IsUp)
{
// Should have not been considered as UP
throw GetNotConnectedException();
}
if (!_canCreateForeground)
{
// Take a new snapshot
connections = _connections.GetSnapshot();
if (connections.Length > 0)
{
return connections;
}
// It's not considered as connected
throw GetNotConnectedException();
}
Connection c;
try
{
// It should only await for the creation of the connection in few selected occasions:
// It's the first time accessing or it has been recently set as UP
// CreateOpenConnection() supports concurrent calls
c = await CreateOpenConnection(true).ConfigureAwait(false);
}
catch (Exception)
{
OnConnectionClosing();
throw;
}
StartCreatingConnection(null);
return new[] { c };
}
public void SetDistance(HostDistance distance)
{
var poolingOptions = _config.GetPoolingOptions(_serializer.ProtocolVersion);
_expectedConnectionLength = poolingOptions.GetCoreConnectionsPerHost(distance);
_maxInflightThreshold = poolingOptions.GetMaxSimultaneousRequestsPerConnectionTreshold(distance);
_maxConnectionLength = poolingOptions.GetMaxConnectionPerHost(distance);
}
}
}
| |
//BSD, 2014-present, WinterDev
//ArthurHub, Jose Manuel Menendez Poo
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.Collections.Generic;
namespace LayoutFarm.WebDom
{
public class CssActiveSheet
{
//major groups...
Dictionary<string, CssRuleSetGroup> _rulesForTagName = new Dictionary<string, CssRuleSetGroup>();
Dictionary<string, CssRuleSetGroup> _rulesForClassName = new Dictionary<string, CssRuleSetGroup>();
Dictionary<string, CssRuleSetGroup> _rulesForElementId = new Dictionary<string, CssRuleSetGroup>();
Dictionary<string, CssRuleSetGroup> _rulesForPsedoClass = new Dictionary<string, CssRuleSetGroup>();
Dictionary<string, CssRuleSetGroup> _rulesForAll = new Dictionary<string, CssRuleSetGroup>();
#if DEBUG
CssActiveSheet dbugOriginal;
#endif
public CssActiveSheet()
{
}
public void LoadCssDoc(WebDom.CssDocument cssDoc)
{
foreach (WebDom.CssDocMember cssDocMember in cssDoc.GetCssDocMemberIter())
{
switch (cssDocMember.MemberKind)
{
case WebDom.CssDocMemberKind.RuleSet:
this.AddRuleSet((WebDom.CssRuleSet)cssDocMember);
break;
case WebDom.CssDocMemberKind.Media:
this.AddMedia((WebDom.CssAtMedia)cssDocMember);
break;
default:
case WebDom.CssDocMemberKind.Page:
throw new NotSupportedException();
}
}
}
void AddRuleSet(WebDom.CssRuleSet ruleset)
{
List<CssRuleSetGroup> relatedRuleSets = new List<CssRuleSetGroup>();
ExpandSelector(relatedRuleSets, ruleset.GetSelector());
CssPropertyAssignmentCollection assignmentCollection = new CssPropertyAssignmentCollection(null);
assignmentCollection.LoadRuleSet(ruleset);
foreach (var ruleSetGroup in relatedRuleSets)
{
//start with share*** rule set
ruleSetGroup.AddRuleSet(assignmentCollection);
}
}
static CssRuleSetGroup GetGroupOrCreateIfNotExists(Dictionary<string, CssRuleSetGroup> dic,
WebDom.CssSimpleElementSelector simpleSelector)
{
CssRuleSetGroup ruleSetGroup;
if (!dic.TryGetValue(simpleSelector.Name, out ruleSetGroup))
{
ruleSetGroup = new CssRuleSetGroup(simpleSelector.Name);
dic.Add(simpleSelector.Name, ruleSetGroup);
}
//-------------
if (simpleSelector.Parent != null)
{
//get or create subgroup
return ruleSetGroup.GetOrCreateSubgroup(simpleSelector);
}
//-------------
return ruleSetGroup;
}
void ExpandSelector(List<CssRuleSetGroup> relatedRuleSets, WebDom.CssElementSelector selector)
{
//recursive
//create active element set
if (selector.IsSimpleSelector)
{
WebDom.CssSimpleElementSelector simpleSelector = (WebDom.CssSimpleElementSelector)selector;
switch (simpleSelector._selectorType)
{
default:
{
throw new NotSupportedException();
}
case WebDom.SimpleElementSelectorKind.ClassName:
{
//any element with specific class name
relatedRuleSets.Add(
GetGroupOrCreateIfNotExists(
_rulesForClassName,
simpleSelector));
}
break;
case WebDom.SimpleElementSelectorKind.Extend:
{
}
break;
case WebDom.SimpleElementSelectorKind.Id:
{
//element with id
relatedRuleSets.Add(
GetGroupOrCreateIfNotExists(
_rulesForElementId,
simpleSelector));
}
break;
case WebDom.SimpleElementSelectorKind.PseudoClass:
{
relatedRuleSets.Add(
GetGroupOrCreateIfNotExists(
_rulesForPsedoClass,
simpleSelector));
}
break;
case WebDom.SimpleElementSelectorKind.TagName:
{
relatedRuleSets.Add(
GetGroupOrCreateIfNotExists(
_rulesForTagName,
simpleSelector));
}
break;
case WebDom.SimpleElementSelectorKind.All:
{
relatedRuleSets.Add(
GetGroupOrCreateIfNotExists(
_rulesForAll,
simpleSelector));
}
break;
}
}
else
{
WebDom.CssCompundElementSelector combiSelector = (WebDom.CssCompundElementSelector)selector;
switch (combiSelector.OperatorName)
{
case WebDom.CssCombinatorOperator.List:
{
ExpandSelector(relatedRuleSets, combiSelector.LeftSelector);
ExpandSelector(relatedRuleSets, combiSelector.RightSelector);
}
break;
case WebDom.CssCombinatorOperator.Descendant:
{
//focus on right side?
ExpandSelector(relatedRuleSets, combiSelector.RightSelector);
}
break;
default:
{
throw new NotSupportedException();
}
}
}
//-----------------------------------------------------------------------------
}
void AddMedia(WebDom.CssAtMedia atMedia)
{
if (!atMedia.HasMediaName)
{
//global media
foreach (WebDom.CssRuleSet ruleSet in atMedia.GetRuleSetIter())
{
this.AddRuleSet(ruleSet);
}
}
else
{
//has media name
}
}
public CssRuleSetGroup GetRuleSetForTagName(string tagName)
{
CssRuleSetGroup found;
_rulesForTagName.TryGetValue(tagName, out found);
return found;
}
public CssRuleSetGroup GetRuleSetForClassName(string className)
{
CssRuleSetGroup found;
_rulesForClassName.TryGetValue(className, out found);
return found;
}
public CssRuleSetGroup GetRuleSetForId(string elementId)
{
CssRuleSetGroup found;
_rulesForElementId.TryGetValue(elementId, out found);
return found;
}
public CssActiveSheet Clone()
{
CssActiveSheet newclone = new CssActiveSheet();
newclone._rulesForTagName = CloneNew(_rulesForTagName);
newclone._rulesForClassName = CloneNew(_rulesForClassName);
newclone._rulesForElementId = CloneNew(_rulesForElementId);
newclone._rulesForPsedoClass = CloneNew(_rulesForPsedoClass);
newclone._rulesForAll = CloneNew(_rulesForAll);
#if DEBUG
newclone.dbugOriginal = this;
#endif
return newclone;
}
/// <summary>
/// consume
/// </summary>
/// <param name="another"></param>
public void Combine(CssActiveSheet another)
{
MergeContent(_rulesForClassName, another._rulesForClassName);
MergeContent(_rulesForAll, another._rulesForAll);
MergeContent(_rulesForElementId, another._rulesForElementId);
MergeContent(_rulesForPsedoClass, another._rulesForPsedoClass);
MergeContent(_rulesForTagName, another._rulesForTagName);
}
static Dictionary<string, CssRuleSetGroup> CloneNew(Dictionary<string, CssRuleSetGroup> source)
{
Dictionary<string, CssRuleSetGroup> newdic = new Dictionary<string, CssRuleSetGroup>();
foreach (var kp in source)
{
newdic[kp.Key] = kp.Value.Clone();
}
return newdic;
}
static void MergeContent(Dictionary<string, CssRuleSetGroup> a, Dictionary<string, CssRuleSetGroup> b)
{
foreach (CssRuleSetGroup b_ruleSet in b.Values)
{
CssRuleSetGroup a_ruleset;
if (!a.TryGetValue(b_ruleSet.Name, out a_ruleset))
{
//not found
a.Add(b_ruleSet.Name, b_ruleSet);
}
else
{
//if found then merge
a_ruleset.Merge(b_ruleSet);
}
}
}
#if DEBUG
public bool dbugIsClone
{
get
{
return this.dbugOriginal != null;
}
}
#endif
#if DEBUG
static int dbugTotalId = 0;
public readonly int dbugId = dbugTotalId++;
#endif
}
/// <summary>
/// ruleset and its subgroups
/// </summary>
public class CssRuleSetGroup
{
CssPropertyAssignmentCollection _assignments;
WebDom.CssSimpleElementSelector _originalSelector;
CssRuleSetGroup _parent;
List<CssRuleSetGroup> _subGroups;
#if DEBUG
static int dbugTotalId = 0;
public readonly int dbugId = dbugTotalId++;
#endif
public CssRuleSetGroup(string name)
{
//if (dbugId == 170)
//{
//}
this.Name = name;
}
private CssRuleSetGroup(CssRuleSetGroup parent, string name, WebDom.CssSimpleElementSelector simpleSelector)
{
//if (dbugId == 170)
//{
//}
this.Name = name;
_parent = parent;
_originalSelector = simpleSelector;
}
public CssRuleSetGroup GetOrCreateSubgroup(WebDom.CssSimpleElementSelector simpleSelector)
{
if (_subGroups == null)
{
_subGroups = new List<CssRuleSetGroup>();
}
int j = _subGroups.Count;
for (int i = 0; i < j; ++i)
{
//find sub group for specific selector
WebDom.CssSimpleElementSelector selector = _subGroups[i]._originalSelector;
if (WebDom.CssSimpleElementSelector.IsCompatible(selector, simpleSelector))
{
//found
return _subGroups[i];
}
}
//if not found then create new one
CssRuleSetGroup newSubgroup = new CssRuleSetGroup(this, this.Name, simpleSelector);
_subGroups.Add(newSubgroup);
return newSubgroup;
}
public string Name
{
get;
private set;
}
public void AddRuleSet(CssPropertyAssignmentCollection otherAssignments)
{
//assignment in this ruleset
//if (dbugId == 170)
//{
//}
if (_assignments == null)
{
//share
_assignments = otherAssignments;
}
else if (_assignments != otherAssignments)
{
//then copy each css property assignment
//from other Assignment and add to this assignment
if (_assignments.OriginalOwner != this)
{
_assignments = _assignments.Clone(this);
}
_assignments.MergeProperties(otherAssignments);
}
else
{
}
}
public CssRuleSetGroup Clone()
{
CssRuleSetGroup newGroup = new CssRuleSetGroup(this.Name);
newGroup._originalSelector = _originalSelector;
if (_assignments != null)
{
newGroup._assignments = _assignments.Clone(newGroup);
}
if (_subGroups != null)
{
foreach (var subgroup in _subGroups)
{
var subclone = subgroup.Clone();
subclone._parent = newGroup;
}
}
return newGroup;
}
public IEnumerable<WebDom.CssPropertyDeclaration> GetPropertyDeclIter()
{
if (_assignments != null)
{
var decls = _assignments.GetDeclarations();
foreach (var decl in decls.Values)
{
yield return decl;
}
}
}
public WebDom.CssPropertyDeclaration GetPropertyDeclaration(WebDom.WellknownCssPropertyName wellknownPropName)
{
if (_assignments != null)
{
WebDom.CssPropertyDeclaration decl;
_assignments.GetDeclarations().TryGetValue(wellknownPropName, out decl);
return decl;
}
return null;
}
public void Merge(CssRuleSetGroup another)
{
//merge
//------------
if (another._assignments != null)
{
if (_assignments == null)
{
_assignments = new CssPropertyAssignmentCollection(this);
}
//merge decl
_assignments.MergeProperties(another._assignments);
}
//find subgroup
if (another._subGroups != null)
{
if (_subGroups == null)
{
_subGroups = new List<CssRuleSetGroup>();
}
foreach (CssRuleSetGroup ruleSetGroup in another._subGroups)
{
//merge to this group
CssRuleSetGroup exiting = GetOrCreateSubgroup(ruleSetGroup._originalSelector);
exiting.Merge(ruleSetGroup);
}
}
}
public int SubGroupCount
{
get
{
if (_subGroups == null)
{
return 0;
}
return _subGroups.Count;
}
}
public CssRuleSetGroup GetSubGroup(int index)
{
return _subGroups[index];
}
public WebDom.CssSimpleElementSelector OriginalSelector
{
get
{
return _originalSelector;
}
}
}
public class CssPropertyAssignmentCollection
{
Dictionary<LayoutFarm.WebDom.WellknownCssPropertyName, WebDom.CssPropertyDeclaration> _myAssignments = new Dictionary<WebDom.WellknownCssPropertyName, WebDom.CssPropertyDeclaration>();
object owner;
#if DEBUG
static int s_dbugTotalId = 0;
public static readonly int _dbugId = s_dbugTotalId++;
#endif
public CssPropertyAssignmentCollection(object owner)
{
this.owner = owner;
}
internal void LoadRuleSet(CssRuleSet ruleSet)
{
foreach (CssPropertyDeclaration otherAssignment in ruleSet.GetAssignmentIter())
{
if (otherAssignment.WellknownPropertyName == WebDom.WellknownCssPropertyName.Unknown)
{
continue;
}
_myAssignments[otherAssignment.WellknownPropertyName] = otherAssignment;
}
}
public object OriginalOwner
{
get
{
return this.owner;
}
}
public CssPropertyAssignmentCollection Clone(object newOwner)
{
CssPropertyAssignmentCollection newclone = new CssPropertyAssignmentCollection(newOwner);
Dictionary<WellknownCssPropertyName, WebDom.CssPropertyDeclaration> newCloneDic = newclone._myAssignments;
foreach (var kp in _myAssignments)
{
newCloneDic.Add(kp.Key, kp.Value);
}
return newclone;
}
public void MergeProperties(CssPropertyAssignmentCollection sourceCollection)
{
Dictionary<WellknownCssPropertyName, CssPropertyDeclaration> fromDic = sourceCollection._myAssignments;
Dictionary<WellknownCssPropertyName, CssPropertyDeclaration> targetDic = _myAssignments;
foreach (CssPropertyDeclaration sourceAssignment in fromDic.Values)
{
//add or replace
targetDic[sourceAssignment.WellknownPropertyName] = sourceAssignment;
}
}
internal Dictionary<WellknownCssPropertyName, CssPropertyDeclaration> GetDeclarations()
{
return _myAssignments;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Common
{
using System;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Threading;
// A simple synchronized pool would simply lock a stack and push/pop on return/take.
//
// This implementation tries to reduce locking by exploiting the case where an item
// is taken and returned by the same thread, which turns out to be common in our
// scenarios.
//
// Initially, all the quota is allocated to a global (non-thread-specific) pool,
// which takes locks. As different threads take and return values, we record their IDs,
// and if we detect that a thread is taking and returning "enough" on the same thread,
// then we decide to "promote" the thread. When a thread is promoted, we decrease the
// quota of the global pool by one, and allocate a thread-specific entry for the thread
// to store it's value. Once this entry is allocated, the thread can take and return
// it's value from that entry without taking any locks. Not only does this avoid
// locks, but it affinitizes pooled items to a particular thread.
//
// There are a couple of additional things worth noting:
//
// It is possible for a thread that we have reserved an entry for to exit. This means
// we will still have a entry allocated for it, but the pooled item stored there
// will never be used. After a while, we could end up with a number of these, and
// as a result we would begin to exhaust the quota of the overall pool. To mitigate this
// case, we throw away the entire per-thread pool, and return all the quota back to
// the global pool if we are unable to promote a thread (due to lack of space). Then
// the set of active threads will be re-promoted as they take and return items.
//
// You may notice that the code does not immediately promote a thread, and does not
// immediately throw away the entire per-thread pool when it is unable to promote a
// thread. Instead, it uses counters (based on the number of calls to the pool)
// and a threshold to figure out when to do these operations. In the case where the
// pool to misconfigured to have too few items for the workload, this avoids constant
// promoting and rebuilding of the per thread entries.
//
// You may also notice that we do not use interlocked methods when adjusting statistics.
// Since the statistics are a heuristic as to how often something is happening, they
// do not need to be perfect.
//
[Fx.Tag.SynchronizationObject(Blocking = false)]
class SynchronizedPool<T> where T : class
{
const int maxPendingEntries = 128;
const int maxPromotionFailures = 64;
const int maxReturnsBeforePromotion = 64;
const int maxThreadItemsPerProcessor = 16;
Entry[] entries;
GlobalPool globalPool;
int maxCount;
PendingEntry[] pending;
int promotionFailures;
public SynchronizedPool(int maxCount)
{
int threadCount = maxCount;
int maxThreadCount = maxThreadItemsPerProcessor + SynchronizedPoolHelper.ProcessorCount;
if (threadCount > maxThreadCount)
{
threadCount = maxThreadCount;
}
this.maxCount = maxCount;
this.entries = new Entry[threadCount];
this.pending = new PendingEntry[4];
this.globalPool = new GlobalPool(maxCount);
}
object ThisLock
{
get
{
return this;
}
}
public void Clear()
{
Entry[] entriesReference = this.entries;
for (int i = 0; i < entriesReference.Length; i++)
{
entriesReference[i].value = null;
}
globalPool.Clear();
}
void HandlePromotionFailure(int thisThreadID)
{
int newPromotionFailures = this.promotionFailures + 1;
if (newPromotionFailures >= maxPromotionFailures)
{
lock (ThisLock)
{
this.entries = new Entry[this.entries.Length];
globalPool.MaxCount = maxCount;
}
PromoteThread(thisThreadID);
}
else
{
this.promotionFailures = newPromotionFailures;
}
}
bool PromoteThread(int thisThreadID)
{
lock (ThisLock)
{
for (int i = 0; i < this.entries.Length; i++)
{
int threadID = this.entries[i].threadID;
if (threadID == thisThreadID)
{
return true;
}
else if (threadID == 0)
{
globalPool.DecrementMaxCount();
this.entries[i].threadID = thisThreadID;
return true;
}
}
}
return false;
}
void RecordReturnToGlobalPool(int thisThreadID)
{
PendingEntry[] localPending = this.pending;
for (int i = 0; i < localPending.Length; i++)
{
int threadID = localPending[i].threadID;
if (threadID == thisThreadID)
{
int newReturnCount = localPending[i].returnCount + 1;
if (newReturnCount >= maxReturnsBeforePromotion)
{
localPending[i].returnCount = 0;
if (!PromoteThread(thisThreadID))
{
HandlePromotionFailure(thisThreadID);
}
}
else
{
localPending[i].returnCount = newReturnCount;
}
break;
}
else if (threadID == 0)
{
break;
}
}
}
void RecordTakeFromGlobalPool(int thisThreadID)
{
PendingEntry[] localPending = this.pending;
for (int i = 0; i < localPending.Length; i++)
{
int threadID = localPending[i].threadID;
if (threadID == thisThreadID)
{
return;
}
else if (threadID == 0)
{
lock (localPending)
{
if (localPending[i].threadID == 0)
{
localPending[i].threadID = thisThreadID;
return;
}
}
}
}
if (localPending.Length >= maxPendingEntries)
{
this.pending = new PendingEntry[localPending.Length];
}
else
{
PendingEntry[] newPending = new PendingEntry[localPending.Length * 2];
Array.Copy(localPending, newPending, localPending.Length);
this.pending = newPending;
}
}
public bool Return(T value)
{
int thisThreadID = Thread.CurrentThread.ManagedThreadId;
if (thisThreadID == 0)
{
return false;
}
if (ReturnToPerThreadPool(thisThreadID, value))
{
return true;
}
return ReturnToGlobalPool(thisThreadID, value);
}
bool ReturnToPerThreadPool(int thisThreadID, T value)
{
Entry[] entriesReference = this.entries;
for (int i = 0; i < entriesReference.Length; i++)
{
int threadID = entriesReference[i].threadID;
if (threadID == thisThreadID)
{
if (entriesReference[i].value == null)
{
entriesReference[i].value = value;
return true;
}
else
{
return false;
}
}
else if (threadID == 0)
{
break;
}
}
return false;
}
bool ReturnToGlobalPool(int thisThreadID, T value)
{
RecordReturnToGlobalPool(thisThreadID);
return globalPool.Return(value);
}
public T Take()
{
int thisThreadID = Thread.CurrentThread.ManagedThreadId;
if (thisThreadID == 0)
{
return null;
}
T value = TakeFromPerThreadPool(thisThreadID);
if (value != null)
{
return value;
}
return TakeFromGlobalPool(thisThreadID);
}
T TakeFromPerThreadPool(int thisThreadID)
{
Entry[] entriesReference = this.entries;
for (int i = 0; i < entriesReference.Length; i++)
{
int threadID = entriesReference[i].threadID;
if (threadID == thisThreadID)
{
T value = entriesReference[i].value;
if (value != null)
{
entriesReference[i].value = null;
return value;
}
else
{
return null;
}
}
else if (threadID == 0)
{
break;
}
}
return null;
}
T TakeFromGlobalPool(int thisThreadID)
{
RecordTakeFromGlobalPool(thisThreadID);
return globalPool.Take();
}
struct Entry
{
public int threadID;
public T value;
}
struct PendingEntry
{
public int returnCount;
public int threadID;
}
static class SynchronizedPoolHelper
{
public static readonly int ProcessorCount = GetProcessorCount();
[Fx.Tag.SecurityNote(Critical = "Asserts in order to get the processor count from the environment", Safe = "This data isn't actually protected so it's ok to leak")]
[EnvironmentPermission(SecurityAction.Assert, Read = "NUMBER_OF_PROCESSORS")]
static int GetProcessorCount()
{
return Environment.ProcessorCount;
}
}
[Fx.Tag.SynchronizationObject(Blocking = false)]
class GlobalPool
{
Stack<T> items;
int maxCount;
public GlobalPool(int maxCount)
{
this.items = new Stack<T>();
this.maxCount = maxCount;
}
public int MaxCount
{
get
{
return maxCount;
}
set
{
lock (ThisLock)
{
while (items.Count > value)
{
items.Pop();
}
maxCount = value;
}
}
}
object ThisLock
{
get
{
return this;
}
}
public void DecrementMaxCount()
{
lock (ThisLock)
{
if (items.Count == maxCount)
{
items.Pop();
}
maxCount--;
}
}
public T Take()
{
if (this.items.Count > 0)
{
lock (ThisLock)
{
if (this.items.Count > 0)
{
return this.items.Pop();
}
}
}
return null;
}
public bool Return(T value)
{
if (this.items.Count < this.MaxCount)
{
lock (ThisLock)
{
if (this.items.Count < this.MaxCount)
{
this.items.Push(value);
return true;
}
}
}
return false;
}
public void Clear()
{
lock (ThisLock)
{
this.items.Clear();
}
}
}
}
}
| |
/*-------------------------------------------------------------------------
Tab.cs -- Symbol Table Management
Compiler Generator Coco/R,
Copyright (c) 1990, 2004 Hanspeter Moessenboeck, University of Linz
extended by M. Loeberbauer & A. Woess, Univ. of Linz
with improvements by Pat Terry, Rhodes University
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, 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.
As an exception, it is allowed to write an extension of Coco/R that is
used as a plugin in non-free software.
If not otherwise stated, any source code generated by Coco/R (other than
Coco/R itself) does not fall under the GNU General Public License.
-------------------------------------------------------------------------*/
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
namespace at.jku.ssw.Coco {
public class Position { // position of source code stretch (e.g. semantic action, resolver expressions)
public int beg; // start relative to the beginning of the file
public int len; // length of stretch
public int col; // column number of start position
public string virtualFile;
public int virtualLine;
public Position(int beg, int len, int col, string file, int line) {
this.beg = beg; this.len = len; this.col = col; this.virtualFile = file; this.virtualLine = line;
}
}
//=====================================================================
// Symbol
//=====================================================================
public class Symbol : IComparable {
// token kinds
public const int fixedToken = 0; // e.g. 'a' ('b' | 'c') (structure of literals)
public const int classToken = 1; // e.g. digit {digit} (at least one char class)
public const int litToken = 2; // e.g. "while"
public const int classLitToken = 3; // e.g. letter {letter} but without literals that have the same structure
public int n; // symbol number
public int typ; // t, nt, pr, unknown, rslv /* ML 29_11_2002 slv added */ /* AW slv --> rslv */
public string name; // symbol name
public Node graph; // nt: to first node of syntax graph
public int tokenKind; // t: token kind (fixedToken, classToken, ...)
public bool deletable; // nt: true if nonterminal is deletable
public bool firstReady; // nt: true if terminal start symbols have already been computed
public BitArray first; // nt: terminal start symbols
public BitArray follow; // nt: terminal followers
public BitArray nts; // nt: nonterminals whose followers have to be added to this sym
public int line; // source text line number of item in this node
public Position attrPos; // nt: position of attributes in source text (or null)
public Position semPos; // pr: pos of semantic action in source text (or null)
// nt: pos of local declarations in source text (or null)
public Symbol(int typ, string name, int line) {
this.typ = typ; this.name = name; this.line = line;
}
public int CompareTo(object x) {
return name.CompareTo(((Symbol)x).name);
}
}
//=====================================================================
// Node
//=====================================================================
public class Node {
// constants for node kinds
public const int t = 1; // terminal symbol
public const int pr = 2; // pragma
public const int nt = 3; // nonterminal symbol
public const int clas = 4; // character class
public const int chr = 5; // character
public const int wt = 6; // weak terminal symbol
public const int any = 7; //
public const int eps = 8; // empty
public const int sync = 9; // synchronization symbol
public const int sem = 10; // semantic action: (. .)
public const int alt = 11; // alternative: |
public const int iter = 12; // iteration: { }
public const int opt = 13; // option: [ ]
public const int rslv = 14; // resolver expr
public const int normalTrans = 0; // transition codes
public const int contextTrans = 1;
public int n; // node number
public int typ; // t, nt, wt, chr, clas, any, eps, sem, sync, alt, iter, opt, rslv
public Node next; // to successor node
public Node down; // alt: to next alternative
public Node sub; // alt, iter, opt: to first node of substructure
public bool up; // true: "next" leads to successor in enclosing structure
public Symbol sym; // nt, t, wt: symbol represented by this node
public int val; // chr: ordinal character value
// clas: index of character class
public int code; // chr, clas: transition code
public BitArray set; // any, sync: the set represented by this node
public Position pos; // nt, t, wt: pos of actual attributes
// sem: pos of semantic action in source text
public int line; // source text line number of item in this node
public State state; // DFA state corresponding to this node
// (only used in DFA.ConvertToStates)
public Node(int typ, Symbol sym, int line) {
this.typ = typ; this.sym = sym; this.line = line;
}
}
//=====================================================================
// Graph
//=====================================================================
public class Graph {
public Node l; // left end of graph = head
public Node r; // right end of graph = list of nodes to be linked to successor graph
public Graph() {
l = null; r = null;
}
public Graph(Node left, Node right) {
l = left; r = right;
}
public Graph(Node p) {
l = p; r = p;
}
}
//=====================================================================
// Sets
//=====================================================================
public class Sets {
public static int Elements(BitArray s) {
int max = s.Count;
int n = 0;
for (int i=0; i<max; i++)
if (s[i]) n++;
return n;
}
public static bool Equals(BitArray a, BitArray b) {
int max = a.Count;
for (int i=0; i<max; i++)
if (a[i] != b[i]) return false;
return true;
}
public static bool Intersect(BitArray a, BitArray b) { // a * b != {}
int max = a.Count;
for (int i=0; i<max; i++)
if (a[i] && b[i]) return true;
return false;
}
public static void Subtract(BitArray a, BitArray b) { // a = a - b
BitArray c = (BitArray) b.Clone();
a.And(c.Not());
}
}
//=====================================================================
// CharClass
//=====================================================================
public class CharClass {
public int n; // class number
public string name; // class name
public CharSet set; // set representing the class
public CharClass(string name, CharSet s) {
this.name = name; this.set = s;
}
}
//=====================================================================
// Tab
//=====================================================================
public class Tab {
public List<Position> semDeclPositions = new List<Position>(); // positions of global semantic declarations
public CharSet ignored; // characters ignored by the scanner
public bool[] ddt = new bool[10]; // debug and test switches
public Symbol gramSy; // root nonterminal; filled by ATG
public Symbol eofSy; // end of file symbol
public Symbol noSym; // used in case of an error
public BitArray allSyncSets; // union of all synchronisation sets
public Hashtable literals; // symbols that are used as literals
public string srcName; // name of the atg file (including path)
public string srcDir; // directory path of the atg file
public string nsName; // namespace for generated files
public string frameDir; // directory containing the frame files
BitArray visited; // mark list for graph traversals
Symbol curSy; // current symbol in computation of sets
Parser parser; // other Coco objects
TextWriter trace;
Errors errors;
public Tab(Parser parser) {
this.parser = parser;
trace = parser.trace;
errors = parser.errors;
eofSy = NewSym(Node.t, "EOF", 0);
dummyNode = NewNode(Node.eps, null, 0);
literals = new Hashtable();
}
//---------------------------------------------------------------------
// Symbol list management
//---------------------------------------------------------------------
public ArrayList terminals = new ArrayList();
public ArrayList pragmas = new ArrayList();
public ArrayList nonterminals = new ArrayList();
string[] tKind = {"fixedToken", "classToken", "litToken", "classLitToken"};
public Symbol NewSym(int typ, string name, int line) {
if (name.Length == 2 && name[0] == '"') {
parser.SemErr("empty token not allowed"); name = "???";
}
Symbol sym = new Symbol(typ, name, line);
switch (typ) {
case Node.t: sym.n = terminals.Count; terminals.Add(sym); break;
case Node.pr: pragmas.Add(sym); break;
case Node.nt: sym.n = nonterminals.Count; nonterminals.Add(sym); break;
}
return sym;
}
public Symbol FindSym(string name) {
foreach (Symbol s in terminals)
if (s.name == name) return s;
foreach (Symbol s in nonterminals)
if (s.name == name) return s;
return null;
}
int Num(Node p) {
if (p == null) return 0; else return p.n;
}
void PrintSym(Symbol sym) {
trace.Write("{0,3} {1,-14} {2}", sym.n, Name(sym.name), nTyp[sym.typ]);
if (sym.attrPos==null) trace.Write(" false "); else trace.Write(" true ");
if (sym.typ == Node.nt) {
trace.Write("{0,5}", Num(sym.graph));
if (sym.deletable) trace.Write(" true "); else trace.Write(" false ");
} else
trace.Write(" ");
trace.WriteLine("{0,5} {1}", sym.line, tKind[sym.tokenKind]);
}
public void PrintSymbolTable() {
trace.WriteLine("Symbol Table:");
trace.WriteLine("------------"); trace.WriteLine();
trace.WriteLine(" nr name typ hasAt graph del line tokenKind");
foreach (Symbol sym in terminals) PrintSym(sym);
foreach (Symbol sym in pragmas) PrintSym(sym);
foreach (Symbol sym in nonterminals) PrintSym(sym);
trace.WriteLine();
trace.WriteLine("Literal Tokens:");
trace.WriteLine("--------------");
foreach (DictionaryEntry e in literals) {
trace.WriteLine("_" + ((Symbol)e.Value).name + " = " + e.Key + ".");
}
trace.WriteLine();
}
public void PrintSet(BitArray s, int indent) {
int col, len;
col = indent;
foreach (Symbol sym in terminals) {
if (s[sym.n]) {
len = sym.name.Length;
if (col + len >= 80) {
trace.WriteLine();
for (col = 1; col < indent; col++) trace.Write(" ");
}
trace.Write("{0} ", sym.name);
col += len + 1;
}
}
if (col == indent) trace.Write("-- empty set --");
trace.WriteLine();
}
//---------------------------------------------------------------------
// Syntax graph management
//---------------------------------------------------------------------
public ArrayList nodes = new ArrayList();
public string[] nTyp =
{" ", "t ", "pr ", "nt ", "clas", "chr ", "wt ", "any ", "eps ",
"sync", "sem ", "alt ", "iter", "opt ", "rslv"};
Node dummyNode;
public Node NewNode(int typ, Symbol sym, int line) {
Node node = new Node(typ, sym, line);
node.n = nodes.Count;
nodes.Add(node);
return node;
}
public Node NewNode(int typ, Node sub) {
Node node = NewNode(typ, null, 0);
node.sub = sub;
return node;
}
public Node NewNode(int typ, int val, int line) {
Node node = NewNode(typ, null, line);
node.val = val;
return node;
}
public void MakeFirstAlt(Graph g) {
g.l = NewNode(Node.alt, g.l); g.l.line = g.l.sub.line;
g.l.next = g.r;
g.r = g.l;
}
public void MakeAlternative(Graph g1, Graph g2) {
g2.l = NewNode(Node.alt, g2.l); g2.l.line = g2.l.sub.line;
Node p = g1.l; while (p.down != null) p = p.down;
p.down = g2.l;
p = g1.r; while (p.next != null) p = p.next;
p.next = g2.r;
}
public void MakeSequence(Graph g1, Graph g2) {
Node p = g1.r.next; g1.r.next = g2.l; // link head node
while (p != null) { // link substructure
Node q = p.next; p.next = g2.l; p.up = true;
p = q;
}
g1.r = g2.r;
}
public void MakeIteration(Graph g) {
g.l = NewNode(Node.iter, g.l);
Node p = g.r;
g.r = g.l;
while (p != null) {
Node q = p.next; p.next = g.l; p.up = true;
p = q;
}
}
public void MakeOption(Graph g) {
g.l = NewNode(Node.opt, g.l);
g.l.next = g.r;
g.r = g.l;
}
public void Finish(Graph g) {
Node p = g.r;
while (p != null) {
Node q = p.next; p.next = null; p = q;
}
}
public void DeleteNodes() {
nodes = new ArrayList();
dummyNode = NewNode(Node.eps, null, 0);
}
public Graph StrToGraph(string str) {
string s = Unescape(str.Substring(1, str.Length-2));
if (s.Length == 0) parser.SemErr("empty token not allowed");
Graph g = new Graph();
g.r = dummyNode;
for (int i = 0; i < s.Length; i++) {
Node p = NewNode(Node.chr, (int)s[i], 0);
g.r.next = p; g.r = p;
}
g.l = dummyNode.next; dummyNode.next = null;
return g;
}
public void SetContextTrans(Node p) { // set transition code in the graph rooted at p
while (p != null) {
if (p.typ == Node.chr || p.typ == Node.clas) {
p.code = Node.contextTrans;
} else if (p.typ == Node.opt || p.typ == Node.iter) {
SetContextTrans(p.sub);
} else if (p.typ == Node.alt) {
SetContextTrans(p.sub); SetContextTrans(p.down);
}
if (p.up) break;
p = p.next;
}
}
//------------ graph deletability check -----------------
public bool DelGraph(Node p) {
return p == null || DelNode(p) && DelGraph(p.next);
}
public bool DelSubGraph(Node p) {
return p == null || DelNode(p) && (p.up || DelSubGraph(p.next));
}
public bool DelAlt(Node p) {
return p == null || DelNode(p) && (p.up || DelAlt(p.next));
}
public bool DelNode(Node p) {
if (p.typ == Node.nt) return p.sym.deletable;
else if (p.typ == Node.alt) return DelAlt(p.sub) || p.down != null && DelAlt(p.down);
else return p.typ == Node.iter || p.typ == Node.opt || p.typ == Node.sem
|| p.typ == Node.eps || p.typ == Node.rslv || p.typ == Node.sync;
}
//----------------- graph printing ----------------------
int Ptr(Node p, bool up) {
if (p == null) return 0;
else if (up) return -p.n;
else return p.n;
}
string Pos(Position pos) {
if (pos == null) return " "; else return String.Format("{0,5}", pos.beg);
}
public string Name(string name) {
return (name + " ").Substring(0, 12);
// found no simpler way to get the first 12 characters of the name
// padded with blanks on the right
}
public void PrintNodes() {
trace.WriteLine("Graph nodes:");
trace.WriteLine("----------------------------------------------------");
trace.WriteLine(" n type name next down sub pos line");
trace.WriteLine(" val code");
trace.WriteLine("----------------------------------------------------");
foreach (Node p in nodes) {
trace.Write("{0,4} {1} ", p.n, nTyp[p.typ]);
if (p.sym != null)
trace.Write("{0,12} ", Name(p.sym.name));
else if (p.typ == Node.clas) {
CharClass c = (CharClass)classes[p.val];
trace.Write("{0,12} ", Name(c.name));
} else trace.Write(" ");
trace.Write("{0,5} ", Ptr(p.next, p.up));
switch (p.typ) {
case Node.t: case Node.nt: case Node.wt:
trace.Write(" {0,5}", Pos(p.pos)); break;
case Node.chr:
trace.Write("{0,5} {1,5} ", p.val, p.code); break;
case Node.clas:
trace.Write(" {0,5} ", p.code); break;
case Node.alt: case Node.iter: case Node.opt:
trace.Write("{0,5} {1,5} ", Ptr(p.down, false), Ptr(p.sub, false)); break;
case Node.sem:
trace.Write(" {0,5}", Pos(p.pos)); break;
case Node.eps: case Node.any: case Node.sync:
trace.Write(" "); break;
}
trace.WriteLine("{0,5}", p.line);
}
trace.WriteLine();
}
//---------------------------------------------------------------------
// Character class management
//---------------------------------------------------------------------
public ArrayList classes = new ArrayList();
public int dummyName = 'A';
public CharClass NewCharClass(string name, CharSet s) {
if (name == "#") name = "#" + (char)dummyName++;
CharClass c = new CharClass(name, s);
c.n = classes.Count;
classes.Add(c);
return c;
}
public CharClass FindCharClass(string name) {
foreach (CharClass c in classes)
if (c.name == name) return c;
return null;
}
public CharClass FindCharClass(CharSet s) {
foreach (CharClass c in classes)
if (s.Equals(c.set)) return c;
return null;
}
public CharSet CharClassSet(int i) {
return ((CharClass)classes[i]).set;
}
//----------- character class printing
string Ch(int ch) {
if (ch < ' ' || ch >= 127 || ch == '\'' || ch == '\\') return ch.ToString();
else return String.Format("'{0}'", (char)ch);
}
void WriteCharSet(CharSet s) {
for (CharSet.Range r = s.head; r != null; r = r.next)
if (r.from < r.to) { trace.Write(Ch(r.from) + ".." + Ch(r.to) + " "); }
else { trace.Write(Ch(r.from) + " "); }
}
public void WriteCharClasses () {
foreach (CharClass c in classes) {
trace.Write("{0,-10}: ", c.name);
WriteCharSet(c.set);
trace.WriteLine();
}
trace.WriteLine();
}
//---------------------------------------------------------------------
// Symbol set computations
//---------------------------------------------------------------------
/* Computes the first set for the graph rooted at p */
BitArray First0(Node p, BitArray mark) {
BitArray fs = new BitArray(terminals.Count);
while (p != null && !mark[p.n]) {
mark[p.n] = true;
switch (p.typ) {
case Node.nt: {
if (p.sym.firstReady) fs.Or(p.sym.first);
else fs.Or(First0(p.sym.graph, mark));
break;
}
case Node.t: case Node.wt: {
fs[p.sym.n] = true; break;
}
case Node.any: {
fs.Or(p.set); break;
}
case Node.alt: {
fs.Or(First0(p.sub, mark));
fs.Or(First0(p.down, mark));
break;
}
case Node.iter: case Node.opt: {
fs.Or(First0(p.sub, mark));
break;
}
}
if (!DelNode(p)) break;
p = p.next;
}
return fs;
}
public BitArray First(Node p) {
BitArray fs = First0(p, new BitArray(nodes.Count));
if (ddt[3]) {
trace.WriteLine();
if (p != null) trace.WriteLine("First: node = {0}", p.n);
else trace.WriteLine("First: node = null");
PrintSet(fs, 0);
}
return fs;
}
void CompFirstSets() {
foreach (Symbol sym in nonterminals) {
sym.first = new BitArray(terminals.Count);
sym.firstReady = false;
}
foreach (Symbol sym in nonterminals) {
sym.first = First(sym.graph);
sym.firstReady = true;
}
}
void CompFollow(Node p) {
while (p != null && !visited[p.n]) {
visited[p.n] = true;
if (p.typ == Node.nt) {
BitArray s = First(p.next);
p.sym.follow.Or(s);
if (DelGraph(p.next))
p.sym.nts[curSy.n] = true;
} else if (p.typ == Node.opt || p.typ == Node.iter) {
CompFollow(p.sub);
} else if (p.typ == Node.alt) {
CompFollow(p.sub); CompFollow(p.down);
}
p = p.next;
}
}
void Complete(Symbol sym) {
if (!visited[sym.n]) {
visited[sym.n] = true;
foreach (Symbol s in nonterminals) {
if (sym.nts[s.n]) {
Complete(s);
sym.follow.Or(s.follow);
if (sym == curSy) sym.nts[s.n] = false;
}
}
}
}
void CompFollowSets() {
foreach (Symbol sym in nonterminals) {
sym.follow = new BitArray(terminals.Count);
sym.nts = new BitArray(nonterminals.Count);
}
gramSy.follow[eofSy.n] = true;
visited = new BitArray(nodes.Count);
foreach (Symbol sym in nonterminals) { // get direct successors of nonterminals
curSy = sym;
CompFollow(sym.graph);
}
foreach (Symbol sym in nonterminals) { // add indirect successors to followers
visited = new BitArray(nonterminals.Count);
curSy = sym;
Complete(sym);
}
}
Node LeadingAny(Node p) {
if (p == null) return null;
Node a = null;
if (p.typ == Node.any) a = p;
else if (p.typ == Node.alt) {
a = LeadingAny(p.sub);
if (a == null) a = LeadingAny(p.down);
}
else if (p.typ == Node.opt || p.typ == Node.iter) a = LeadingAny(p.sub);
else if (DelNode(p) && !p.up) a = LeadingAny(p.next);
return a;
}
void FindAS(Node p) { // find ANY sets
Node a;
while (p != null) {
if (p.typ == Node.opt || p.typ == Node.iter) {
FindAS(p.sub);
a = LeadingAny(p.sub);
if (a != null) Sets.Subtract(a.set, First(p.next));
} else if (p.typ == Node.alt) {
BitArray s1 = new BitArray(terminals.Count);
Node q = p;
while (q != null) {
FindAS(q.sub);
a = LeadingAny(q.sub);
if (a != null)
Sets.Subtract(a.set, First(q.down).Or(s1));
else
s1.Or(First(q.sub));
q = q.down;
}
}
if (p.up) break;
p = p.next;
}
}
void CompAnySets() {
foreach (Symbol sym in nonterminals) FindAS(sym.graph);
}
public BitArray Expected(Node p, Symbol curSy) {
BitArray s = First(p);
if (DelGraph(p)) s.Or(curSy.follow);
return s;
}
// does not look behind resolvers; only called during LL(1) test and in CheckRes
public BitArray Expected0(Node p, Symbol curSy) {
if (p.typ == Node.rslv) return new BitArray(terminals.Count);
else return Expected(p, curSy);
}
void CompSync(Node p) {
while (p != null && !visited[p.n]) {
visited[p.n] = true;
if (p.typ == Node.sync) {
BitArray s = Expected(p.next, curSy);
s[eofSy.n] = true;
allSyncSets.Or(s);
p.set = s;
} else if (p.typ == Node.alt) {
CompSync(p.sub); CompSync(p.down);
} else if (p.typ == Node.opt || p.typ == Node.iter)
CompSync(p.sub);
p = p.next;
}
}
void CompSyncSets() {
allSyncSets = new BitArray(terminals.Count);
allSyncSets[eofSy.n] = true;
visited = new BitArray(nodes.Count);
foreach (Symbol sym in nonterminals) {
curSy = sym;
CompSync(curSy.graph);
}
}
public void SetupAnys() {
foreach (Node p in nodes)
if (p.typ == Node.any) {
p.set = new BitArray(terminals.Count, true);
p.set[eofSy.n] = false;
}
}
public void CompDeletableSymbols() {
bool changed;
do {
changed = false;
foreach (Symbol sym in nonterminals)
if (!sym.deletable && sym.graph != null && DelGraph(sym.graph)) {
sym.deletable = true; changed = true;
}
} while (changed);
foreach (Symbol sym in nonterminals)
if (sym.deletable) errors.Warning(" " + sym.name + " deletable");
}
public void RenumberPragmas() {
int n = terminals.Count;
foreach (Symbol sym in pragmas) sym.n = n++;
}
public void CompSymbolSets() {
CompDeletableSymbols();
CompFirstSets();
CompFollowSets();
CompAnySets();
CompSyncSets();
if (ddt[1]) {
trace.WriteLine();
trace.WriteLine("First & follow symbols:");
trace.WriteLine("----------------------"); trace.WriteLine();
foreach (Symbol sym in nonterminals) {
trace.WriteLine(sym.name);
trace.Write("first: "); PrintSet(sym.first, 10);
trace.Write("follow: "); PrintSet(sym.follow, 10);
trace.WriteLine();
}
}
if (ddt[4]) {
trace.WriteLine();
trace.WriteLine("ANY and SYNC sets:");
trace.WriteLine("-----------------");
foreach (Node p in nodes)
if (p.typ == Node.any || p.typ == Node.sync) {
trace.Write("{0,4} {1,4}: ", p.n, nTyp[p.typ]);
PrintSet(p.set, 11);
}
}
}
//---------------------------------------------------------------------
// String handling
//---------------------------------------------------------------------
char Hex2Char(string s) {
int val = 0;
for (int i = 0; i < s.Length; i++) {
char ch = s[i];
if ('0' <= ch && ch <= '9') val = 16 * val + (ch - '0');
else if ('a' <= ch && ch <= 'f') val = 16 * val + (10 + ch - 'a');
else if ('A' <= ch && ch <= 'F') val = 16 * val + (10 + ch - 'A');
else parser.SemErr("bad escape sequence in string or character");
}
if (val > char.MaxValue) /* pdt */
parser.SemErr("bad escape sequence in string or character");
return (char)val;
}
string Char2Hex(char ch) {
StringWriter w = new StringWriter();
w.Write("\\u{0:x4}", (int)ch);
return w.ToString();
}
public string Unescape (string s) {
/* replaces escape sequences in s by their Unicode values. */
StringBuilder buf = new StringBuilder();
int i = 0;
while (i < s.Length) {
if (s[i] == '\\') {
switch (s[i+1]) {
case '\\': buf.Append('\\'); i += 2; break;
case '\'': buf.Append('\''); i += 2; break;
case '\"': buf.Append('\"'); i += 2; break;
case 'r': buf.Append('\r'); i += 2; break;
case 'n': buf.Append('\n'); i += 2; break;
case 't': buf.Append('\t'); i += 2; break;
case '0': buf.Append('\0'); i += 2; break;
case 'a': buf.Append('\a'); i += 2; break;
case 'b': buf.Append('\b'); i += 2; break;
case 'f': buf.Append('\f'); i += 2; break;
case 'v': buf.Append('\v'); i += 2; break;
case 'u': case 'x':
if (i + 6 <= s.Length) {
buf.Append(Hex2Char(s.Substring(i+2, 4))); i += 6; break;
} else {
parser.SemErr("bad escape sequence in string or character"); i = s.Length; break;
}
default: parser.SemErr("bad escape sequence in string or character"); i += 2; break;
}
} else {
buf.Append(s[i]);
i++;
}
}
return buf.ToString();
}
public string Escape (string s) {
StringBuilder buf = new StringBuilder();
foreach (char ch in s) {
switch(ch) {
case '\\': buf.Append("\\\\"); break;
case '\'': buf.Append("\\'"); break;
case '\"': buf.Append("\\\""); break;
case '\t': buf.Append("\\t"); break;
case '\r': buf.Append("\\r"); break;
case '\n': buf.Append("\\n"); break;
default:
if (ch < ' ' || ch > '\u007f') buf.Append(Char2Hex(ch));
else buf.Append(ch);
break;
}
}
return buf.ToString();
}
//---------------------------------------------------------------------
// Grammar checks
//---------------------------------------------------------------------
public bool GrammarOk() {
bool ok = NtsComplete()
&& AllNtReached()
&& NoCircularProductions()
&& AllNtToTerm();
if (ok) { CheckResolvers(); CheckLL1(); }
return ok;
}
//--------------- check for circular productions ----------------------
class CNode { // node of list for finding circular productions
public Symbol left, right;
public CNode (Symbol l, Symbol r) {
left = l; right = r;
}
}
void GetSingles(Node p, ArrayList singles) {
if (p == null) return; // end of graph
if (p.typ == Node.nt) {
if (p.up || DelGraph(p.next)) singles.Add(p.sym);
} else if (p.typ == Node.alt || p.typ == Node.iter || p.typ == Node.opt) {
if (p.up || DelGraph(p.next)) {
GetSingles(p.sub, singles);
if (p.typ == Node.alt) GetSingles(p.down, singles);
}
}
if (!p.up && DelNode(p)) GetSingles(p.next, singles);
}
public bool NoCircularProductions() {
bool ok, changed, onLeftSide, onRightSide;
ArrayList list = new ArrayList();
foreach (Symbol sym in nonterminals) {
ArrayList singles = new ArrayList();
GetSingles(sym.graph, singles); // get nonterminals s such that sym-->s
foreach (Symbol s in singles) list.Add(new CNode(sym, s));
}
do {
changed = false;
for (int i = 0; i < list.Count; i++) {
CNode n = (CNode)list[i];
onLeftSide = false; onRightSide = false;
foreach (CNode m in list) {
if (n.left == m.right) onRightSide = true;
if (n.right == m.left) onLeftSide = true;
}
if (!onLeftSide || !onRightSide) {
list.Remove(n); i--; changed = true;
}
}
} while(changed);
ok = true;
foreach (CNode n in list) {
ok = false;
errors.SemErr(" " + n.left.name + " --> " + n.right.name);
}
return ok;
}
//--------------- check for LL(1) errors ----------------------
void LL1Error(int cond, Symbol sym) {
string s = " LL1 warning in " + curSy.name + ": ";
if (sym != null) s += sym.name + " is ";
switch (cond) {
case 1: s += "start of several alternatives"; break;
case 2: s += "start & successor of deletable structure"; break;
case 3: s += "an ANY node that matches no symbol"; break;
case 4: s += "contents of [...] or {...} must not be deletable"; break;
}
errors.Warning(s);
}
void CheckOverlap(BitArray s1, BitArray s2, int cond) {
foreach (Symbol sym in terminals) {
if (s1[sym.n] && s2[sym.n]) LL1Error(cond, sym);
}
}
void CheckAlts(Node p) {
BitArray s1, s2;
while (p != null) {
if (p.typ == Node.alt) {
Node q = p;
s1 = new BitArray(terminals.Count);
while (q != null) { // for all alternatives
s2 = Expected0(q.sub, curSy);
CheckOverlap(s1, s2, 1);
s1.Or(s2);
CheckAlts(q.sub);
q = q.down;
}
} else if (p.typ == Node.opt || p.typ == Node.iter) {
if (DelSubGraph(p.sub)) LL1Error(4, null); // e.g. [[...]]
else {
s1 = Expected0(p.sub, curSy);
s2 = Expected(p.next, curSy);
CheckOverlap(s1, s2, 2);
}
CheckAlts(p.sub);
} else if (p.typ == Node.any) {
if (Sets.Elements(p.set) == 0) LL1Error(3, null);
// e.g. {ANY} ANY or [ANY] ANY
}
if (p.up) break;
p = p.next;
}
}
public void CheckLL1() {
foreach (Symbol sym in nonterminals) {
curSy = sym;
CheckAlts(curSy.graph);
}
}
//------------- check if resolvers are legal --------------------
void ResErr(Node p, string msg) {
errors.Warning(p.line, p.pos.col, msg);
}
void CheckRes(Node p, bool rslvAllowed) {
while (p != null) {
switch (p.typ) {
case Node.alt:
BitArray expected = new BitArray(terminals.Count);
for (Node q = p; q != null; q = q.down)
expected.Or(Expected0(q.sub, curSy));
BitArray soFar = new BitArray(terminals.Count);
for (Node q = p; q != null; q = q.down) {
if (q.sub.typ == Node.rslv) {
BitArray fs = Expected(q.sub.next, curSy);
if (Sets.Intersect(fs, soFar))
ResErr(q.sub, "Warning: Resolver will never be evaluated. " +
"Place it at previous conflicting alternative.");
if (!Sets.Intersect(fs, expected))
ResErr(q.sub, "Warning: Misplaced resolver: no LL(1) conflict.");
} else soFar.Or(Expected(q.sub, curSy));
CheckRes(q.sub, true);
}
break;
case Node.iter: case Node.opt:
if (p.sub.typ == Node.rslv) {
BitArray fs = First(p.sub.next);
BitArray fsNext = Expected(p.next, curSy);
if (!Sets.Intersect(fs, fsNext))
ResErr(p.sub, "Warning: Misplaced resolver: no LL(1) conflict.");
}
CheckRes(p.sub, true);
break;
case Node.rslv:
if (!rslvAllowed)
ResErr(p, "Warning: Misplaced resolver: no alternative.");
break;
}
if (p.up) break;
p = p.next;
rslvAllowed = false;
}
}
public void CheckResolvers() {
foreach (Symbol sym in nonterminals) {
curSy = sym;
CheckRes(curSy.graph, false);
}
}
//------------- check if every nts has a production --------------------
public bool NtsComplete() {
bool complete = true;
foreach (Symbol sym in nonterminals) {
if (sym.graph == null) {
complete = false;
errors.SemErr(" No production for " + sym.name);
}
}
return complete;
}
//-------------- check if every nts can be reached -----------------
void MarkReachedNts(Node p) {
while (p != null) {
if (p.typ == Node.nt && !visited[p.sym.n]) { // new nt reached
visited[p.sym.n] = true;
MarkReachedNts(p.sym.graph);
} else if (p.typ == Node.alt || p.typ == Node.iter || p.typ == Node.opt) {
MarkReachedNts(p.sub);
if (p.typ == Node.alt) MarkReachedNts(p.down);
}
if (p.up) break;
p = p.next;
}
}
public bool AllNtReached() {
bool ok = true;
visited = new BitArray(nonterminals.Count);
visited[gramSy.n] = true;
MarkReachedNts(gramSy.graph);
foreach (Symbol sym in nonterminals) {
if (!visited[sym.n]) {
ok = false;
errors.SemErr(" " + sym.name + " cannot be reached");
}
}
return ok;
}
//--------- check if every nts can be derived to terminals ------------
bool IsTerm(Node p, BitArray mark) { // true if graph can be derived to terminals
while (p != null) {
if (p.typ == Node.nt && !mark[p.sym.n]) return false;
if (p.typ == Node.alt && !IsTerm(p.sub, mark)
&& (p.down == null || !IsTerm(p.down, mark))) return false;
if (p.up) break;
p = p.next;
}
return true;
}
public bool AllNtToTerm() {
bool changed, ok = true;
BitArray mark = new BitArray(nonterminals.Count);
// a nonterminal is marked if it can be derived to terminal symbols
do {
changed = false;
foreach (Symbol sym in nonterminals)
if (!mark[sym.n] && IsTerm(sym.graph, mark)) {
mark[sym.n] = true; changed = true;
}
} while (changed);
foreach (Symbol sym in nonterminals)
if (!mark[sym.n]) {
ok = false;
errors.SemErr(" " + sym.name + " cannot be derived to terminals");
}
return ok;
}
//---------------------------------------------------------------------
// Cross reference list
//---------------------------------------------------------------------
public void XRef() {
SortedList xref = new SortedList();
// collect lines where symbols have been defined
foreach (Symbol sym in nonterminals) {
ArrayList list = (ArrayList)xref[sym];
if (list == null) {list = new ArrayList(); xref[sym] = list;}
list.Add(- sym.line);
}
// collect lines where symbols have been referenced
foreach (Node n in nodes) {
if (n.typ == Node.t || n.typ == Node.wt || n.typ == Node.nt) {
ArrayList list = (ArrayList)xref[n.sym];
if (list == null) {list = new ArrayList(); xref[n.sym] = list;}
list.Add(n.line);
}
}
// print cross reference list
trace.WriteLine();
trace.WriteLine("Cross reference list:");
trace.WriteLine("--------------------"); trace.WriteLine();
foreach (Symbol sym in xref.Keys) {
trace.Write(" {0,-12}", Name(sym.name));
ArrayList list = (ArrayList)xref[sym];
int col = 14;
foreach (int line in list) {
if (col + 5 > 80) {
trace.WriteLine();
for (col = 1; col <= 14; col++) trace.Write(" ");
}
trace.Write("{0,5}", line); col += 5;
}
trace.WriteLine();
}
trace.WriteLine(); trace.WriteLine();
}
public void SetDDT(string s) {
s = s.ToUpper();
foreach (char ch in s) {
if ('0' <= ch && ch <= '9') ddt[ch - '0'] = true;
else switch (ch) {
case 'A' : ddt[0] = true; break; // trace automaton
case 'F' : ddt[1] = true; break; // list first/follow sets
case 'G' : ddt[2] = true; break; // print syntax graph
case 'I' : ddt[3] = true; break; // trace computation of first sets
case 'J' : ddt[4] = true; break; // print ANY and SYNC sets
case 'P' : ddt[8] = true; break; // print statistics
case 'S' : ddt[6] = true; break; // list symbol table
case 'X' : ddt[7] = true; break; // list cross reference table
default : break;
}
}
}
} // end Tab
} // end namespace
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using Fixtures.Azure;
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>
/// HeaderOperations operations.
/// </summary>
internal partial class HeaderOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IHeaderOperations
{
/// <summary>
/// Initializes a new instance of the HeaderOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal HeaderOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the
/// header of the request
/// </summary>
/// <param name='fooClientRequestId'>
/// The fooRequestId
/// </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<AzureOperationHeaderResponse<HeaderCustomNamedRequestIdHeaders>> CustomNamedRequestIdWithHttpMessagesAsync(string fooClientRequestId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (fooClientRequestId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fooClientRequestId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fooClientRequestId", fooClientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CustomNamedRequestId", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/customNamedRequestId").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("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", System.Guid.NewGuid().ToString());
}
if (fooClientRequestId != null)
{
if (_httpRequest.Headers.Contains("foo-client-request-id"))
{
_httpRequest.Headers.Remove("foo-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", fooClientRequestId);
}
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 AzureOperationHeaderResponse<HeaderCustomNamedRequestIdHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("foo-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("foo-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HeaderCustomNamedRequestIdHeaders>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the
/// header of the request, via a parameter group
/// </summary>
/// <param name='headerCustomNamedRequestIdParamGroupingParameters'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="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<AzureOperationHeaderResponse<HeaderCustomNamedRequestIdParamGroupingHeaders>> CustomNamedRequestIdParamGroupingWithHttpMessagesAsync(HeaderCustomNamedRequestIdParamGroupingParameters headerCustomNamedRequestIdParamGroupingParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (headerCustomNamedRequestIdParamGroupingParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "headerCustomNamedRequestIdParamGroupingParameters");
}
if (headerCustomNamedRequestIdParamGroupingParameters != null)
{
headerCustomNamedRequestIdParamGroupingParameters.Validate();
}
string fooClientRequestId = default(string);
if (headerCustomNamedRequestIdParamGroupingParameters != null)
{
fooClientRequestId = headerCustomNamedRequestIdParamGroupingParameters.FooClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fooClientRequestId", fooClientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CustomNamedRequestIdParamGrouping", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/customNamedRequestIdParamGrouping").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("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("foo-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 (fooClientRequestId != null)
{
if (_httpRequest.Headers.Contains("foo-client-request-id"))
{
_httpRequest.Headers.Remove("foo-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", fooClientRequestId);
}
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 AzureOperationHeaderResponse<HeaderCustomNamedRequestIdParamGroupingHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("foo-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("foo-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HeaderCustomNamedRequestIdParamGroupingHeaders>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the
/// header of the request
/// </summary>
/// <param name='fooClientRequestId'>
/// The fooRequestId
/// </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<bool,HeaderCustomNamedRequestIdHeadHeaders>> CustomNamedRequestIdHeadWithHttpMessagesAsync(string fooClientRequestId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (fooClientRequestId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fooClientRequestId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fooClientRequestId", fooClientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CustomNamedRequestIdHead", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/customNamedRequestIdHead").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("HEAD");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", System.Guid.NewGuid().ToString());
}
if (fooClientRequestId != null)
{
if (_httpRequest.Headers.Contains("foo-client-request-id"))
{
_httpRequest.Headers.Remove("foo-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", fooClientRequestId);
}
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, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 404)
{
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<bool,HeaderCustomNamedRequestIdHeadHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
_result.Body = _statusCode == System.Net.HttpStatusCode.OK;
if (_httpResponse.Headers.Contains("foo-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("foo-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HeaderCustomNamedRequestIdHeadHeaders>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Text.Formatting;
using System.Text.RegularExpressions;
using System.Threading;
namespace ZeroLog.Appenders
{
internal class PrefixWriter
{
private const int _maxLength = 512;
private const string _dateFormat = "yyyy-MM-dd";
private readonly StringBuffer _stringBuffer = new StringBuffer(_maxLength);
private readonly byte[] _buffer = new byte[_maxLength * sizeof(char)];
private readonly char[] _strings;
private readonly Action<PrefixWriter, ILogEventHeader> _appendMethod;
public PrefixWriter(string pattern)
{
var parts = OptimizeParts(ParsePattern(pattern)).ToList();
_strings = BuildStrings(parts, out var stringMap);
_appendMethod = BuildAppendMethod(parts, stringMap);
}
private static IEnumerable<PatternPart> ParsePattern(string pattern)
{
var position = 0;
foreach (Match? match in Regex.Matches(pattern, @"%(?:(?<part>\w+)|\{\s*(?<part>\w+)\s*\})", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase))
{
if (position < match!.Index)
yield return new PatternPart(pattern.Substring(position, match.Index - position));
yield return match.Groups["part"].Value.ToLowerInvariant() switch
{
"date" => new PatternPart(PatternPartType.Date),
"time" => new PatternPart(PatternPartType.Time),
"thread" => new PatternPart(PatternPartType.Thread),
"level" => new PatternPart(PatternPartType.Level),
"logger" => new PatternPart(PatternPartType.Logger),
_ => new PatternPart(match.Value)
};
position = match.Index + match.Length;
}
if (position < pattern.Length)
yield return new PatternPart(pattern.Substring(position, pattern.Length - position));
}
private static IEnumerable<PatternPart> OptimizeParts(IEnumerable<PatternPart> parts)
{
var currentString = string.Empty;
foreach (var part in parts)
{
if (part.Type == PatternPartType.String)
{
currentString += part.Value;
}
else
{
if (currentString.Length != 0)
{
yield return new PatternPart(currentString);
currentString = string.Empty;
}
yield return part;
}
}
if (currentString.Length != 0)
yield return new PatternPart(currentString);
}
private static char[] BuildStrings(IEnumerable<PatternPart> parts, out Dictionary<string, (int offset, int length)> map)
{
var stringOffsets = new Dictionary<string, (int offset, int length)>();
var stringsBuilder = new StringBuilder();
foreach (var part in parts)
{
switch (part.Type)
{
case PatternPartType.String:
AddString(part.Value!);
break;
case PatternPartType.Date:
AddString(_dateFormat);
break;
}
}
void AddString(string value)
{
if (stringOffsets.ContainsKey(value))
return;
var offset = stringsBuilder.Length;
stringsBuilder.Append(value);
stringOffsets[value] = (offset, value.Length);
}
if (stringsBuilder.Length == 0)
AddString(" ");
var strings = new char[stringsBuilder.Length];
stringsBuilder.CopyTo(0, strings, 0, stringsBuilder.Length);
map = stringOffsets;
return strings;
}
private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollection<PatternPart> parts, Dictionary<string, (int offset, int length)> stringMap)
{
var method = new DynamicMethod("WritePrefix", typeof(void), new[] { typeof(PrefixWriter), typeof(ILogEventHeader) }, typeof(PrefixWriter), false)
{
InitLocals = false
};
var il = method.GetILGenerator();
var stringBufferLocal = il.DeclareLocal(typeof(StringBuffer));
var stringsLocal = il.DeclareLocal(typeof(char).MakeByRefType(), true);
var dateTimeLocal = default(LocalBuilder);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_stringBuffer), BindingFlags.Instance | BindingFlags.NonPublic)!);
il.Emit(OpCodes.Stloc, stringBufferLocal);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_strings), BindingFlags.Instance | BindingFlags.NonPublic)!);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ldelema, typeof(char));
il.Emit(OpCodes.Stloc, stringsLocal);
foreach (var part in parts)
{
switch (part.Type)
{
case PatternPartType.String:
{
// _stringBuffer.Append(&_strings[0] + offset * sizeof(char), length);
var (offset, length) = stringMap[part.Value!];
il.Emit(OpCodes.Ldloc, stringBufferLocal);
il.Emit(OpCodes.Ldloc, stringsLocal);
il.Emit(OpCodes.Conv_U);
il.Emit(OpCodes.Ldc_I4, offset * sizeof(char));
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ldc_I4, length);
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(char*), typeof(int) })!);
break;
}
case PatternPartType.Date:
{
// _stringBuffer.Append(logEventHeader.Timestamp, new StringView(&_strings[0] + offset * sizeof(char), length));
var (offset, length) = stringMap[_dateFormat];
il.Emit(OpCodes.Ldloc, stringBufferLocal);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);
il.Emit(OpCodes.Ldloc, stringsLocal);
il.Emit(OpCodes.Conv_U);
il.Emit(OpCodes.Ldc_I4, offset * sizeof(char));
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ldc_I4, length);
il.Emit(OpCodes.Newobj, typeof(StringView).GetConstructor(new[] { typeof(char*), typeof(int) })!);
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(DateTime), typeof(StringView) })!);
break;
}
case PatternPartType.Time:
{
// _stringBuffer.Append(logEventHeader.Timestamp.TimeOfDay, StringView.Empty);
il.Emit(OpCodes.Ldloc, stringBufferLocal);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);
il.Emit(OpCodes.Stloc, dateTimeLocal ??= il.DeclareLocal(typeof(DateTime)));
il.Emit(OpCodes.Ldloca, dateTimeLocal);
il.Emit(OpCodes.Call, typeof(DateTime).GetProperty(nameof(DateTime.TimeOfDay))?.GetGetMethod()!);
il.Emit(OpCodes.Ldsfld, typeof(StringView).GetField(nameof(StringView.Empty))!);
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(TimeSpan), typeof(StringView) })!);
break;
}
case PatternPartType.Thread:
{
// AppendThread(logEventHeader.Thread);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Thread))?.GetGetMethod()!);
il.Emit(OpCodes.Call, typeof(PrefixWriter).GetMethod(nameof(AppendThread), BindingFlags.Instance | BindingFlags.NonPublic)!);
break;
}
case PatternPartType.Level:
{
// _stringBuffer.Append(LevelStringCache.GetLevelString(logEventHeader.Level));
il.Emit(OpCodes.Ldloc, stringBufferLocal);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Level))?.GetGetMethod()!);
il.Emit(OpCodes.Call, typeof(LevelStringCache).GetMethod(nameof(LevelStringCache.GetLevelString))!);
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
break;
}
case PatternPartType.Logger:
{
// _stringBuffer.Append(logEventHeader.Name);
il.Emit(OpCodes.Ldloc, stringBufferLocal);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Name))?.GetGetMethod()!);
il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
break;
}
default:
throw new ArgumentOutOfRangeException();
}
}
il.Emit(OpCodes.Ret);
return (Action<PrefixWriter, ILogEventHeader>)method.CreateDelegate(typeof(Action<PrefixWriter, ILogEventHeader>));
}
public unsafe int WritePrefix(Stream stream, ILogEventHeader logEventHeader, Encoding encoding)
{
_stringBuffer.Clear();
_appendMethod(this, logEventHeader);
int bytesWritten;
fixed (byte* buf = &_buffer[0])
bytesWritten = _stringBuffer.CopyTo(buf, _buffer.Length, 0, _stringBuffer.Count, encoding);
stream.Write(_buffer, 0, bytesWritten);
return bytesWritten;
}
internal void AppendThread(Thread? thread)
{
if (thread != null)
{
if (thread.Name != null)
_stringBuffer.Append(thread.Name);
else
_stringBuffer.Append(thread.ManagedThreadId, StringView.Empty);
}
else
{
_stringBuffer.Append('0');
}
}
private enum PatternPartType
{
String,
Date,
Time,
Thread,
Level,
Logger
}
private readonly struct PatternPart
{
public PatternPartType Type { get; }
public string? Value { get; }
public PatternPart(PatternPartType type)
{
Type = type;
Value = null;
}
public PatternPart(string value)
{
Type = PatternPartType.String;
Value = value;
}
}
}
}
| |
// 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.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Web.Script.Serialization;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing.Ast;
using Microsoft.PythonTools.Projects;
namespace Microsoft.PythonTools.Django.Analysis {
[Export(typeof(IAnalysisExtension))]
[AnalysisExtensionName(Name)]
partial class DjangoAnalyzer : IDisposable, IAnalysisExtension {
internal const string Name = "django";
internal readonly Dictionary<string, TagInfo> _tags = new Dictionary<string, TagInfo>();
internal readonly Dictionary<string, TagInfo> _filters = new Dictionary<string, TagInfo>();
internal readonly IList<DjangoUrl> _urls = new List<DjangoUrl>();
private readonly HashSet<IPythonProjectEntry> _hookedEntries = new HashSet<IPythonProjectEntry>();
internal readonly Dictionary<string, TemplateVariables> _templateFiles = new Dictionary<string, TemplateVariables>(StringComparer.OrdinalIgnoreCase);
private ConditionalWeakTable<Node, ContextMarker> _contextTable = new ConditionalWeakTable<Node, ContextMarker>();
private ConditionalWeakTable<Node, DeferredDecorator> _decoratorTable = new ConditionalWeakTable<Node, DeferredDecorator>();
private readonly Dictionary<string, GetTemplateAnalysisValue> _templateAnalysis = new Dictionary<string, GetTemplateAnalysisValue>();
private PythonAnalyzer _analyzer;
internal static readonly Dictionary<string, string> _knownTags = MakeKnownTagsTable();
internal static readonly Dictionary<string, string> _knownFilters = MakeKnownFiltersTable();
public DjangoAnalyzer() {
foreach (var tagName in _nestedEndTags) {
_tags[tagName] = new TagInfo("", null);
}
}
internal static readonly Dictionary<string, string> _nestedTags = new Dictionary<string, string>() {
{ "for", "endfor" },
{ "if", "endif" },
{ "ifequal", "endifequal" },
{ "ifnotequal", "endifnotequal" },
{ "ifchanged", "endifchanged" },
{ "autoescape", "endautoescape" },
{ "comment", "endcomment" },
{ "filter", "endfilter" },
{ "spaceless", "endspaceless" },
{ "with", "endwith" },
{ "empty", "endfor" },
{ "else", "endif" },
};
internal static readonly HashSet<string> _nestedEndTags = MakeNestedEndTags();
internal static readonly HashSet<string> _nestedStartTags = MakeNestedStartTags();
internal static class Commands {
public const string GetTags = "getTags";
public const string GetVariables = "getVariables";
public const string GetFilters = "getFilters";
public const string GetUrls = "getUrls";
public const string GetMembers = "getMembers";
}
public string HandleCommand(string commandId, string body) {
var serializer = new JavaScriptSerializer();
Dictionary<string, HashSet<AnalysisValue>> variables;
switch (commandId) {
case Commands.GetTags:
return serializer.Serialize(_tags.Keys.ToArray());
case Commands.GetVariables:
variables = GetVariablesForTemplateFile(body);
if (variables != null) {
return serializer.Serialize(variables.Keys.ToArray());
}
return "[]";
case Commands.GetFilters:
Dictionary<string, string> res = new Dictionary<string, string>();
foreach (var filter in _filters) {
res[filter.Key] = filter.Value.Documentation;
}
return serializer.Serialize(res);
case Commands.GetUrls:
// GroupBy + Select have the same effect as Distinct with a long EqualityComparer
return serializer.Serialize(_urls.GroupBy(url => url.FullName).Select(urlGroup => urlGroup.First()));
case Commands.GetMembers:
string[] args = serializer.Deserialize<string[]>(body);
var file = args[0];
var varName = args[1];
variables = GetVariablesForTemplateFile(file);
HashSet<AnalysisValue> values;
IProjectEntry projEntry;
if (_analyzer.TryGetProjectEntryByPath(file, out projEntry)) {
var context = projEntry.AnalysisContext;
if (variables != null && variables.TryGetValue(varName, out values)) {
var newTags = new Dictionary<string, PythonMemberType>();
foreach (var member in values.SelectMany(item => item.GetAllMembers(context))) {
string name = member.Key;
PythonMemberType type, newType = GetMemberType(member.Value);
if (!newTags.TryGetValue(name, out type)) {
newTags[name] = newType;
} else if (type != newType && type != PythonMemberType.Unknown && newType != PythonMemberType.Unknown) {
newTags[name] = PythonMemberType.Multiple;
}
}
var dict = newTags.ToDictionary(x => x.Key, x => x.Value.ToString().ToLower());
return serializer.Serialize(dict);
}
}
return "{}";
default:
return String.Empty;
}
}
private static PythonMemberType GetMemberType(IAnalysisSet values) {
PythonMemberType newType = PythonMemberType.Unknown;
foreach (var value in values) {
if (value.MemberType == newType) {
continue;
} else if (newType == PythonMemberType.Unknown) {
newType = value.MemberType;
} else {
newType = PythonMemberType.Multiple;
break;
}
}
return newType;
}
public void Register(PythonAnalyzer analyzer) {
if (analyzer == null) {
throw new ArgumentNullException("analyzer");
}
_tags.Clear();
_filters.Clear();
_urls.Clear();
foreach (var entry in _hookedEntries) {
entry.OnNewParseTree -= OnNewParseTree;
}
_hookedEntries.Clear();
_templateAnalysis.Clear();
_templateFiles.Clear();
_contextTable = new ConditionalWeakTable<Node, ContextMarker>();
_decoratorTable = new ConditionalWeakTable<Node, DeferredDecorator>();
foreach (var keyValue in _knownTags) {
_tags[keyValue.Key] = new TagInfo(keyValue.Value, null);
}
foreach (var keyValue in _knownFilters) {
_filters[keyValue.Key] = new TagInfo(keyValue.Value, null);
}
HookAnalysis(analyzer);
_analyzer = analyzer;
}
private void OnNewParseTree(object sender, EventArgs e) {
var entry = sender as IPythonProjectEntry;
if (entry != null && _hookedEntries.Remove(entry)) {
var removeTags = _tags.Where(kv => kv.Value.Entry == entry).Select(kv => kv.Key).ToList();
var removeFilters = _filters.Where(kv => kv.Value.Entry == entry).Select(kv => kv.Key).ToList();
foreach (var key in removeTags) {
_tags.Remove(key);
}
foreach (var key in removeFilters) {
_filters.Remove(key);
}
}
}
private void HookAnalysis(PythonAnalyzer analyzer) {
analyzer.SpecializeFunction("django.template.loader", "render_to_string", RenderToStringProcessor, true);
analyzer.SpecializeFunction("django.shortcuts", "render_to_response", RenderToStringProcessor, true);
analyzer.SpecializeFunction("django.shortcuts", "render", RenderProcessor, true);
analyzer.SpecializeFunction("django.contrib.gis.shortcuts", "render_to_kml", RenderToStringProcessor, true);
analyzer.SpecializeFunction("django.contrib.gis.shortcuts", "render_to_kmz", RenderToStringProcessor, true);
analyzer.SpecializeFunction("django.contrib.gis.shortcuts", "render_to_text", RenderToStringProcessor, true);
analyzer.SpecializeFunction("django.template.base.Library", "filter", FilterProcessor, true);
analyzer.SpecializeFunction("django.template.base.Library", "filter_function", FilterProcessor, true);
analyzer.SpecializeFunction("django.template.base.Library", "tag", TagProcessor, true);
analyzer.SpecializeFunction("django.template.base.Library", "tag_function", TagProcessor, true);
analyzer.SpecializeFunction("django.template.base.Library", "assignment_tag", TagProcessor, true);
analyzer.SpecializeFunction("django.template.base.Library", "simple_tag", TagProcessor, true);
analyzer.SpecializeFunction("django.template.base.Parser", "parse", ParseProcessor, true);
analyzer.SpecializeFunction("django.template.base", "import_library", "django.template.base.Library", true);
analyzer.SpecializeFunction("django.template.loader", "get_template", GetTemplateProcessor, true);
analyzer.SpecializeFunction("django.template.context", "Context", ContextClassProcessor, true);
analyzer.SpecializeFunction("django.template", "RequestContext", RequestContextClassProcessor, true);
analyzer.SpecializeFunction("django.template.context", "RequestContext", RequestContextClassProcessor, true);
analyzer.SpecializeFunction("django.template.base.Template", "render", TemplateRenderProcessor, true);
// View specializers
analyzer.SpecializeFunction("django.views.generic.detail.DetailView", "as_view", DetailViewProcessor, true);
analyzer.SpecializeFunction("django.views.generic.DetailView", "as_view", DetailViewProcessor, true);
analyzer.SpecializeFunction("django.views.generic.list.ListView", "as_view", ListViewProcessor, true);
analyzer.SpecializeFunction("django.views.generic.ListView", "as_view", ListViewProcessor, true);
// Urls specializers
analyzer.SpecializeFunction("django.conf.urls", "url", UrlProcessor, true);
}
private IAnalysisSet ParseProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
// def parse(self, parse_until=None):
// We want to find closing tags here passed to parse_until...
if (args.Length >= 2) {
foreach (var tuple in args[1]) {
foreach (var indexValue in tuple.GetItems()) {
var values = indexValue.Value;
foreach (var value in values) {
var str = value.GetConstantValueAsString();
if (str != null) {
RegisterTag(unit.Project, _tags, str);
}
}
}
}
}
return AnalysisSet.Empty;
}
#region IDisposable Members
public void Dispose() {
_filters.Clear();
_tags.Clear();
foreach (var entry in _hookedEntries) {
entry.OnNewParseTree -= OnNewParseTree;
}
_hookedEntries.Clear();
_templateAnalysis.Clear();
_templateFiles.Clear();
}
#endregion
/// <summary>
/// Specializes "DetailView.as_view"
/// </summary>
private IAnalysisSet DetailViewProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
return ViewProcessor(node, unit, args, keywordArgNames, "_details.html");
}
/// <summary>
/// Specializes "ListView.as_view"
/// </summary>
private IAnalysisSet ListViewProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
return ViewProcessor(node, unit, args, keywordArgNames, "_list.html");
}
private IAnalysisSet ViewProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames, string defaultTemplateNameSuffix) {
var templateNames = GetArg(args, keywordArgNames, "template_name", -1, AnalysisSet.Empty)
.Select(v => v.GetConstantValueAsString())
.Where(s => !string.IsNullOrEmpty(s))
.ToList();
var templateNameSuffix = GetArg(args, keywordArgNames, "template_name_suffix", -1, AnalysisSet.Empty)
.Select(v => v.GetConstantValueAsString())
.Where(s => !string.IsNullOrEmpty(s))
.ToList();
var contextObjName = GetArg(args, keywordArgNames, "context_object_name", -1, AnalysisSet.Empty)
.Select(v => v.GetConstantValueAsString())
.Where(s => !string.IsNullOrEmpty(s))
.ToList();
var model = GetArg(args, keywordArgNames, "model", -1);
// TODO: Support this (this requires some analyis improvements as currently we
// typically don't get useful values for queryset
// Right now, queryset only flows into the template if template_name
// is also specified.
var querySet = GetArg(args, keywordArgNames, "queryset", -1);
if (templateNames.Any()) {
foreach (var templateName in templateNames) {
AddViewTemplate(unit, model, querySet, contextObjName, templateName);
}
} else if (model != null) {
// template name is [app]/[modelname]_[template_name_suffix]
string appName;
int firstDot = unit.Project.ModuleName.IndexOf('.');
if (firstDot != -1) {
appName = unit.Project.ModuleName.Substring(0, firstDot);
} else {
appName = unit.Project.ModuleName;
}
foreach (var modelInst in model) {
string baseName = appName + "/" + modelInst.Name.ToLower();
foreach (var suffix in templateNameSuffix.DefaultIfEmpty(defaultTemplateNameSuffix)) {
AddViewTemplate(unit, model, querySet, contextObjName, baseName + suffix);
}
}
}
return AnalysisSet.Empty;
}
private void AddViewTemplate(
AnalysisUnit unit,
IAnalysisSet model,
IAnalysisSet querySet,
IEnumerable<string> contextObjName,
string templateName
) {
TemplateVariables tags;
if (!_templateFiles.TryGetValue(templateName, out tags)) {
_templateFiles[templateName] = tags = new TemplateVariables();
}
if (querySet != null) {
foreach (var name in contextObjName) {
tags.UpdateVariable(name, unit, AnalysisSet.Empty);
}
} else if (model != null) {
foreach (var modelInst in model) {
foreach (var name in contextObjName.DefaultIfEmpty(modelInst.Name.ToLower())) {
tags.UpdateVariable(name, unit, modelInst.GetInstanceType());
}
}
}
}
private IAnalysisSet UrlProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
// No completion if the url has no name (reverse matching not possible)
if (keywordArgNames.Length == 0) {
return AnalysisSet.Empty;
}
IAnalysisSet urlNames = GetArg(args, keywordArgNames, "name", -1);
if (urlNames == null) { // The kwargs do not contain a name arg
return AnalysisSet.Empty;
}
string urlName = urlNames.First().GetConstantValueAsString();
string urlRegex = args.First().First().GetConstantValueAsString();
_urls.Add(new DjangoUrl(urlName, urlRegex));
return AnalysisSet.Empty;
}
private static void GetStringArguments(HashSet<string> arguments, IAnalysisSet arg) {
foreach (var value in arg) {
string templateName = value.GetConstantValueAsString();
if (templateName != null) {
arguments.Add(templateName);
}
}
}
private IAnalysisSet FilterProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
return ProcessTags(node, unit, args, keywordArgNames, _filters);
}
private IAnalysisSet TagProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
return ProcessTags(node, unit, args, keywordArgNames, _tags);
}
class DeferredDecorator : AnalysisValue {
private readonly DjangoAnalyzer _analyzer;
private readonly IAnalysisSet _name;
private readonly Dictionary<string, TagInfo> _tags;
public DeferredDecorator(DjangoAnalyzer analyzer, IAnalysisSet name, Dictionary<string, TagInfo> tags) {
_analyzer = analyzer;
_name = name;
_tags = tags;
}
public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
_analyzer.ProcessTags(node, unit, new[] { AnalysisSet.Empty, _name, args[0] }, NameExpression.EmptyArray, _tags);
return AnalysisSet.Empty;
}
}
private IAnalysisSet ProcessTags(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames, Dictionary<string, TagInfo> tags) {
if (args.Length >= 3) {
// library.filter(name, value)
foreach (var name in args[1]) {
var constName = name.GetConstantValue();
if (constName == Type.Missing) {
if (name.Name != null) {
RegisterTag(unit.Project, tags, name.Name, name.Documentation);
}
} else {
var strName = name.GetConstantValueAsString();
if (strName != null) {
RegisterTag(unit.Project, tags, strName);
}
}
}
foreach (var func in args[2]) {
// TODO: Find a better node
var parser = unit.FindAnalysisValueByName(node, "django.template.base.Parser");
if (parser != null) {
func.Call(node, unit, new[] { parser, AnalysisSet.Empty }, NameExpression.EmptyArray);
}
}
} else if (args.Length >= 2) {
// library.filter(value)
foreach (var name in args[1]) {
string tagName = name.Name ?? name.GetConstantValueAsString();
if (tagName != null) {
RegisterTag(unit.Project, tags, tagName, name.Documentation);
}
if (name.MemberType != PythonMemberType.Constant) {
var parser = unit.FindAnalysisValueByName(node, "django.template.base.Parser");
if (parser != null) {
name.Call(node, unit, new[] { parser, AnalysisSet.Empty }, NameExpression.EmptyArray);
}
}
}
} else if (args.Length == 1) {
foreach (var name in args[0]) {
if (name.MemberType == PythonMemberType.Constant) {
// library.filter('name')
DeferredDecorator dec;
if (!_decoratorTable.TryGetValue(node, out dec)) {
dec = new DeferredDecorator(this, name, tags);
_decoratorTable.Add(node, dec);
}
return dec;
} else if (name.Name != null) {
// library.filter
RegisterTag(unit.Project, tags, name.Name, name.Documentation);
}
}
}
return AnalysisSet.Empty;
}
private void RegisterTag(IPythonProjectEntry entry, Dictionary<string, TagInfo> tags, string name, string documentation = null) {
TagInfo tag;
if (!tags.TryGetValue(name, out tag) || (String.IsNullOrWhiteSpace(tag.Documentation) && !String.IsNullOrEmpty(documentation))) {
tags[name] = tag = new TagInfo(documentation, entry);
if (entry != null && _hookedEntries.Add(entry)) {
entry.OnNewParseTree += OnNewParseTree;
}
}
}
private IAnalysisSet RenderToStringProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
var names = GetArg(args, keywordArgNames, "template_name", 0);
var context = GetArg(args, keywordArgNames, "context_instance", 2);
var dictArgs = context == null ? GetArg(args, keywordArgNames, "dictionary", 1) : null;
if (dictArgs != null || context != null) {
foreach (var name in names.Select(n => n.GetConstantValueAsString()).Where(n => !string.IsNullOrEmpty(n))) {
AddTemplateMapping(unit, name, dictArgs, context);
}
}
return AnalysisSet.Empty;
}
private IAnalysisSet RenderProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
var names = GetArg(args, keywordArgNames, "template_name", 1);
var context = GetArg(args, keywordArgNames, "context_instance", 3);
var dictArgs = context == null ? GetArg(args, keywordArgNames, "dictionary", 2) : null;
if (dictArgs != null || context != null) {
foreach (var name in names.Select(n => n.GetConstantValueAsString()).Where(n => !string.IsNullOrEmpty(n))) {
AddTemplateMapping(unit, name, dictArgs, context);
}
}
return AnalysisSet.Empty;
}
private void AddTemplateMapping(
AnalysisUnit unit,
string filename,
IEnumerable<AnalysisValue> dictArgs,
IEnumerable<AnalysisValue> context
) {
TemplateVariables tags;
if (!_templateFiles.TryGetValue(filename, out tags)) {
_templateFiles[filename] = tags = new TemplateVariables();
}
IEnumerable<KeyValuePair<IAnalysisSet, IAnalysisSet>> items = null;
if (context != null) {
items = context.OfType<ContextMarker>()
.SelectMany(ctxt => ctxt.Arguments.SelectMany(v => v.GetItems()));
} else if (dictArgs != null) {
items = dictArgs.SelectMany(v => v.GetItems());
}
if (items != null) {
foreach (var keyValue in items) {
foreach (var key in keyValue.Key) {
var keyName = key.GetConstantValueAsString();
if (keyName != null) {
tags.UpdateVariable(keyName, unit, keyValue.Value);
}
}
}
}
}
class GetTemplateAnalysisValue : AnalysisValue {
public readonly string Filename;
public readonly TemplateRenderMethod RenderMethod;
public readonly DjangoAnalyzer Analyzer;
public GetTemplateAnalysisValue(DjangoAnalyzer analyzer, string name) {
Analyzer = analyzer;
Filename = name;
RenderMethod = new TemplateRenderMethod(this);
}
public override IAnalysisSet GetMember(Node node, AnalysisUnit unit, string name) {
if (name == "render") {
return RenderMethod;
}
return base.GetMember(node, unit, name);
}
}
class TemplateRenderMethod : AnalysisValue {
public readonly GetTemplateAnalysisValue GetTemplateValue;
public TemplateRenderMethod(GetTemplateAnalysisValue getTemplateAnalysisValue) {
this.GetTemplateValue = getTemplateAnalysisValue;
}
public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
if (args.Length == 1) {
string filename = GetTemplateValue.Filename;
GetTemplateValue.Analyzer.AddTemplateMapping(unit, filename, null, args[0]);
}
return base.Call(node, unit, args, keywordArgNames);
}
}
private IAnalysisSet GetTemplateProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
var res = AnalysisSet.Empty;
if (args.Length >= 1) {
foreach (var filename in args[0]) {
var file = filename.GetConstantValueAsString();
if (file != null) {
GetTemplateAnalysisValue value;
if (!_templateAnalysis.TryGetValue(file, out value)) {
_templateAnalysis[file] = value = new GetTemplateAnalysisValue(this, file);
}
res = res.Add(value);
}
}
}
return res;
}
class ContextMarker : AnalysisValue {
public readonly HashSet<AnalysisValue> Arguments;
public ContextMarker() {
Arguments = new HashSet<AnalysisValue>();
}
public override IEnumerable<KeyValuePair<IAnalysisSet, IAnalysisSet>> GetItems() {
return Arguments.SelectMany(av => av.GetItems());
}
}
private IAnalysisSet ContextClassProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
var dict = GetArg(args, keywordArgNames, "dict_", 0);
if (dict != null && dict.Any()) {
ContextMarker contextValue;
if (!_contextTable.TryGetValue(node, out contextValue)) {
contextValue = new ContextMarker();
_contextTable.Add(node, contextValue);
}
contextValue.Arguments.UnionWith(dict);
return contextValue;
}
return AnalysisSet.Empty;
}
private IAnalysisSet RequestContextClassProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
var dict = GetArg(args, keywordArgNames, "dict_", 1);
if (dict != null) {
return ContextClassProcessor(node, unit, new[] { dict }, NameExpression.EmptyArray);
}
return AnalysisSet.Empty;
}
private IAnalysisSet TemplateRenderProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
if (args.Length == 2) {
foreach (var templateValue in args[0].OfType<GetTemplateAnalysisValue>()) {
AddTemplateMapping(unit, templateValue.Filename, null, args[1]);
}
}
return AnalysisSet.Empty;
}
private static IAnalysisSet GetArg(
IAnalysisSet[] args,
NameExpression[] keywordArgNames,
string name,
int index,
IAnalysisSet defaultValue = null
) {
for (int i = 0, j = args.Length - keywordArgNames.Length;
i < keywordArgNames.Length && j < args.Length;
++i, ++j) {
var kwArg = keywordArgNames[i];
if (kwArg == null) {
Debug.Fail("Null keyword argument");
} else if (kwArg.Name == name) {
return args[j];
}
}
if (0 <= index && index < args.Length) {
return args[index];
}
return defaultValue;
}
public Dictionary<string, HashSet<AnalysisValue>> GetVariablesForTemplateFile(string filename) {
string curLevel = filename; // is C:\Fob\Oar\Baz\fob.html
string curPath = filename = Path.GetFileName(filename); // is fob.html
for (; ; ) {
string curFilename = filename.Replace('\\', '/');
TemplateVariables res;
if (_templateFiles.TryGetValue(curFilename, out res)) {
return res.GetAllValues();
}
curLevel = Path.GetDirectoryName(curLevel); // C:\Fob\Oar\Baz\fob.html gets us C:\Fob\Oar\Baz
var fn2 = Path.GetFileName(curLevel); // Gets us Baz
if (String.IsNullOrEmpty(fn2)) {
break;
}
curPath = Path.Combine(fn2, curPath); // Get us Baz\fob.html
filename = curPath;
}
return null;
}
private static HashSet<string> MakeNestedEndTags() {
HashSet<string> res = new HashSet<string>();
foreach (var value in _nestedTags.Values) {
res.Add(value);
}
return res;
}
private static HashSet<string> MakeNestedStartTags() {
HashSet<string> res = new HashSet<string>();
foreach (var key in _nestedTags.Keys) {
res.Add(key);
}
return res;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2021 Tim Stair
//
// 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.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using CardMaker.XML;
namespace Support.UI
{
public partial class RGBColorSelectDialog : Form
{
private int m_nPreviousColorIndex = -1;
bool m_bEventsEnabled = true;
private Color m_lastColor = Color.Black;
readonly Bitmap m_BitmapHue;
private const int PREVIOUS_COLOR_WIDTH = 16;
private static readonly List<Color> s_listPreviousColors = new List<Color>();
private static bool s_bZeroXChecked = true;
// A delegate type for hooking up change notifications.
public delegate void ColorPreviewEvent(object sender, Color zColor);
public event ColorPreviewEvent PreviewEvent;
private readonly PictureBoxSelectable[] m_arrayPictureBoxes;
public RGBColorSelectDialog()
{
InitializeComponent();
m_BitmapHue = new Bitmap(pictureColorHue.ClientSize.Width, pictureColorHue.ClientSize.Height);
pictureColorHue.Image = m_BitmapHue;
pictureColorHue.SelectionIndicator = PictureBoxSelectable.IndicatorType.Both;
var m_bitmapRedToPurple = new Bitmap(pictureRedToPurple.ClientSize.Width, 255);
var m_bitmapPurpleToBlue = new Bitmap(pictureRedToPurple.ClientSize.Width, 255);
var m_bitmapBlueToTeal = new Bitmap(pictureRedToPurple.ClientSize.Width, 255);
var m_bitmapTealToGreen = new Bitmap(pictureRedToPurple.ClientSize.Width, 255);
var m_bitmapGreenToYellow = new Bitmap(pictureRedToPurple.ClientSize.Width, 255);
var m_bitmapYellowToRed = new Bitmap(pictureRedToPurple.ClientSize.Width, 255);
GenerateColorBar(m_bitmapRedToPurple, Color.FromArgb(255, 0, 0), Color.FromArgb(255, 0, 255));
GenerateColorBar(m_bitmapPurpleToBlue, Color.FromArgb(255, 0, 255), Color.FromArgb(0, 0, 255));
GenerateColorBar(m_bitmapBlueToTeal, Color.FromArgb(0, 0, 255), Color.FromArgb(0, 255, 255));
GenerateColorBar(m_bitmapTealToGreen, Color.FromArgb(0, 255, 255), Color.FromArgb(0, 255, 0));
GenerateColorBar(m_bitmapGreenToYellow, Color.FromArgb(0, 255, 0), Color.FromArgb(255, 255, 0));
GenerateColorBar(m_bitmapYellowToRed, Color.FromArgb(255, 255, 0), Color.FromArgb(255, 0, 0));
pictureRedToPurple.Image = m_bitmapRedToPurple;
picturePurpleToBlue.Image = m_bitmapPurpleToBlue;
pictureBlueToTeal.Image = m_bitmapBlueToTeal;
pictureTealToGreen.Image = m_bitmapTealToGreen;
pictureGreenToYellow.Image = m_bitmapGreenToYellow;
pictureYellowToRed.Image = m_bitmapYellowToRed;
pictureRedToPurple.Tag = m_bitmapRedToPurple;
picturePurpleToBlue.Tag = m_bitmapPurpleToBlue;
pictureBlueToTeal.Tag = m_bitmapBlueToTeal;
pictureTealToGreen.Tag = m_bitmapTealToGreen;
pictureGreenToYellow.Tag = m_bitmapGreenToYellow;
pictureYellowToRed.Tag = m_bitmapYellowToRed;
pictureRedToPurple.SelectionIndicator = PictureBoxSelectable.IndicatorType.HLine;
picturePurpleToBlue.SelectionIndicator = PictureBoxSelectable.IndicatorType.HLine;
pictureBlueToTeal.SelectionIndicator = PictureBoxSelectable.IndicatorType.HLine;
pictureTealToGreen.SelectionIndicator = PictureBoxSelectable.IndicatorType.HLine;
pictureGreenToYellow.SelectionIndicator = PictureBoxSelectable.IndicatorType.HLine;
pictureYellowToRed.SelectionIndicator = PictureBoxSelectable.IndicatorType.HLine;
m_arrayPictureBoxes = new [] {
pictureRedToPurple,
picturePurpleToBlue,
pictureBlueToTeal,
pictureTealToGreen,
pictureGreenToYellow,
pictureYellowToRed };
// populate the previous colors
if (0 < s_listPreviousColors.Count)
{
var zBmp = new Bitmap(panelPreviousColors.ClientRectangle.Width, panelPreviousColors.ClientRectangle.Height);
var zGraphics = Graphics.FromImage(zBmp);
var nXOffset = 0;
foreach (var prevColor in s_listPreviousColors)
{
zGraphics.FillRectangle(new SolidBrush(prevColor), nXOffset, 0, PREVIOUS_COLOR_WIDTH, panelPreviousColors.Height);
nXOffset += PREVIOUS_COLOR_WIDTH;
}
panelPreviousColors.BackgroundImage = zBmp;
}
UpdateHue(Color.Red);
UpdateColorBox(m_lastColor);
}
#if false
public void SetColor(Color zColor)
{
UpdateColorBox(zColor);
panelColor.BackColor = zColor;
int nRed = 0;
int nGreen = 0;
int nBlue = 0;
if (zColor.R > zColor.B)
{
nRed = zColor.R;
if (zColor.G > zColor.B)
{
nGreen = zColor.G;
}
else
{
nBlue = zColor.B;
}
}
else
{
nBlue = zColor.B;
if (zColor.G > zColor.B)
{
nGreen = zColor.G;
}
else
{
nBlue = zColor.B;
}
}
//Color colorSeek = Color.FromArgb(255, nRed, nGreen, nBlue);
//for (int nIdx = 0; nIdx < m_BitmapColors.Height; nIdx++)
//{
// Color pixelColor = m_BitmapColors.GetPixel(0, nIdx);
// Console.WriteLine(pixelColor + "::" + colorSeek);
// if (colorSeek == pixelColor)
// {
// pictureRedToPurple.Yposition = nIdx;
// break;
// }
//}
}
#endif
public void UpdateColorBox(Color colorCurrent, object sender = null)
{
m_bEventsEnabled = false;
numericRed.Value = colorCurrent.R;
numericGreen.Value = colorCurrent.G;
numericBlue.Value = colorCurrent.B;
numericAlpha.Value = colorCurrent.A;
m_lastColor = colorCurrent;
if (sender != txtHexColor)
{
UpdateColorHexText();
}
panelColor.BackColor = colorCurrent;
m_bEventsEnabled = true;
PreviewEvent?.Invoke(this, colorCurrent);
}
private void UpdateColorHexText()
{
txtHexColor.Text =
(checkBoxAddZeroX.Checked ? "0x" : string.Empty) +
m_lastColor.R.ToString("X").PadLeft(2, '0') +
m_lastColor.G.ToString("X").PadLeft(2, '0') +
m_lastColor.B.ToString("X").PadLeft(2, '0') +
m_lastColor.A.ToString("X").PadLeft(2, '0');
}
public Color Color => Color.FromArgb((int)numericAlpha.Value, (int)numericRed.Value, (int)numericGreen.Value, (int)numericBlue.Value);
public void SetHueColor()
{
UpdateColorBox(Color.FromArgb((int)numericAlpha.Value, m_BitmapHue.GetPixel(pictureColorHue.Xposition, pictureColorHue.Yposition)));
}
private void GenerateColorBar(Bitmap zBmp, Color colorFrom, Color colorTo)
{
var zGraphics = Graphics.FromImage(zBmp);
var zLinear = new LinearGradientBrush(new Rectangle(0, 0, zBmp.Width, zBmp.Height), colorFrom, colorTo, 90);
zGraphics.FillRectangle(zLinear, new Rectangle(0, 0, zBmp.Width, zBmp.Height));
}
private void UpdateHue(Color zColor)
{
var zGraphics = Graphics.FromImage(m_BitmapHue);
int nRedMax = zColor.R;
int nGreenMax = zColor.G;
int nBlueMax = zColor.B;
var fRedInterval = (float)(255 - nRedMax) / (float)255;
var fGreenInterval = (float)(255 - nGreenMax) / (float)255;
var fBlueInterval = (float)(255 - nBlueMax) / (float)255;
for (int nRow = 0; nRow < m_BitmapHue.Height; nRow++)
{
var nRed = (int)((float)nRedMax + (float)nRow * fRedInterval);
var nGreen = (int)((float)nGreenMax + (float)nRow * fGreenInterval);
var nBlue = (int)((float)nBlueMax + (float)nRow * fBlueInterval);
if ((m_BitmapHue.Height - 1) == nRow)
{
nRed = 255;
nGreen = 255;
nBlue = 255;
}
nRed = GetWithinRange(nRed, 0, 255);
nGreen = GetWithinRange(nGreen, 0, 255);
nBlue = GetWithinRange(nBlue, 0, 255);
zGraphics.FillRectangle(
new LinearGradientBrush(new Point(0, 0), new Point(m_BitmapHue.Width -1, 0),
Color.Black, Color.FromArgb(nRed, nGreen, nBlue)),
new Rectangle(0, nRow, m_BitmapHue.Width, 1));
}
pictureColorHue.Invalidate();
}
public int GetWithinRange(int nValue, int nMin, int nMax)
{
if (nValue > nMax)
{
return nMax;
}
if (nValue < nMin)
{
return nMin;
}
return nValue;
}
private void numeric_ValueChanged(object sender, EventArgs e)
{
if(m_bEventsEnabled)
{
UpdateColorBox(Color.FromArgb((int)numericAlpha.Value, (int)numericRed.Value, (int)numericGreen.Value, (int)numericBlue.Value));
}
}
private void pictureColor_MouseEnter(object sender, EventArgs e)
{
Cursor = Cursors.Cross;
}
private void pictureColor_MouseLeave(object sender, EventArgs e)
{
Cursor = Cursors.Default;
}
public void HandleMouseHueColor(object sender, MouseEventArgs e)
{
switch (e.Button)
{
case MouseButtons.Left:
UpdateColorBox(Color.FromArgb((int)numericAlpha.Value, m_BitmapHue.GetPixel(pictureColorHue.Xposition, pictureColorHue.Yposition)));
break;
}
}
public void HandleMouseColor(object sender, MouseEventArgs e)
{
switch (e.Button)
{
case MouseButtons.Left:
var pictureBox = (PictureBoxSelectable)sender;
if ((-1 < e.Y) && (pictureBox.Image.Height > e.Y))
{
Color colorSelected = ((Bitmap)pictureBox.Tag).GetPixel(0, e.Y);
UpdateHue(colorSelected);
SetHueColor();
foreach (PictureBoxSelectable picBox in m_arrayPictureBoxes)
{
if (picBox != pictureBox)
{
picBox.Yposition = 0;
picBox.Invalidate();
}
}
}
break;
}
}
private void btnOK_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Color colorSelected = Color.FromArgb((int)numericAlpha.Value, (int)numericRed.Value, (int)numericGreen.Value, (int)numericBlue.Value);
int nMaxPreviousColors = panelPreviousColors.Width / PREVIOUS_COLOR_WIDTH;
if (0 == s_listPreviousColors.Count ||
(0 < s_listPreviousColors.Count && s_listPreviousColors[0] != colorSelected))
{
// clean up any existing copies of the selected color
int nIdx = 0;
while (nIdx < s_listPreviousColors.Count)
{
if (s_listPreviousColors[nIdx] != colorSelected)
nIdx++;
else
s_listPreviousColors.RemoveAt(nIdx);
}
// make room for the new "previous" color
while (s_listPreviousColors.Count >= nMaxPreviousColors)
s_listPreviousColors.RemoveAt(s_listPreviousColors.Count - 1);
s_listPreviousColors.Insert(0, colorSelected);
}
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void panelPreviousColors_MouseDown(object sender, MouseEventArgs e)
{
if (m_nPreviousColorIndex < s_listPreviousColors.Count)
{
UpdateColorBox(Color.FromArgb(
s_listPreviousColors[m_nPreviousColorIndex].A,
s_listPreviousColors[m_nPreviousColorIndex].R,
s_listPreviousColors[m_nPreviousColorIndex].G,
s_listPreviousColors[m_nPreviousColorIndex].B));
}
}
private void panelPreviousColors_MouseMove(object sender, MouseEventArgs e)
{
int nColorIndex = e.X / PREVIOUS_COLOR_WIDTH;
if (m_nPreviousColorIndex == nColorIndex)
return;
m_nPreviousColorIndex = nColorIndex;
if (m_nPreviousColorIndex < s_listPreviousColors.Count)
{
toolTipPreviouscolor.SetToolTip(panelPreviousColors,
"A:" + s_listPreviousColors[m_nPreviousColorIndex].A.ToString("000") + " " +
"R:" + s_listPreviousColors[m_nPreviousColorIndex].R.ToString("000") + " " +
"G:" + s_listPreviousColors[m_nPreviousColorIndex].G.ToString("000") + " " +
"B:" + s_listPreviousColors[m_nPreviousColorIndex].B.ToString("000"));
}
}
private void checkBoxAddZeroX_CheckedChanged(object sender, EventArgs e)
{
UpdateColorHexText();
}
private void RGBColorSelectDialog_FormClosing(object sender, FormClosingEventArgs e)
{
s_bZeroXChecked = checkBoxAddZeroX.Checked;
}
private void RGBColorSelectDialog_Load(object sender, EventArgs e)
{
checkBoxAddZeroX.Checked = s_bZeroXChecked;
}
private void txtHexColor_TextChanged(object sender, EventArgs e)
{
if (m_bEventsEnabled)
{
var bSucceeded = false;
var zColor = ProjectLayoutElement.TranslateColorString(txtHexColor.Text, 255, out bSucceeded);
if (bSucceeded)
{
UpdateColorBox(zColor, txtHexColor);
}
}
}
}
class PictureBoxSelectable : PictureBox
{
private int m_nPosX;
private int m_nPosY;
private IndicatorType m_eIndicatorType = IndicatorType.None;
public IndicatorType SelectionIndicator
{
get
{
return m_eIndicatorType;
}
set
{
m_eIndicatorType = value;
}
}
public int Xposition
{
get
{
return m_nPosX;
}
set
{
m_nPosX = value;
}
}
public int Yposition
{
get
{
return m_nPosY;
}
set
{
m_nPosY = value;
}
}
public enum IndicatorType
{
VLine,
HLine,
Both,
None
}
public PictureBoxSelectable()
{
MouseMove += PictureBoxSelectable_MouseMove;
}
void PictureBoxSelectable_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// clamp the selection to be inside the client
if (ClientRectangle.Contains(e.X, 0))
{
m_nPosX = e.X;
}
else if (e.X < ClientRectangle.Left)
{
m_nPosX = ClientRectangle.Left;
}
else if (e.X > ClientRectangle.Right - 1)
{
m_nPosX = ClientRectangle.Right - 1;
}
if (ClientRectangle.Contains(0, e.Y))
{
m_nPosY = e.Y;
}
else if (e.Y < ClientRectangle.Top)
{
m_nPosY = ClientRectangle.Top;
}
else if (e.Y > ClientRectangle.Bottom - 1)
{
m_nPosY = ClientRectangle.Bottom - 1;
}
Invalidate();
}
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
switch (m_eIndicatorType)
{
case IndicatorType.HLine:
pe.Graphics.DrawLine(new Pen(Color.FromArgb(255, 255, 255, 255)), new Point(0, m_nPosY), new Point(ClientSize.Width, m_nPosY));
break;
case IndicatorType.VLine:
pe.Graphics.DrawLine(new Pen(Color.FromArgb(255, 255, 255, 255)), new Point(m_nPosX, 0), new Point(m_nPosX, ClientSize.Height));
break;
case IndicatorType.Both:
pe.Graphics.DrawLine(new Pen(Color.FromArgb(255, 255, 255, 255)), new Point(0, m_nPosY), new Point(ClientSize.Width, m_nPosY));
pe.Graphics.DrawLine(new Pen(Color.FromArgb(255, 255, 255, 255)), new Point(m_nPosX, 0), new Point(m_nPosX, ClientSize.Height));
break;
}
}
}
}
| |
// * **************************************************************************
// * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C.
// * This source code is subject to terms and conditions of the MIT License.
// * 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.
// * **************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssert;
using JetBrains.Annotations;
using NUnit.Framework;
namespace MvbaCore.Tests.Extensions
{
[UsedImplicitly]
public class StringExtensionsTests
{
[TestFixture]
public class When_asked_if_a_string_IsNullOrEmpty
{
[Test]
public void Should_return_false_if_the_input_is_not_empty()
{
const string input = "\r\n";
var result = input.IsNullOrEmpty();
result.ShouldBeFalse();
}
[Test]
public void Should_return_true_if_the_input_is_empty()
{
var input = string.Empty;
var result = input.IsNullOrEmpty();
result.ShouldBeTrue();
}
[Test]
public void Should_return_true_if_the_input_is_null()
{
const string input = null;
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
var result = input.IsNullOrEmpty();
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
result.ShouldBeTrue();
}
}
[TestFixture]
public class When_asked_if_a_string_is_null_or_empty_with_optional_trim
{
private string _input;
private bool _result;
private bool _trim;
[Test]
public void Given_a_null_string_and_trim_is_false()
{
Test.Verify(
with_a_null_string,
with_trim_set_to_false,
when_asked_if_a_string_is_null_or_empty,
should_return_true
);
}
[Test]
public void Given_a_null_string_and_trim_is_true()
{
Test.Verify(
with_a_null_string,
with_trim_set_to_true,
when_asked_if_a_string_is_null_or_empty,
should_return_true
);
}
[Test]
public void Given_a_string_containing_non_whitespace_and_trim_is_false()
{
Test.Verify(
with_a_string_containing_non_whitespace,
with_trim_set_to_false,
when_asked_if_a_string_is_null_or_empty,
should_return_false
);
}
[Test]
public void Given_a_string_containing_non_whitespace_and_trim_is_true()
{
Test.Verify(
with_a_string_containing_non_whitespace,
with_trim_set_to_true,
when_asked_if_a_string_is_null_or_empty,
should_return_false
);
}
[Test]
public void Given_a_string_containing_only_whitespace_and_trim_is_false()
{
Test.Verify(
with_a_string_containing_only_whitespace,
with_trim_set_to_false,
when_asked_if_a_string_is_null_or_empty,
should_return_false
);
}
[Test]
public void Given_a_string_containing_only_whitespace_and_trim_is_true()
{
Test.Verify(
with_a_string_containing_only_whitespace,
with_trim_set_to_true,
when_asked_if_a_string_is_null_or_empty,
should_return_true
);
}
[Test]
public void Given_an_empty_string_and_trim_is_false()
{
Test.Verify(
with_an_empty_string,
with_trim_set_to_false,
when_asked_if_a_string_is_null_or_empty,
should_return_true
);
}
[Test]
public void Given_an_empty_string_and_trim_is_true()
{
Test.Verify(
with_an_empty_string,
with_trim_set_to_true,
when_asked_if_a_string_is_null_or_empty,
should_return_true
);
}
private void should_return_false()
{
_result.ShouldBeFalse();
}
private void should_return_true()
{
_result.ShouldBeTrue();
}
private void when_asked_if_a_string_is_null_or_empty()
{
_result = _input.IsNullOrEmpty(_trim);
}
private void with_a_null_string()
{
_input = null;
}
private void with_a_string_containing_non_whitespace()
{
_input = "aa";
}
private void with_a_string_containing_only_whitespace()
{
_input = "\n\r\t ";
}
private void with_an_empty_string()
{
_input = "";
}
private void with_trim_set_to_false()
{
_trim = false;
}
private void with_trim_set_to_true()
{
_trim = true;
}
}
[TestFixture]
public class When_asked_to_add_an_item_to_a_list
{
private List<string> _list;
[SetUp]
public void BeforeEachTest()
{
_list = new List<string>();
}
[Test]
public void Should_add_the_item_if_it_is_not_null_and_not_empty()
{
const string item = "Test";
_list.AddIfNotNullOrEmpty(item);
_list.Count.ShouldBeEqualTo(1);
_list.First().ShouldBeEqualTo(item);
}
[Test]
public void Should_not_add_the_item_if_it_is_empty()
{
_list.AddIfNotNullOrEmpty("");
_list.Count.ShouldBeEqualTo(0);
}
[Test]
public void Should_not_add_the_item_if_it_is_null()
{
_list.AddIfNotNullOrEmpty(null);
_list.Count.ShouldBeEqualTo(0);
}
}
[TestFixture]
public class When_asked_to_change_a_string_ToCamelCase
{
[Test]
public void Should_make_the_first_character_lower_case_but_not_change_the_case_of_the_rest()
{
const string test = "TEST";
test.ToCamelCase().ShouldBeEqualTo("tEST");
}
[Test]
public void Should_make_the_first_character_lower_case_if_the_string_is_only_one_character_long()
{
const string test = "A";
test.ToCamelCase().ShouldBeEqualTo("a");
}
[Test]
public void Should_return_empty_if_the_input_is_empty()
{
const string test = "";
test.ToCamelCase().ShouldBeEqualTo("");
}
[Test]
public void Should_return_empty_string_if_the_input_is_null()
{
const string test = null;
// ReSharper disable once ExpressionIsAlwaysNull
test.ToCamelCase().ShouldBeEqualTo("");
}
}
[TestFixture]
public class When_asked_to_convert_newlines_to_BR
{
[Test]
public void Should_replace_the_newlines()
{
var input = "food" + Environment.NewLine + "bar";
var result = input.NewlinesToBr();
Assert.AreEqual("food<br />bar", result);
}
[Test]
public void Should_return_null_if_the_input_is_null()
{
const string input = null;
// ReSharper disable once ExpressionIsAlwaysNull
var result = input.NewlinesToBr();
Assert.IsNull(result);
}
}
[TestFixture]
public class When_asked_to_convert_tabs_to_Nbsp
{
[Test]
public void Should_replace_the_tabs()
{
const string input = "food" + "\t" + "bar";
var result = input.TabsToNbsp();
Assert.AreEqual("food bar", result);
}
[Test]
public void Should_return_null_if_the_input_is_null()
{
const string input = null;
// ReSharper disable once ExpressionIsAlwaysNull
var result = input.NewlinesToBr();
Assert.IsNull(result);
}
}
[TestFixture]
public class When_asked_to_convert_to_title_case
{
[Test]
public void Should_return_the_empty_string_for_string_of_length_zero()
{
Assert.AreEqual("", "".ToTitleCase());
}
[Test]
public void Should_return_the_letter_in_caps_for_string_of_length_equal_to_one()
{
Assert.AreEqual("V", "v".ToTitleCase());
}
[Test]
public void Should_return_the_string_in_title_case_for_string_of_length_greater_than_one()
{
Assert.AreEqual("Value", "value".ToTitleCase());
}
}
[TestFixture]
public class When_asked_to_get_a_non_null_value_for_a_string
{
[Test]
public void Should_return_the_string_given_a_non_null_input()
{
const string input = "hello";
var result = input.ToNonNull();
result.ShouldBeEqualTo(input);
}
[Test]
public void Should_return_the_string_given_a_null_input()
{
const string input = null;
var result = input.ToNonNull();
result.ShouldNotBeNull();
}
}
[TestFixture]
public class When_asked_to_get_an_MD5_hash
{
[Test]
public void Given__The_quick_brown_fox_jumps_over_the_lazy_dog()
{
// http://en.wikipedia.org/wiki/Md5
const string input = "The quick brown fox jumps over the lazy dog";
var result = input.GetMD5Hash();
result.ShouldBeEqualTo("9e107d9d372bb6826bd81d3542a419d6");
}
[Test]
public void Given_an_empty_string()
{
// http://en.wikipedia.org/wiki/Md5
const string input = "";
var result = input.GetMD5Hash();
result.ShouldBeEqualTo("d41d8cd98f00b204e9800998ecf8427e");
}
}
[UsedImplicitly]
public class When_asked_to_group_items_in_a_string_array
{
[TestFixture]
public class Given_a_null_separator
{
[Test]
public void Should_throw_an_exception()
{
var lines = new string[0];
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
Assert.Throws<ArgumentException>(() => lines.GroupBy(null));
}
}
[TestFixture]
public class Given_an_array_containing_data_and_a_trailing_separator
{
[Test]
public void Should_return_the_data_in_one_group()
{
var lines = new[] { "a", "b", "c" };
var grouped = lines.GroupBy("c");
grouped.Count.ShouldBeEqualTo(1);
grouped.First().ShouldContainAllInOrder(new[] { "a", "b" });
}
}
[TestFixture]
public class Given_an_array_containing_data_then_a_separator_then_more_data
{
[Test]
public void Should_return_the_data_in_one_group()
{
var lines = new[] { "a", "b", "c", "d", "e" };
var grouped = lines.GroupBy("c");
grouped.Count.ShouldBeEqualTo(2);
grouped.First().ShouldContainAllInOrder(new[] { "a", "b" });
grouped.Last().ShouldContainAllInOrder(new[] { "d", "e" });
}
}
[TestFixture]
public class Given_an_array_containing_only_multiple_copies_of_the_separator
{
[Test]
public void Should_return_an_empty_group_for_each_instance_of_the_separator()
{
var lines = new[] { "a", "a", "a" };
var grouped = lines.GroupBy("a");
grouped.Count.ShouldBeEqualTo(lines.Length);
grouped.First().Count.ShouldBeEqualTo(0);
grouped.Skip(1).First().Count.ShouldBeEqualTo(0);
grouped.Skip(2).First().Count.ShouldBeEqualTo(0);
}
}
[TestFixture]
public class Given_an_array_containing_only_one_copy_of_the_separator
{
[Test]
public void Should_return_an_empty_group()
{
var lines = new[] { "a" };
var grouped = lines.GroupBy("a");
grouped.Count.ShouldBeEqualTo(lines.Length);
grouped.First().Count.ShouldBeEqualTo(0);
}
}
[TestFixture]
public class Given_an_array_that_does_not_contain_the_separator
{
[Test]
public void Should_return_the_entire_input_in_a_single_group()
{
var lines = new[] { "a", "b", "c" };
var grouped = lines.GroupBy("d");
grouped.Count.ShouldBeEqualTo(1);
grouped.First().ShouldContainAllInOrder(lines);
}
}
[TestFixture]
public class Given_an_empty_array
{
[Test]
public void Should_return_an_empty_list()
{
var lines = new string[0];
var grouped = lines.GroupBy("");
grouped.ShouldNotBeNull();
grouped.Count.ShouldBeEqualTo(0);
}
}
[TestFixture]
public class Given_data_lines_containing_only_whitespace
{
[Test]
public void Should_remove_the_whitespace_lines()
{
var lines = new[] { " ", "\t", "a", "\r", "\n" };
var grouped = lines.GroupBy("d");
grouped.Count.ShouldBeEqualTo(1);
grouped.First().Count.ShouldBeEqualTo(1);
grouped.First().ShouldContainAllInOrder(new[] { "a" });
}
}
}
[TestFixture]
public class When_asked_to_make_a_string_plural
{
[Test]
public void Should_add__es__if_the_input_ends_with__ch()
{
const string input = "church";
Assert.AreEqual("churches", input.ToPlural());
}
[Test]
public void Should_add__es__if_the_input_ends_with__s()
{
const string input = "atlas";
Assert.AreEqual("atlases", input.ToPlural());
}
[Test]
public void Should_add__es__if_the_input_ends_with__sh()
{
const string input = "bush";
Assert.AreEqual("bushes", input.ToPlural());
}
[Test]
public void Should_add__es__if_the_input_ends_with__x()
{
const string input = "Box";
Assert.AreEqual("Boxes", input.ToPlural());
}
[Test]
public void Should_add__s__if_the_input_does_not_end_with__y_x_sh_ch__or__s()
{
const string input = "cat";
Assert.AreEqual(input + "s", input.ToPlural());
}
[Test]
public void Should_add__s__if_the_input_ends_with_a_vowel_followed_by__y()
{
const string input = "day";
Assert.AreEqual("days", input.ToPlural());
}
[Test]
public void Should_replace__y__with__ies__if_the_input_ends_with_a_consonant_followed_by__y()
{
const string input = "pony";
Assert.AreEqual("ponies", input.ToPlural());
}
}
[TestFixture]
public class When_asked_to_prefix_a_string_with_a_or_an
{
[Test]
public void Should_prefix_with__a__if_the_input_does_not_start_with__a_e_i_o_u__or_h()
{
const string input = "cat";
input.PrefixWithAOrAn().ShouldBeEqualTo("a " + input);
}
[Test]
public void Should_prefix_with__a__if_the_input_starts_with__ha()
{
const string input = "Hawaii";
input.PrefixWithAOrAn().ShouldBeEqualTo("a " + input);
}
[Test]
public void Should_prefix_with__a__if_the_input_starts_with__hot()
{
const string input = "Hotel";
input.PrefixWithAOrAn().ShouldBeEqualTo("a " + input);
}
[Test]
public void Should_prefix_with__a__if_the_input_starts_with__uni()
{
const string input = "Unicorn";
input.PrefixWithAOrAn().ShouldBeEqualTo("a " + input);
}
[Test]
public void Should_prefix_with__a__if_the_input_starts_with__ut_but_not_with_utt()
{
const string input = "Utah";
input.PrefixWithAOrAn().ShouldBeEqualTo("a " + input);
}
[Test]
public void Should_prefix_with__an__if_the_input_starts_with__a()
{
const string input = "Aardvark";
input.PrefixWithAOrAn().ShouldBeEqualTo("an " + input);
}
[Test]
public void Should_prefix_with__an__if_the_input_starts_with__e()
{
const string input = "Egret";
input.PrefixWithAOrAn().ShouldBeEqualTo("an " + input);
}
[Test]
public void Should_prefix_with__an__if_the_input_starts_with__h_but_not_with_hot()
{
const string input = "Hour";
input.PrefixWithAOrAn().ShouldBeEqualTo("an " + input);
}
[Test]
public void Should_prefix_with__an__if_the_input_starts_with__i()
{
const string input = "Ibex";
input.PrefixWithAOrAn().ShouldBeEqualTo("an " + input);
}
[Test]
public void Should_prefix_with__an__if_the_input_starts_with__o()
{
const string input = "Ocelot";
input.PrefixWithAOrAn().ShouldBeEqualTo("an " + input);
}
[Test]
public void Should_prefix_with__an__if_the_input_starts_with__u_but_not_with_uni()
{
const string input = "Uncle";
input.PrefixWithAOrAn().ShouldBeEqualTo("an " + input);
}
[Test]
public void Should_prefix_with__an__if_the_input_starts_with__uni()
{
const string input = "Unicorn";
input.PrefixWithAOrAn().ShouldBeEqualTo("a " + input);
}
[Test]
public void Should_prefix_with__an__if_the_input_starts_with__utt()
{
const string input = "Utter";
input.PrefixWithAOrAn().ShouldBeEqualTo("an " + input);
}
}
[TestFixture]
public class When_asked_to_replace_old_values_with_new_values_in_a_string
{
private const string NewValue = "New";
private const string OldValue = "Old";
[Test]
public void Should_replace_the_old_values_with_new_values_if_the_string_is_not_null()
{
const string input = "Old Value";
var result = input.ReplaceIfExists(OldValue, NewValue);
Assert.AreEqual("New Value", result);
}
[Test]
public void Should_return_null_if_the_input_is_null()
{
const string input = null;
// ReSharper disable once ExpressionIsAlwaysNull
var result = input.ReplaceIfExists(OldValue, NewValue);
Assert.IsNull(result);
}
[Test]
public void Should_return_the_input_as_is_if_the_old_value_is_null_or_empty()
{
const string input = "Old Value";
var result = input.ReplaceIfExists("", NewValue);
Assert.AreEqual(input, result);
}
}
[TestFixture]
public class When_asked_to_trim_if_longer_than_certain_length
{
private const int MaxLength = 10;
[Test]
public void Should_return_the_string_as_is_if_it_is_shorter_than_specified_length()
{
const string item = "Test";
item.TrimIfLongerThan(MaxLength).ShouldBeEqualTo(item);
}
[Test]
public void Should_return_the_trimmed_string_if_it_is_longer_than_specified_length()
{
const string item = "Test on the horizon";
item.TrimIfLongerThan(MaxLength).ShouldBeEqualTo(item.Substring(0, MaxLength));
}
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections.Specialized;
using System.IO;
using System.Text.RegularExpressions;
namespace DBlog.Tools.Web
{
public class Renderer
{
public Renderer()
{
}
public static string Render(object message)
{
if (message == null) return string.Empty;
return Render(message.ToString());
}
public static string Render(string message)
{
if (message == null) return string.Empty;
string result = HttpUtility.HtmlEncode(message);
if (result.IndexOf("<P>", StringComparison.InvariantCultureIgnoreCase) < 0)
{
result = result.Replace("\n", "<br/>\n");
}
return result;
}
public static string RenderEx(object message, string basehref, string rewritehref)
{
if (message == null) return string.Empty;
return RenderEx(message.ToString(), basehref, rewritehref);
}
public static string RenderEx(string message, string basehref, string rewritehref)
{
string result = CleanHtml(message, basehref, rewritehref);
if (result.IndexOf("<P>", StringComparison.InvariantCultureIgnoreCase) < 0)
{
result = result.Replace("\n", "<br/>\n");
}
return result;
}
public static Regex HtmlExpression = new Regex(@"<[^>]*>", RegexOptions.IgnoreCase);
public static Regex BrExpression = new Regex(@"<br[\/ ]*>", RegexOptions.IgnoreCase);
public static string RemoveHtml(object message)
{
if (message == null) return string.Empty;
return RemoveHtml(message.ToString());
}
public static string RemoveHtml(string message)
{
message = BrExpression.Replace(message, "\n");
message = HtmlExpression.Replace(message, string.Empty);
message = message.Trim('\n');
return message;
}
public static string CleanHtml(object message)
{
if (message == null) return string.Empty;
return CleanHtml(message.ToString());
}
public static string CleanHtml(string html)
{
return CleanHtml(html, null, null);
}
public static string CleanHtml(string html, string basehref, string rewritehref)
{
try
{
Html.HtmlReader r = new Html.HtmlReader(html);
StringWriter sw = new StringWriter();
Html.HtmlWriter w = new Html.HtmlWriter(sw);
if (!string.IsNullOrEmpty(basehref)) w.Options.BaseHref = new Uri(basehref);
if (!string.IsNullOrEmpty(rewritehref)) w.Options.RewriteHref = new Uri(rewritehref);
while (! r.EOF)
{
w.WriteNode(r, true);
}
w.Close();
return sw.ToString();
}
catch (Exception e)
{
return e.Message;
}
}
public static string UrlEncode(string message)
{
if (message == null) return string.Empty;
return HttpUtility.UrlEncode(message);
}
public static string UrlEncode(object message)
{
if (message == null) return string.Empty;
return UrlEncode(message.ToString());
}
public static string UrlDecode(string message)
{
if (message == null) return string.Empty;
return HttpUtility.UrlDecode(message);
}
public static string UrlDecode(object message)
{
if (message == null) return string.Empty;
return UrlDecode(message.ToString());
}
static string HrefHandler(Match ParameterMatch)
{
string result = ParameterMatch.Value;
// quoted results within other tags are ignored
if (result.StartsWith("\"") && result.EndsWith("\""))
return result;
string afterresult = string.Empty;
const string punctutation = ".,;:";
while ((result.Length > 0) && (punctutation.IndexOf(result[result.Length - 1]) >= 0))
{
afterresult = afterresult + result[result.Length - 1];
result = result.Remove(result.Length - 1, 1);
}
string shortenedresult = result;
int cut = shortenedresult.IndexOf("?");
if (cut >= 0)
{
shortenedresult = shortenedresult.Substring(0, cut) + " ...";
}
result = RemoveMarkups(result);
result = string.Format("<a target=\"_blank\" href=\"{0}\">{1}</a>{2}",
result,
shortenedresult,
afterresult);
return result;
}
public static Regex HrefExpression = new Regex(@"[\'\""]{0,1}[\w]+://[a-zA-Z0-9\/\,\(\)\.\?\&+\##\%~=:;_\-\@]*[\'\""]{0,1}", RegexOptions.IgnoreCase);
public static string RenderHref(string RenderValue)
{
MatchEvaluator HrefHandlerDelegate = new MatchEvaluator(HrefHandler);
return HrefExpression.Replace(RenderValue, HrefHandlerDelegate);
}
class NameValueMap : StringDictionary
{
public NameValueMap()
{
Add("[small]", "<small>");
Add("[/small]", "</small>");
Add("[h1]", "<h1>");
Add("[h2]", "<h2>");
Add("[h3]", "<h3>");
Add("[big]", "<big>");
Add("[/h1]", "</h1>");
Add("[/h2]", "</h2>");
Add("[/h3]", "</h3>");
Add("[/big]", "</big>");
Add("[b]", "<b>");
Add("[/b]", "</b>");
Add("[em]", "<em>");
Add("[/em]", "</em>");
Add("[i]", "<em>");
Add("[/i]", "</em>");
Add("[red]", "<font color=\"red\">");
Add("[/red]", "</font>");
Add("[green]", "<font color=\"green\">");
Add("[/green]", "</font>");
Add("[blue]", "<font color=\"blue\">");
Add("[/blue]", "</font>");
Add("[img]", "<img border=\"0\" src=\"");
Add("[/img]", "\">");
Add("[image]", "<img border=\"0\" src=\"");
Add("[/image]", "\"/>");
Add("[center]", "<div style=\"text-align: center;\">");
Add("[/center]", "</div>");
Add("[code]", "<div class=code><pre>");
Add("[/code]", "</pre></div>");
}
};
static NameValueMap sMarkupMap = new NameValueMap();
static string MarkupHandler(Match ParameterMatch)
{
string word = ParameterMatch.Value;
if (word.StartsWith("[[") && word.EndsWith("]]"))
return word.Substring(1, word.Length - 2);
string result = sMarkupMap[word];
return string.IsNullOrEmpty(result) ? word : result;
}
static string MarkupClearHandler(Match ParameterMatch)
{
return string.Empty;
}
static Regex MarkupExpression = new Regex(@"[\[]+\/*\w*[\]]+", RegexOptions.IgnoreCase);
public static string RenderMarkups(string RenderValue)
{
MatchEvaluator MarkupHandlerDelegate = new MatchEvaluator(MarkupHandler);
return MarkupExpression.Replace(RenderValue, MarkupHandlerDelegate);
}
public static string RemoveMarkups(string RenderValue)
{
MatchEvaluator MarkupHandlerDelegate = new MatchEvaluator(MarkupClearHandler);
return MarkupExpression.Replace(RenderValue, MarkupHandlerDelegate);
}
public static string SqlEncode(string Value)
{
return Value.Replace("'", "''");
}
public static string GetSummary(string summary)
{
string result = RemoveHtml(RemoveMarkups(summary));
if (result.Length > 256) result = result.Substring(0, 256) + " ...";
return result;
}
public static string GetLink(string uri, string text)
{
return string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", uri, text);
}
public static string ToRfc822(DateTime value)
{
return string.Format("{0} GMT",
value.ToString("ddd, dd MMM yyyy HH:mm:ss"));
}
/// <summary>
/// Transform a string into a slug.
/// See http://www.intrepidstudios.com/blog/2009/2/10/function-to-generate-a-url-friendly-string.aspx
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string ToSlug(string s)
{
s = s.ToLower();
// invalid chars, make into spaces
s = Regex.Replace(s, @"[^a-z0-9\s-]", "");
// convert multiple spaces/hyphens into one space
s = Regex.Replace(s, @"[\s-]+", " ").Trim();
// hyphens
s = Regex.Replace(s, @"\s", "-");
return s;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Timers;
using Nalarium;
using NetInterop.Routing.Core;
namespace NetInterop.Routing.Ospf
{
[DebuggerDisplay("Address: {Address}, RouterID: {RouterID}, DR: {DR}, BDR: {BDR}")]
internal class Neighbor
{
private static readonly object Lock = new object();
private StateMachine<OspfNeighborState, NeighborEventType> _stateMachine;
private RoutingController _controller;
private Timer _dbdResendTimer;
private bool _hasAttemptedAdjacency;
private uint _helloInterval;
private Timer _inactivityTimer;
private Timer _sendTimer;
private DateTime _dbdSendTimerLastSend;
private bool _isNew = true;
private byte _priority;
private Map<uint, Tuple<IPAddress, OspfDbdHeader, OspfLlsDataBlockHeader, OspfLlsDataBlockTlv>> _dbdSendList;
private MapEntry<uint, Tuple<IPAddress, OspfDbdHeader, OspfLlsDataBlockHeader, OspfLlsDataBlockTlv>> _dbdPendingAck;
private OspfModule Module { get; set; }
private Interface Interface { get; set; }
private MasterSlaveState LocalMSState { get; set; }
private OspfOptions DiscoveredOptions { get; set; }
private uint DDSequenceNumber { get; set; }
private OspfDbdHeader LastOspfDBDSeen { get; set; }
private object LastReceivedDBD { get; set; }
private List<OspfLsaHeader> LSRetransmissionList { get; set; }
private List<OspfLsaHeader> DBSummaryList { get; set; }
private List<OspfLsaHeader> LSRequestList { get; set; }
internal IPAddress Address { get; set; }
internal IPAddress DR { get; set; }
internal IPAddress BDR { get; set; }
private OspfNeighborState _ospfNeighborState;
internal OspfNeighborState OspfNeighborState
{
get
{
return _ospfNeighborState;
}
set
{
_ospfNeighborState = value;
Log.Write("OSPF", "NEIGHBOR", "State change: " + value);
}
}
internal IPAddress RouterID { get; set; }
public byte Priority
{
get
{
return _priority;
}
set
{
if (value < 0)
{
throw new InvalidOperationException("Priority must be at least 0.");
}
_priority = value;
}
}
public DateTime LastSeen { get; set; }
//public uint RouterDeadInterval { get; set; }
//public uint HelloInterval
//{
// get
// {
// return _helloInterval;
// }
// set
// {
// _inactivityTimer.Interval = value;
// _helloInterval = value;
// }
//}
private Neighbor()
{
}
private static Neighbor QuickCreate(IPAddress dr, IPAddress bdr)
{
return new Neighbor
{
DR = dr,
BDR = bdr
};
}
public static Neighbor Create(OspfModule module, RoutingController controller, Interface ospfInterface, IPAddress source, IPAddress rid, OspfOptions options, byte priority, IPAddress dr, IPAddress bdr)
{
var n = new Neighbor
{
_controller = controller,
Module = module,
Interface = ospfInterface,
RouterID = rid,
DiscoveredOptions = options,
//TODO: is THIS the source??
Address = source,
Priority = priority,
OspfNeighborState = OspfNeighborState.Down,
DR = dr,
BDR = bdr,
LastSeen = DateTime.Now
};
n.Init();
return n;
}
private void Init()
{
_sendTimer = new Timer(100);
_inactivityTimer = new Timer();
InitListData();
_stateMachine = new StateMachine<OspfNeighborState, NeighborEventType>();
////++ NBMA
////_stateMachine.Add(OspfNeighborState.Down, NeighborEventType.Start, Start);
////_stateMachine.Add(OspfNeighborState.Attempt, NeighborEventType.HelloReceived, HelloReceived);
_stateMachine.Add(OspfNeighborState.Down, NeighborEventType.HelloReceived, HelloReceived, nextState: OspfNeighborState.Init);
_stateMachine.Add(OspfNeighborState.Init, NeighborEventType.HelloReceived, HelloReceived, StateEntryMode.AtLeast, nextStateMode: NextStateMode.NoAction);
_stateMachine.Add(OspfNeighborState.Init, NeighborEventType.TwoWayReceived, TwoWayReceived);
_stateMachine.Add(OspfNeighborState.ExStart, NeighborEventType.NegotiationDone, NegotiationDone);
_stateMachine.Add(OspfNeighborState.Exchange, NeighborEventType.ExchangeDone, ExchangeDone);
//_stateMachine.Add(OspfNeighborState.Loading, NeighborEventType.LoadingDone, LoadingDone);
_stateMachine.Add(OspfNeighborState.TwoWay, NeighborEventType.AdjOK, AdjOK);
_stateMachine.Add(OspfNeighborState.ExStart, NeighborEventType.AdjOK, AdjOK, StateEntryMode.AtLeast);
_stateMachine.Add(OspfNeighborState.Exchange, NeighborEventType.SeqNumberMismatch, SeqNumberMismatch, StateEntryMode.AtLeast);
//_stateMachine.Add(OspfNeighborState.Exchange, NeighborEventType.BadLSReq, BadLSReq, StateEntryMode.AtLeast);
_stateMachine.Add(NeighborEventType.KillNbr, (s, e, o) =>
{
InitListData();
_inactivityTimer.Stop();
}, OspfNeighborState.Down);
_stateMachine.Add(NeighborEventType.LLDown, (s, e, o) =>
{
InitListData();
_inactivityTimer.Stop();
}, OspfNeighborState.Down);
_stateMachine.Add(NeighborEventType.InactivityTimer, (s, e, o) => InitListData(), OspfNeighborState.Down);
_stateMachine.Add(OspfNeighborState.TwoWay, NeighborEventType.OneWayReceived, (s, e, o) => InitListData(), StateEntryMode.AtLeast, OspfNeighborState.Init);
_stateMachine.Add(OspfNeighborState.TwoWay, NeighborEventType.TwoWayReceived, StateEntryMode.AtLeast, NextStateMode.NoAction);
_stateMachine.Add(OspfNeighborState.Init, NeighborEventType.OneWayReceived, NextStateMode.NoAction);
_sendTimer.Elapsed += (s, e) =>
{
SendDBDReady();
};
_sendTimer.Start();
}
private void InitListData()
{
LSRetransmissionList = new List<OspfLsaHeader>();
DBSummaryList = new List<OspfLsaHeader>();
LSRequestList = new List<OspfLsaHeader>();
_dbdSendList = new Map<uint, Tuple<IPAddress, OspfDbdHeader, OspfLlsDataBlockHeader, OspfLlsDataBlockTlv>>();
}
private void HelloReceived(OspfNeighborState state, NeighborEventType evt, object data)
{
_inactivityTimer = new Timer();
_inactivityTimer.Interval = 1000;
_inactivityTimer.Elapsed += (s, e) =>
{
if ((DateTime.Now - LastSeen).Seconds > Interface.RouterDeadInterval)
{
RaiseEvent(NeighborEventType.InactivityTimer);
}
};
_inactivityTimer.Start();
OspfNeighborState nextState;
if (_stateMachine.GetNext(state, evt, out nextState))
{
OspfNeighborState = nextState;
}
}
private void TwoWayReceived(OspfNeighborState state, NeighborEventType evt, object data)
{
var tupleData = data as Tuple<IPHeader, OspfHeader, Tuple<IPAddress, IPAddress>>;
var dr = tupleData.Item3.Item1;
var bdr = tupleData.Item3.Item2;
var newTupleData = new Tuple<IPAddress, IPAddress, IPAddress>(dr, bdr, tupleData.Item1.SourceAddress);
if (ShouldBeAdjacent(newTupleData))
{
ProcessAdjacency(newTupleData);
}
else
{
OspfNeighborState = OspfNeighborState.TwoWay;
}
}
private void ProcessAdjacency(Tuple<IPAddress, IPAddress, IPAddress> tupleData)
{
OspfNeighborState = OspfNeighborState.ExStart;
if (_hasAttemptedAdjacency)
{
DDSequenceNumber++;
}
else
{
//++ sending blank DBDs to start things off
DDSequenceNumber = (uint)DateTime.Now.Ticks;
LocalMSState = MasterSlaveState.Master;
Action sendDBD = () =>
{
_dbdPendingAck = null;
PrepareSendDBD(tupleData.Item3, GetDBDOptions(isFirstRun: true, hasMore: true));
};
//_dbdResendTimer = new Timer(1000);
//_dbdResendTimer.Elapsed += (s, e) =>
// {
// //TODO: does this need a "stillWaitingOnFirst" check or something?
// if ((DateTime.Now - _dbdSendTimerLastSend).Seconds == Interface.RxmtInterval)
// {
// sendDBD();
// }
// };
sendDBD();
_dbdSendTimerLastSend = DateTime.Now;
//_dbdResendTimer.Start();
//TODO: should this ever be reset?
_hasAttemptedAdjacency = true;
}
}
private void NegotiationDone(OspfNeighborState state, NeighborEventType evt, object data)
{
var tupleData = data as Tuple<IPHeader, OspfHeader, object>;
//+
DBSummaryList.AddRange(Interface.Area.RouterLSAMap.Values.Where(p => p.CommonHeader.LSAge < Constant.MaxAge).Select(p => p.CommonHeader));
LSRetransmissionList.AddRange(Interface.Area.RouterLSAMap.Values.Where(p => p.CommonHeader.LSAge >= Constant.MaxAge).Select(p => p.CommonHeader));
//+
DBSummaryList.AddRange(Interface.Area.NetworkLSAMap.Values.Where(p => p.CommonHeader.LSAge < Constant.MaxAge).Select(p => p.CommonHeader));
LSRetransmissionList.AddRange(Interface.Area.NetworkLSAMap.Values.Where(p => p.CommonHeader.LSAge >= Constant.MaxAge).Select(p => p.CommonHeader));
//+
DBSummaryList.AddRange(Interface.Area.SummaryLSAMap.Values.Where(p => p.CommonHeader.LSAge < Constant.MaxAge).Select(p => p.CommonHeader));
LSRetransmissionList.AddRange(Interface.Area.SummaryLSAMap.Values.Where(p => p.CommonHeader.LSAge >= Constant.MaxAge).Select(p => p.CommonHeader));
//+
if (Interface.OspfNetworkType != OspfNetworkType.VirtualLink && Interface.Area.ExternalRoutingCapability)
{
DBSummaryList.AddRange(Module.ASExternalLSAMap.Values.Where(p => p.CommonHeader.LSAge < Constant.MaxAge).Select(p => p.CommonHeader));
LSRetransmissionList.AddRange(Module.ASExternalLSAMap.Values.Where(p => p.CommonHeader.LSAge < Constant.MaxAge).Select(p => p.CommonHeader));
}
OspfNeighborState = OspfNeighborState.Exchange;
}
private void AdjOK(OspfNeighborState state, NeighborEventType evt, object data)
{
var tupleData = data as Tuple<IPAddress, IPAddress, IPAddress>;
if (OspfNeighborState == OspfNeighborState.TwoWay)
{
if (ShouldBeAdjacent(tupleData))
{
OspfNeighborState = OspfNeighborState.ExStart;
ProcessAdjacency(tupleData);
}
}
else if (OspfNeighborState == OspfNeighborState.ExStart)
{
if (!ShouldBeAdjacent(tupleData))
{
InitListData();
OspfNeighborState = OspfNeighborState.TwoWay;
}
}
}
private void ExchangeDone(OspfNeighborState state, NeighborEventType evt, object data)
{
if (LSRequestList.Count == 0)
{
OspfNeighborState = OspfNeighborState.Full;
}
else
{
OspfNeighborState = OspfNeighborState.Loading;
BeginLSRProcess();
}
}
private void BeginLSRProcess()
{
var headerList = new List<IHeader>();
foreach (var lsaHeader in LSRequestList)
{
var header = (OspfLsrHeader)_controller.GetSingletonHandler("OSPFDBD").Build(
Value.Create("OspfLSRHeader:Type", lsaHeader.LSType),
Value.Create("OspfLSRHeader:LSID", lsaHeader.LSID),
Value.Create("OspfLSRHeader:AdvertisingRouter", lsaHeader.AdvertisingRouter));
headerList.Add(header);
}
//TODO: is this address right?
//TODO: need a RxmtInterval timer here
Module.ContinueSend(Interface.DeviceID, Address, headerList.ToArray(), Value.Raw("OspfHeader:Type", (byte)OspfPacketType.LinkStateRequest));
}
private void SeqNumberMismatch(OspfNeighborState state, NeighborEventType evt, object data)
{
var tupleData = data as Tuple<IPHeader, OspfHeader, Tuple<OspfDbdHeader, OspfLsaHeader[]>>;
OspfNeighborState = OspfNeighborState.ExStart;
InitListData();
DDSequenceNumber++;
LocalMSState = MasterSlaveState.Master;
PrepareSendDBD(tupleData.Item1.SourceAddress, GetDBDOptions(isFirstRun: true, hasMore: true));
}
private DBDOptions GetDBDOptions(bool isFirstRun, bool hasMore)
{
var options = new DBDOptions();
if (isFirstRun)
{
options |= DBDOptions.Initial;
}
if (LocalMSState == MasterSlaveState.Master)
{
options |= DBDOptions.Master;
}
if (hasMore)
{
options |= DBDOptions.More;
}
return options;
}
private void PrepareSendDBD(IPAddress destinationAddress, DBDOptions dbdOptions, Boolean sendLsaHeaderData = false)
{
lock (Lock)
{
//++ parsers build the header
ushort mtu = Interface.OspfNetworkType == OspfNetworkType.VirtualLink ? (ushort)0 : OspfDbdHeader.EthernetAndP2PMtu;
var ospfLlsDataBlockTlv = (OspfLlsDataBlockTlv)_controller.GetSingletonHandler("OSPFLLSDATABLOCKTLV").Build();
var ospfLlsDataBlockHeader = (OspfLlsDataBlockHeader)_controller.GetSingletonHandler("OSPFLLSDATABLOCK").Build();
List<OspfLsaHeader> headerList = null;
if (sendLsaHeaderData)
{
headerList = DBSummaryList;
}
var dbdHeader = (OspfDbdHeader)_controller.GetSingletonHandler("OSPFDBD").Build(
Value.Raw("OspfDbdHeader:Mtu", mtu),
Value.Raw("OspfDbdHeader:Options", (byte)Interface.Area.GetOptions(supportOBit: true)),
Value.Raw("OspfDbdHeader:Flags", (byte)dbdOptions),
Value.Raw("OspfDbdHeader:SequenceNumber", DDSequenceNumber));
dbdHeader.LsaList = headerList;
_dbdSendList.Add(DDSequenceNumber, new Tuple<IPAddress, OspfDbdHeader, OspfLlsDataBlockHeader, OspfLlsDataBlockTlv>(destinationAddress, dbdHeader, ospfLlsDataBlockHeader, ospfLlsDataBlockTlv));
SendDBDReady();
}
}
private void SendDBDReady()
{
if (_dbdPendingAck != null && (DateTime.Now - _dbdSendTimerLastSend).Seconds >= Interface.RxmtInterval)
{
_dbdSendList.Add(_dbdPendingAck.Key, _dbdPendingAck.Value);
_dbdPendingAck = null;
}
if (_dbdPendingAck == null && _dbdSendList.Count > 0)
{
var dbd = _dbdSendList.OrderBy(p => p.Key).FirstOrDefault();
_dbdSendList.Remove(dbd.Key);
if (dbd.Value != null)
{
_dbdPendingAck = MapEntry<uint, Tuple<IPAddress, OspfDbdHeader, OspfLlsDataBlockHeader, OspfLlsDataBlockTlv>>.Create(dbd.Key, dbd.Value);
_dbdSendTimerLastSend = DateTime.Now;
var count = dbd.Value.Item2.LsaList == null ? 0 : dbd.Value.Item2.LsaList.Count;
Log.Write("OSPF", "NEIGHBOR", string.Format("Sending DBD (to {0}). SN: {1}, LSA count: {2}, List count: {3}", dbd.Value.Item1, dbd.Value.Item2.SequenceNumber, count, _dbdSendList.Count));
SendDBD(dbd.Value);
}
}
}
private void SendDBD(Tuple<IPAddress, OspfDbdHeader, OspfLlsDataBlockHeader, OspfLlsDataBlockTlv> data)
{
var destinationAddress = data.Item1;
var dbdHeader = data.Item2;
var ospfLlsDataBlockHeader = data.Item3;
var ospfLlsDataBlockTlv = data.Item4;
Module.ContinueSend(Interface.DeviceID, destinationAddress, ospfLlsDataBlockTlv, ospfLlsDataBlockHeader, dbdHeader,
Value.Raw("OspfHeader:Type", (byte)OspfPacketType.DatabaseDescriptor));
}
private bool ShouldBeAdjacent(Tuple<IPAddress, IPAddress, IPAddress> tupleData)
{
IPAddress dr = tupleData.Item1 == IPAddress.GetDefault() ? DR : tupleData.Item1;
IPAddress bdr = tupleData.Item2 == IPAddress.GetDefault() ? BDR : tupleData.Item2;
IPAddress saddr = tupleData.Item3;
if (Interface.OspfNetworkType == OspfNetworkType.PointToPoint ||
Interface.OspfNetworkType == OspfNetworkType.PointToMultiPoint ||
Interface.OspfNetworkType == OspfNetworkType.VirtualLink)
{
return true;
}
else if (Interface.IsDR || Interface.IsDR)
{
return true;
}
else if (saddr == dr || saddr == bdr)
{
return true;
}
return false;
}
internal void OnHelloReceive(IPHeader ipHeader, OspfHeader ospfHeader, OspfHelloHeader ospfHelloHeader)
{
lock (Lock)
{
LastSeen = DateTime.Now;
Log.Write("OSPF", "NEIGHBOR", string.Format("Hello received. From: {0}, State: {1}", ospfHeader.RouterID, OspfNeighborState));
RaiseEvent(NeighborEventType.HelloReceived);
if (ospfHelloHeader.Neighbor.Any(p => p == Module.RouterID))
{
var tupleData = new Tuple<IPHeader, OspfHeader, Tuple<IPAddress, IPAddress>>(ipHeader, ospfHeader,
new Tuple<IPAddress, IPAddress>(ospfHelloHeader.Dr, ospfHelloHeader.Bdr));
RaiseEvent(NeighborEventType.TwoWayReceived, tupleData);
}
else
{
var tupleData = new Tuple<IPHeader, OspfHeader, object>(ipHeader, ospfHeader, ospfHelloHeader);
RaiseEvent(NeighborEventType.OneWayReceived, tupleData);
}
}
}
internal void OnDBDReceive(IPHeader ipHeader, OspfHeader ospfHeader, Tuple<OspfDbdHeader, OspfLsaHeader[]> dbdHeaderData)
{
lock (Lock)
{
Log.Write("OSPF", "NEIGHBOR", string.Format("DBD received. From: {0}, State: {1}", ospfHeader.RouterID, OspfNeighborState));
var tupleData = new Tuple<IPHeader, OspfHeader, Tuple<OspfDbdHeader, OspfLsaHeader[]>>(ipHeader, ospfHeader, dbdHeaderData);
var ospfDBDHeader = dbdHeaderData.Item1;
var ospfLsaHeaderArray = (OspfLsaHeader[])dbdHeaderData.Item2;
switch (OspfNeighborState)
{
case OspfNeighborState.Down:
case OspfNeighborState.Attempt:
return;
case OspfNeighborState.Init:
RaiseEvent(NeighborEventType.TwoWayReceived, new Tuple<IPHeader, OspfHeader, Tuple<IPAddress, IPAddress>>(ipHeader, ospfHeader,
new Tuple<IPAddress, IPAddress>(DR, BDR)));
return;
case OspfNeighborState.TwoWay:
return;
case OspfNeighborState.ExStart:
if (ospfDBDHeader.IsInitial &&
ospfDBDHeader.HasMore &&
ospfDBDHeader.IsMaster &&
(dbdHeaderData.Item2 == null || ospfLsaHeaderArray.Length == 0) &&
ospfHeader.RouterID > Module.RouterID)
{
Log.Write("OSPF", "NEIGHBOR---------EXSTART", "IS SLAVE TO " + ospfHeader.RouterID);
LocalMSState = MasterSlaveState.Slave;
_dbdPendingAck = null;
DDSequenceNumber = ospfDBDHeader.SequenceNumber;
LastOspfDBDSeen = ospfDBDHeader;
DiscoveredOptions = ospfDBDHeader.OspfOptions;
RaiseEvent(NeighborEventType.NegotiationDone);
ProcessDBD(tupleData);
}
else if (!ospfDBDHeader.IsInitial && !ospfDBDHeader.IsMaster &&
DDSequenceNumber == dbdHeaderData.Item1.SequenceNumber &&
ospfHeader.RouterID < Module.RouterID)
{
Log.Write("OSPF", "NEIGHBOR---------EXSTART", "IS MASTER OF" + ospfHeader.RouterID);
LocalMSState = MasterSlaveState.Master;
_dbdPendingAck = null;
LastOspfDBDSeen = ospfDBDHeader;
DiscoveredOptions = ospfDBDHeader.OspfOptions;
RaiseEvent(NeighborEventType.NegotiationDone);
ProcessDBD(tupleData);
}
return;
case OspfNeighborState.Exchange:
//TODO: duplicate check?
if (dbdHeaderData.Item1.IsMaster && LocalMSState == MasterSlaveState.Master)
{
RaiseEvent(NeighborEventType.SeqNumberMismatch,
new Tuple<IPHeader, OspfHeader, Tuple<OspfDbdHeader, OspfLsaHeader[]>>(ipHeader, ospfHeader,
new Tuple<OspfDbdHeader, OspfLsaHeader[]>(ospfDBDHeader, null)));
return;
}
else if (!dbdHeaderData.Item1.IsMaster && LocalMSState == MasterSlaveState.Slave)
{
RaiseEvent(NeighborEventType.SeqNumberMismatch,
new Tuple<IPHeader, OspfHeader, Tuple<OspfDbdHeader, OspfLsaHeader[]>>(ipHeader, ospfHeader,
new Tuple<OspfDbdHeader, OspfLsaHeader[]>(ospfDBDHeader, null)));
return;
}
else if (dbdHeaderData.Item1.IsInitial)
{
RaiseEvent(NeighborEventType.SeqNumberMismatch, tupleData);
return;
}
else if (dbdHeaderData.Item1.OspfOptions != DiscoveredOptions)
{
RaiseEvent(NeighborEventType.SeqNumberMismatch, tupleData);
return;
}
else if ((LocalMSState == MasterSlaveState.Master && dbdHeaderData.Item1.SequenceNumber == DDSequenceNumber) ||
(LocalMSState == MasterSlaveState.Slave && dbdHeaderData.Item1.SequenceNumber == DDSequenceNumber + 1))
{
LastOspfDBDSeen = dbdHeaderData.Item1;
ProcessDBD(tupleData);
RaiseEvent(NeighborEventType.ExchangeDone);
return;
}
else
{
RaiseEvent(NeighborEventType.SeqNumberMismatch, tupleData);
return;
}
case OspfNeighborState.Loading:
break;
case OspfNeighborState.Full:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
private void ProcessDBD(Tuple<IPHeader, OspfHeader, Tuple<OspfDbdHeader, OspfLsaHeader[]>> tupleData)
{
OspfDbdHeader ospfDbdHeader = tupleData.Item3.Item1;
var lsaCount = Collection.IsNullOrEmpty(ospfDbdHeader.LsaList) ? 0 : ospfDbdHeader.LsaList.Count;
Log.Write("OSPF", "NEIGHBOR", string.Format("Processing DBD (from {0}). SN: {1}, LSA count: {2}", tupleData.Item2.RouterID, tupleData.Item3.Item1.SequenceNumber, lsaCount));
//if (ospfDbdHeader.seqnum == _dbdPendingAck.Value.Item2.seqnum)
//{
// _dbdPendingAck = null;
//}
if (!Collection.IsNullOrEmpty(ospfDbdHeader.LsaList))
{
foreach (OspfLsaHeader item in ospfDbdHeader.LsaList)
{
var lsaType = (int)item.OspfLsaType;
//TODO: consider type 7 for NSSA
if (lsaType < 1 || lsaType > 5)
{
RaiseEvent(NeighborEventType.SeqNumberMismatch, tupleData);
continue;
}
else if (lsaType == 5 && !Interface.Area.ExternalRoutingCapability)
{
RaiseEvent(NeighborEventType.SeqNumberMismatch, tupleData);
continue;
}
else
{
switch (item.OspfLsaType)
{
case OspfLsaType.Route:
if (Interface.Area.RouterLSAMap.ContainsKey(item.Key))
{
LSRequestList.Add(item);
}
break;
case OspfLsaType.Network:
if (Interface.Area.NetworkLSAMap.ContainsKey(item.Key))
{
LSRequestList.Add(item);
}
break;
case OspfLsaType.SummaryNetwork:
case OspfLsaType.SummaryAsbr:
if (Interface.Area.SummaryLSAMap.ContainsKey(item.Key))
{
LSRequestList.Add(item);
}
break;
//TODO: do externals even do anything here?
case OspfLsaType.External:
break;
//case OspfLsaType.Nssa:
// break;
}
}
}
}
if (DDSequenceNumber == ospfDbdHeader.SequenceNumber)
{
if (LocalMSState == MasterSlaveState.Master)
{
DDSequenceNumber++;
if (DBSummaryList.Count == 0 && !ospfDbdHeader.HasMore)
{
RaiseEvent(NeighborEventType.ExchangeDone);
}
}
else if (LocalMSState == MasterSlaveState.Slave)
{
DDSequenceNumber = ospfDbdHeader.SequenceNumber;
//++ 1 means about to send last
if (DBSummaryList.Count == 1 && !ospfDbdHeader.HasMore)
{
//++ process will continue with last one
RaiseEvent(NeighborEventType.ExchangeDone);
}
else
{
//++ done; final confirmation
//_currentTxDDSequenceNumber = DDSequenceNumber;
PrepareSendDBD(tupleData.Item1.SourceAddress, GetDBDOptions(isFirstRun: false, hasMore: false), true);
}
}
}
}
internal void RaiseEvent(NeighborEventType eventType, object data = null)
{
lock (Lock)
{
Log.Write("OSPF", "NEIGHBOREVENT", string.Format("State: {0}, Event: {1}", OspfNeighborState, eventType));
_stateMachine.RaiseEvent(OspfNeighborState, eventType, data);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Security;
using System.Threading.Tasks;
namespace System.ServiceModel
{
public abstract class ChannelFactory : CommunicationObject, IChannelFactory, IDisposable
{
private string _configurationName;
private IChannelFactory _innerFactory;
private ServiceEndpoint _serviceEndpoint;
private ClientCredentials _readOnlyClientCredentials;
private object _openLock = new object();
//Overload for activation DuplexChannelFactory
protected ChannelFactory()
: base()
{
TraceUtility.SetEtwProviderId();
this.TraceOpenAndClose = true;
}
public ClientCredentials Credentials
{
get
{
if (this.Endpoint == null)
return null;
if (this.State == CommunicationState.Created || this.State == CommunicationState.Opening)
{
return EnsureCredentials(this.Endpoint);
}
else
{
if (_readOnlyClientCredentials == null)
{
ClientCredentials c = new ClientCredentials();
c.MakeReadOnly();
_readOnlyClientCredentials = c;
}
return _readOnlyClientCredentials;
}
}
}
protected override TimeSpan DefaultCloseTimeout
{
get
{
if (this.Endpoint != null && this.Endpoint.Binding != null)
{
return this.Endpoint.Binding.CloseTimeout;
}
else
{
return ServiceDefaults.CloseTimeout;
}
}
}
protected override TimeSpan DefaultOpenTimeout
{
get
{
if (this.Endpoint != null && this.Endpoint.Binding != null)
{
return this.Endpoint.Binding.OpenTimeout;
}
else
{
return ServiceDefaults.OpenTimeout;
}
}
}
public ServiceEndpoint Endpoint
{
get
{
return _serviceEndpoint;
}
}
internal IChannelFactory InnerFactory
{
get { return _innerFactory; }
}
// This boolean is used to determine if we should read ahead by a single
// Message for IDuplexSessionChannels in order to detect null and
// autoclose the underlying channel in that case.
// Currently only accessed from the Send activity.
[Fx.Tag.FriendAccessAllowed("System.ServiceModel.Activities")]
internal bool UseActiveAutoClose
{
get;
set;
}
protected internal void EnsureOpened()
{
base.ThrowIfDisposed();
if (this.State != CommunicationState.Opened)
{
lock (_openLock)
{
if (this.State != CommunicationState.Opened)
{
this.Open();
}
}
}
}
// configurationName can be:
// 1. null: don't bind any per-endpoint config (load common behaviors only)
// 2. "*" (wildcard): match any endpoint config provided there's exactly 1
// 3. anything else (including ""): match the endpoint config with the same name
protected virtual void ApplyConfiguration(string configurationName)
{
// This method is in the public contract but is not supported on CORECLR or NETNATIVE
if (!String.IsNullOrEmpty(configurationName))
{
throw ExceptionHelper.PlatformNotSupported();
}
}
protected abstract ServiceEndpoint CreateDescription();
internal EndpointAddress CreateEndpointAddress(ServiceEndpoint endpoint)
{
if (endpoint.Address == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryEndpointAddressUri));
}
return endpoint.Address;
}
protected virtual IChannelFactory CreateFactory()
{
if (this.Endpoint == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryCannotCreateFactoryWithoutDescription));
}
if (this.Endpoint.Binding == null)
{
if (_configurationName != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxChannelFactoryNoBindingFoundInConfig1, _configurationName)));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryNoBindingFoundInConfigOrCode));
}
}
return ServiceChannelFactory.BuildChannelFactory(this.Endpoint, this.UseActiveAutoClose);
}
void IDisposable.Dispose()
{
this.Close();
}
private void EnsureSecurityCredentialsManager(ServiceEndpoint endpoint)
{
Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, "");
if (endpoint.Behaviors.Find<SecurityCredentialsManager>() == null)
{
endpoint.Behaviors.Add(new ClientCredentials());
}
}
private ClientCredentials EnsureCredentials(ServiceEndpoint endpoint)
{
Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, "");
ClientCredentials c = endpoint.Behaviors.Find<ClientCredentials>();
if (c == null)
{
c = new ClientCredentials();
endpoint.Behaviors.Add(c);
}
return c;
}
public T GetProperty<T>() where T : class
{
if (_innerFactory != null)
{
return _innerFactory.GetProperty<T>();
}
else
{
return null;
}
}
internal bool HasDuplexOperations()
{
OperationDescriptionCollection operations = this.Endpoint.Contract.Operations;
for (int i = 0; i < operations.Count; i++)
{
OperationDescription operation = operations[i];
if (operation.IsServerInitiated())
{
return true;
}
}
return false;
}
protected void InitializeEndpoint(string configurationName, EndpointAddress address)
{
_serviceEndpoint = this.CreateDescription();
ServiceEndpoint serviceEndpointFromConfig = null;
// Project N and K do not support System.Configuration, but this method is part of Windows Store contract.
// The configurationName==null path occurs in normal use.
if (configurationName != null)
{
throw ExceptionHelper.PlatformNotSupported();
// serviceEndpointFromConfig = ConfigLoader.LookupEndpoint(configurationName, address, this.serviceEndpoint.Contract);
}
if (serviceEndpointFromConfig != null)
{
_serviceEndpoint = serviceEndpointFromConfig;
}
else
{
if (address != null)
{
this.Endpoint.Address = address;
}
ApplyConfiguration(configurationName);
}
_configurationName = configurationName;
EnsureSecurityCredentialsManager(_serviceEndpoint);
}
protected void InitializeEndpoint(ServiceEndpoint endpoint)
{
if (endpoint == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint");
}
_serviceEndpoint = endpoint;
ApplyConfiguration(null);
EnsureSecurityCredentialsManager(_serviceEndpoint);
}
protected void InitializeEndpoint(Binding binding, EndpointAddress address)
{
_serviceEndpoint = this.CreateDescription();
if (binding != null)
{
this.Endpoint.Binding = binding;
}
if (address != null)
{
this.Endpoint.Address = address;
}
ApplyConfiguration(null);
EnsureSecurityCredentialsManager(_serviceEndpoint);
}
protected override void OnOpened()
{
// if a client credentials has been configured cache a readonly snapshot of it
if (this.Endpoint != null)
{
ClientCredentials credentials = this.Endpoint.Behaviors.Find<ClientCredentials>();
if (credentials != null)
{
ClientCredentials credentialsCopy = credentials.Clone();
credentialsCopy.MakeReadOnly();
_readOnlyClientCredentials = credentialsCopy;
}
}
base.OnOpened();
}
protected override void OnAbort()
{
if (_innerFactory != null)
{
_innerFactory.Abort();
}
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginClose(this, timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
internal protected override async Task OnCloseAsync(TimeSpan timeout)
{
if (_innerFactory != null)
{
IAsyncChannelFactory asyncFactory = _innerFactory as IAsyncChannelFactory;
if (asyncFactory != null)
{
await asyncFactory.CloseAsync(timeout);
}
else
{
_innerFactory.Close(timeout);
}
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginOpen(this, timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected internal override async Task OnOpenAsync(TimeSpan timeout)
{
if (_innerFactory != null)
{
IAsyncChannelFactory asyncFactory = _innerFactory as IAsyncChannelFactory;
if (asyncFactory != null)
{
await asyncFactory.OpenAsync(timeout);
}
else
{
_innerFactory.Open(timeout);
}
}
}
protected override void OnClose(TimeSpan timeout)
{
if (_innerFactory != null)
{
_innerFactory.Close(timeout);
}
}
protected override void OnOpen(TimeSpan timeout)
{
_innerFactory.Open(timeout);
}
protected override void OnOpening()
{
base.OnOpening();
_innerFactory = CreateFactory();
if (WcfEventSource.Instance.ChannelFactoryCreatedIsEnabled())
{
WcfEventSource.Instance.ChannelFactoryCreated(this);
}
if (_innerFactory == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.InnerChannelFactoryWasNotSet));
}
}
public class ChannelFactory<TChannel> : ChannelFactory, IChannelFactory<TChannel>
{
private InstanceContext _callbackInstance;
private Type _channelType;
private TypeLoader _typeLoader;
private Type _callbackType;
//Overload for activation DuplexChannelFactory
protected ChannelFactory(Type channelType)
: base()
{
if (channelType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelType");
}
if (!channelType.IsInterface())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryTypeMustBeInterface));
}
_channelType = channelType;
}
// TChannel provides ContractDescription
public ChannelFactory()
: this(typeof(TChannel))
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, typeof(TChannel).FullName), ActivityType.Construct);
}
this.InitializeEndpoint((string)null, null);
}
}
// TChannel provides ContractDescription, attr/config [TChannel,name] provides Address,Binding
public ChannelFactory(string endpointConfigurationName)
: this(endpointConfigurationName, null)
{
}
// TChannel provides ContractDescription, attr/config [TChannel,name] provides Binding, provide Address explicitly
public ChannelFactory(string endpointConfigurationName, EndpointAddress remoteAddress)
: this(typeof(TChannel))
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, typeof(TChannel).FullName), ActivityType.Construct);
}
if (endpointConfigurationName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointConfigurationName");
}
this.InitializeEndpoint(endpointConfigurationName, remoteAddress);
}
}
// TChannel provides ContractDescription, attr/config [TChannel,name] provides Address,Binding
public ChannelFactory(Binding binding)
: this(binding, (EndpointAddress)null)
{
}
public ChannelFactory(Binding binding, String remoteAddress)
: this(binding, new EndpointAddress(remoteAddress))
{
}
// TChannel provides ContractDescription, provide Address,Binding explicitly
public ChannelFactory(Binding binding, EndpointAddress remoteAddress)
: this(typeof(TChannel))
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, typeof(TChannel).FullName), ActivityType.Construct);
}
if (binding == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding");
}
this.InitializeEndpoint(binding, remoteAddress);
}
}
// provide ContractDescription,Address,Binding explicitly
public ChannelFactory(ServiceEndpoint endpoint)
: this(typeof(TChannel))
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, typeof(TChannel).FullName), ActivityType.Construct);
}
if (endpoint == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint");
}
this.InitializeEndpoint(endpoint);
}
}
internal InstanceContext CallbackInstance
{
get { return _callbackInstance; }
set { _callbackInstance = value; }
}
internal Type CallbackType
{
get { return _callbackType; }
set { _callbackType = value; }
}
internal ServiceChannelFactory ServiceChannelFactory
{
get { return (ServiceChannelFactory)InnerFactory; }
}
internal TypeLoader TypeLoader
{
get
{
if (_typeLoader == null)
{
_typeLoader = new TypeLoader();
}
return _typeLoader;
}
}
public TChannel CreateChannel(EndpointAddress address)
{
if (address == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address");
}
return CreateChannel(address, address.Uri);
}
public virtual TChannel CreateChannel(EndpointAddress address, Uri via)
{
bool traceOpenAndClose = this.TraceOpenAndClose;
try
{
if (address == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address");
}
if (this.HasDuplexOperations())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxCreateNonDuplexChannel1, this.Endpoint.Contract.Name)));
}
EnsureOpened();
return (TChannel)this.ServiceChannelFactory.CreateChannel<TChannel>(address, via);
}
finally
{
this.TraceOpenAndClose = traceOpenAndClose;
}
}
public TChannel CreateChannel()
{
return CreateChannel(this.CreateEndpointAddress(this.Endpoint), null);
}
protected override ServiceEndpoint CreateDescription()
{
ContractDescription contractDescription = this.TypeLoader.LoadContractDescription(_channelType);
ServiceEndpoint endpoint = new ServiceEndpoint(contractDescription);
ReflectOnCallbackInstance(endpoint);
this.TypeLoader.AddBehaviorsSFx(endpoint, _channelType);
return endpoint;
}
private void ReflectOnCallbackInstance(ServiceEndpoint endpoint)
{
if (_callbackType != null)
{
if (endpoint.Contract.CallbackContractType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SfxCallbackTypeCannotBeNull, endpoint.Contract.ContractType.FullName)));
}
this.TypeLoader.AddBehaviorsFromImplementationType(endpoint, _callbackType);
}
else if (this.CallbackInstance != null && this.CallbackInstance.UserObject != null)
{
if (endpoint.Contract.CallbackContractType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SfxCallbackTypeCannotBeNull, endpoint.Contract.ContractType.FullName)));
}
object implementation = this.CallbackInstance.UserObject;
Type implementationType = implementation.GetType();
this.TypeLoader.AddBehaviorsFromImplementationType(endpoint, implementationType);
IEndpointBehavior channelBehavior = implementation as IEndpointBehavior;
if (channelBehavior != null)
{
endpoint.Behaviors.Add(channelBehavior);
}
IContractBehavior contractBehavior = implementation as IContractBehavior;
if (contractBehavior != null)
{
endpoint.Contract.Behaviors.Add(contractBehavior);
}
}
}
//Static funtions to create channels
protected static TChannel CreateChannel(String endpointConfigurationName)
{
ChannelFactory<TChannel> channelFactory = new ChannelFactory<TChannel>(endpointConfigurationName);
if (channelFactory.HasDuplexOperations())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStaticOverloadCalledForDuplexChannelFactory1, channelFactory._channelType.Name)));
}
TChannel channel = channelFactory.CreateChannel();
SetFactoryToAutoClose(channel);
return channel;
}
public static TChannel CreateChannel(Binding binding, EndpointAddress endpointAddress)
{
ChannelFactory<TChannel> channelFactory = new ChannelFactory<TChannel>(binding, endpointAddress);
if (channelFactory.HasDuplexOperations())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStaticOverloadCalledForDuplexChannelFactory1, channelFactory._channelType.Name)));
}
TChannel channel = channelFactory.CreateChannel();
SetFactoryToAutoClose(channel);
return channel;
}
public static TChannel CreateChannel(Binding binding, EndpointAddress endpointAddress, Uri via)
{
ChannelFactory<TChannel> channelFactory = new ChannelFactory<TChannel>(binding);
if (channelFactory.HasDuplexOperations())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStaticOverloadCalledForDuplexChannelFactory1, channelFactory._channelType.Name)));
}
TChannel channel = channelFactory.CreateChannel(endpointAddress, via);
SetFactoryToAutoClose(channel);
return channel;
}
internal static void SetFactoryToAutoClose(TChannel channel)
{
//Set the Channel to auto close its ChannelFactory.
ServiceChannel serviceChannel = ServiceChannelFactory.GetServiceChannel(channel);
serviceChannel.CloseFactory = true;
}
}
}
| |
// *****************************************************************************
//
// (c) Crownwood Consulting Limited 2002
// All rights reserved. The software and associated documentation
// supplied hereunder are the proprietary information of Crownwood Consulting
// Limited, Haxey, North Lincolnshire, England and are supplied subject to
// licence terms.
//
// IDE Version 1.7 www.dotnetmagic.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using IDE.Collections;
namespace IDE.Menus
{
// Declare event signature
internal delegate void CommandHandler(MenuCommand item);
// Should animation be shown?
internal enum Animate
{
No,
Yes,
System
}
// How should animation be displayed?
internal enum Animation
{
System = 0x00100000,
Blend = 0x00080000,
SlideCenter = 0x00040010,
SlideHorVerPositive = 0x00040005,
SlideHorVerNegative = 0x0004000A,
SlideHorPosVerNegative = 0x00040009,
SlideHorNegVerPositive = 0x00040006
}
[ToolboxItem(false)]
[DefaultProperty("Text")]
[DefaultEvent("Click")]
internal class MenuCommand : Component
{
// Enumeration of property change events
internal enum Property
{
Text,
Enabled,
ImageIndex,
ImageList,
Image,
Shortcut,
Checked,
RadioCheck,
Break,
Infrequent,
Visible,
Description
}
// Declare the property change event signature
internal delegate void PropChangeHandler(MenuCommand item, Property prop);
// Instance fields
protected bool _visible;
protected bool _break;
protected string _text;
protected string _description;
protected bool _enabled;
protected bool _checked;
protected int _imageIndex;
protected bool _infrequent;
protected object _tag;
protected bool _radioCheck;
protected Shortcut _shortcut;
protected ImageList _imageList;
protected Image _image;
protected MenuCommandCollection _menuItems;
// Exposed events
public event EventHandler Click;
public event EventHandler Update;
public event CommandHandler PopupStart;
public event CommandHandler PopupEnd;
public event PropChangeHandler PropertyChanged;
public MenuCommand()
{
InternalConstruct("MenuItem", null, -1, Shortcut.None, null);
}
public MenuCommand(string text)
{
InternalConstruct(text, null, -1, Shortcut.None, null);
}
public MenuCommand(string text, EventHandler clickHandler)
{
InternalConstruct(text, null, -1, Shortcut.None, clickHandler);
}
public MenuCommand(string text, Shortcut shortcut)
{
InternalConstruct(text, null, -1, shortcut, null);
}
public MenuCommand(string text, Shortcut shortcut, EventHandler clickHandler)
{
InternalConstruct(text, null, -1, shortcut, clickHandler);
}
public MenuCommand(string text, ImageList imageList, int imageIndex)
{
InternalConstruct(text, imageList, imageIndex, Shortcut.None, null);
}
public MenuCommand(string text, ImageList imageList, int imageIndex, Shortcut shortcut)
{
InternalConstruct(text, imageList, imageIndex, shortcut, null);
}
public MenuCommand(string text, ImageList imageList, int imageIndex, EventHandler clickHandler)
{
InternalConstruct(text, imageList, imageIndex, Shortcut.None, clickHandler);
}
public MenuCommand(string text,
ImageList imageList,
int imageIndex,
Shortcut shortcut,
EventHandler clickHandler)
{
InternalConstruct(text, imageList, imageIndex, shortcut, clickHandler);
}
protected void InternalConstruct(string text,
ImageList imageList,
int imageIndex,
Shortcut shortcut,
EventHandler clickHandler)
{
// Save parameters
_text = text;
_imageList = imageList;
_imageIndex = imageIndex;
_shortcut = shortcut;
_description = text;
if (clickHandler != null)
Click += clickHandler;
// Define defaults for others
_enabled = true;
_checked = false;
_radioCheck = false;
_break = false;
_tag = null;
_visible = true;
_infrequent = false;
_image = null;
// Create the collection of embedded menu commands
_menuItems = new MenuCommandCollection();
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public MenuCommandCollection MenuCommands
{
get { return _menuItems; }
}
[DefaultValue("MenuItem")]
[Localizable(true)]
public string Text
{
get { return _text; }
set
{
if (_text != value)
{
_text = value;
OnPropertyChanged(Property.Text);
}
}
}
[DefaultValue(true)]
public bool Enabled
{
get { return _enabled; }
set
{
if (_enabled != value)
{
_enabled = value;
OnPropertyChanged(Property.Enabled);
}
}
}
[DefaultValue(-1)]
public int ImageIndex
{
get { return _imageIndex; }
set
{
if (_imageIndex != value)
{
_imageIndex = value;
OnPropertyChanged(Property.ImageIndex);
}
}
}
[DefaultValue(null)]
public ImageList ImageList
{
get { return _imageList; }
set
{
if (_imageList != value)
{
_imageList = value;
OnPropertyChanged(Property.ImageList);
}
}
}
[DefaultValue(null)]
public Image Image
{
get { return _image; }
set
{
if (_image != value)
{
_image = value;
OnPropertyChanged(Property.Image);
}
}
}
[DefaultValue(typeof(Shortcut), "None")]
public Shortcut Shortcut
{
get { return _shortcut; }
set
{
if (_shortcut != value)
{
_shortcut = value;
OnPropertyChanged(Property.Shortcut);
}
}
}
[DefaultValue(false)]
public bool Checked
{
get { return _checked; }
set
{
if (_checked != value)
{
_checked = value;
OnPropertyChanged(Property.Checked);
}
}
}
[DefaultValue(false)]
public bool RadioCheck
{
get { return _radioCheck; }
set
{
if (_radioCheck != value)
{
_radioCheck = value;
OnPropertyChanged(Property.RadioCheck);
}
}
}
[DefaultValue(false)]
public bool Break
{
get { return _break; }
set
{
if (_break != value)
{
_break = value;
OnPropertyChanged(Property.Break);
}
}
}
[DefaultValue(false)]
public bool Infrequent
{
get { return _infrequent; }
set
{
if (_infrequent != value)
{
_infrequent = value;
OnPropertyChanged(Property.Infrequent);
}
}
}
[DefaultValue(true)]
public bool Visible
{
get { return _visible; }
set
{
if (_visible != value)
{
_visible = value;
OnPropertyChanged(Property.Visible);
}
}
}
[Browsable(false)]
public bool IsParent
{
get { return (_menuItems.Count > 0); }
}
[DefaultValue("")]
[Localizable(true)]
public string Description
{
get { return _description; }
set { _description = value; }
}
[DefaultValue(null)]
public object Tag
{
get { return _tag; }
set { _tag = value; }
}
public virtual void OnPropertyChanged(Property prop)
{
// Any attached event handlers?
if (PropertyChanged != null)
PropertyChanged(this, prop);
}
public void PerformClick()
{
// Update command with correct state
OnUpdate(EventArgs.Empty);
// Notify event handlers of click event
OnClick(EventArgs.Empty);
}
public virtual void OnClick(EventArgs e)
{
// Any attached event handlers?
if (Click != null)
Click(this, e);
}
public virtual void OnUpdate(EventArgs e)
{
// Any attached event handlers?
if (Update != null)
Update(this, e);
}
public virtual void OnPopupStart()
{
// Any attached event handlers?
if (PopupStart != null)
PopupStart(this);
}
public virtual void OnPopupEnd()
{
// Any attached event handlers?
if (PopupEnd != null)
PopupEnd(this);
}
}
}
| |
/*
* 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 Apache.Ignite.Core.Impl.Common
{
using System;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
/// <summary>
/// Converts generic and non-generic delegates.
/// </summary>
public static class DelegateConverter
{
/** */
private const string DefaultMethodName = "Invoke";
/// <summary>
/// Compiles a function without arguments.
/// </summary>
/// <param name="targetType">Type of the target.</param>
/// <returns>Compiled function that calls specified method on specified target.</returns>
public static Func<object, object> CompileFunc(Type targetType)
{
var method = targetType.GetMethod(DefaultMethodName);
var targetParam = Expression.Parameter(typeof(object));
var targetParamConverted = Expression.Convert(targetParam, targetType);
var callExpr = Expression.Call(targetParamConverted, method);
var convertResultExpr = Expression.Convert(callExpr, typeof(object));
return Expression.Lambda<Func<object, object>>(convertResultExpr, targetParam).Compile();
}
/// <summary>
/// Compiles a function with arbitrary number of arguments.
/// </summary>
/// <typeparam name="T">Resulting delegate type.</typeparam>
/// <param name="targetType">Type of the target.</param>
/// <param name="argTypes">Argument types.</param>
/// <param name="convertToObject">
/// Flags that indicate whether func params and/or return value should be converted from/to object.
/// </param>
/// <param name="methodName">Name of the method.</param>
/// <returns>
/// Compiled function that calls specified method on specified target.
/// </returns>
public static T CompileFunc<T>(Type targetType, Type[] argTypes, bool[] convertToObject = null,
string methodName = null)
where T : class
{
var method = targetType.GetMethod(methodName ?? DefaultMethodName, argTypes);
return CompileFunc<T>(targetType, method, argTypes, convertToObject);
}
/// <summary>
/// Compiles a function with arbitrary number of arguments.
/// </summary>
/// <typeparam name="T">Resulting delegate type.</typeparam>
/// <param name="method">Method.</param>
/// <param name="targetType">Type of the target.</param>
/// <param name="argTypes">Argument types.</param>
/// <param name="convertToObject">
/// Flags that indicate whether func params and/or return value should be converted from/to object.
/// </param>
/// <returns>
/// Compiled function that calls specified method on specified target.
/// </returns>
public static T CompileFunc<T>(Type targetType, MethodInfo method, Type[] argTypes,
bool[] convertToObject = null)
where T : class
{
if (argTypes == null)
{
var args = method.GetParameters();
argTypes = new Type[args.Length];
for (int i = 0; i < args.Length; i++)
argTypes[i] = args[i].ParameterType;
}
Debug.Assert(convertToObject == null || (convertToObject.Length == argTypes.Length + 1));
Debug.Assert(method != null);
targetType = method.IsStatic ? null : (targetType ?? method.DeclaringType);
var targetParam = Expression.Parameter(typeof(object));
Expression targetParamConverted = null;
ParameterExpression[] argParams;
int argParamsOffset = 0;
if (targetType != null)
{
targetParamConverted = Expression.Convert(targetParam, targetType);
argParams = new ParameterExpression[argTypes.Length + 1];
argParams[0] = targetParam;
argParamsOffset = 1;
}
else
argParams = new ParameterExpression[argTypes.Length]; // static method
var argParamsConverted = new Expression[argTypes.Length];
for (var i = 0; i < argTypes.Length; i++)
{
if (convertToObject == null || convertToObject[i])
{
var argParam = Expression.Parameter(typeof (object));
argParams[i + argParamsOffset] = argParam;
argParamsConverted[i] = Expression.Convert(argParam, argTypes[i]);
}
else
{
var argParam = Expression.Parameter(argTypes[i]);
argParams[i + argParamsOffset] = argParam;
argParamsConverted[i] = argParam;
}
}
Expression callExpr = Expression.Call(targetParamConverted, method, argParamsConverted);
if (convertToObject == null || convertToObject[argTypes.Length])
callExpr = Expression.Convert(callExpr, typeof(object));
return Expression.Lambda<T>(callExpr, argParams).Compile();
}
/// <summary>
/// Compiles a generic ctor with arbitrary number of arguments.
/// </summary>
/// <typeparam name="T">Result func type.</typeparam>
/// <param name="ctor">Contructor info.</param>
/// <param name="argTypes">Argument types.</param>
/// <param name="convertResultToObject">if set to <c>true</c> [convert result to object].
/// Flag that indicates whether ctor return value should be converted to object.</param>
/// <returns>
/// Compiled generic constructor.
/// </returns>
public static T CompileCtor<T>(ConstructorInfo ctor, Type[] argTypes, bool convertResultToObject = true)
{
Debug.Assert(ctor != null);
var args = new ParameterExpression[argTypes.Length];
var argsConverted = new Expression[argTypes.Length];
for (var i = 0; i < argTypes.Length; i++)
{
var arg = Expression.Parameter(typeof(object));
args[i] = arg;
argsConverted[i] = Expression.Convert(arg, argTypes[i]);
}
Expression ctorExpr = Expression.New(ctor, argsConverted); // ctor takes args of specific types
if (convertResultToObject)
ctorExpr = Expression.Convert(ctorExpr, typeof(object)); // convert ctor result to object
return Expression.Lambda<T>(ctorExpr, args).Compile(); // lambda takes args as objects
}
/// <summary>
/// Compiles a generic ctor with arbitrary number of arguments.
/// </summary>
/// <typeparam name="T">Result func type.</typeparam>
/// <param name="type">Type to be created by ctor.</param>
/// <param name="argTypes">Argument types.</param>
/// <param name="convertResultToObject">if set to <c>true</c> [convert result to object].
/// Flag that indicates whether ctor return value should be converted to object.
/// </param>
/// <returns>
/// Compiled generic constructor.
/// </returns>
public static T CompileCtor<T>(Type type, Type[] argTypes, bool convertResultToObject = true)
{
var ctor = type.GetConstructor(argTypes);
return CompileCtor<T>(ctor, argTypes, convertResultToObject);
}
/// <summary>
/// Compiles the field setter.
/// </summary>
/// <param name="field">The field.</param>
/// <returns>Compiled field setter.</returns>
public static Action<object, object> CompileFieldSetter(FieldInfo field)
{
Debug.Assert(field != null);
Debug.Assert(field.DeclaringType != null); // non-static
var targetParam = Expression.Parameter(typeof(object));
var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType);
var valParam = Expression.Parameter(typeof(object));
var valParamConverted = Expression.Convert(valParam, field.FieldType);
var assignExpr = Expression.Call(GetWriteFieldMethod(field), targetParamConverted, valParamConverted);
return Expression.Lambda<Action<object, object>>(assignExpr, targetParam, valParam).Compile();
}
/// <summary>
/// Compiles the property setter.
/// </summary>
/// <param name="prop">The property.</param>
/// <returns>Compiled property setter.</returns>
public static Action<object, object> CompilePropertySetter(PropertyInfo prop)
{
Debug.Assert(prop != null);
Debug.Assert(prop.DeclaringType != null); // non-static
var targetParam = Expression.Parameter(typeof(object));
var targetParamConverted = Expression.Convert(targetParam, prop.DeclaringType);
var valParam = Expression.Parameter(typeof(object));
var valParamConverted = Expression.Convert(valParam, prop.PropertyType);
var fld = Expression.Property(targetParamConverted, prop);
var assignExpr = Expression.Assign(fld, valParamConverted);
return Expression.Lambda<Action<object, object>>(assignExpr, targetParam, valParam).Compile();
}
/// <summary>
/// Gets a method to write a field (including private and readonly).
/// NOTE: Expression Trees can't write readonly fields.
/// </summary>
/// <param name="field">The field.</param>
/// <returns>Resulting MethodInfo.</returns>
public static DynamicMethod GetWriteFieldMethod(FieldInfo field)
{
Debug.Assert(field != null);
var module = Assembly.GetExecutingAssembly().GetModules()[0];
var method = new DynamicMethod(string.Empty, null, new[] { field.DeclaringType, field.FieldType }, module,
true);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stfld, field);
il.Emit(OpCodes.Ret);
return method;
}
}
}
| |
/*
*
* 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 Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Queries;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;
namespace Lucene.Net.Tests.Queries
{
public class BooleanFilterTest : LuceneTestCase
{
private Directory directory;
private AtomicReader reader;
[SetUp]
public override void SetUp()
{
base.SetUp();
directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, directory, new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false));
AddDoc(writer, @"admin guest", @"010", @"20040101", @"Y");
AddDoc(writer, @"guest", @"020", @"20040101", @"Y");
AddDoc(writer, @"guest", @"020", @"20050101", @"Y");
AddDoc(writer, @"admin", @"020", @"20050101", @"Maybe");
AddDoc(writer, @"admin guest", @"030", @"20050101", @"N");
reader = SlowCompositeReaderWrapper.Wrap(writer.GetReader());
writer.Dispose();
}
[TearDown]
public override void TearDown()
{
reader.Dispose();
directory.Dispose();
base.TearDown();
}
private void AddDoc(RandomIndexWriter writer, string accessRights, string price, string date, string inStock)
{
Document doc = new Document();
doc.Add(NewTextField(@"accessRights", accessRights, Field.Store.YES));
doc.Add(NewTextField(@"price", price, Field.Store.YES));
doc.Add(NewTextField(@"date", date, Field.Store.YES));
doc.Add(NewTextField(@"inStock", inStock, Field.Store.YES));
writer.AddDocument(doc);
}
private Filter GetRangeFilter(string field, string lowerPrice, string upperPrice)
{
Filter f = TermRangeFilter.NewStringRange(field, lowerPrice, upperPrice, true, true);
return f;
}
private Filter GetTermsFilter(string field, string text)
{
return new TermsFilter(new Term(field, text));
}
private Filter GetWrappedTermQuery(string field, string text)
{
return new QueryWrapperFilter(new TermQuery(new Term(field, text)));
}
private Filter GetEmptyFilter()
{
return new AnonymousFilter(this);
}
private sealed class AnonymousFilter : Filter
{
public AnonymousFilter(BooleanFilterTest parent)
{
this.parent = parent;
}
private readonly BooleanFilterTest parent;
public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs)
{
return new FixedBitSet(context.AtomicReader.MaxDoc);
}
}
private Filter GetNullDISFilter()
{
return new AnonymousFilter1(this);
}
private sealed class AnonymousFilter1 : Filter
{
public AnonymousFilter1(BooleanFilterTest parent)
{
this.parent = parent;
}
private readonly BooleanFilterTest parent;
public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs)
{
return null;
}
}
private Filter GetNullDISIFilter()
{
return new AnonymousFilter2(this);
}
private sealed class AnonymousDocIdSet : DocIdSet
{
public override DocIdSetIterator GetIterator()
{
return null;
}
public override bool IsCacheable => true;
}
private sealed class AnonymousFilter2 : Filter
{
public AnonymousFilter2(BooleanFilterTest parent)
{
this.parent = parent;
}
private readonly BooleanFilterTest parent;
public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs)
{
return new AnonymousDocIdSet();
}
}
private void TstFilterCard(string mes, int expected, Filter filt)
{
DocIdSet docIdSet = filt.GetDocIdSet(reader.AtomicContext, reader.LiveDocs);
int actual = 0;
if (docIdSet != null)
{
DocIdSetIterator disi = docIdSet.GetIterator();
while (disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS)
{
actual++;
}
}
assertEquals(mes, expected, actual);
}
[Test]
public void TestShould()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetTermsFilter(@"price", @"030"), Occur.SHOULD);
TstFilterCard(@"Should retrieves only 1 doc", 1, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetWrappedTermQuery(@"price", @"030"), Occur.SHOULD);
TstFilterCard(@"Should retrieves only 1 doc", 1, booleanFilter);
}
[Test]
public void TestShoulds()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetRangeFilter(@"price", @"010", @"020"), Occur.SHOULD);
booleanFilter.Add(GetRangeFilter(@"price", @"020", @"030"), Occur.SHOULD);
TstFilterCard(@"Shoulds are Ored together", 5, booleanFilter);
}
[Test]
public void TestShouldsAndMustNot()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetRangeFilter(@"price", @"010", @"020"), Occur.SHOULD);
booleanFilter.Add(GetRangeFilter(@"price", @"020", @"030"), Occur.SHOULD);
booleanFilter.Add(GetTermsFilter(@"inStock", @"N"), Occur.MUST_NOT);
TstFilterCard(@"Shoulds Ored but AndNot", 4, booleanFilter);
booleanFilter.Add(GetTermsFilter(@"inStock", @"Maybe"), Occur.MUST_NOT);
TstFilterCard(@"Shoulds Ored but AndNots", 3, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetRangeFilter(@"price", @"010", @"020"), Occur.SHOULD);
booleanFilter.Add(GetRangeFilter(@"price", @"020", @"030"), Occur.SHOULD);
booleanFilter.Add(GetWrappedTermQuery(@"inStock", @"N"), Occur.MUST_NOT);
TstFilterCard(@"Shoulds Ored but AndNot", 4, booleanFilter);
booleanFilter.Add(GetWrappedTermQuery(@"inStock", @"Maybe"), Occur.MUST_NOT);
TstFilterCard(@"Shoulds Ored but AndNots", 3, booleanFilter);
}
[Test]
public void TestShouldsAndMust()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetRangeFilter(@"price", @"010", @"020"), Occur.SHOULD);
booleanFilter.Add(GetRangeFilter(@"price", @"020", @"030"), Occur.SHOULD);
booleanFilter.Add(GetTermsFilter(@"accessRights", @"admin"), Occur.MUST);
TstFilterCard(@"Shoulds Ored but MUST", 3, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetRangeFilter(@"price", @"010", @"020"), Occur.SHOULD);
booleanFilter.Add(GetRangeFilter(@"price", @"020", @"030"), Occur.SHOULD);
booleanFilter.Add(GetWrappedTermQuery(@"accessRights", @"admin"), Occur.MUST);
TstFilterCard(@"Shoulds Ored but MUST", 3, booleanFilter);
}
[Test]
public void TestShouldsAndMusts()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetRangeFilter(@"price", @"010", @"020"), Occur.SHOULD);
booleanFilter.Add(GetRangeFilter(@"price", @"020", @"030"), Occur.SHOULD);
booleanFilter.Add(GetTermsFilter(@"accessRights", @"admin"), Occur.MUST);
booleanFilter.Add(GetRangeFilter(@"date", @"20040101", @"20041231"), Occur.MUST);
TstFilterCard(@"Shoulds Ored but MUSTs ANDED", 1, booleanFilter);
}
[Test]
public void TestShouldsAndMustsAndMustNot()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetRangeFilter(@"price", @"030", @"040"), Occur.SHOULD);
booleanFilter.Add(GetTermsFilter(@"accessRights", @"admin"), Occur.MUST);
booleanFilter.Add(GetRangeFilter(@"date", @"20050101", @"20051231"), Occur.MUST);
booleanFilter.Add(GetTermsFilter(@"inStock", @"N"), Occur.MUST_NOT);
TstFilterCard(@"Shoulds Ored but MUSTs ANDED and MustNot", 0, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetRangeFilter(@"price", @"030", @"040"), Occur.SHOULD);
booleanFilter.Add(GetWrappedTermQuery(@"accessRights", @"admin"), Occur.MUST);
booleanFilter.Add(GetRangeFilter(@"date", @"20050101", @"20051231"), Occur.MUST);
booleanFilter.Add(GetWrappedTermQuery(@"inStock", @"N"), Occur.MUST_NOT);
TstFilterCard(@"Shoulds Ored but MUSTs ANDED and MustNot", 0, booleanFilter);
}
[Test]
public void TestJustMust()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetTermsFilter(@"accessRights", @"admin"), Occur.MUST);
TstFilterCard(@"MUST", 3, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetWrappedTermQuery(@"accessRights", @"admin"), Occur.MUST);
TstFilterCard(@"MUST", 3, booleanFilter);
}
[Test]
public void TestJustMustNot()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetTermsFilter(@"inStock", @"N"), Occur.MUST_NOT);
TstFilterCard(@"MUST_NOT", 4, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetWrappedTermQuery(@"inStock", @"N"), Occur.MUST_NOT);
TstFilterCard(@"MUST_NOT", 4, booleanFilter);
}
[Test]
public void TestMustAndMustNot()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetTermsFilter(@"inStock", @"N"), Occur.MUST);
booleanFilter.Add(GetTermsFilter(@"price", @"030"), Occur.MUST_NOT);
TstFilterCard(@"MUST_NOT wins over MUST for same docs", 0, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetWrappedTermQuery(@"inStock", @"N"), Occur.MUST);
booleanFilter.Add(GetWrappedTermQuery(@"price", @"030"), Occur.MUST_NOT);
TstFilterCard(@"MUST_NOT wins over MUST for same docs", 0, booleanFilter);
}
[Test]
public void TestEmpty()
{
BooleanFilter booleanFilter = new BooleanFilter();
TstFilterCard(@"empty BooleanFilter returns no results", 0, booleanFilter);
}
[Test]
public void TestCombinedNullDocIdSets()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetTermsFilter(@"price", @"030"), Occur.MUST);
booleanFilter.Add(GetNullDISFilter(), Occur.MUST);
TstFilterCard(@"A MUST filter that returns a null DIS should never return documents", 0, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetTermsFilter(@"price", @"030"), Occur.MUST);
booleanFilter.Add(GetNullDISIFilter(), Occur.MUST);
TstFilterCard(@"A MUST filter that returns a null DISI should never return documents", 0, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetTermsFilter(@"price", @"030"), Occur.SHOULD);
booleanFilter.Add(GetNullDISFilter(), Occur.SHOULD);
TstFilterCard(@"A SHOULD filter that returns a null DIS should be invisible", 1, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetTermsFilter(@"price", @"030"), Occur.SHOULD);
booleanFilter.Add(GetNullDISIFilter(), Occur.SHOULD);
TstFilterCard(@"A SHOULD filter that returns a null DISI should be invisible", 1, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetTermsFilter(@"price", @"030"), Occur.MUST);
booleanFilter.Add(GetNullDISFilter(), Occur.MUST_NOT);
TstFilterCard(@"A MUST_NOT filter that returns a null DIS should be invisible", 1, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetTermsFilter(@"price", @"030"), Occur.MUST);
booleanFilter.Add(GetNullDISIFilter(), Occur.MUST_NOT);
TstFilterCard(@"A MUST_NOT filter that returns a null DISI should be invisible", 1, booleanFilter);
}
[Test]
public void TestJustNullDocIdSets()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetNullDISFilter(), Occur.MUST);
TstFilterCard(@"A MUST filter that returns a null DIS should never return documents", 0, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetNullDISIFilter(), Occur.MUST);
TstFilterCard(@"A MUST filter that returns a null DISI should never return documents", 0, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetNullDISFilter(), Occur.SHOULD);
TstFilterCard(@"A single SHOULD filter that returns a null DIS should never return documents", 0, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetNullDISIFilter(), Occur.SHOULD);
TstFilterCard(@"A single SHOULD filter that returns a null DISI should never return documents", 0, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetNullDISFilter(), Occur.MUST_NOT);
TstFilterCard(@"A single MUST_NOT filter that returns a null DIS should be invisible", 5, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetNullDISIFilter(), Occur.MUST_NOT);
TstFilterCard(@"A single MUST_NOT filter that returns a null DIS should be invisible", 5, booleanFilter);
}
[Test]
public void TestNonMatchingShouldsAndMusts()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetEmptyFilter(), Occur.SHOULD);
booleanFilter.Add(GetTermsFilter(@"accessRights", @"admin"), Occur.MUST);
TstFilterCard(@">0 shoulds with no matches should return no docs", 0, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetNullDISFilter(), Occur.SHOULD);
booleanFilter.Add(GetTermsFilter(@"accessRights", @"admin"), Occur.MUST);
TstFilterCard(@">0 shoulds with no matches should return no docs", 0, booleanFilter);
booleanFilter = new BooleanFilter();
booleanFilter.Add(GetNullDISIFilter(), Occur.SHOULD);
booleanFilter.Add(GetTermsFilter(@"accessRights", @"admin"), Occur.MUST);
TstFilterCard(@">0 shoulds with no matches should return no docs", 0, booleanFilter);
}
[Test]
public void TestToStringOfBooleanFilterContainingTermsFilter()
{
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.Add(GetTermsFilter(@"inStock", @"N"), Occur.MUST);
booleanFilter.Add(GetTermsFilter(@"isFragile", @"Y"), Occur.MUST);
assertEquals(@"BooleanFilter(+inStock:N +isFragile:Y)", booleanFilter.ToString());
}
[Test]
public void TestToStringOfWrappedBooleanFilters()
{
BooleanFilter orFilter = new BooleanFilter();
BooleanFilter stockFilter = new BooleanFilter();
stockFilter.Add(new FilterClause(GetTermsFilter(@"inStock", @"Y"), Occur.MUST));
stockFilter.Add(new FilterClause(GetTermsFilter(@"barCode", @"12345678"), Occur.MUST));
orFilter.Add(new FilterClause(stockFilter, Occur.SHOULD));
BooleanFilter productPropertyFilter = new BooleanFilter();
productPropertyFilter.Add(new FilterClause(GetTermsFilter(@"isHeavy", @"N"), Occur.MUST));
productPropertyFilter.Add(new FilterClause(GetTermsFilter(@"isDamaged", @"Y"), Occur.MUST));
orFilter.Add(new FilterClause(productPropertyFilter, Occur.SHOULD));
BooleanFilter composedFilter = new BooleanFilter();
composedFilter.Add(new FilterClause(orFilter, Occur.MUST));
assertEquals(@"BooleanFilter(+BooleanFilter(BooleanFilter(+inStock:Y +barCode:12345678) BooleanFilter(+isHeavy:N +isDamaged:Y)))", composedFilter.ToString());
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
function initializeConvexEditor()
{
echo(" % - Initializing Sketch Tool");
exec( "./convexEditor.cs" );
exec( "./convexEditorGui.gui" );
exec( "./convexEditorToolbar.ed.gui" );
exec( "./convexEditorGui.cs" );
ConvexEditorGui.setVisible( false );
ConvexEditorOptionsWindow.setVisible( false );
ConvexEditorTreeWindow.setVisible( false );
ConvexEditorToolbar.setVisible( false );
EditorGui.add( ConvexEditorGui );
EditorGui.add( ConvexEditorOptionsWindow );
EditorGui.add( ConvexEditorTreeWindow );
EditorGui.add( ConvexEditorToolbar );
new ScriptObject( ConvexEditorPlugin )
{
superClass = "EditorPlugin";
editorGui = ConvexEditorGui;
};
// Note that we use the WorldEditor's Toolbar.
%map = new ActionMap();
%map.bindCmd( keyboard, "1", "ConvexEditorNoneModeBtn.performClick();", "" ); // Select
%map.bindCmd( keyboard, "2", "ConvexEditorMoveModeBtn.performClick();", "" ); // Move
%map.bindCmd( keyboard, "3", "ConvexEditorRotateModeBtn.performClick();", "" );// Rotate
%map.bindCmd( keyboard, "4", "ConvexEditorScaleModeBtn.performClick();", "" ); // Scale
ConvexEditorPlugin.map = %map;
ConvexEditorPlugin.initSettings();
}
function ConvexEditorPlugin::onWorldEditorStartup( %this )
{
// Add ourselves to the window menu.
%accel = EditorGui.addToEditorsMenu( "Sketch Tool", "", ConvexEditorPlugin );
// Add ourselves to the ToolsToolbar
%tooltip = "Sketch Tool (" @ %accel @ ")";
EditorGui.addToToolsToolbar( "ConvexEditorPlugin", "ConvexEditorPalette", expandFilename("tools/convexEditor/images/convex-editor-btn"), %tooltip );
//connect editor windows
GuiWindowCtrl::attach( ConvexEditorOptionsWindow, ConvexEditorTreeWindow);
// Allocate our special menu.
// It will be added/removed when this editor is activated/deactivated.
if ( !isObject( ConvexActionsMenu ) )
{
singleton PopupMenu( ConvexActionsMenu )
{
superClass = "MenuBuilder";
barTitle = "Sketch";
Item[0] = "Hollow Selected Shape" TAB "" TAB "ConvexEditorGui.hollowSelection();";
item[1] = "Recenter Selected Shape" TAB "" TAB "ConvexEditorGui.recenterSelection();";
};
}
%this.popupMenu = ConvexActionsMenu;
exec( "./convexEditorSettingsTab.ed.gui" );
ESettingsWindow.addTabPage( EConvexEditorSettingsPage );
}
function ConvexEditorPlugin::onActivated( %this )
{
%this.readSettings();
EditorGui.bringToFront( ConvexEditorGui );
ConvexEditorGui.setVisible( true );
ConvexEditorToolbar.setVisible( true );
ConvexEditorGui.makeFirstResponder( true );
%this.map.push();
// Set the status bar here until all tool have been hooked up
EditorGuiStatusBar.setInfo( "Sketch Tool." );
EditorGuiStatusBar.setSelection( "" );
// Add our menu.
EditorGui.menuBar.insert( ConvexActionsMenu, EditorGui.menuBar.dynamicItemInsertPos );
// Sync the pallete button state with the gizmo mode.
%mode = GlobalGizmoProfile.mode;
switch$ (%mode)
{
case "None":
ConvexEditorNoneModeBtn.performClick();
case "Move":
ConvexEditorMoveModeBtn.performClick();
case "Rotate":
ConvexEditorRotateModeBtn.performClick();
case "Scale":
ConvexEditorScaleModeBtn.performClick();
}
Parent::onActivated( %this );
}
function ConvexEditorPlugin::onDeactivated( %this )
{
%this.writeSettings();
ConvexEditorGui.setVisible( false );
ConvexEditorOptionsWindow.setVisible( false );
ConvexEditorTreeWindow.setVisible( false );
ConvexEditorToolbar.setVisible( false );
%this.map.pop();
// Remove our menu.
EditorGui.menuBar.remove( ConvexActionsMenu );
Parent::onDeactivated( %this );
}
function ConvexEditorPlugin::onEditMenuSelect( %this, %editMenu )
{
%hasSelection = false;
if ( ConvexEditorGui.hasSelection() )
%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, %hasSelection ); // Deselect
}
function ConvexEditorPlugin::handleDelete( %this )
{
ConvexEditorGui.handleDelete();
}
function ConvexEditorPlugin::handleDeselect( %this )
{
ConvexEditorGui.handleDeselect();
}
function ConvexEditorPlugin::handleCut( %this )
{
//WorldEditorInspectorPlugin.handleCut();
}
function ConvexEditorPlugin::handleCopy( %this )
{
//WorldEditorInspectorPlugin.handleCopy();
}
function ConvexEditorPlugin::handlePaste( %this )
{
//WorldEditorInspectorPlugin.handlePaste();
}
function ConvexEditorPlugin::isDirty( %this )
{
return ConvexEditorGui.isDirty;
}
function ConvexEditorPlugin::onSaveMission( %this, %missionFile )
{
if( ConvexEditorGui.isDirty )
{
MissionGroup.save( %missionFile );
ConvexEditorGui.isDirty = false;
}
}
//-----------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------
function ConvexEditorPlugin::initSettings( %this )
{
EditorSettings.beginGroup( "ConvexEditor", true );
EditorSettings.setDefaultValue( "MaterialName", "Grid512_OrangeLines_Mat" );
EditorSettings.endGroup();
}
function ConvexEditorPlugin::readSettings( %this )
{
EditorSettings.beginGroup( "ConvexEditor", true );
ConvexEditorGui.materialName = EditorSettings.value("MaterialName");
EditorSettings.endGroup();
}
function ConvexEditorPlugin::writeSettings( %this )
{
EditorSettings.beginGroup( "ConvexEditor", true );
EditorSettings.setValue( "MaterialName", ConvexEditorGui.materialName );
EditorSettings.endGroup();
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.IO;
using NLog.Common;
using NLog.Config;
using NLog.Targets.Wrappers;
using Xunit;
using Xunit.Extensions;
namespace NLog.UnitTests.Config
{
public class XmlConfigTests : NLogTestBase
{
[Fact]
public void ParseNLogOptionsDefaultTest()
{
using (new InternalLoggerScope())
{
var xml = "<nlog></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.False(config.AutoReload);
Assert.True(config.InitializeSucceeded);
Assert.Equal("", InternalLogger.LogFile);
Assert.True(InternalLogger.IncludeTimestamp);
Assert.False(InternalLogger.LogToConsole);
Assert.False(InternalLogger.LogToConsoleError);
Assert.Null(InternalLogger.LogWriter);
Assert.Equal(LogLevel.Off, InternalLogger.LogLevel);
}
}
[Fact]
public void ParseNLogOptionsTest()
{
using (new InternalLoggerScope(true))
{
var xml = "<nlog logfile='test.txt' internalLogIncludeTimestamp='false' internalLogToConsole='true' internalLogToConsoleError='true'></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.False(config.AutoReload);
Assert.True(config.InitializeSucceeded);
Assert.Equal("", InternalLogger.LogFile);
Assert.False(InternalLogger.IncludeTimestamp);
Assert.True(InternalLogger.LogToConsole);
Assert.True(InternalLogger.LogToConsoleError);
Assert.Null(InternalLogger.LogWriter);
Assert.Equal(LogLevel.Info, InternalLogger.LogLevel);
}
}
[Fact]
public void ParseNLogInternalLoggerPathTest()
{
using (new InternalLoggerScope(true))
{
var xml = "<nlog internalLogFile='${CurrentDir}test.txt'></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.Contains(System.IO.Directory.GetCurrentDirectory(), InternalLogger.LogFile);
}
using (new InternalLoggerScope(true))
{
var xml = "<nlog internalLogFile='${BaseDir}test.txt'></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.Contains(AppDomain.CurrentDomain.BaseDirectory, InternalLogger.LogFile);
}
using (new InternalLoggerScope(true))
{
var xml = "<nlog internalLogFile='${TempDir}test.txt'></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.Contains(System.IO.Path.GetTempPath(), InternalLogger.LogFile);
}
#if !NETSTANDARD1_3
using (new InternalLoggerScope(true))
{
var xml = "<nlog internalLogFile='${ProcessDir}test.txt'></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.Contains(Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess()?.MainModule?.FileName), InternalLogger.LogFile);
}
#endif
using (new InternalLoggerScope(true))
{
var userName = Environment.GetEnvironmentVariable("USERNAME") ?? string.Empty;
var xml = "<nlog internalLogFile='%USERNAME%_test.txt'></nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
if (!string.IsNullOrEmpty(userName))
Assert.Contains(userName, InternalLogger.LogFile);
}
}
[Theory]
[InlineData("0:0:0:1", 1)]
[InlineData("0:0:1", 1)]
[InlineData("0:1", 60)] //1 minute
[InlineData("0:1:0", 60)]
[InlineData("00:00:00:1", 1)]
[InlineData("000:0000:000:001", 1)]
[InlineData("0:0:1:1", 61)]
[InlineData("1:0:0", 3600)] // 1 hour
[InlineData("2:3:4", 7384)]
[InlineData("1:0:0:0", 86400)] //1 day
public void SetTimeSpanFromXmlTest(string interval, int seconds)
{
var config = XmlLoggingConfiguration.CreateFromXmlString($@"
<nlog throwExceptions='true'>
<targets>
<wrapper-target name='limiting' type='LimitingWrapper' messagelimit='5' interval='{interval}'>
<target name='debug' type='Debug' layout='${{message}}' />
</wrapper-target>
</targets>
<rules>
<logger name='*' level='Debug' writeTo='limiting' />
</rules>
</nlog>");
var target = config.FindTargetByName<LimitingTargetWrapper>("limiting");
Assert.NotNull(target);
Assert.Equal(TimeSpan.FromSeconds(seconds), target.Interval);
}
[Fact]
public void InvalidInternalLogLevel_shouldNotSetLevel()
{
using (new InternalLoggerScope(true))
using (new NoThrowNLogExceptions())
{
// Arrange
InternalLogger.LogLevel = LogLevel.Error;
var xml = @"<nlog internalLogLevel='bogus' >
</nlog>";
// Act
XmlLoggingConfiguration.CreateFromXmlString(xml);
// Assert
Assert.Equal(LogLevel.Error, InternalLogger.LogLevel);
}
}
[Fact]
public void InvalidNLogAttributeValues_shouldNotBreakLogging()
{
using (new InternalLoggerScope(true))
using (new NoThrowNLogExceptions())
{
// Arrange
var xml = @"<nlog internalLogLevel='oops' globalThreshold='noooos'>
<targets>
<target name='debug' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='debug' appendto='debug' />
</rules>
</nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
LogManager.Configuration = config;
var logger = LogManager.GetLogger("InvalidInternalLogLevel_shouldNotBreakLogging");
// Act
logger.Debug("message 1");
// Assert
var message = GetDebugLastMessage("debug");
Assert.Equal("message 1", message);
}
}
[Fact]
public void XmlConfig_ParseUtf8Encoding_WithoutHyphen()
{
// Arrange
var xml = @"<nlog>
<targets>
<target name='file' type='File' encoding='utf8' layout='${message}' fileName='hello.txt' />
</targets>
<rules>
<logger name='*' minlevel='debug' appendto='file' />
</rules>
</nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.Single(config.AllTargets);
Assert.Equal(System.Text.Encoding.UTF8, (config.AllTargets[0] as NLog.Targets.FileTarget)?.Encoding);
}
[Fact]
public void XmlConfig_ParseFilter_WithoutAttributes()
{
// Arrange
var xml = @"<nlog>
<targets>
<target name='debug' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='debug' appendto='debug' filterDefaultAction='ignore'>
<filters>
<whenContains />
</filters>
</logger>
</rules>
</nlog>";
var config = XmlLoggingConfiguration.CreateFromXmlString(xml);
Assert.Single(config.LoggingRules);
Assert.Single(config.LoggingRules[0].Filters);
}
[Theory]
[InlineData("xsi")]
[InlineData("test")]
public void XmlConfig_attributes_shouldNotLogWarningsToInternalLog(string @namespace)
{
// Arrange
var xml = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd""
xmlns:{@namespace}=""http://www.w3.org/2001/XMLSchema-instance""
{@namespace}:schemaLocation=""somewhere""
{@namespace}:type=""asa""
internalLogToConsole=""true"" internalLogLevel=""Warn"">
</nlog>";
try
{
// ReSharper disable once UnusedVariable
var factory = ConfigurationItemFactory.Default; // retrieve factory for calling preload and so won't assert those warnings
TextWriter textWriter = new StringWriter();
InternalLogger.LogWriter = textWriter;
InternalLogger.IncludeTimestamp = false;
// Act
XmlLoggingConfiguration.CreateFromXmlString(xml);
// Assert
InternalLogger.LogWriter.Flush();
var warning = textWriter.ToString();
Assert.Equal("", warning);
}
finally
{
// cleanup
InternalLogger.LogWriter = null;
}
}
}
}
| |
namespace OpenKh.Tools.ItbEditor
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.LoadITBButton = new System.Windows.Forms.Button();
this.SaveITBButton = new System.Windows.Forms.Button();
this.ItbTabControl = new System.Windows.Forms.TabControl();
this.TabDP = new System.Windows.Forms.TabPage();
this.FlowDP = new System.Windows.Forms.FlowLayoutPanel();
this.TabSW = new System.Windows.Forms.TabPage();
this.FlowSW = new System.Windows.Forms.FlowLayoutPanel();
this.TabCD = new System.Windows.Forms.TabPage();
this.FlowCD = new System.Windows.Forms.FlowLayoutPanel();
this.TabSB = new System.Windows.Forms.TabPage();
this.FlowSB = new System.Windows.Forms.FlowLayoutPanel();
this.TabYT = new System.Windows.Forms.TabPage();
this.FlowYT = new System.Windows.Forms.FlowLayoutPanel();
this.TabRG = new System.Windows.Forms.TabPage();
this.FlowRG = new System.Windows.Forms.FlowLayoutPanel();
this.TabJB = new System.Windows.Forms.TabPage();
this.FlowJB = new System.Windows.Forms.FlowLayoutPanel();
this.TabHE = new System.Windows.Forms.TabPage();
this.FlowHE = new System.Windows.Forms.FlowLayoutPanel();
this.TabLS = new System.Windows.Forms.TabPage();
this.FlowLS = new System.Windows.Forms.FlowLayoutPanel();
this.TabDI = new System.Windows.Forms.TabPage();
this.FlowDI = new System.Windows.Forms.FlowLayoutPanel();
this.TabPP = new System.Windows.Forms.TabPage();
this.FlowPP = new System.Windows.Forms.FlowLayoutPanel();
this.TabDC = new System.Windows.Forms.TabPage();
this.FlowDC = new System.Windows.Forms.FlowLayoutPanel();
this.TabKG = new System.Windows.Forms.TabPage();
this.FlowKG = new System.Windows.Forms.FlowLayoutPanel();
this.TabVS = new System.Windows.Forms.TabPage();
this.FlowVS = new System.Windows.Forms.FlowLayoutPanel();
this.TabBD = new System.Windows.Forms.TabPage();
this.FlowBD = new System.Windows.Forms.FlowLayoutPanel();
this.TabWM = new System.Windows.Forms.TabPage();
this.FlowWM = new System.Windows.Forms.FlowLayoutPanel();
this.NewChestButton = new System.Windows.Forms.Button();
this.ItbTabControl.SuspendLayout();
this.TabDP.SuspendLayout();
this.TabSW.SuspendLayout();
this.TabCD.SuspendLayout();
this.TabSB.SuspendLayout();
this.TabYT.SuspendLayout();
this.TabRG.SuspendLayout();
this.TabJB.SuspendLayout();
this.TabHE.SuspendLayout();
this.TabLS.SuspendLayout();
this.TabDI.SuspendLayout();
this.TabPP.SuspendLayout();
this.TabDC.SuspendLayout();
this.TabKG.SuspendLayout();
this.TabVS.SuspendLayout();
this.TabBD.SuspendLayout();
this.TabWM.SuspendLayout();
this.SuspendLayout();
//
// LoadITBButton
//
this.LoadITBButton.Font = new System.Drawing.Font("Segoe UI Historic", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.LoadITBButton.Location = new System.Drawing.Point(13, 13);
this.LoadITBButton.Name = "LoadITBButton";
this.LoadITBButton.Size = new System.Drawing.Size(75, 23);
this.LoadITBButton.TabIndex = 0;
this.LoadITBButton.Text = "Load ITB";
this.LoadITBButton.UseVisualStyleBackColor = true;
this.LoadITBButton.Click += new System.EventHandler(this.LoadITCButton_Click);
//
// SaveITBButton
//
this.SaveITBButton.Enabled = false;
this.SaveITBButton.Font = new System.Drawing.Font("Segoe UI Historic", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.SaveITBButton.Location = new System.Drawing.Point(94, 13);
this.SaveITBButton.Name = "SaveITBButton";
this.SaveITBButton.Size = new System.Drawing.Size(75, 23);
this.SaveITBButton.TabIndex = 1;
this.SaveITBButton.Text = "Save as...";
this.SaveITBButton.UseVisualStyleBackColor = true;
this.SaveITBButton.Click += new System.EventHandler(this.SaveITCButton_Click);
//
// ItbTabControl
//
this.ItbTabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ItbTabControl.Controls.Add(this.TabDP);
this.ItbTabControl.Controls.Add(this.TabSW);
this.ItbTabControl.Controls.Add(this.TabCD);
this.ItbTabControl.Controls.Add(this.TabSB);
this.ItbTabControl.Controls.Add(this.TabYT);
this.ItbTabControl.Controls.Add(this.TabRG);
this.ItbTabControl.Controls.Add(this.TabJB);
this.ItbTabControl.Controls.Add(this.TabHE);
this.ItbTabControl.Controls.Add(this.TabLS);
this.ItbTabControl.Controls.Add(this.TabDI);
this.ItbTabControl.Controls.Add(this.TabPP);
this.ItbTabControl.Controls.Add(this.TabDC);
this.ItbTabControl.Controls.Add(this.TabKG);
this.ItbTabControl.Controls.Add(this.TabVS);
this.ItbTabControl.Controls.Add(this.TabBD);
this.ItbTabControl.Controls.Add(this.TabWM);
this.ItbTabControl.ItemSize = new System.Drawing.Size(40, 20);
this.ItbTabControl.Location = new System.Drawing.Point(12, 42);
this.ItbTabControl.Name = "ItbTabControl";
this.ItbTabControl.SelectedIndex = 0;
this.ItbTabControl.Size = new System.Drawing.Size(645, 390);
this.ItbTabControl.SizeMode = System.Windows.Forms.TabSizeMode.Fixed;
this.ItbTabControl.TabIndex = 2;
//
// TabDP
//
this.TabDP.AutoScroll = true;
this.TabDP.BackColor = System.Drawing.Color.White;
this.TabDP.Controls.Add(this.FlowDP);
this.TabDP.ForeColor = System.Drawing.SystemColors.ControlText;
this.TabDP.Location = new System.Drawing.Point(4, 24);
this.TabDP.Name = "TabDP";
this.TabDP.Size = new System.Drawing.Size(637, 362);
this.TabDP.TabIndex = 0;
this.TabDP.Text = "DP";
//
// FlowDP
//
this.FlowDP.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowDP.AutoScroll = true;
this.FlowDP.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowDP.Location = new System.Drawing.Point(3, 3);
this.FlowDP.Name = "FlowDP";
this.FlowDP.Size = new System.Drawing.Size(631, 356);
this.FlowDP.TabIndex = 0;
//
// TabSW
//
this.TabSW.AutoScroll = true;
this.TabSW.Controls.Add(this.FlowSW);
this.TabSW.Location = new System.Drawing.Point(4, 24);
this.TabSW.Name = "TabSW";
this.TabSW.Size = new System.Drawing.Size(637, 362);
this.TabSW.TabIndex = 1;
this.TabSW.Text = "SW";
this.TabSW.UseVisualStyleBackColor = true;
//
// FlowSW
//
this.FlowSW.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowSW.AutoScroll = true;
this.FlowSW.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowSW.Location = new System.Drawing.Point(3, 3);
this.FlowSW.Name = "FlowSW";
this.FlowSW.Size = new System.Drawing.Size(631, 356);
this.FlowSW.TabIndex = 1;
//
// TabCD
//
this.TabCD.AutoScroll = true;
this.TabCD.Controls.Add(this.FlowCD);
this.TabCD.Location = new System.Drawing.Point(4, 24);
this.TabCD.Name = "TabCD";
this.TabCD.Size = new System.Drawing.Size(637, 362);
this.TabCD.TabIndex = 2;
this.TabCD.Text = "CD";
this.TabCD.UseVisualStyleBackColor = true;
//
// FlowCD
//
this.FlowCD.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowCD.AutoScroll = true;
this.FlowCD.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowCD.Location = new System.Drawing.Point(3, 3);
this.FlowCD.Name = "FlowCD";
this.FlowCD.Size = new System.Drawing.Size(631, 356);
this.FlowCD.TabIndex = 1;
//
// TabSB
//
this.TabSB.AutoScroll = true;
this.TabSB.Controls.Add(this.FlowSB);
this.TabSB.Location = new System.Drawing.Point(4, 24);
this.TabSB.Name = "TabSB";
this.TabSB.Size = new System.Drawing.Size(637, 362);
this.TabSB.TabIndex = 3;
this.TabSB.Text = "SB";
this.TabSB.UseVisualStyleBackColor = true;
//
// FlowSB
//
this.FlowSB.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowSB.AutoScroll = true;
this.FlowSB.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowSB.Location = new System.Drawing.Point(3, 3);
this.FlowSB.Name = "FlowSB";
this.FlowSB.Size = new System.Drawing.Size(631, 356);
this.FlowSB.TabIndex = 1;
//
// TabYT
//
this.TabYT.AutoScroll = true;
this.TabYT.Controls.Add(this.FlowYT);
this.TabYT.Location = new System.Drawing.Point(4, 24);
this.TabYT.Name = "TabYT";
this.TabYT.Size = new System.Drawing.Size(637, 362);
this.TabYT.TabIndex = 4;
this.TabYT.Text = "YT";
this.TabYT.UseVisualStyleBackColor = true;
//
// FlowYT
//
this.FlowYT.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowYT.AutoScroll = true;
this.FlowYT.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowYT.Location = new System.Drawing.Point(3, 3);
this.FlowYT.Name = "FlowYT";
this.FlowYT.Size = new System.Drawing.Size(631, 356);
this.FlowYT.TabIndex = 1;
//
// TabRG
//
this.TabRG.AutoScroll = true;
this.TabRG.Controls.Add(this.FlowRG);
this.TabRG.Location = new System.Drawing.Point(4, 24);
this.TabRG.Name = "TabRG";
this.TabRG.Size = new System.Drawing.Size(637, 362);
this.TabRG.TabIndex = 5;
this.TabRG.Text = "RG";
this.TabRG.UseVisualStyleBackColor = true;
//
// FlowRG
//
this.FlowRG.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowRG.AutoScroll = true;
this.FlowRG.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowRG.Location = new System.Drawing.Point(3, 3);
this.FlowRG.Name = "FlowRG";
this.FlowRG.Size = new System.Drawing.Size(631, 356);
this.FlowRG.TabIndex = 1;
//
// TabJB
//
this.TabJB.AutoScroll = true;
this.TabJB.Controls.Add(this.FlowJB);
this.TabJB.Location = new System.Drawing.Point(4, 24);
this.TabJB.Name = "TabJB";
this.TabJB.Size = new System.Drawing.Size(637, 362);
this.TabJB.TabIndex = 6;
this.TabJB.Text = "JB";
this.TabJB.UseVisualStyleBackColor = true;
//
// FlowJB
//
this.FlowJB.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowJB.AutoScroll = true;
this.FlowJB.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowJB.Location = new System.Drawing.Point(3, 3);
this.FlowJB.Name = "FlowJB";
this.FlowJB.Size = new System.Drawing.Size(631, 356);
this.FlowJB.TabIndex = 1;
//
// TabHE
//
this.TabHE.AutoScroll = true;
this.TabHE.Controls.Add(this.FlowHE);
this.TabHE.Location = new System.Drawing.Point(4, 24);
this.TabHE.Name = "TabHE";
this.TabHE.Size = new System.Drawing.Size(637, 362);
this.TabHE.TabIndex = 7;
this.TabHE.Text = "HE";
this.TabHE.UseVisualStyleBackColor = true;
//
// FlowHE
//
this.FlowHE.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowHE.AutoScroll = true;
this.FlowHE.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowHE.Location = new System.Drawing.Point(3, 3);
this.FlowHE.Name = "FlowHE";
this.FlowHE.Size = new System.Drawing.Size(631, 356);
this.FlowHE.TabIndex = 1;
//
// TabLS
//
this.TabLS.AutoScroll = true;
this.TabLS.Controls.Add(this.FlowLS);
this.TabLS.Location = new System.Drawing.Point(4, 24);
this.TabLS.Name = "TabLS";
this.TabLS.Size = new System.Drawing.Size(637, 362);
this.TabLS.TabIndex = 8;
this.TabLS.Text = "LS";
this.TabLS.UseVisualStyleBackColor = true;
//
// FlowLS
//
this.FlowLS.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowLS.AutoScroll = true;
this.FlowLS.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowLS.Location = new System.Drawing.Point(3, 3);
this.FlowLS.Name = "FlowLS";
this.FlowLS.Size = new System.Drawing.Size(631, 356);
this.FlowLS.TabIndex = 1;
//
// TabDI
//
this.TabDI.AutoScroll = true;
this.TabDI.Controls.Add(this.FlowDI);
this.TabDI.Location = new System.Drawing.Point(4, 24);
this.TabDI.Name = "TabDI";
this.TabDI.Size = new System.Drawing.Size(637, 362);
this.TabDI.TabIndex = 9;
this.TabDI.Text = "DI";
this.TabDI.UseVisualStyleBackColor = true;
//
// FlowDI
//
this.FlowDI.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowDI.AutoScroll = true;
this.FlowDI.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowDI.Location = new System.Drawing.Point(3, 3);
this.FlowDI.Name = "FlowDI";
this.FlowDI.Size = new System.Drawing.Size(631, 356);
this.FlowDI.TabIndex = 1;
//
// TabPP
//
this.TabPP.AutoScroll = true;
this.TabPP.Controls.Add(this.FlowPP);
this.TabPP.Location = new System.Drawing.Point(4, 24);
this.TabPP.Name = "TabPP";
this.TabPP.Size = new System.Drawing.Size(637, 362);
this.TabPP.TabIndex = 10;
this.TabPP.Text = "PP";
this.TabPP.UseVisualStyleBackColor = true;
//
// FlowPP
//
this.FlowPP.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowPP.AutoScroll = true;
this.FlowPP.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowPP.Location = new System.Drawing.Point(3, 3);
this.FlowPP.Name = "FlowPP";
this.FlowPP.Size = new System.Drawing.Size(631, 356);
this.FlowPP.TabIndex = 1;
//
// TabDC
//
this.TabDC.AutoScroll = true;
this.TabDC.Controls.Add(this.FlowDC);
this.TabDC.Location = new System.Drawing.Point(4, 24);
this.TabDC.Name = "TabDC";
this.TabDC.Size = new System.Drawing.Size(637, 362);
this.TabDC.TabIndex = 11;
this.TabDC.Text = "DC";
this.TabDC.UseVisualStyleBackColor = true;
//
// FlowDC
//
this.FlowDC.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowDC.AutoScroll = true;
this.FlowDC.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowDC.Location = new System.Drawing.Point(3, 3);
this.FlowDC.Name = "FlowDC";
this.FlowDC.Size = new System.Drawing.Size(631, 356);
this.FlowDC.TabIndex = 1;
//
// TabKG
//
this.TabKG.AutoScroll = true;
this.TabKG.Controls.Add(this.FlowKG);
this.TabKG.Location = new System.Drawing.Point(4, 24);
this.TabKG.Name = "TabKG";
this.TabKG.Size = new System.Drawing.Size(637, 362);
this.TabKG.TabIndex = 12;
this.TabKG.Text = "KG";
this.TabKG.UseVisualStyleBackColor = true;
//
// FlowKG
//
this.FlowKG.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowKG.AutoScroll = true;
this.FlowKG.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowKG.Location = new System.Drawing.Point(3, 3);
this.FlowKG.Name = "FlowKG";
this.FlowKG.Size = new System.Drawing.Size(631, 356);
this.FlowKG.TabIndex = 1;
//
// TabVS
//
this.TabVS.AutoScroll = true;
this.TabVS.Controls.Add(this.FlowVS);
this.TabVS.Location = new System.Drawing.Point(4, 24);
this.TabVS.Name = "TabVS";
this.TabVS.Size = new System.Drawing.Size(637, 362);
this.TabVS.TabIndex = 13;
this.TabVS.Text = "VS";
this.TabVS.UseVisualStyleBackColor = true;
//
// FlowVS
//
this.FlowVS.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowVS.AutoScroll = true;
this.FlowVS.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowVS.Location = new System.Drawing.Point(3, 3);
this.FlowVS.Name = "FlowVS";
this.FlowVS.Size = new System.Drawing.Size(631, 356);
this.FlowVS.TabIndex = 1;
//
// TabBD
//
this.TabBD.AutoScroll = true;
this.TabBD.Controls.Add(this.FlowBD);
this.TabBD.Location = new System.Drawing.Point(4, 24);
this.TabBD.Name = "TabBD";
this.TabBD.Size = new System.Drawing.Size(637, 362);
this.TabBD.TabIndex = 14;
this.TabBD.Text = "BD";
this.TabBD.UseVisualStyleBackColor = true;
//
// FlowBD
//
this.FlowBD.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowBD.AutoScroll = true;
this.FlowBD.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowBD.Location = new System.Drawing.Point(3, 3);
this.FlowBD.Name = "FlowBD";
this.FlowBD.Size = new System.Drawing.Size(631, 356);
this.FlowBD.TabIndex = 1;
//
// TabWM
//
this.TabWM.AutoScroll = true;
this.TabWM.Controls.Add(this.FlowWM);
this.TabWM.Location = new System.Drawing.Point(4, 24);
this.TabWM.Name = "TabWM";
this.TabWM.Size = new System.Drawing.Size(637, 362);
this.TabWM.TabIndex = 15;
this.TabWM.Text = "WM";
this.TabWM.UseVisualStyleBackColor = true;
//
// FlowWM
//
this.FlowWM.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FlowWM.AutoScroll = true;
this.FlowWM.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.FlowWM.Location = new System.Drawing.Point(3, 3);
this.FlowWM.Name = "FlowWM";
this.FlowWM.Size = new System.Drawing.Size(631, 356);
this.FlowWM.TabIndex = 1;
//
// NewChestButton
//
this.NewChestButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.NewChestButton.Enabled = false;
this.NewChestButton.Location = new System.Drawing.Point(493, 13);
this.NewChestButton.Name = "NewChestButton";
this.NewChestButton.Size = new System.Drawing.Size(160, 23);
this.NewChestButton.TabIndex = 3;
this.NewChestButton.Text = "Add Chest to this world";
this.NewChestButton.UseVisualStyleBackColor = true;
this.NewChestButton.Click += new System.EventHandler(this.NewChestButton_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(664, 441);
this.Controls.Add(this.NewChestButton);
this.Controls.Add(this.ItbTabControl);
this.Controls.Add(this.SaveITBButton);
this.Controls.Add(this.LoadITBButton);
this.Font = new System.Drawing.Font("Segoe UI Historic", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.Name = "Form1";
this.Text = "ITB Editor (Item Treasure Box)";
this.ItbTabControl.ResumeLayout(false);
this.TabDP.ResumeLayout(false);
this.TabSW.ResumeLayout(false);
this.TabCD.ResumeLayout(false);
this.TabSB.ResumeLayout(false);
this.TabYT.ResumeLayout(false);
this.TabRG.ResumeLayout(false);
this.TabJB.ResumeLayout(false);
this.TabHE.ResumeLayout(false);
this.TabLS.ResumeLayout(false);
this.TabDI.ResumeLayout(false);
this.TabPP.ResumeLayout(false);
this.TabDC.ResumeLayout(false);
this.TabKG.ResumeLayout(false);
this.TabVS.ResumeLayout(false);
this.TabBD.ResumeLayout(false);
this.TabWM.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button LoadITBButton;
private System.Windows.Forms.Button SaveITBButton;
private System.Windows.Forms.TabControl ItbTabControl;
private System.Windows.Forms.TabPage TabDP;
private System.Windows.Forms.TabPage TabSW;
private System.Windows.Forms.TabPage TabCD;
private System.Windows.Forms.TabPage TabSB;
private System.Windows.Forms.TabPage TabYT;
private System.Windows.Forms.TabPage TabRG;
private System.Windows.Forms.TabPage TabJB;
private System.Windows.Forms.TabPage TabHE;
private System.Windows.Forms.TabPage TabLS;
private System.Windows.Forms.TabPage TabDI;
private System.Windows.Forms.TabPage TabPP;
private System.Windows.Forms.TabPage TabDC;
private System.Windows.Forms.TabPage TabKG;
private System.Windows.Forms.TabPage TabVS;
private System.Windows.Forms.TabPage TabBD;
private System.Windows.Forms.TabPage TabWM;
private System.Windows.Forms.FlowLayoutPanel FlowDP;
private System.Windows.Forms.FlowLayoutPanel FlowSW;
private System.Windows.Forms.FlowLayoutPanel FlowCD;
private System.Windows.Forms.FlowLayoutPanel FlowSB;
private System.Windows.Forms.FlowLayoutPanel FlowYT;
private System.Windows.Forms.FlowLayoutPanel FlowRG;
private System.Windows.Forms.FlowLayoutPanel FlowJB;
private System.Windows.Forms.FlowLayoutPanel FlowHE;
private System.Windows.Forms.FlowLayoutPanel FlowLS;
private System.Windows.Forms.FlowLayoutPanel FlowDI;
private System.Windows.Forms.FlowLayoutPanel FlowPP;
private System.Windows.Forms.FlowLayoutPanel FlowDC;
private System.Windows.Forms.FlowLayoutPanel FlowKG;
private System.Windows.Forms.FlowLayoutPanel FlowVS;
private System.Windows.Forms.FlowLayoutPanel FlowBD;
private System.Windows.Forms.FlowLayoutPanel FlowWM;
private System.Windows.Forms.Button NewChestButton;
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Creditor Purchase Requisitions Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class CRPRDataSet : EduHubDataSet<CRPR>
{
/// <inheritdoc />
public override string Name { get { return "CRPR"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal CRPRDataSet(EduHubContext Context)
: base(Context)
{
Index_APPROVED_BY = new Lazy<NullDictionary<string, IReadOnlyList<CRPR>>>(() => this.ToGroupedNullDictionary(i => i.APPROVED_BY));
Index_CODE = new Lazy<Dictionary<string, IReadOnlyList<CRPR>>>(() => this.ToGroupedDictionary(i => i.CODE));
Index_INITIATIVE = new Lazy<NullDictionary<string, IReadOnlyList<CRPR>>>(() => this.ToGroupedNullDictionary(i => i.INITIATIVE));
Index_STAFF_ORDER_BY = new Lazy<NullDictionary<string, IReadOnlyList<CRPR>>>(() => this.ToGroupedNullDictionary(i => i.STAFF_ORDER_BY));
Index_SUBPROGRAM = new Lazy<NullDictionary<string, IReadOnlyList<CRPR>>>(() => this.ToGroupedNullDictionary(i => i.SUBPROGRAM));
Index_TID = new Lazy<Dictionary<int, CRPR>>(() => this.ToDictionary(i => i.TID));
Index_TRREF = new Lazy<NullDictionary<string, IReadOnlyList<CRPR>>>(() => this.ToGroupedNullDictionary(i => i.TRREF));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="CRPR" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="CRPR" /> fields for each CSV column header</returns>
internal override Action<CRPR, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<CRPR, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "CODE":
mapper[i] = (e, v) => e.CODE = v;
break;
case "TRTYPE":
mapper[i] = (e, v) => e.TRTYPE = v;
break;
case "TRDATE":
mapper[i] = (e, v) => e.TRDATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "TRREF":
mapper[i] = (e, v) => e.TRREF = v;
break;
case "TRXLEDGER":
mapper[i] = (e, v) => e.TRXLEDGER = v;
break;
case "TRXCODE":
mapper[i] = (e, v) => e.TRXCODE = v;
break;
case "SUBPROGRAM":
mapper[i] = (e, v) => e.SUBPROGRAM = v;
break;
case "INITIATIVE":
mapper[i] = (e, v) => e.INITIATIVE = v;
break;
case "TRCOST":
mapper[i] = (e, v) => e.TRCOST = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "TRQTY":
mapper[i] = (e, v) => e.TRQTY = v == null ? (int?)null : int.Parse(v);
break;
case "TRDET":
mapper[i] = (e, v) => e.TRDET = v;
break;
case "TRORDER":
mapper[i] = (e, v) => e.TRORDER = v;
break;
case "STAFF_ORDER_BY":
mapper[i] = (e, v) => e.STAFF_ORDER_BY = v;
break;
case "APPROVED_BY":
mapper[i] = (e, v) => e.APPROVED_BY = v;
break;
case "POCOMMENT":
mapper[i] = (e, v) => e.POCOMMENT = v;
break;
case "TRNETT":
mapper[i] = (e, v) => e.TRNETT = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LINE_NO":
mapper[i] = (e, v) => e.LINE_NO = v == null ? (int?)null : int.Parse(v);
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="CRPR" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="CRPR" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="CRPR" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{CRPR}"/> of entities</returns>
internal override IEnumerable<CRPR> ApplyDeltaEntities(IEnumerable<CRPR> Entities, List<CRPR> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.CODE;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.CODE.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<CRPR>>> Index_APPROVED_BY;
private Lazy<Dictionary<string, IReadOnlyList<CRPR>>> Index_CODE;
private Lazy<NullDictionary<string, IReadOnlyList<CRPR>>> Index_INITIATIVE;
private Lazy<NullDictionary<string, IReadOnlyList<CRPR>>> Index_STAFF_ORDER_BY;
private Lazy<NullDictionary<string, IReadOnlyList<CRPR>>> Index_SUBPROGRAM;
private Lazy<Dictionary<int, CRPR>> Index_TID;
private Lazy<NullDictionary<string, IReadOnlyList<CRPR>>> Index_TRREF;
#endregion
#region Index Methods
/// <summary>
/// Find CRPR by APPROVED_BY field
/// </summary>
/// <param name="APPROVED_BY">APPROVED_BY value used to find CRPR</param>
/// <returns>List of related CRPR entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<CRPR> FindByAPPROVED_BY(string APPROVED_BY)
{
return Index_APPROVED_BY.Value[APPROVED_BY];
}
/// <summary>
/// Attempt to find CRPR by APPROVED_BY field
/// </summary>
/// <param name="APPROVED_BY">APPROVED_BY value used to find CRPR</param>
/// <param name="Value">List of related CRPR entities</param>
/// <returns>True if the list of related CRPR entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByAPPROVED_BY(string APPROVED_BY, out IReadOnlyList<CRPR> Value)
{
return Index_APPROVED_BY.Value.TryGetValue(APPROVED_BY, out Value);
}
/// <summary>
/// Attempt to find CRPR by APPROVED_BY field
/// </summary>
/// <param name="APPROVED_BY">APPROVED_BY value used to find CRPR</param>
/// <returns>List of related CRPR entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<CRPR> TryFindByAPPROVED_BY(string APPROVED_BY)
{
IReadOnlyList<CRPR> value;
if (Index_APPROVED_BY.Value.TryGetValue(APPROVED_BY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find CRPR by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find CRPR</param>
/// <returns>List of related CRPR entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<CRPR> FindByCODE(string CODE)
{
return Index_CODE.Value[CODE];
}
/// <summary>
/// Attempt to find CRPR by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find CRPR</param>
/// <param name="Value">List of related CRPR entities</param>
/// <returns>True if the list of related CRPR entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByCODE(string CODE, out IReadOnlyList<CRPR> Value)
{
return Index_CODE.Value.TryGetValue(CODE, out Value);
}
/// <summary>
/// Attempt to find CRPR by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find CRPR</param>
/// <returns>List of related CRPR entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<CRPR> TryFindByCODE(string CODE)
{
IReadOnlyList<CRPR> value;
if (Index_CODE.Value.TryGetValue(CODE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find CRPR by INITIATIVE field
/// </summary>
/// <param name="INITIATIVE">INITIATIVE value used to find CRPR</param>
/// <returns>List of related CRPR entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<CRPR> FindByINITIATIVE(string INITIATIVE)
{
return Index_INITIATIVE.Value[INITIATIVE];
}
/// <summary>
/// Attempt to find CRPR by INITIATIVE field
/// </summary>
/// <param name="INITIATIVE">INITIATIVE value used to find CRPR</param>
/// <param name="Value">List of related CRPR entities</param>
/// <returns>True if the list of related CRPR entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByINITIATIVE(string INITIATIVE, out IReadOnlyList<CRPR> Value)
{
return Index_INITIATIVE.Value.TryGetValue(INITIATIVE, out Value);
}
/// <summary>
/// Attempt to find CRPR by INITIATIVE field
/// </summary>
/// <param name="INITIATIVE">INITIATIVE value used to find CRPR</param>
/// <returns>List of related CRPR entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<CRPR> TryFindByINITIATIVE(string INITIATIVE)
{
IReadOnlyList<CRPR> value;
if (Index_INITIATIVE.Value.TryGetValue(INITIATIVE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find CRPR by STAFF_ORDER_BY field
/// </summary>
/// <param name="STAFF_ORDER_BY">STAFF_ORDER_BY value used to find CRPR</param>
/// <returns>List of related CRPR entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<CRPR> FindBySTAFF_ORDER_BY(string STAFF_ORDER_BY)
{
return Index_STAFF_ORDER_BY.Value[STAFF_ORDER_BY];
}
/// <summary>
/// Attempt to find CRPR by STAFF_ORDER_BY field
/// </summary>
/// <param name="STAFF_ORDER_BY">STAFF_ORDER_BY value used to find CRPR</param>
/// <param name="Value">List of related CRPR entities</param>
/// <returns>True if the list of related CRPR entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySTAFF_ORDER_BY(string STAFF_ORDER_BY, out IReadOnlyList<CRPR> Value)
{
return Index_STAFF_ORDER_BY.Value.TryGetValue(STAFF_ORDER_BY, out Value);
}
/// <summary>
/// Attempt to find CRPR by STAFF_ORDER_BY field
/// </summary>
/// <param name="STAFF_ORDER_BY">STAFF_ORDER_BY value used to find CRPR</param>
/// <returns>List of related CRPR entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<CRPR> TryFindBySTAFF_ORDER_BY(string STAFF_ORDER_BY)
{
IReadOnlyList<CRPR> value;
if (Index_STAFF_ORDER_BY.Value.TryGetValue(STAFF_ORDER_BY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find CRPR by SUBPROGRAM field
/// </summary>
/// <param name="SUBPROGRAM">SUBPROGRAM value used to find CRPR</param>
/// <returns>List of related CRPR entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<CRPR> FindBySUBPROGRAM(string SUBPROGRAM)
{
return Index_SUBPROGRAM.Value[SUBPROGRAM];
}
/// <summary>
/// Attempt to find CRPR by SUBPROGRAM field
/// </summary>
/// <param name="SUBPROGRAM">SUBPROGRAM value used to find CRPR</param>
/// <param name="Value">List of related CRPR entities</param>
/// <returns>True if the list of related CRPR entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySUBPROGRAM(string SUBPROGRAM, out IReadOnlyList<CRPR> Value)
{
return Index_SUBPROGRAM.Value.TryGetValue(SUBPROGRAM, out Value);
}
/// <summary>
/// Attempt to find CRPR by SUBPROGRAM field
/// </summary>
/// <param name="SUBPROGRAM">SUBPROGRAM value used to find CRPR</param>
/// <returns>List of related CRPR entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<CRPR> TryFindBySUBPROGRAM(string SUBPROGRAM)
{
IReadOnlyList<CRPR> value;
if (Index_SUBPROGRAM.Value.TryGetValue(SUBPROGRAM, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find CRPR by TID field
/// </summary>
/// <param name="TID">TID value used to find CRPR</param>
/// <returns>Related CRPR entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public CRPR FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find CRPR by TID field
/// </summary>
/// <param name="TID">TID value used to find CRPR</param>
/// <param name="Value">Related CRPR entity</param>
/// <returns>True if the related CRPR entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out CRPR Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find CRPR by TID field
/// </summary>
/// <param name="TID">TID value used to find CRPR</param>
/// <returns>Related CRPR entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public CRPR TryFindByTID(int TID)
{
CRPR value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find CRPR by TRREF field
/// </summary>
/// <param name="TRREF">TRREF value used to find CRPR</param>
/// <returns>List of related CRPR entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<CRPR> FindByTRREF(string TRREF)
{
return Index_TRREF.Value[TRREF];
}
/// <summary>
/// Attempt to find CRPR by TRREF field
/// </summary>
/// <param name="TRREF">TRREF value used to find CRPR</param>
/// <param name="Value">List of related CRPR entities</param>
/// <returns>True if the list of related CRPR entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTRREF(string TRREF, out IReadOnlyList<CRPR> Value)
{
return Index_TRREF.Value.TryGetValue(TRREF, out Value);
}
/// <summary>
/// Attempt to find CRPR by TRREF field
/// </summary>
/// <param name="TRREF">TRREF value used to find CRPR</param>
/// <returns>List of related CRPR entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<CRPR> TryFindByTRREF(string TRREF)
{
IReadOnlyList<CRPR> value;
if (Index_TRREF.Value.TryGetValue(TRREF, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a CRPR table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[CRPR](
[TID] int IDENTITY NOT NULL,
[CODE] varchar(10) NOT NULL,
[TRTYPE] varchar(1) NULL,
[TRDATE] datetime NULL,
[TRREF] varchar(10) NULL,
[TRXLEDGER] varchar(2) NULL,
[TRXCODE] varchar(10) NULL,
[SUBPROGRAM] varchar(4) NULL,
[INITIATIVE] varchar(3) NULL,
[TRCOST] money NULL,
[TRQTY] int NULL,
[TRDET] varchar(30) NULL,
[TRORDER] varchar(10) NULL,
[STAFF_ORDER_BY] varchar(4) NULL,
[APPROVED_BY] varchar(4) NULL,
[POCOMMENT] varchar(MAX) NULL,
[TRNETT] money NULL,
[LINE_NO] int NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [CRPR_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE NONCLUSTERED INDEX [CRPR_Index_APPROVED_BY] ON [dbo].[CRPR]
(
[APPROVED_BY] ASC
);
CREATE CLUSTERED INDEX [CRPR_Index_CODE] ON [dbo].[CRPR]
(
[CODE] ASC
);
CREATE NONCLUSTERED INDEX [CRPR_Index_INITIATIVE] ON [dbo].[CRPR]
(
[INITIATIVE] ASC
);
CREATE NONCLUSTERED INDEX [CRPR_Index_STAFF_ORDER_BY] ON [dbo].[CRPR]
(
[STAFF_ORDER_BY] ASC
);
CREATE NONCLUSTERED INDEX [CRPR_Index_SUBPROGRAM] ON [dbo].[CRPR]
(
[SUBPROGRAM] ASC
);
CREATE NONCLUSTERED INDEX [CRPR_Index_TRREF] ON [dbo].[CRPR]
(
[TRREF] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND name = N'CRPR_Index_APPROVED_BY')
ALTER INDEX [CRPR_Index_APPROVED_BY] ON [dbo].[CRPR] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND name = N'CRPR_Index_INITIATIVE')
ALTER INDEX [CRPR_Index_INITIATIVE] ON [dbo].[CRPR] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND name = N'CRPR_Index_STAFF_ORDER_BY')
ALTER INDEX [CRPR_Index_STAFF_ORDER_BY] ON [dbo].[CRPR] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND name = N'CRPR_Index_SUBPROGRAM')
ALTER INDEX [CRPR_Index_SUBPROGRAM] ON [dbo].[CRPR] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND name = N'CRPR_Index_TID')
ALTER INDEX [CRPR_Index_TID] ON [dbo].[CRPR] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND name = N'CRPR_Index_TRREF')
ALTER INDEX [CRPR_Index_TRREF] ON [dbo].[CRPR] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND name = N'CRPR_Index_APPROVED_BY')
ALTER INDEX [CRPR_Index_APPROVED_BY] ON [dbo].[CRPR] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND name = N'CRPR_Index_INITIATIVE')
ALTER INDEX [CRPR_Index_INITIATIVE] ON [dbo].[CRPR] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND name = N'CRPR_Index_STAFF_ORDER_BY')
ALTER INDEX [CRPR_Index_STAFF_ORDER_BY] ON [dbo].[CRPR] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND name = N'CRPR_Index_SUBPROGRAM')
ALTER INDEX [CRPR_Index_SUBPROGRAM] ON [dbo].[CRPR] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND name = N'CRPR_Index_TID')
ALTER INDEX [CRPR_Index_TID] ON [dbo].[CRPR] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRPR]') AND name = N'CRPR_Index_TRREF')
ALTER INDEX [CRPR_Index_TRREF] ON [dbo].[CRPR] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="CRPR"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="CRPR"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<CRPR> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[CRPR] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the CRPR data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the CRPR data set</returns>
public override EduHubDataSetDataReader<CRPR> GetDataSetDataReader()
{
return new CRPRDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the CRPR data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the CRPR data set</returns>
public override EduHubDataSetDataReader<CRPR> GetDataSetDataReader(List<CRPR> Entities)
{
return new CRPRDataReader(new EduHubDataSetLoadedReader<CRPR>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class CRPRDataReader : EduHubDataSetDataReader<CRPR>
{
public CRPRDataReader(IEduHubDataSetReader<CRPR> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 21; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // CODE
return Current.CODE;
case 2: // TRTYPE
return Current.TRTYPE;
case 3: // TRDATE
return Current.TRDATE;
case 4: // TRREF
return Current.TRREF;
case 5: // TRXLEDGER
return Current.TRXLEDGER;
case 6: // TRXCODE
return Current.TRXCODE;
case 7: // SUBPROGRAM
return Current.SUBPROGRAM;
case 8: // INITIATIVE
return Current.INITIATIVE;
case 9: // TRCOST
return Current.TRCOST;
case 10: // TRQTY
return Current.TRQTY;
case 11: // TRDET
return Current.TRDET;
case 12: // TRORDER
return Current.TRORDER;
case 13: // STAFF_ORDER_BY
return Current.STAFF_ORDER_BY;
case 14: // APPROVED_BY
return Current.APPROVED_BY;
case 15: // POCOMMENT
return Current.POCOMMENT;
case 16: // TRNETT
return Current.TRNETT;
case 17: // LINE_NO
return Current.LINE_NO;
case 18: // LW_DATE
return Current.LW_DATE;
case 19: // LW_TIME
return Current.LW_TIME;
case 20: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // TRTYPE
return Current.TRTYPE == null;
case 3: // TRDATE
return Current.TRDATE == null;
case 4: // TRREF
return Current.TRREF == null;
case 5: // TRXLEDGER
return Current.TRXLEDGER == null;
case 6: // TRXCODE
return Current.TRXCODE == null;
case 7: // SUBPROGRAM
return Current.SUBPROGRAM == null;
case 8: // INITIATIVE
return Current.INITIATIVE == null;
case 9: // TRCOST
return Current.TRCOST == null;
case 10: // TRQTY
return Current.TRQTY == null;
case 11: // TRDET
return Current.TRDET == null;
case 12: // TRORDER
return Current.TRORDER == null;
case 13: // STAFF_ORDER_BY
return Current.STAFF_ORDER_BY == null;
case 14: // APPROVED_BY
return Current.APPROVED_BY == null;
case 15: // POCOMMENT
return Current.POCOMMENT == null;
case 16: // TRNETT
return Current.TRNETT == null;
case 17: // LINE_NO
return Current.LINE_NO == null;
case 18: // LW_DATE
return Current.LW_DATE == null;
case 19: // LW_TIME
return Current.LW_TIME == null;
case 20: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // CODE
return "CODE";
case 2: // TRTYPE
return "TRTYPE";
case 3: // TRDATE
return "TRDATE";
case 4: // TRREF
return "TRREF";
case 5: // TRXLEDGER
return "TRXLEDGER";
case 6: // TRXCODE
return "TRXCODE";
case 7: // SUBPROGRAM
return "SUBPROGRAM";
case 8: // INITIATIVE
return "INITIATIVE";
case 9: // TRCOST
return "TRCOST";
case 10: // TRQTY
return "TRQTY";
case 11: // TRDET
return "TRDET";
case 12: // TRORDER
return "TRORDER";
case 13: // STAFF_ORDER_BY
return "STAFF_ORDER_BY";
case 14: // APPROVED_BY
return "APPROVED_BY";
case 15: // POCOMMENT
return "POCOMMENT";
case 16: // TRNETT
return "TRNETT";
case 17: // LINE_NO
return "LINE_NO";
case 18: // LW_DATE
return "LW_DATE";
case 19: // LW_TIME
return "LW_TIME";
case 20: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "CODE":
return 1;
case "TRTYPE":
return 2;
case "TRDATE":
return 3;
case "TRREF":
return 4;
case "TRXLEDGER":
return 5;
case "TRXCODE":
return 6;
case "SUBPROGRAM":
return 7;
case "INITIATIVE":
return 8;
case "TRCOST":
return 9;
case "TRQTY":
return 10;
case "TRDET":
return 11;
case "TRORDER":
return 12;
case "STAFF_ORDER_BY":
return 13;
case "APPROVED_BY":
return 14;
case "POCOMMENT":
return 15;
case "TRNETT":
return 16;
case "LINE_NO":
return 17;
case "LW_DATE":
return 18;
case "LW_TIME":
return 19;
case "LW_USER":
return 20;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DMLibTestHelper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace DMLibTest
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
#if BINARY_SERIALIZATION
using System.Runtime.Serialization.Formatters.Binary;
#endif
using System.Threading;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.DataMovement;
using Microsoft.WindowsAzure.Storage.File;
using MS.Test.Common.MsTestLib;
using StorageBlob = Microsoft.WindowsAzure.Storage.Blob;
public enum FileSizeUnit
{
B,
KB,
MB,
GB,
}
public enum TestAgainst
{
PublicAzure,
TestTenant,
DevFabric
}
public class SummaryInterval
{
/// <summary>
/// Min value which is inclusive.
/// </summary>
private int minValue;
/// <summary>
/// Max value which is inclusive.
/// </summary>
private int maxValue;
public SummaryInterval(int minValue, int maxValue)
{
this.minValue = minValue;
this.maxValue = maxValue;
}
public int MinValue
{
get
{
return this.minValue;
}
}
public int MaxValue
{
get
{
return this.maxValue;
}
}
public bool InsideInterval(int value)
{
return value >= this.minValue && value <= this.maxValue;
}
}
public static class DMLibTestHelper
{
private static Random random = new Random();
private static readonly char[] validSuffixChars = "abcdefghijkjlmnopqrstuvwxyz".ToCharArray();
public static TransferCheckpoint SaveAndReloadCheckpoint(TransferCheckpoint checkpoint)
{
//return checkpoint;
Test.Info("Save and reload checkpoint");
#if BINARY_SERIALIZATION
IFormatter formatter = new BinaryFormatter();
#else
var formatter = new DataContractSerializer(typeof(TransferCheckpoint));
#endif
TransferCheckpoint reloadedCheckpoint;
string tempFileName = Guid.NewGuid().ToString();
using (var stream = new FileStream(tempFileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
formatter.Serialize(stream, checkpoint);
}
using (var stream = new FileStream(tempFileName, FileMode.Open, FileAccess.Read, FileShare.None))
{
reloadedCheckpoint = formatter.Deserialize(stream) as TransferCheckpoint;
}
File.Delete(tempFileName);
return reloadedCheckpoint;
}
public static TransferCheckpoint RandomReloadCheckpoint(TransferCheckpoint checkpoint)
{
if (Helper.RandomBoolean())
{
Test.Info("Save and reload checkpoint");
return DMLibTestHelper.SaveAndReloadCheckpoint(checkpoint);
}
return checkpoint;
}
public static void KeepFilesWhenCaseFail(params string[] filesToKeep)
{
if (Test.ErrorCount > 0)
{
const string debugFilePrefix = "debug_file_";
string folderName = Guid.NewGuid().ToString();
Directory.CreateDirectory(folderName);
Test.Info("Move files to folder {0} for debug.", folderName);
for (int i = 0; i < filesToKeep.Length; ++i)
{
string debugFileName = debugFilePrefix + i;
string debugFilePath = Path.Combine(folderName, debugFileName);
File.Move(filesToKeep[i], debugFilePath);
Test.Info("{0} ---> {1}", filesToKeep[i], debugFileName);
}
}
}
public static string RandomContainerName()
{
return Test.Data.Get("containerName") + RandomNameSuffix();
}
public static string RandomNameSuffix()
{
return FileOp.NextString(random, 6, validSuffixChars);
}
public static bool WaitForProcessExit(Process p, int timeoutInSecond)
{
bool exit = p.WaitForExit(timeoutInSecond * 1000);
if (!exit)
{
Test.Assert(false, "Process {0} should exit in {1} s.", p.ProcessName, timeoutInSecond);
p.Kill();
return false;
}
return true;
}
public static string RandomizeCase(string value)
{
return ConvertRandomCharsToUpperCase(value.ToLower());
}
public static void UploadFromByteArray(this StorageBlob.CloudBlob cloudBlob, byte[] randomData)
{
if (StorageBlob.BlobType.BlockBlob == cloudBlob.BlobType)
{
(cloudBlob as StorageBlob.CloudBlockBlob).UploadFromByteArray(randomData, 0, randomData.Length);
}
else if (StorageBlob.BlobType.PageBlob == cloudBlob.BlobType)
{
(cloudBlob as StorageBlob.CloudPageBlob).UploadFromByteArray(randomData, 0, randomData.Length);
}
else if (StorageBlob.BlobType.AppendBlob == cloudBlob.BlobType)
{
(cloudBlob as StorageBlob.CloudAppendBlob).UploadFromByteArray(randomData, 0, randomData.Length);
}
else
{
throw new InvalidOperationException(string.Format("Invalid blob type: {0}", cloudBlob.BlobType));
}
}
public static void UploadFromFile(this StorageBlob.CloudBlob cloudBlob,
string path,
AccessCondition accessCondition = null,
StorageBlob.BlobRequestOptions options = null,
OperationContext operationContext = null)
{
if (StorageBlob.BlobType.BlockBlob == cloudBlob.BlobType)
{
(cloudBlob as StorageBlob.CloudBlockBlob).UploadFromFile(path, accessCondition, options, operationContext);
}
else if (StorageBlob.BlobType.PageBlob == cloudBlob.BlobType)
{
(cloudBlob as StorageBlob.CloudPageBlob).UploadFromFile(path, accessCondition, options, operationContext);
}
else if (StorageBlob.BlobType.AppendBlob == cloudBlob.BlobType)
{
(cloudBlob as StorageBlob.CloudAppendBlob).UploadFromFile(path, accessCondition, options, operationContext);
}
else
{
throw new InvalidOperationException(string.Format("Invalid blob type: {0}", cloudBlob.BlobType));
}
}
public static void UploadFromStream(this StorageBlob.CloudBlob cloudBlob, Stream source)
{
if (StorageBlob.BlobType.BlockBlob == cloudBlob.BlobType)
{
(cloudBlob as StorageBlob.CloudBlockBlob).UploadFromStream(source);
}
else if (StorageBlob.BlobType.PageBlob == cloudBlob.BlobType)
{
(cloudBlob as StorageBlob.CloudPageBlob).UploadFromStream(source);
}
else if (StorageBlob.BlobType.AppendBlob == cloudBlob.BlobType)
{
(cloudBlob as StorageBlob.CloudAppendBlob).UploadFromStream(source);
}
else
{
throw new InvalidOperationException(string.Format("Invalid blob type: {0}", cloudBlob.BlobType));
}
}
public static void WaitForACLTakeEffect()
{
if (DMLibTestHelper.GetTestAgainst() != TestAgainst.DevFabric)
{
Test.Info("Waiting for 30s to ensure the ACL take effect on server side...");
Thread.Sleep(30 * 1000);
}
}
public static string RandomProtocol()
{
if (0 == new Random().Next(2))
{
return Protocol.Http;
}
return Protocol.Https;
}
public static bool DisableHttps()
{
if (DMLibTestHelper.GetTestAgainst() == TestAgainst.TestTenant)
{
return true;
}
return false;
}
public static TestAgainst GetTestAgainst()
{
string testAgainst = string.Empty;
try
{
testAgainst = Test.Data.Get("TestAgainst");
}
catch
{
}
if (String.Compare(testAgainst, "publicazure", true) == 0)
{
return TestAgainst.PublicAzure;
}
else if (String.Compare(testAgainst, "testtenant", true) == 0)
{
return TestAgainst.TestTenant;
}
else if (String.Compare(testAgainst, "devfabric", true) == 0)
{
return TestAgainst.DevFabric;
}
// Use dev fabric by default
return TestAgainst.DevFabric;
}
public static List<FileAttributes> GetFileAttributesFromParameter(string s)
{
List<FileAttributes> Lfa = new List<FileAttributes>();
if (null == s)
{
return Lfa;
}
foreach (char c in s)
{
switch (c)
{
case 'R':
if (!Lfa.Contains(FileAttributes.ReadOnly))
Lfa.Add(FileAttributes.ReadOnly);
break;
case 'A':
if (!Lfa.Contains(FileAttributes.Archive))
Lfa.Add(FileAttributes.Archive);
break;
case 'S':
if (!Lfa.Contains(FileAttributes.System))
Lfa.Add(FileAttributes.System);
break;
case 'H':
if (!Lfa.Contains(FileAttributes.Hidden))
Lfa.Add(FileAttributes.Hidden);
break;
case 'C':
if (!Lfa.Contains(FileAttributes.Compressed))
Lfa.Add(FileAttributes.Compressed);
break;
case 'N':
if (!Lfa.Contains(FileAttributes.Normal))
Lfa.Add(FileAttributes.Normal);
break;
case 'E':
if (!Lfa.Contains(FileAttributes.Encrypted))
Lfa.Add(FileAttributes.Encrypted);
break;
case 'T':
if (!Lfa.Contains(FileAttributes.Temporary))
Lfa.Add(FileAttributes.Temporary);
break;
case 'O':
if (!Lfa.Contains(FileAttributes.Offline))
Lfa.Add(FileAttributes.Offline);
break;
case 'I':
if (!Lfa.Contains(FileAttributes.NotContentIndexed))
Lfa.Add(FileAttributes.NotContentIndexed);
break;
default:
break;
}
}
return Lfa;
}
public static List<string> GenerateFileWithAttributes(
string folder,
string filePrefix,
int number,
List<FileAttributes> includeAttributes,
List<FileAttributes> excludeAttributes,
int fileSizeInUnit = 1,
FileSizeUnit unit = FileSizeUnit.KB)
{
List<string> fileNames = new List<string>(number);
for (int i = 0; i < number; i++)
{
string fileName = filePrefix + i.ToString();
string filePath = Path.Combine(folder, fileName);
fileNames.Add(fileName);
DMLibTestHelper.PrepareLocalFile(filePath, fileSizeInUnit, unit);
if (includeAttributes != null)
foreach (FileAttributes fa in includeAttributes)
FileOp.SetFileAttribute(filePath, fa);
if (excludeAttributes != null)
foreach (FileAttributes fa in excludeAttributes)
FileOp.RemoveFileAttribute(filePath, fa);
}
return fileNames;
}
public static void PrepareLocalFile(string filePath, long fileSizeInUnit, FileSizeUnit fileSizeUnit)
{
if (FileSizeUnit.B == fileSizeUnit)
{
Helper.GenerateFileInBytes(filePath, fileSizeInUnit);
}
else if (FileSizeUnit.KB == fileSizeUnit)
{
Helper.GenerateFileInKB(filePath, fileSizeInUnit);
}
else if (FileSizeUnit.MB == fileSizeUnit)
{
Helper.GenerateFileInMB(filePath, fileSizeInUnit);
}
else
{
Helper.GenerateFileInGB(filePath, fileSizeInUnit);
}
}
public static bool ContainsIgnoreCase(string baseString, string subString)
{
return (baseString.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0);
}
private static string ConvertRandomCharsToUpperCase(string input)
{
Random rnd = new Random();
char[] array = input.ToCharArray();
for (int i = 0; i < array.Length; ++i)
{
if (Char.IsLower(array[i]) && rnd.Next() % 2 != 0)
{
array[i] = Char.ToUpper(array[i]);
}
}
return new string(array);
}
/// <summary>
/// Append snapshot time to a file name.
/// </summary>
/// <param name="fileName">Original file name.</param>
/// <param name="snapshotTime">Snapshot time to append.</param>
/// <returns>A file name with appended snapshot time.</returns>
public static string AppendSnapShotTimeToFileName(string fileName, DateTimeOffset? snapshotTime)
{
string resultName = fileName;
if (snapshotTime.HasValue)
{
string pathAndFileNameNoExt = Path.ChangeExtension(fileName, null);
string extension = Path.GetExtension(fileName);
string timeStamp = string.Format(
CultureInfo.InvariantCulture,
"{0:yyyy-MM-dd HHmmss fff}",
snapshotTime.Value);
resultName = string.Format(
CultureInfo.InvariantCulture,
"{0} ({1}){2}",
pathAndFileNameNoExt,
timeStamp,
extension);
}
return resultName;
}
public static string TransferInstanceToString(object transferInstance)
{
CloudBlob blob = transferInstance as CloudBlob;
if (null != blob)
{
return blob.SnapshotQualifiedUri.ToString();
}
CloudFile file = transferInstance as CloudFile;
if (null != file)
{
return file.Uri.ToString();
}
string filePath = transferInstance as string;
if (null != filePath)
{
return filePath;
}
Uri uri = transferInstance as Uri;
if (null != uri)
{
return uri.ToString();
}
Stream stream = transferInstance as Stream;
if (null != stream)
{
return stream.ToString();
}
throw new InvalidOperationException(string.Format("Invalid transfer target: {0}", transferInstance));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace HttpServer.Authentication
{
/// <summary>
/// Implements HTTP Digest authentication. It's more secure than Basic auth since password is
/// encrypted with a "key" from the server.
/// </summary>
/// <remarks>
/// Keep in mind that the password is encrypted with MD5. Use a combination of SSL and digest auth to be secure.
/// </remarks>
public class DigestAuthentication : AuthenticationModule
{
static readonly Dictionary<string, DateTime> _nonces = new Dictionary<string, DateTime>();
private static Timer _timer;
/// <summary>
/// Initializes a new instance of the <see cref="DigestAuthentication"/> class.
/// </summary>
/// <param name="authenticator">Delegate used to provide information used during authentication.</param>
/// <param name="authenticationRequiredHandler">Delegate used to determine if authentication is required (may be null).</param>
public DigestAuthentication(AuthenticationHandler authenticator, AuthenticationRequiredHandler authenticationRequiredHandler)
: base(authenticator, authenticationRequiredHandler)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DigestAuthentication"/> class.
/// </summary>
/// <param name="authenticator">Delegate used to provide information used during authentication.</param>
public DigestAuthentication(AuthenticationHandler authenticator)
: base(authenticator)
{
}
/// <summary>
/// Used by test classes to be able to use hardcoded values
/// </summary>
public static bool DisableNonceCheck;
/// <summary>
/// name used in http request.
/// </summary>
public override string Name
{
get { return "digest"; }
}
/// <summary>
/// An authentication response have been received from the web browser.
/// Check if it's correct
/// </summary>
/// <param name="authenticationHeader">Contents from the Authorization header</param>
/// <param name="realm">Realm that should be authenticated</param>
/// <param name="httpVerb">GET/POST/PUT/DELETE etc.</param>
/// <param name="options">First option: true if username/password is correct but not cnonce</param>
/// <returns>
/// Authentication object that is stored for the request. A user class or something like that.
/// </returns>
/// <exception cref="ArgumentException">if authenticationHeader is invalid</exception>
/// <exception cref="ArgumentNullException">If any of the paramters is empty or null.</exception>
public override object Authenticate(string authenticationHeader, string realm, string httpVerb, object[] options)
{
lock (_nonces)
{
if (_timer == null)
_timer = new Timer(ManageNonces, null, 15000, 15000);
}
if (!authenticationHeader.StartsWith("Digest", true, CultureInfo.CurrentCulture))
return null;
bool staleNonce;
if (options.Length > 0)
staleNonce = (bool) options[0];
else staleNonce = false;
NameValueCollection reqInfo = Decode(authenticationHeader, Encoding.UTF8);
if (!IsValidNonce(reqInfo["nonce"]) && !DisableNonceCheck)
return null;
string username = reqInfo["username"];
string password = string.Empty;
object state;
if (!CheckAuthentication(realm, username, ref password, out state))
return null;
string HA1;
if (!TokenIsHA1)
{
string A1 = String.Format("{0}:{1}:{2}", username, realm, password);
HA1 = GetMD5HashBinHex2(A1);
}
else
HA1 = password;
string A2 = String.Format("{0}:{1}", httpVerb, reqInfo["uri"]);
string HA2 = GetMD5HashBinHex2(A2);
string hashedDigest = Encrypt(HA1, HA2, reqInfo["qop"],
reqInfo["nonce"], reqInfo["nc"], reqInfo["cnonce"]);
if (reqInfo["response"] == hashedDigest && !staleNonce)
return state;
return null;
}
/// <summary>
/// Gets or sets whether the token supplied in <see cref="AuthenticationHandler"/> is a
/// HA1 generated string.
/// </summary>
public bool TokenIsHA1 { get; set; }
/// <summary>
/// Encrypts parameters into a Digest string
/// </summary>
/// <param name="realm">Realm that the user want to log into.</param>
/// <param name="userName">User logging in</param>
/// <param name="password">Users password.</param>
/// <param name="method">HTTP method.</param>
/// <param name="uri">Uri/domain that generated the login prompt.</param>
/// <param name="qop">Quality of Protection.</param>
/// <param name="nonce">"Number used ONCE"</param>
/// <param name="nc">Hexadecimal request counter.</param>
/// <param name="cnonce">"Client Number used ONCE"</param>
/// <returns>Digest encrypted string</returns>
public static string Encrypt(string realm, string userName, string password, string method, string uri, string qop, string nonce, string nc, string cnonce)
{
string A1 = String.Format("{0}:{1}:{2}", userName, realm, password);
string HA1 = GetMD5HashBinHex2(A1);
string A2 = String.Format("{0}:{1}", method, uri);
string HA2 = GetMD5HashBinHex2(A2);
string unhashedDigest;
if (qop != null)
{
unhashedDigest = String.Format("{0}:{1}:{2}:{3}:{4}:{5}",
HA1,
nonce,
nc,
cnonce,
qop,
HA2);
}
else
{
unhashedDigest = String.Format("{0}:{1}:{2}",
HA1,
nonce,
HA2);
}
return GetMD5HashBinHex2(unhashedDigest);
}
/// <summary>
///
/// </summary>
/// <param name="ha1">Md5 hex encoded "userName:realm:password", without the quotes.</param>
/// <param name="ha2">Md5 hex encoded "method:uri", without the quotes</param>
/// <param name="qop">Quality of Protection</param>
/// <param name="nonce">"Number used ONCE"</param>
/// <param name="nc">Hexadecimal request counter.</param>
/// <param name="cnonce">Client number used once</param>
/// <returns></returns>
protected virtual string Encrypt(string ha1, string ha2, string qop, string nonce, string nc, string cnonce)
{
string unhashedDigest;
if (qop != null)
{
unhashedDigest = String.Format("{0}:{1}:{2}:{3}:{4}:{5}",
ha1,
nonce,
nc,
cnonce,
qop,
ha2);
}
else
{
unhashedDigest = String.Format("{0}:{1}:{2}",
ha1,
nonce,
ha2);
}
return GetMD5HashBinHex2(unhashedDigest);
}
private static void ManageNonces(object state)
{
lock (_nonces)
{
foreach (KeyValuePair<string, DateTime> pair in _nonces)
{
if (pair.Value >= DateTime.Now)
continue;
_nonces.Remove(pair.Key);
return;
}
}
}
/// <summary>
/// Create a response that can be sent in the WWW-Authenticate header.
/// </summary>
/// <param name="realm">Realm that the user should authenticate in</param>
/// <param name="options">First options specifies if true if username/password is correct but not cnonce.</param>
/// <returns>A correct auth request.</returns>
/// <exception cref="ArgumentNullException">If realm is empty or null.</exception>
public override string CreateResponse(string realm, object[] options)
{
string nonce = GetCurrentNonce();
StringBuilder challenge = new StringBuilder("Digest realm=\"");
challenge.Append(realm);
challenge.Append("\"");
challenge.Append(", nonce=\"");
challenge.Append(nonce);
challenge.Append("\"");
challenge.Append(", opaque=\"" + Guid.NewGuid().ToString().Replace("-", string.Empty) + "\"");
challenge.Append(", stale=");
if (options.Length > 0)
challenge.Append((bool)options[0] ? "true" : "false");
else
challenge.Append("false");
challenge.Append(", algorithm=MD5");
challenge.Append(", qop=auth");
return challenge.ToString();
}
/// <summary>
/// Decodes authorization header value
/// </summary>
/// <param name="buffer">header value</param>
/// <param name="encoding">Encoding that the buffer is in</param>
/// <returns>All headers and their values if successful; otherwise null</returns>
/// <example>
/// NameValueCollection header = DigestAuthentication.Decode("response=\"6629fae49393a05397450978507c4ef1\",\r\nc=00001", Encoding.ASCII);
/// </example>
/// <remarks>Can handle lots of whitespaces and new lines without failing.</remarks>
public static NameValueCollection Decode(string buffer, Encoding encoding)
{
if (string.Compare(buffer.Substring(0, 7), "Digest ", true) == 0)
buffer = buffer.Remove(0, 7).Trim(' ');
NameValueCollection values = new NameValueCollection();
int step = 0;
bool inQuote = false;
string name = string.Empty;
int start = 0;
for (int i = start; i < buffer.Length; ++i)
{
char ch = buffer[i];
if (ch == '"')
inQuote = !inQuote;
//find start of name
switch (step)
{
case 0:
if (!char.IsWhiteSpace(ch))
{
if (!char.IsLetterOrDigit(ch) && ch != '"')
return null;
start = i;
++step;
}
break;
case 1:
if (char.IsWhiteSpace(ch) || ch == '=')
{
if (start == -1)
return null;
name = buffer.Substring(start, i - start);
start = -1;
++step;
}
else if (!char.IsLetterOrDigit(ch) && ch != '"')
return null;
break;
case 2:
if (!char.IsWhiteSpace(ch) && ch != '=')
{
start = i;
++step;
}
break;
}
// find end of value
if (step == 3)
{
if (inQuote)
continue;
if (ch == ',' || char.IsWhiteSpace(ch) || i == buffer.Length -1)
{
if (start == -1)
return null;
int stop = i;
if (buffer[start] == '"')
{
++start;
--stop;
}
if (i == buffer.Length - 1 || (i == buffer.Length - 2 && buffer[buffer.Length - 1] == '"'))
++stop;
values.Add(name.ToLower(), buffer.Substring(start, stop - start));
name = string.Empty;
start = -1;
step = 0;
}
}
}
return values.Count == 0 ? null : values;
}
/// <summary>
/// Gets the current nonce.
/// </summary>
/// <returns></returns>
protected virtual string GetCurrentNonce()
{
string nonce = Guid.NewGuid().ToString().Replace("-", string.Empty);
lock (_nonces)
_nonces.Add(nonce, DateTime.Now.AddSeconds(30));
return nonce;
}
/// <summary>
/// Gets the Md5 hash bin hex2.
/// </summary>
/// <param name="toBeHashed">To be hashed.</param>
/// <returns></returns>
public static string GetMD5HashBinHex2(string toBeHashed)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(Encoding.ASCII.GetBytes(toBeHashed));
StringBuilder sb = new StringBuilder();
foreach (byte b in result)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
/// <summary>
/// determines if the nonce is valid or has expired.
/// </summary>
/// <param name="nonce">nonce value (check wikipedia for info)</param>
/// <returns>true if the nonce has not expired.</returns>
protected virtual bool IsValidNonce(string nonce)
{
lock (_nonces)
{
if (_nonces.ContainsKey(nonce))
{
if (_nonces[nonce] < DateTime.Now)
{
_nonces.Remove(nonce);
return false;
}
return true;
}
}
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;
using System.Collections.Generic;
using Internal.Runtime;
using Internal.Text;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.DependencyAnalysis
{
public class GCStaticDescNode : EmbeddedObjectNode, ISymbolDefinitionNode
{
private MetadataType _type;
private GCPointerMap _gcMap;
private bool _isThreadStatic;
public GCStaticDescNode(MetadataType type, bool isThreadStatic)
{
_type = type;
_gcMap = isThreadStatic ? GCPointerMap.FromThreadStaticLayout(type) : GCPointerMap.FromStaticLayout(type);
_isThreadStatic = isThreadStatic;
}
protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler);
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append(GetMangledName(nameMangler, _type, _isThreadStatic));
}
public static string GetMangledName(NameMangler nameMangler, MetadataType type, bool isThreadStatic)
{
string prefix = isThreadStatic ? "__ThreadStaticGCDesc_" : "__GCStaticDesc_";
return prefix + nameMangler.GetMangledTypeName(type);
}
public int NumSeries
{
get
{
return _gcMap.NumSeries;
}
}
int ISymbolNode.Offset => 0;
int ISymbolDefinitionNode.Offset => OffsetFromBeginningOfArray;
private GCStaticDescRegionNode Region(NodeFactory factory)
{
UtcNodeFactory utcNodeFactory = (UtcNodeFactory)factory;
if (_type.IsCanonicalSubtype(CanonicalFormKind.Any))
{
return null;
}
else
{
if (_isThreadStatic)
{
return utcNodeFactory.ThreadStaticGCDescRegion;
}
else
{
return utcNodeFactory.GCStaticDescRegion;
}
}
}
private ISymbolNode GCStaticsSymbol(NodeFactory factory)
{
UtcNodeFactory utcNodeFactory = (UtcNodeFactory)factory;
if (_isThreadStatic)
{
return utcNodeFactory.TypeThreadStaticsSymbol(_type);
}
else
{
return utcNodeFactory.TypeGCStaticsSymbol(_type);
}
}
protected override void OnMarked(NodeFactory factory)
{
GCStaticDescRegionNode region = Region(factory);
if (region != null)
region.AddEmbeddedObject(this);
}
public override bool StaticDependenciesAreComputed
{
get
{
return true;
}
}
public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
{
DependencyListEntry[] result;
if (!_type.IsCanonicalSubtype(CanonicalFormKind.Any))
{
result = new DependencyListEntry[2];
result[0] = new DependencyListEntry(Region(factory), "GCStaticDesc Region");
result[1] = new DependencyListEntry(GCStaticsSymbol(factory), "GC Static Base Symbol");
}
else
{
Debug.Assert(Region(factory) == null);
result = new DependencyListEntry[1];
result[0] = new DependencyListEntry(((UtcNodeFactory)factory).StandaloneGCStaticDescRegion(this), "Standalone GCStaticDesc holder");
}
return result;
}
public override void EncodeData(ref ObjectDataBuilder builder, NodeFactory factory, bool relocsOnly)
{
int gcFieldCount = 0;
int startIndex = 0;
int numSeries = 0;
for (int i = 0; i < _gcMap.Size; i++)
{
// Skip non-GC fields
if (!_gcMap[i])
continue;
gcFieldCount++;
if (i == 0 || !_gcMap[i - 1])
{
// The cell starts a new series
startIndex = i;
}
if (i == _gcMap.Size - 1 || !_gcMap[i + 1])
{
if (_type.IsCanonicalSubtype(CanonicalFormKind.Any))
{
// The cell ends the current series
builder.EmitInt(gcFieldCount * factory.Target.PointerSize);
builder.EmitInt(startIndex * factory.Target.PointerSize);
}
else
{
// The cell ends the current series
builder.EmitInt(gcFieldCount);
if (_isThreadStatic)
{
builder.EmitReloc(factory.TypeThreadStaticsSymbol(_type), RelocType.IMAGE_REL_SECREL, startIndex * factory.Target.PointerSize);
}
else
{
builder.EmitReloc(factory.TypeGCStaticsSymbol(_type), RelocType.IMAGE_REL_BASED_RELPTR32, startIndex * factory.Target.PointerSize);
}
}
gcFieldCount = 0;
numSeries++;
}
}
Debug.Assert(numSeries == NumSeries);
}
}
public class GCStaticDescRegionNode : ArrayOfEmbeddedDataNode<GCStaticDescNode>
{
public GCStaticDescRegionNode(string startSymbolMangledName, string endSymbolMangledName)
: base(startSymbolMangledName, endSymbolMangledName, null)
{
}
protected override void GetElementDataForNodes(ref ObjectDataBuilder builder, NodeFactory factory, bool relocsOnly)
{
int numSeries = 0;
foreach (GCStaticDescNode descNode in NodesList)
{
numSeries += descNode.NumSeries;
}
builder.EmitInt(numSeries);
foreach (GCStaticDescNode node in NodesList)
{
if (!relocsOnly)
node.InitializeOffsetFromBeginningOfArray(builder.CountBytes);
node.EncodeData(ref builder, factory, relocsOnly);
builder.AddSymbol(node);
}
}
}
public class StandaloneGCStaticDescRegionNode : ObjectNode
{
GCStaticDescNode _standaloneGCStaticDesc;
public StandaloneGCStaticDescRegionNode(GCStaticDescNode standaloneGCStaticDesc)
{
_standaloneGCStaticDesc = standaloneGCStaticDesc;
}
public override ObjectNodeSection Section => ObjectNodeSection.ReadOnlyDataSection;
public override bool IsShareable => true;
public override bool StaticDependenciesAreComputed => true;
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
{
ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly);
builder.RequireInitialPointerAlignment();
builder.AddSymbol(_standaloneGCStaticDesc);
_standaloneGCStaticDesc.InitializeOffsetFromBeginningOfArray(0);
builder.EmitInt(_standaloneGCStaticDesc.NumSeries);
_standaloneGCStaticDesc.EncodeData(ref builder, factory, relocsOnly);
return builder.ToObjectData();
}
protected override string GetName(NodeFactory context)
{
return "Standalone" + _standaloneGCStaticDesc.GetMangledName(context.NameMangler);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Reflection;
using Microsoft.Win32;
namespace System.Diagnostics.Tracing
{
public partial class EventSource
{
// ActivityID support (see also WriteEventWithRelatedActivityIdCore)
/// <summary>
/// When a thread starts work that is on behalf of 'something else' (typically another
/// thread or network request) it should mark the thread as working on that other work.
/// This API marks the current thread as working on activity 'activityID'. This API
/// should be used when the caller knows the thread's current activity (the one being
/// overwritten) has completed. Otherwise, callers should prefer the overload that
/// return the oldActivityThatWillContinue (below).
///
/// All events created with the EventSource on this thread are also tagged with the
/// activity ID of the thread.
///
/// It is common, and good practice after setting the thread to an activity to log an event
/// with a 'start' opcode to indicate that precise time/thread where the new activity
/// started.
/// </summary>
/// <param name="activityId">A Guid that represents the new activity with which to mark
/// the current thread</param>
[System.Security.SecuritySafeCritical]
public static void SetCurrentThreadActivityId(Guid activityId)
{
if (TplEtwProvider.Log != null)
TplEtwProvider.Log.SetActivityId(activityId);
#if FEATURE_MANAGED_ETW
#if FEATURE_ACTIVITYSAMPLING
Guid newId = activityId;
#endif // FEATURE_ACTIVITYSAMPLING
// We ignore errors to keep with the convention that EventSources do not throw errors.
// Note we can't access m_throwOnWrites because this is a static method.
if (UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID,
ref activityId) == 0)
{
#if FEATURE_ACTIVITYSAMPLING
var activityDying = s_activityDying;
if (activityDying != null && newId != activityId)
{
if (activityId == Guid.Empty)
{
activityId = FallbackActivityId;
}
// OutputDebugString(string.Format("Activity dying: {0} -> {1}", activityId, newId));
activityDying(activityId); // This is actually the OLD activity ID.
}
#endif // FEATURE_ACTIVITYSAMPLING
}
#endif // FEATURE_MANAGED_ETW
}
/// <summary>
/// When a thread starts work that is on behalf of 'something else' (typically another
/// thread or network request) it should mark the thread as working on that other work.
/// This API marks the current thread as working on activity 'activityID'. It returns
/// whatever activity the thread was previously marked with. There is a convention that
/// callers can assume that callees restore this activity mark before the callee returns.
/// To encourage this this API returns the old activity, so that it can be restored later.
///
/// All events created with the EventSource on this thread are also tagged with the
/// activity ID of the thread.
///
/// It is common, and good practice after setting the thread to an activity to log an event
/// with a 'start' opcode to indicate that precise time/thread where the new activity
/// started.
/// </summary>
/// <param name="activityId">A Guid that represents the new activity with which to mark
/// the current thread</param>
/// <param name="oldActivityThatWillContinue">The Guid that represents the current activity
/// which will continue at some point in the future, on the current thread</param>
[System.Security.SecuritySafeCritical]
public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActivityThatWillContinue)
{
oldActivityThatWillContinue = activityId;
#if FEATURE_MANAGED_ETW
// We ignore errors to keep with the convention that EventSources do not throw errors.
// Note we can't access m_throwOnWrites because this is a static method.
UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID,
ref oldActivityThatWillContinue);
#endif // FEATURE_MANAGED_ETW
// We don't call the activityDying callback here because the caller has declared that
// it is not dying.
if (TplEtwProvider.Log != null)
TplEtwProvider.Log.SetActivityId(activityId);
}
/// <summary>
/// Retrieves the ETW activity ID associated with the current thread.
/// </summary>
public static Guid CurrentThreadActivityId
{
[System.Security.SecuritySafeCritical]
get
{
// We ignore errors to keep with the convention that EventSources do not throw
// errors. Note we can't access m_throwOnWrites because this is a static method.
Guid retVal = new Guid();
#if FEATURE_MANAGED_ETW
UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID,
ref retVal);
#endif // FEATURE_MANAGED_ETW
return retVal;
}
}
private int GetParameterCount(EventMetadata eventData)
{
return eventData.Parameters.Length;
}
private Type GetDataType(EventMetadata eventData, int parameterId)
{
return eventData.Parameters[parameterId].ParameterType;
}
private static string GetResourceString(string key, params object[] args)
{
return Environment.GetResourceString(key, args);
}
private static readonly bool m_EventSourcePreventRecursion = false;
}
internal partial class ManifestBuilder
{
private string GetTypeNameHelper(Type type)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
return "win:Boolean";
case TypeCode.Byte:
return "win:UInt8";
case TypeCode.Char:
case TypeCode.UInt16:
return "win:UInt16";
case TypeCode.UInt32:
return "win:UInt32";
case TypeCode.UInt64:
return "win:UInt64";
case TypeCode.SByte:
return "win:Int8";
case TypeCode.Int16:
return "win:Int16";
case TypeCode.Int32:
return "win:Int32";
case TypeCode.Int64:
return "win:Int64";
case TypeCode.String:
return "win:UnicodeString";
case TypeCode.Single:
return "win:Float";
case TypeCode.Double:
return "win:Double";
case TypeCode.DateTime:
return "win:FILETIME";
default:
if (type == typeof(Guid))
return "win:GUID";
else if (type == typeof(IntPtr))
return "win:Pointer";
else if ((type.IsArray || type.IsPointer) && type.GetElementType() == typeof(byte))
return "win:Binary";
ManifestError(Resources.GetResourceString("EventSource_UnsupportedEventTypeInManifest", type.Name), true);
return string.Empty;
}
}
}
internal partial class EventProvider
{
[System.Security.SecurityCritical]
internal unsafe int SetInformation(
UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS eventInfoClass,
IntPtr data,
uint dataSize)
{
int status = UnsafeNativeMethods.ManifestEtw.ERROR_NOT_SUPPORTED;
if (!m_setInformationMissing)
{
try
{
status = UnsafeNativeMethods.ManifestEtw.EventSetInformation(
m_regHandle,
eventInfoClass,
(void *)data,
(int)dataSize);
}
catch (TypeLoadException)
{
m_setInformationMissing = true;
}
}
return status;
}
}
internal static class Resources
{
internal static string GetResourceString(string key, params object[] args)
{
return Environment.GetResourceString(key, args);
}
}
}
| |
#define MCG_WINRT_SUPPORTED
using Mcg.System;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
// -----------------------------------------------------------------------------------------------------------
//
// WARNING: THIS SOURCE FILE IS FOR 32-BIT BUILDS ONLY!
//
// MCG GENERATED CODE
//
// This C# source file is generated by MCG and is added into the application at compile time to support interop features.
//
// It has three primary components:
//
// 1. Public type definitions with interop implementation used by this application including WinRT & COM data structures and P/Invokes.
//
// 2. The 'McgInterop' class containing marshaling code that acts as a bridge from managed code to native code.
//
// 3. The 'McgNative' class containing marshaling code and native type definitions that call into native code and are called by native code.
//
// -----------------------------------------------------------------------------------------------------------
//
// warning CS0067: The event 'event' is never used
#pragma warning disable 67
// warning CS0169: The field 'field' is never used
#pragma warning disable 169
// warning CS0649: Field 'field' is never assigned to, and will always have its default value 0
#pragma warning disable 649
// warning CS1591: Missing XML comment for publicly visible type or member 'Type_or_Member'
#pragma warning disable 1591
// warning CS0108 'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended.
#pragma warning disable 108
// warning CS0114 'member1' hides inherited member 'member2'. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword.
#pragma warning disable 114
// warning CS0659 'type' overrides Object.Equals but does not override GetHashCode.
#pragma warning disable 659
// warning CS0465 Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?
#pragma warning disable 465
// warning CS0028 'function declaration' has the wrong signature to be an entry point
#pragma warning disable 28
// warning CS0162 Unreachable code Detected
#pragma warning disable 162
// warning CS0628 new protected member declared in sealed class
#pragma warning disable 628
namespace McgInterop
{
/// <summary>
/// P/Invoke class for module '[MRT]'
/// </summary>
public unsafe static partial class _MRT_
{
// Signature, RhWaitForPendingFinalizers, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhWaitForPendingFinalizers")]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void RhWaitForPendingFinalizers(int allowReentrantWait)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.RhWaitForPendingFinalizers(allowReentrantWait);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, RhCompatibleReentrantWaitAny, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr___ptr__w64 int *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhCompatibleReentrantWaitAny")]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop._MRT__PInvokes.RhCompatibleReentrantWaitAny(
alertable,
timeout,
count,
((global::System.IntPtr*)handles)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, _ecvt_s, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "_ecvt_s")]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes._ecvt_s(
((byte*)buffer),
sizeInBytes,
value,
count,
((int*)dec),
((int*)sign)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, memmove, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "memmove")]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void memmove(
byte* dmem,
byte* smem,
uint size)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.memmove(
((byte*)dmem),
((byte*)smem),
size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll
{
// Signature, RoInitialize, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "RoInitialize")]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static int RoInitialize(uint initType)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_l1_1_0_dll_PInvokes.RoInitialize(initType);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-localization-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll
{
// Signature, IsValidLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "IsValidLocaleName")]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static int IsValidLocaleName(char* lpLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.IsValidLocaleName(((ushort*)lpLocaleName));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ResolveLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "ResolveLocaleName")]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static int ResolveLocaleName(
char* lpNameToResolve,
char* lpLocaleName,
int cchLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.ResolveLocaleName(
((ushort*)lpNameToResolve),
((ushort*)lpLocaleName),
cchLocaleName
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, GetCPInfoExW, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages___ptrInterop_mincore__CPINFOEXW__System_Text_Encoding_CodePages *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Text.Encoding.CodePages, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetCPInfoExW")]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop.mincore.CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.GetCPInfoExW(
CodePage,
dwFlags,
((global::Interop.mincore.CPINFOEXW__System_Text_Encoding_CodePages*)lpCPInfoEx)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-com-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll
{
// Signature, CoCreateInstance, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.StackTraceGenerator.StackTraceGenerator", "CoCreateInstance")]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
out global::System.IntPtr ppv)
{
// Setup
global::System.IntPtr unsafe_ppv;
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_com_l1_1_0_dll_PInvokes.CoCreateInstance(
((byte*)rclsid),
pUnkOuter,
dwClsContext,
((byte*)riid),
&(unsafe_ppv)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
ppv = unsafe_ppv;
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'OleAut32'
/// </summary>
public unsafe static partial class OleAut32
{
// Signature, SysFreeString, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.LightweightInterop.MarshalExtensions", "SysFreeString")]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void SysFreeString(global::System.IntPtr bstr)
{
// Marshalling
// Call to native method
global::McgInterop.OleAut32_PInvokes.SysFreeString(bstr);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
public unsafe static partial class _MRT__PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]")]
public extern static void RhWaitForPendingFinalizers(int allowReentrantWait);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]")]
public extern static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]")]
public extern static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]")]
public extern static void memmove(
byte* dmem,
byte* smem,
uint size);
}
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-l1-1-0.dll")]
public extern static int RoInitialize(uint initType);
}
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll")]
public extern static int IsValidLocaleName(ushort* lpLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll")]
public extern static int ResolveLocaleName(
ushort* lpNameToResolve,
ushort* lpLocaleName,
int cchLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll")]
public extern static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop.mincore.CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx);
}
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-com-l1-1-0.dll")]
public extern static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
global::System.IntPtr* ppv);
}
public unsafe static partial class OleAut32_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("oleaut32.dll", EntryPoint="#6")]
public extern static void SysFreeString(global::System.IntPtr bstr);
}
}
| |
//
// GenericOutputter.cs
//
// Authors:
// Oleg Tkachenko (oleg@tkachenko.com)
// Atsushi Enomoto (ginga@kit.hi-ho.ne.jp)
//
// (C) 2003 Oleg Tkachenko, Atsushi Enomoto
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Xml;
using System.IO;
using System.Text;
namespace Mono.Xml.Xsl
{
/// <summary>
/// Generic implemenatation of the Outputter.
/// Works as a buffer between Transformation classes and an Emitter.
/// Implements attributes dublicate checking, nemaspace stuff and
/// choosing of right Emitter implementation.
/// </summary>
internal class GenericOutputter : Outputter {
private Hashtable _outputs;
//Current xsl:output
private XslOutput _currentOutput;
//Underlying emitter
private Emitter _emitter;
// destination TextWriter,
// which is pended until the actual output is determined.
private TextWriter pendingTextWriter;
// also, whitespaces before the first element are cached.
StringBuilder pendingFirstSpaces;
//Outputting state
private WriteState _state;
// Collection of pending attributes. TODO: Can we make adding an attribute
// O(1)? I'm not sure it is that important (this would only really make a difference
// if elements had like 10 attributes, which is very rare).
Attribute [] pendingAttributes = new Attribute [10];
int pendingAttributesPos = 0;
//Namespace manager. Subject to optimization.
private XmlNamespaceManager _nsManager;
private ListDictionary _currentNamespaceDecls;
// See CheckState(). This is just a cache.
private ArrayList newNamespaces = new ArrayList();
//Name table
private NameTable _nt;
// Specified encoding (for TextWriter output)
Encoding _encoding;
//Determines whether xsl:copy can output attribute-sets or not.
bool _canProcessAttributes;
bool _insideCData;
// bool _isVariable;
bool _omitXmlDeclaration;
int _xpCount;
private GenericOutputter (Hashtable outputs, Encoding encoding)
{
_encoding = encoding;
_outputs = outputs;
_currentOutput = (XslOutput)outputs [String.Empty];
_state = WriteState.Prolog;
//TODO: Optimize using nametable
_nt = new NameTable ();
_nsManager = new XmlNamespaceManager (_nt);
_currentNamespaceDecls = new ListDictionary ();
_omitXmlDeclaration = false;
}
public GenericOutputter (XmlWriter writer, Hashtable outputs, Encoding encoding)
: this (writer, outputs, encoding, false)
{
}
internal GenericOutputter (XmlWriter writer, Hashtable outputs, Encoding encoding, bool isVariable)
: this (outputs, encoding)
{
_emitter = new XmlWriterEmitter (writer);
_state = writer.WriteState;
// _isVariable = isVariable;
_omitXmlDeclaration = true; // .Net never writes XML declaration via XmlWriter
}
public GenericOutputter (TextWriter writer, Hashtable outputs, Encoding encoding)
: this (outputs, encoding)
{
this.pendingTextWriter = writer;
}
internal GenericOutputter (TextWriter writer, Hashtable outputs)
: this (writer, outputs, null)
{
}
internal GenericOutputter (XmlWriter writer, Hashtable outputs)
: this (writer, outputs, null)
{
}
private Emitter Emitter {
get {
if (_emitter == null)
DetermineOutputMethod (null, null);
return _emitter;
}
}
private void DetermineOutputMethod (string localName, string ns)
{
XslOutput xslOutput = (XslOutput)_outputs [String.Empty];
switch (xslOutput.Method) {
default: // .Custom format is not supported, only handled as unknown
case OutputMethod.Unknown:
if (localName != null && String.Compare (localName, "html", true, CultureInfo.InvariantCulture) == 0 && ns == String.Empty)
goto case OutputMethod.HTML;
goto case OutputMethod.XML;
case OutputMethod.HTML:
_emitter = new HtmlEmitter (pendingTextWriter, xslOutput);
break;
case OutputMethod.XML:
XmlTextWriter w = new XmlTextWriter (pendingTextWriter);
if (xslOutput.Indent == "yes")
w.Formatting = Formatting.Indented;
_emitter = new XmlWriterEmitter (w);
if (!_omitXmlDeclaration && !xslOutput.OmitXmlDeclaration)
_emitter.WriteStartDocument (
_encoding != null ? _encoding : xslOutput.Encoding,
xslOutput.Standalone);
break;
case OutputMethod.Text:
_emitter = new TextEmitter (pendingTextWriter);
break;
}
pendingTextWriter = null;
}
/// <summary>
/// Checks output state and flushes pending attributes and namespaces
/// when it's appropriate.
/// </summary>
private void CheckState ()
{
if (_state == WriteState.Element) {
//Emit pending attributes
_nsManager.PushScope ();
foreach (string prefix in _currentNamespaceDecls.Keys)
{
string uri = _currentNamespaceDecls [prefix] as string;
if (_nsManager.LookupNamespace (prefix, false) == uri)
continue;
newNamespaces.Add (prefix);
_nsManager.AddNamespace (prefix, uri);
}
for (int i = 0; i < pendingAttributesPos; i++)
{
Attribute attr = pendingAttributes [i];
string prefix = attr.Prefix;
if (prefix == XmlNamespaceManager.PrefixXml &&
attr.Namespace != XmlNamespaceManager.XmlnsXml)
// don't allow mapping from "xml" to other namespaces.
prefix = String.Empty;
string existing = _nsManager.LookupPrefix (attr.Namespace, false);
if (prefix.Length == 0 && attr.Namespace.Length > 0)
prefix = existing;
if (attr.Namespace.Length > 0) {
if (prefix == null || prefix == String.Empty)
{ // ADD
// empty prefix is not allowed
// for non-local attributes.
prefix = "xp_" + _xpCount++;
//if (existing != prefix) {
while (_nsManager.LookupNamespace (prefix) != null)
prefix = "xp_" + _xpCount++;
newNamespaces.Add (prefix);
_currentNamespaceDecls.Add (prefix, attr.Namespace);
_nsManager.AddNamespace (prefix, attr.Namespace);
//}
} // ADD
}
Emitter.WriteAttributeString (prefix, attr.LocalName, attr.Namespace, attr.Value);
}
for (int i = 0; i < newNamespaces.Count; i++)
{
string prefix = (string) newNamespaces [i];
string uri = _currentNamespaceDecls [prefix] as string;
if (prefix != String.Empty)
Emitter.WriteAttributeString ("xmlns", prefix, XmlNamespaceManager.XmlnsXmlns, uri);
else
Emitter.WriteAttributeString (String.Empty, "xmlns", XmlNamespaceManager.XmlnsXmlns, uri);
}
_currentNamespaceDecls.Clear ();
//Attributes flushed, state is Content now
_state = WriteState.Content;
newNamespaces.Clear ();
}
_canProcessAttributes = false;
}
#region Outputter's methods implementation
public override void WriteStartElement (string prefix, string localName, string nsURI)
{
if (_emitter == null) {
this.DetermineOutputMethod (localName, nsURI);
if (pendingFirstSpaces != null) {
WriteWhitespace (pendingFirstSpaces.ToString ());
pendingFirstSpaces = null;
}
}
if (_state == WriteState.Prolog) {
//Seems to be the first element - take care of Doctype
// Note that HTML does not require SYSTEM identifier.
if (_currentOutput.DoctypePublic != null || _currentOutput.DoctypeSystem != null)
Emitter.WriteDocType (prefix + (prefix==null? ":" : "") + localName,
_currentOutput.DoctypePublic, _currentOutput.DoctypeSystem);
}
CheckState ();
if (nsURI == String.Empty)
prefix = String.Empty;
Emitter.WriteStartElement (prefix, localName, nsURI);
_state = WriteState.Element;
if (_nsManager.LookupNamespace (prefix, false) != nsURI)
// _nsManager.AddNamespace (prefix, nsURI);
_currentNamespaceDecls [prefix] = nsURI;
pendingAttributesPos = 0;
_canProcessAttributes = true;
}
public override void WriteEndElement ()
{
WriteEndElementInternal (false);
}
public override void WriteFullEndElement()
{
WriteEndElementInternal (true);
}
private void WriteEndElementInternal (bool fullEndElement)
{
CheckState ();
if (fullEndElement)
Emitter.WriteFullEndElement ();
else
Emitter.WriteEndElement ();
_state = WriteState.Content;
//Pop namespace scope
_nsManager.PopScope ();
}
public override void WriteAttributeString (string prefix, string localName, string nsURI, string value)
{
//Put attribute to pending attributes collection, replacing namesake one
for (int i = 0; i < pendingAttributesPos; i++) {
Attribute attr = pendingAttributes [i];
if (attr.LocalName == localName && attr.Namespace == nsURI) {
pendingAttributes [i].Value = value;
pendingAttributes [i].Prefix = prefix;
return;
}
}
if (pendingAttributesPos == pendingAttributes.Length) {
Attribute [] old = pendingAttributes;
pendingAttributes = new Attribute [pendingAttributesPos * 2 + 1];
if (pendingAttributesPos > 0)
Array.Copy (old, 0, pendingAttributes, 0, pendingAttributesPos);
}
pendingAttributes [pendingAttributesPos].Prefix = prefix;
pendingAttributes [pendingAttributesPos].Namespace = nsURI;
pendingAttributes [pendingAttributesPos].LocalName = localName;
pendingAttributes [pendingAttributesPos].Value = value;
pendingAttributesPos++;
}
public override void WriteNamespaceDecl (string prefix, string nsUri)
{
if (_nsManager.LookupNamespace (prefix, false) == nsUri)
return; // do nothing
for (int i = 0; i < pendingAttributesPos; i++) {
Attribute attr = pendingAttributes [i];
if (attr.Prefix == prefix || attr.Namespace == nsUri)
return; //don't touch explicitly declared attributes
}
if (_currentNamespaceDecls [prefix] as string != nsUri)
_currentNamespaceDecls [prefix] = nsUri;
}
public override void WriteComment (string text)
{
CheckState ();
Emitter.WriteComment (text);
}
public override void WriteProcessingInstruction (string name, string text)
{
CheckState ();
Emitter.WriteProcessingInstruction (name, text);
}
public override void WriteString (string text)
{
CheckState ();
if (_insideCData)
Emitter.WriteCDataSection (text);
// This weird check is required to reject Doctype
// after non-whitespace nodes but also to allow
// Doctype after whitespace nodes. It especially
// happens when there is an xsl:text before the
// document element (e.g. BVTs_bvt066 testcase).
else if (_state != WriteState.Content &&
text.Length > 0 && XmlChar.IsWhitespace (text))
Emitter.WriteWhitespace (text);
else
Emitter.WriteString (text);
}
public override void WriteRaw (string data)
{
CheckState ();
Emitter.WriteRaw (data);
}
public override void WriteWhitespace (string text)
{
if (_emitter == null) {
if (pendingFirstSpaces == null)
pendingFirstSpaces = new StringBuilder ();
pendingFirstSpaces.Append (text);
if (_state == WriteState.Start)
_state = WriteState.Prolog;
} else {
CheckState ();
Emitter.WriteWhitespace (text);
}
}
public override void Done ()
{
Emitter.Done ();
_state = WriteState.Closed;
}
public override bool CanProcessAttributes {
get { return _canProcessAttributes; }
}
public override bool InsideCDataSection {
get { return _insideCData; }
set { _insideCData = value; }
}
#endregion
}
}
| |
class C
{
public static void N0()
{
N19();
N47();
N81();
N52();
N77();
N39();
}
public static void N1()
{
N40();
N25();
N14();
N52();
}
public static void N2()
{
N78();
N56();
N8();
}
public static void N3()
{
N45();
N83();
N60();
N80();
N50();
N94();
}
public static void N4()
{
N90();
N96();
N44();
N8();
}
public static void N5()
{
N72();
N39();
N21();
N93();
N0();
}
public static void N6()
{
N73();
N54();
N28();
N40();
N30();
N7();
N65();
}
public static void N7()
{
N83();
N84();
N18();
}
public static void N8()
{
N63();
N12();
N30();
N88();
N45();
N61();
N58();
}
public static void N9()
{
N16();
N94();
N27();
N90();
N5();
}
public static void N10()
{
N87();
N60();
N24();
N67();
}
public static void N11()
{
N12();
N39();
N52();
N92();
N98();
}
public static void N12()
{
N90();
N12();
N78();
N59();
N49();
N84();
N63();
}
public static void N13()
{
N52();
N83();
N40();
N44();
N23();
}
public static void N14()
{
N91();
N38();
N68();
N60();
N34();
}
public static void N15()
{
N43();
N39();
N82();
N56();
N52();
N71();
}
public static void N16()
{
N88();
N50();
N7();
N34();
N60();
N18();
}
public static void N17()
{
N86();
N78();
N89();
N12();
N95();
}
public static void N18()
{
N92();
N71();
N51();
}
public static void N19()
{
N55();
N65();
N29();
N88();
N64();
N43();
N21();
}
public static void N20()
{
N23();
N92();
N43();
N7();
N9();
N62();
}
public static void N21()
{
N26();
N40();
N87();
}
public static void N22()
{
N30();
N1();
N20();
N85();
}
public static void N23()
{
N20();
N1();
N14();
N94();
}
public static void N24()
{
N15();
N70();
N77();
N74();
N13();
N62();
N76();
N67();
N17();
N63();
N36();
}
public static void N25()
{
N90();
N86();
N96();
N19();
N91();
}
public static void N26()
{
N47();
N79();
N59();
N45();
N49();
N0();
}
public static void N27()
{
N2();
N70();
N32();
N55();
N36();
N73();
N98();
N50();
N59();
N14();
}
public static void N28()
{
N29();
N1();
N81();
N57();
}
public static void N29()
{
N90();
N58();
N51();
}
public static void N30()
{
N92();
N35();
N46();
}
public static void N31()
{
N53();
N71();
N7();
}
public static void N32()
{
N79();
N7();
N80();
}
public static void N33()
{
N83();
N10();
N41();
}
public static void N34()
{
N69();
N11();
N43();
N68();
N20();
N57();
N8();
N64();
N25();
N26();
N21();
}
public static void N35()
{
N9();
N61();
N19();
N32();
N51();
N67();
}
public static void N36()
{
N42();
N8();
N0();
N39();
N56();
N71();
N77();
N16();
}
public static void N37()
{
N15();
N5();
N51();
N25();
N90();
}
public static void N38()
{
N49();
N5();
}
public static void N39()
{
N14();
N5();
N53();
N2();
}
public static void N40()
{
N31();
N44();
N72();
N65();
N15();
}
public static void N41()
{
N49();
N31();
N19();
}
public static void N42()
{
N92();
N31();
N56();
}
public static void N43()
{
N91();
N19();
N4();
N25();
}
public static void N44()
{
N66();
N43();
N12();
N76();
N6();
N38();
N5();
N19();
}
public static void N45()
{
N72();
N89();
N70();
N15();
N85();
N74();
N21();
N84();
N33();
N59();
}
public static void N46()
{
N54();
N85();
N66();
N78();
N53();
}
public static void N47()
{
N19();
N64();
N94();
N8();
N82();
N56();
}
public static void N48()
{
N11();
N52();
N17();
N39();
}
public static void N49()
{
N84();
N65();
N1();
N28();
N35();
}
public static void N50()
{
N25();
N2();
}
public static void N51()
{
N50();
N64();
N56();
N78();
N20();
N12();
N47();
N86();
}
public static void N52()
{
N67();
N63();
N77();
N11();
N35();
N58();
}
public static void N53()
{
N92();
N76();
N62();
N89();
}
public static void N54()
{
N77();
N94();
N57();
N86();
N2();
N37();
}
public static void N55()
{
N98();
N4();
N79();
N18();
}
public static void N56()
{
N52();
}
public static void N57()
{
N1();
N50();
N64();
N42();
N2();
N19();
}
public static void N58()
{
N27();
N49();
N87();
N24();
N42();
N64();
}
public static void N59()
{
N40();
N64();
N63();
N95();
N2();
N12();
}
public static void N60()
{
N85();
N3();
N48();
N1();
}
public static void N61()
{
N22();
N4();
N8();
N38();
N39();
N84();
N56();
}
public static void N62()
{
N61();
N88();
N24();
N15();
}
public static void N63()
{
N45();
N21();
N24();
N4();
N7();
}
public static void N64()
{
N35();
N12();
N39();
N6();
N31();
}
public static void N65()
{
N27();
N6();
N16();
N81();
N13();
}
public static void N66()
{
N83();
N16();
N49();
N55();
N27();
N96();
}
public static void N67()
{
N2();
N78();
N51();
N67();
}
public static void N68()
{
}
public static void N69()
{
N39();
N21();
N23();
}
public static void N70()
{
N49();
N58();
N98();
N77();
N32();
}
public static void N71()
{
N55();
N48();
}
public static void N72()
{
N18();
N9();
}
public static void N73()
{
N34();
N45();
N20();
N73();
}
public static void N74()
{
N94();
N18();
N69();
N23();
}
public static void N75()
{
N16();
N87();
N44();
}
public static void N76()
{
N97();
N50();
N35();
N60();
N28();
}
public static void N77()
{
N65();
N10();
N64();
N19();
N86();
}
public static void N78()
{
N44();
N23();
N81();
N34();
N79();
N74();
N72();
N16();
}
public static void N79()
{
N35();
N37();
N49();
N98();
N94();
}
public static void N80()
{
N45();
N19();
N74();
N97();
N91();
N98();
}
public static void N81()
{
N16();
N38();
N44();
N7();
N37();
}
public static void N82()
{
N90();
N75();
N7();
N92();
N45();
}
public static void N83()
{
N70();
N22();
N92();
}
public static void N84()
{
N40();
N66();
N24();
N67();
N39();
N33();
N16();
N50();
N78();
N30();
N52();
}
public static void N85()
{
N0();
N60();
N15();
N44();
}
public static void N86()
{
N1();
N39();
N41();
N53();
}
public static void N87()
{
N84();
N63();
N58();
}
public static void N88()
{
N48();
N72();
N18();
N37();
N12();
}
public static void N89()
{
N98();
N37();
N59();
N14();
N81();
N2();
N51();
}
public static void N90()
{
N32();
N14();
N45();
N15();
}
public static void N91()
{
N89();
N67();
N74();
N27();
N39();
}
public static void N92()
{
N6();
N49();
N22();
N29();
N95();
N13();
N85();
}
public static void N93()
{
N4();
N41();
N47();
N93();
}
public static void N94()
{
N22();
}
public static void N95()
{
N80();
N89();
N45();
N94();
N2();
N4();
}
public static void N96()
{
N79();
N64();
N78();
N98();
N29();
}
public static void N97()
{
N15();
N64();
N90();
}
public static void N98()
{
N81();
N4();
N61();
N20();
N70();
}
public static void N99()
{
}
public static void Main()
{
N0();
N1();
N2();
N3();
N4();
N5();
N6();
N7();
N8();
N9();
N10();
N11();
N12();
N13();
N14();
N15();
N16();
N17();
N18();
N19();
N20();
N21();
N22();
N23();
N24();
N25();
N26();
N27();
N28();
N29();
N30();
N31();
N32();
N33();
N34();
N35();
N36();
N37();
N38();
N39();
N40();
N41();
N42();
N43();
N44();
N45();
N46();
N47();
N48();
N49();
N50();
N51();
N52();
N53();
N54();
N55();
N56();
N57();
N58();
N59();
N60();
N61();
N62();
N63();
N64();
N65();
N66();
N67();
N68();
N69();
N70();
N71();
N72();
N73();
N74();
N75();
N76();
N77();
N78();
N79();
N80();
N81();
N82();
N83();
N84();
N85();
N86();
N87();
N88();
N89();
N90();
N91();
N92();
N93();
N94();
N95();
N96();
N97();
N98();
N99();
Main();
}
}
| |
// 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.Text;
namespace System.Data.SqlClient
{
// VSTFDevDiv# 643319 - Improve timeout error message reported when SqlConnection.Open fails
internal enum SqlConnectionTimeoutErrorPhase
{
Undefined = 0,
PreLoginBegin, // [PRE-LOGIN PHASE] Start of the pre-login phase; Initialize global variables;
InitializeConnection, // [PRE-LOGIN PHASE] Create and initialize socket.
SendPreLoginHandshake, // [PRE-LOGIN PHASE] Make pre-login handshake request.
ConsumePreLoginHandshake, // [PRE-LOGIN PHASE] Receive pre-login handshake response and consume it; Establish an SSL channel.
LoginBegin, // [LOGIN PHASE] End of the pre-login phase; Start of the login phase;
ProcessConnectionAuth, // [LOGIN PHASE] Process SSPI or SQL Authenticate.
PostLogin, // [POST-LOGIN PHASE] End of the login phase; And post-login phase;
Complete, // Marker for the successful completion of the connection
Count // ** This is to track the length of the enum. ** Do not add any phase after this. **
}
internal enum SqlConnectionInternalSourceType
{
Principle,
Failover,
RoutingDestination
}
// DEVNOTE: Class to capture the duration spent in each SqlConnectionTimeoutErrorPhase.
internal class SqlConnectionTimeoutPhaseDuration
{
private Stopwatch _swDuration = new Stopwatch();
internal void StartCapture()
{
Debug.Assert(_swDuration != null, "Time capture stopwatch cannot be null.");
_swDuration.Start();
}
internal void StopCapture()
{
//Debug.Assert(swDuration.IsRunning == true, "The stop operation of the stopwatch cannot be called when it is not running.");
if (_swDuration.IsRunning == true)
_swDuration.Stop();
}
internal long GetMilliSecondDuration()
{
// DEVNOTE: In a phase fails in between a phase, the stop watch may still be running.
// Hence the check to verify if the stop watch is running hasn't been added in.
return _swDuration.ElapsedMilliseconds;
}
}
internal class SqlConnectionTimeoutErrorInternal
{
private SqlConnectionTimeoutPhaseDuration[] _phaseDurations = null;
private SqlConnectionTimeoutPhaseDuration[] _originalPhaseDurations = null;
private SqlConnectionTimeoutErrorPhase _currentPhase = SqlConnectionTimeoutErrorPhase.Undefined;
private SqlConnectionInternalSourceType _currentSourceType = SqlConnectionInternalSourceType.Principle;
private bool _isFailoverScenario = false;
internal SqlConnectionTimeoutErrorPhase CurrentPhase
{
get { return _currentPhase; }
}
public SqlConnectionTimeoutErrorInternal()
{
_phaseDurations = new SqlConnectionTimeoutPhaseDuration[(int)SqlConnectionTimeoutErrorPhase.Count];
for (int i = 0; i < _phaseDurations.Length; i++)
_phaseDurations[i] = null;
}
public void SetFailoverScenario(bool useFailoverServer)
{
_isFailoverScenario = useFailoverServer;
}
public void SetInternalSourceType(SqlConnectionInternalSourceType sourceType)
{
_currentSourceType = sourceType;
if (_currentSourceType == SqlConnectionInternalSourceType.RoutingDestination)
{
// When we get routed, save the current phase durations so that we can use them in the error message later
Debug.Assert(_currentPhase == SqlConnectionTimeoutErrorPhase.PostLogin, "Should not be switching to the routing destination until Post Login is completed");
_originalPhaseDurations = _phaseDurations;
_phaseDurations = new SqlConnectionTimeoutPhaseDuration[(int)SqlConnectionTimeoutErrorPhase.Count];
SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.PreLoginBegin);
}
}
internal void ResetAndRestartPhase()
{
_currentPhase = SqlConnectionTimeoutErrorPhase.PreLoginBegin;
for (int i = 0; i < _phaseDurations.Length; i++)
_phaseDurations[i] = null;
}
internal void SetAndBeginPhase(SqlConnectionTimeoutErrorPhase timeoutErrorPhase)
{
_currentPhase = timeoutErrorPhase;
if (_phaseDurations[(int)timeoutErrorPhase] == null)
{
_phaseDurations[(int)timeoutErrorPhase] = new SqlConnectionTimeoutPhaseDuration();
}
_phaseDurations[(int)timeoutErrorPhase].StartCapture();
}
internal void EndPhase(SqlConnectionTimeoutErrorPhase timeoutErrorPhase)
{
Debug.Assert(_phaseDurations[(int)timeoutErrorPhase] != null, "End phase capture cannot be invoked when the phase duration object is a null.");
_phaseDurations[(int)timeoutErrorPhase].StopCapture();
}
internal void SetAllCompleteMarker()
{
_currentPhase = SqlConnectionTimeoutErrorPhase.Complete;
}
internal string GetErrorMessage()
{
StringBuilder errorBuilder;
string durationString;
switch (_currentPhase)
{
case SqlConnectionTimeoutErrorPhase.PreLoginBegin:
errorBuilder = new StringBuilder(SQLMessage.Timeout_PreLogin_Begin());
durationString = SQLMessage.Duration_PreLogin_Begin(
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration());
break;
case SqlConnectionTimeoutErrorPhase.InitializeConnection:
errorBuilder = new StringBuilder(SQLMessage.Timeout_PreLogin_InitializeConnection());
durationString = SQLMessage.Duration_PreLogin_Begin(
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration());
break;
case SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake:
errorBuilder = new StringBuilder(SQLMessage.Timeout_PreLogin_SendHandshake());
durationString = SQLMessage.Duration_PreLoginHandshake(
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration());
break;
case SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake:
errorBuilder = new StringBuilder(SQLMessage.Timeout_PreLogin_ConsumeHandshake());
durationString = SQLMessage.Duration_PreLoginHandshake(
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration());
break;
case SqlConnectionTimeoutErrorPhase.LoginBegin:
errorBuilder = new StringBuilder(SQLMessage.Timeout_Login_Begin());
durationString = SQLMessage.Duration_Login_Begin(
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration(),
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.LoginBegin].GetMilliSecondDuration());
break;
case SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth:
errorBuilder = new StringBuilder(SQLMessage.Timeout_Login_ProcessConnectionAuth());
durationString = SQLMessage.Duration_Login_ProcessConnectionAuth(
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration(),
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.LoginBegin].GetMilliSecondDuration(),
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth].GetMilliSecondDuration());
break;
case SqlConnectionTimeoutErrorPhase.PostLogin:
errorBuilder = new StringBuilder(SQLMessage.Timeout_PostLogin());
durationString = SQLMessage.Duration_PostLogin(
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration(),
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.LoginBegin].GetMilliSecondDuration(),
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth].GetMilliSecondDuration(),
_phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PostLogin].GetMilliSecondDuration());
break;
default:
errorBuilder = new StringBuilder(SQLMessage.Timeout());
durationString = null;
break;
}
// This message is to be added only when within the various stages of a connection.
// In all other cases, it will default to the original error message.
if ((_currentPhase != SqlConnectionTimeoutErrorPhase.Undefined) && (_currentPhase != SqlConnectionTimeoutErrorPhase.Complete))
{
// NOTE: In case of a failover scenario, add a string that this failure occurred as part of the primary or secondary server
if (_isFailoverScenario)
{
errorBuilder.Append(" ");
errorBuilder.AppendFormat((IFormatProvider)null, SQLMessage.Timeout_FailoverInfo(), _currentSourceType);
}
else if (_currentSourceType == SqlConnectionInternalSourceType.RoutingDestination)
{
errorBuilder.Append(" ");
errorBuilder.AppendFormat((IFormatProvider)null, SQLMessage.Timeout_RoutingDestination(),
_originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
_originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
_originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
_originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration(),
_originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.LoginBegin].GetMilliSecondDuration(),
_originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth].GetMilliSecondDuration(),
_originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.PostLogin].GetMilliSecondDuration());
}
}
// NOTE: To display duration in each phase.
if (durationString != null)
{
errorBuilder.Append(" ");
errorBuilder.Append(durationString);
}
return errorBuilder.ToString();
}
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
// Federico Di Gregorio <fog@initd.org>
// Rolf Bjarne Kvinge <rolf@xamarin.com>
//
// Copyright (C) 2008 Novell (http://www.novell.com)
// Copyright (C) 2009 Federico Di Gregorio.
// Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections.Generic;
#if LINQ
using System.Linq;
#endif
#if TEST
using NDesk.Options;
#endif
#if NDESK_OPTIONS
namespace NDesk.Options
#else
namespace Mono.Options
#endif
{
internal static class StringCoda
{
public static IEnumerable<string> WrappedLines(string self, params int[] widths)
{
IEnumerable<int> w = widths;
return WrappedLines(self, w);
}
public static IEnumerable<string> WrappedLines(string self, IEnumerable<int> widths)
{
if (widths == null)
throw new ArgumentNullException("widths");
return CreateWrappedLinesIterator(self, widths);
}
static IEnumerable<string> CreateWrappedLinesIterator(string self, IEnumerable<int> widths)
{
if (string.IsNullOrEmpty(self))
{
yield return string.Empty;
yield break;
}
using (IEnumerator<int> ewidths = widths.GetEnumerator())
{
bool? hw = null;
int width = GetNextWidth(ewidths, int.MaxValue, ref hw);
int start = 0, end;
do
{
end = GetLineEnd(start, width, self);
char c = self[end - 1];
if (char.IsWhiteSpace(c))
--end;
bool needContinuation = end != self.Length && !IsEolChar(c);
string continuation = "";
if (needContinuation)
{
--end;
continuation = "-";
}
string line = self.Substring(start, end - start) + continuation;
yield return line;
start = end;
if (char.IsWhiteSpace(c))
++start;
width = GetNextWidth(ewidths, width, ref hw);
} while (start < self.Length);
}
}
static int GetNextWidth(IEnumerator<int> ewidths, int curWidth, ref bool? eValid)
{
if (!eValid.HasValue || (eValid.HasValue && eValid.Value))
{
curWidth = (eValid = ewidths.MoveNext()).Value ? ewidths.Current : curWidth;
// '.' is any character, - is for a continuation
const string minWidth = ".-";
if (curWidth < minWidth.Length)
{
throw new ArgumentOutOfRangeException("widths",
string.Format("Element must be >= {0}, was {1}.", minWidth.Length, curWidth));
}
return curWidth;
}
// no more elements, use the last element.
return curWidth;
}
static bool IsEolChar(char c)
{
return !char.IsLetterOrDigit(c);
}
static int GetLineEnd(int start, int length, string description)
{
int end = System.Math.Min(start + length, description.Length);
int sep = -1;
for (int i = start; i < end; ++i)
{
if (description[i] == '\n')
return i + 1;
if (IsEolChar(description[i]))
sep = i + 1;
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
}
| |
// 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.AcceptanceTestsHttp
{
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>
/// HttpFailure operations.
/// </summary>
public partial class HttpFailure : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpFailure
{
/// <summary>
/// Initializes a new instance of the HttpFailure class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public HttpFailure(AutoRestHttpInfrastructureTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHttpInfrastructureTestService
/// </summary>
public AutoRestHttpInfrastructureTestService Client { get; private set; }
/// <summary>
/// Get empty error form server
/// </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<bool?>> GetEmptyErrorWithHttpMessagesAsync(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, "GetEmptyError", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/emptybody/error").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<bool?>();
_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<bool?>(_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 empty error form server
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<bool?>> GetNoModelErrorWithHttpMessagesAsync(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, "GetNoModelError", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/nomodel/error").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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<bool?>();
_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<bool?>(_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 empty response from server
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<bool?>> GetNoModelEmptyWithHttpMessagesAsync(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, "GetNoModelEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/nomodel/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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<bool?>();
_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<bool?>(_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 (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for InboundNatRulesOperations.
/// </summary>
public static partial class InboundNatRulesOperationsExtensions
{
/// <summary>
/// Gets all the inbound nat rules in a load balancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
public static IPage<InboundNatRule> List(this IInboundNatRulesOperations operations, string resourceGroupName, string loadBalancerName)
{
return operations.ListAsync(resourceGroupName, loadBalancerName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the inbound nat rules in a load balancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<InboundNatRule>> ListAsync(this IInboundNatRulesOperations operations, string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, loadBalancerName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified load balancer inbound nat rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='inboundNatRuleName'>
/// The name of the inbound nat rule.
/// </param>
public static void Delete(this IInboundNatRulesOperations operations, string resourceGroupName, string loadBalancerName, string inboundNatRuleName)
{
operations.DeleteAsync(resourceGroupName, loadBalancerName, inboundNatRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified load balancer inbound nat rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='inboundNatRuleName'>
/// The name of the inbound nat rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IInboundNatRulesOperations operations, string resourceGroupName, string loadBalancerName, string inboundNatRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified load balancer inbound nat rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='inboundNatRuleName'>
/// The name of the inbound nat rule.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
public static InboundNatRule Get(this IInboundNatRulesOperations operations, string resourceGroupName, string loadBalancerName, string inboundNatRuleName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified load balancer inbound nat rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='inboundNatRuleName'>
/// The name of the inbound nat rule.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<InboundNatRule> GetAsync(this IInboundNatRulesOperations operations, string resourceGroupName, string loadBalancerName, string inboundNatRuleName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a load balancer inbound nat rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='inboundNatRuleName'>
/// The name of the inbound nat rule.
/// </param>
/// <param name='inboundNatRuleParameters'>
/// Parameters supplied to the create or update inbound nat rule operation.
/// </param>
public static InboundNatRule CreateOrUpdate(this IInboundNatRulesOperations operations, string resourceGroupName, string loadBalancerName, string inboundNatRuleName, InboundNatRule inboundNatRuleParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a load balancer inbound nat rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='inboundNatRuleName'>
/// The name of the inbound nat rule.
/// </param>
/// <param name='inboundNatRuleParameters'>
/// Parameters supplied to the create or update inbound nat rule operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<InboundNatRule> CreateOrUpdateAsync(this IInboundNatRulesOperations operations, string resourceGroupName, string loadBalancerName, string inboundNatRuleName, InboundNatRule inboundNatRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified load balancer inbound nat rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='inboundNatRuleName'>
/// The name of the inbound nat rule.
/// </param>
public static void BeginDelete(this IInboundNatRulesOperations operations, string resourceGroupName, string loadBalancerName, string inboundNatRuleName)
{
operations.BeginDeleteAsync(resourceGroupName, loadBalancerName, inboundNatRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified load balancer inbound nat rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='inboundNatRuleName'>
/// The name of the inbound nat rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IInboundNatRulesOperations operations, string resourceGroupName, string loadBalancerName, string inboundNatRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a load balancer inbound nat rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='inboundNatRuleName'>
/// The name of the inbound nat rule.
/// </param>
/// <param name='inboundNatRuleParameters'>
/// Parameters supplied to the create or update inbound nat rule operation.
/// </param>
public static InboundNatRule BeginCreateOrUpdate(this IInboundNatRulesOperations operations, string resourceGroupName, string loadBalancerName, string inboundNatRuleName, InboundNatRule inboundNatRuleParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a load balancer inbound nat rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='inboundNatRuleName'>
/// The name of the inbound nat rule.
/// </param>
/// <param name='inboundNatRuleParameters'>
/// Parameters supplied to the create or update inbound nat rule operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<InboundNatRule> BeginCreateOrUpdateAsync(this IInboundNatRulesOperations operations, string resourceGroupName, string loadBalancerName, string inboundNatRuleName, InboundNatRule inboundNatRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the inbound nat rules in a load balancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<InboundNatRule> ListNext(this IInboundNatRulesOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the inbound nat rules in a load balancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<InboundNatRule>> ListNextAsync(this IInboundNatRulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// 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.Linq;
using System.Numerics;
using Xunit;
namespace System.Security.Cryptography.Rsa.Tests
{
public partial class ImportExport
{
private static bool EphemeralKeysAreExportable => !PlatformDetection.IsFullFramework || PlatformDetection.IsNetfx462OrNewer();
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void ExportAutoKey()
{
RSAParameters privateParams;
RSAParameters publicParams;
int keySize;
using (RSA rsa = RSAFactory.Create())
{
keySize = rsa.KeySize;
// We've not done anything with this instance yet, but it should automatically
// create the key, because we'll now asked about it.
privateParams = rsa.ExportParameters(true);
publicParams = rsa.ExportParameters(false);
// It shouldn't be changing things when it generated the key.
Assert.Equal(keySize, rsa.KeySize);
}
Assert.Null(publicParams.D);
Assert.NotNull(privateParams.D);
ValidateParameters(ref publicParams);
ValidateParameters(ref privateParams);
Assert.Equal(privateParams.Modulus, publicParams.Modulus);
Assert.Equal(privateParams.Exponent, publicParams.Exponent);
}
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void PaddedExport()
{
// OpenSSL's numeric type for the storage of RSA key parts disregards zero-valued
// prefix bytes.
//
// The .NET 4.5 RSACryptoServiceProvider type verifies that all of the D breakdown
// values (P, DP, Q, DQ, InverseQ) are exactly half the size of D (which is itself
// the same size as Modulus).
//
// These two things, in combination, suggest that we ensure that all .NET
// implementations of RSA export their keys to the fixed array size suggested by their
// KeySize property.
RSAParameters diminishedDPParameters = TestData.DiminishedDPParameters;
RSAParameters exported;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(diminishedDPParameters);
exported = rsa.ExportParameters(true);
}
// DP is the most likely to fail, the rest just otherwise ensure that Export
// isn't losing data.
AssertKeyEquals(ref diminishedDPParameters, ref exported);
}
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void LargeKeyImportExport()
{
RSAParameters imported = TestData.RSA16384Params;
using (RSA rsa = RSAFactory.Create())
{
try
{
rsa.ImportParameters(imported);
}
catch (CryptographicException)
{
// The key is pretty big, perhaps it was refused.
return;
}
RSAParameters exported = rsa.ExportParameters(false);
Assert.Equal(exported.Modulus, imported.Modulus);
Assert.Equal(exported.Exponent, imported.Exponent);
Assert.Null(exported.D);
exported = rsa.ExportParameters(true);
AssertKeyEquals(ref imported, ref exported);
}
}
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void UnusualExponentImportExport()
{
// Most choices for the Exponent value in an RSA key use a Fermat prime.
// Since a Fermat prime is 2^(2^m) + 1, it always only has two bits set, and
// frequently has the form { 0x01, [some number of 0x00s], 0x01 }, which has the same
// representation in both big- and little-endian.
//
// The only real requirement for an Exponent value is that it be coprime to (p-1)(q-1).
// So here we'll use the (non-Fermat) prime value 433 (0x01B1) to ensure big-endian export.
RSAParameters unusualExponentParameters = TestData.UnusualExponentParameters;
RSAParameters exported;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(unusualExponentParameters);
exported = rsa.ExportParameters(true);
}
// Exponent is the most likely to fail, the rest just otherwise ensure that Export
// isn't losing data.
AssertKeyEquals(ref unusualExponentParameters, ref exported);
}
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void ImportExport1032()
{
RSAParameters imported = TestData.RSA1032Parameters;
RSAParameters exported;
RSAParameters exportedPublic;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(imported);
exported = rsa.ExportParameters(true);
exportedPublic = rsa.ExportParameters(false);
}
AssertKeyEquals(ref imported, ref exported);
Assert.Equal(exportedPublic.Modulus, imported.Modulus);
Assert.Equal(exportedPublic.Exponent, imported.Exponent);
Assert.Null(exportedPublic.D);
}
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void ImportReset()
{
using (RSA rsa = RSAFactory.Create())
{
RSAParameters exported = rsa.ExportParameters(true);
RSAParameters imported;
// Ensure that we cause the KeySize value to change.
if (rsa.KeySize == 1024)
{
imported = TestData.RSA2048Params;
}
else
{
imported = TestData.RSA1024Params;
}
Assert.NotEqual(imported.Modulus.Length * 8, rsa.KeySize);
Assert.NotEqual(imported.Modulus, exported.Modulus);
rsa.ImportParameters(imported);
Assert.Equal(imported.Modulus.Length * 8, rsa.KeySize);
exported = rsa.ExportParameters(true);
AssertKeyEquals(ref imported, ref exported);
}
}
[Fact]
public static void ImportPrivateExportPublic()
{
RSAParameters imported = TestData.RSA1024Params;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(imported);
RSAParameters exportedPublic = rsa.ExportParameters(false);
Assert.Equal(imported.Modulus, exportedPublic.Modulus);
Assert.Equal(imported.Exponent, exportedPublic.Exponent);
Assert.Null(exportedPublic.D);
ValidateParameters(ref exportedPublic);
}
}
[ConditionalFact(nameof(EphemeralKeysAreExportable))]
public static void MultiExport()
{
RSAParameters imported = TestData.RSA1024Params;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(imported);
RSAParameters exportedPrivate = rsa.ExportParameters(true);
RSAParameters exportedPrivate2 = rsa.ExportParameters(true);
RSAParameters exportedPublic = rsa.ExportParameters(false);
RSAParameters exportedPublic2 = rsa.ExportParameters(false);
RSAParameters exportedPrivate3 = rsa.ExportParameters(true);
RSAParameters exportedPublic3 = rsa.ExportParameters(false);
AssertKeyEquals(ref imported, ref exportedPrivate);
Assert.Equal(imported.Modulus, exportedPublic.Modulus);
Assert.Equal(imported.Exponent, exportedPublic.Exponent);
Assert.Null(exportedPublic.D);
ValidateParameters(ref exportedPublic);
AssertKeyEquals(ref exportedPrivate, ref exportedPrivate2);
AssertKeyEquals(ref exportedPrivate, ref exportedPrivate3);
AssertKeyEquals(ref exportedPublic, ref exportedPublic2);
AssertKeyEquals(ref exportedPublic, ref exportedPublic3);
}
}
[Fact]
public static void PublicOnlyPrivateExport()
{
RSAParameters imported = new RSAParameters
{
Modulus = TestData.RSA1024Params.Modulus,
Exponent = TestData.RSA1024Params.Exponent,
};
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(imported);
Assert.ThrowsAny<CryptographicException>(() => rsa.ExportParameters(true));
}
}
[Fact]
public static void ImportNoExponent()
{
RSAParameters imported = new RSAParameters
{
Modulus = TestData.RSA1024Params.Modulus,
};
using (RSA rsa = RSAFactory.Create())
{
if (rsa is RSACng && PlatformDetection.IsFullFramework)
Assert.Throws<ArgumentException>(() => rsa.ImportParameters(imported));
else
Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported));
}
}
[Fact]
public static void ImportNoModulus()
{
RSAParameters imported = new RSAParameters
{
Exponent = TestData.RSA1024Params.Exponent,
};
using (RSA rsa = RSAFactory.Create())
{
if (rsa is RSACng && PlatformDetection.IsFullFramework)
Assert.Throws<ArgumentException>(() => rsa.ImportParameters(imported));
else
Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported));
}
}
[Fact]
#if TESTING_CNG_IMPLEMENTATION
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "https://github.com/dotnet/corefx/issues/18882")]
#endif
public static void ImportNoDP()
{
// Because RSAParameters is a struct, this is a copy,
// so assigning DP is not destructive to other tests.
RSAParameters imported = TestData.RSA1024Params;
imported.DP = null;
using (RSA rsa = RSAFactory.Create())
{
Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported));
}
}
internal static void AssertKeyEquals(ref RSAParameters expected, ref RSAParameters actual)
{
Assert.Equal(expected.Modulus, actual.Modulus);
Assert.Equal(expected.Exponent, actual.Exponent);
Assert.Equal(expected.P, actual.P);
Assert.Equal(expected.DP, actual.DP);
Assert.Equal(expected.Q, actual.Q);
Assert.Equal(expected.DQ, actual.DQ);
Assert.Equal(expected.InverseQ, actual.InverseQ);
if (expected.D == null)
{
Assert.Null(actual.D);
}
else
{
Assert.NotNull(actual.D);
// If the value matched expected, take that as valid and shortcut the math.
// If it didn't, we'll test that the value is at least legal.
if (!expected.D.SequenceEqual(actual.D))
{
VerifyDValue(ref actual);
}
}
}
internal static void ValidateParameters(ref RSAParameters rsaParams)
{
Assert.NotNull(rsaParams.Modulus);
Assert.NotNull(rsaParams.Exponent);
// Key compatibility: RSA as an algorithm is achievable using just N (Modulus),
// E (public Exponent) and D (private exponent). Having all of the breakdowns
// of D make the algorithm faster, and shipped versions of RSACryptoServiceProvider
// have thrown if D is provided and the rest of the private key values are not.
// So, here we're going to assert that none of them were null for private keys.
if (rsaParams.D == null)
{
Assert.Null(rsaParams.P);
Assert.Null(rsaParams.DP);
Assert.Null(rsaParams.Q);
Assert.Null(rsaParams.DQ);
Assert.Null(rsaParams.InverseQ);
}
else
{
Assert.NotNull(rsaParams.P);
Assert.NotNull(rsaParams.DP);
Assert.NotNull(rsaParams.Q);
Assert.NotNull(rsaParams.DQ);
Assert.NotNull(rsaParams.InverseQ);
}
}
private static void VerifyDValue(ref RSAParameters rsaParams)
{
if (rsaParams.P == null)
{
return;
}
// Verify that the formula (D * E) % LCM(p - 1, q - 1) == 1
// is true.
//
// This is NOT the same as saying D = ModInv(E, LCM(p - 1, q - 1)),
// because D = ModInv(E, (p - 1) * (q - 1)) is a valid choice, but will
// still work through this formula.
BigInteger p = PositiveBigInteger(rsaParams.P);
BigInteger q = PositiveBigInteger(rsaParams.Q);
BigInteger e = PositiveBigInteger(rsaParams.Exponent);
BigInteger d = PositiveBigInteger(rsaParams.D);
BigInteger lambda = LeastCommonMultiple(p - 1, q - 1);
BigInteger modProduct = (d * e) % lambda;
Assert.Equal(BigInteger.One, modProduct);
}
private static BigInteger LeastCommonMultiple(BigInteger a, BigInteger b)
{
BigInteger gcd = BigInteger.GreatestCommonDivisor(a, b);
return BigInteger.Abs(a) / gcd * BigInteger.Abs(b);
}
private static BigInteger PositiveBigInteger(byte[] bigEndianBytes)
{
byte[] littleEndianBytes;
if (bigEndianBytes[0] >= 0x80)
{
// Insert a padding 00 byte so the number is treated as positive.
littleEndianBytes = new byte[bigEndianBytes.Length + 1];
Buffer.BlockCopy(bigEndianBytes, 0, littleEndianBytes, 1, bigEndianBytes.Length);
}
else
{
littleEndianBytes = (byte[])bigEndianBytes.Clone();
}
Array.Reverse(littleEndianBytes);
return new BigInteger(littleEndianBytes);
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.Forms.dll
// Description: The Windows Forms user interface layer for the DotSpatial.Symbology library.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 3/3/2009 10:46:05 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// CharacterControl
/// </summary>
[DefaultEvent("PopupClicked")]
public class CharacterControl : VerticalScrollControl
{
#region Public Events
/// <summary>
/// Occurs when a magnification box is clicked
/// </summary>
public event EventHandler PopupClicked;
#endregion
#region Private Variables
private Size _cellSize;
private bool _dynamicColumns;
private IWindowsFormsEditorService _editorService;
private bool _isPopup;
private bool _isSelected;
private int _numColumns;
private byte _selectedChar;
private Color _selectionBackColor;
private Color _selectionForeColor;
private ICharacterSymbol _symbol;
private byte _typeSet;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of CharacterControl
/// </summary>
public CharacterControl()
{
Configure();
}
/// <summary>
/// Creates a new instance of a CharacterControl designed to edit the specific symbol
/// </summary>
/// <param name="editorService"></param>
/// <param name="symbol"></param>
public CharacterControl(IWindowsFormsEditorService editorService, ICharacterSymbol symbol)
{
_editorService = editorService;
_symbol = symbol;
Configure();
}
private void Configure()
{
Font = new Font("DotSpatialSymbols", 18F, GraphicsUnit.Pixel);
_typeSet = 0;
_cellSize = new Size(22, 22);
_numColumns = 16;
_dynamicColumns = true;
_selectionBackColor = Color.CornflowerBlue;
_selectionForeColor = Color.White;
DocumentRectangle = new Rectangle(0, 0, _cellSize.Width * 16, _cellSize.Height * 16);
ResetScroll();
}
#endregion
#region Methods
#endregion
#region Properties
/// <summary>
/// Gets or sets the cell size.
/// </summary>
public Size CellSize
{
get { return _cellSize; }
set
{
_cellSize = value;
// base.DocumentRectangle = new Rectangle(0, 0, (int)_cellSize.Width * 16, (int)_cellSize.Height * 16);
Invalidate();
}
}
/// <summary>
/// Overrides underlying behavior to hide it in the properties list for this control from serialization
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override Rectangle DocumentRectangle
{
get
{
return base.DocumentRectangle;
}
set
{
base.DocumentRectangle = value;
}
}
/// <summary>
/// Gets or sets a boolean that, if true, indicates that this form should restructure the columns
/// as it is resized so that all the columns are visible.
/// </summary>
public bool DynamicColumns
{
get { return _dynamicColumns; }
set
{
_dynamicColumns = value;
}
}
/// <summary>
/// Gets or sets whether or not this item is selected
/// </summary>
public bool IsSelected
{
get { return _isSelected; }
set { _isSelected = value; }
}
/// <summary>
/// Gets or sets the number of columns
/// </summary>
public int NumColumns
{
get { return _numColumns; }
set
{
_numColumns = value;
Invalidate();
}
}
/// <summary>
/// Gets the number of rows, which is controlled by having to show 256 cells
/// in the given number of columns.
/// </summary>
public int NumRows
{
get
{
if (_numColumns == 0) return 256;
return (int)Math.Ceiling(256 / (double)_numColumns);
}
}
/// <summary>
/// Gets or sets the background color for the selection
/// </summary>
public Color SelectionBackColor
{
get { return _selectionBackColor; }
set { _selectionBackColor = value; }
}
/// <summary>
/// The Font Color for the selection
/// </summary>
public Color SelectionForeColor
{
get { return _selectionForeColor; }
set { _selectionForeColor = value; }
}
/// <summary>
/// Gets or sets the byte that describes the "larger" of the two bytes for a unicode set.
/// The 256 character slots illustrate the sub-categories for those elements.
/// </summary>
public byte TypeSet
{
get { return _typeSet; }
set { _typeSet = value; }
}
/// <summary>
/// Gets or sets the selected character
/// </summary>
public byte SelectedChar
{
get { return _selectedChar; }
set { _selectedChar = value; }
}
/// <summary>
/// Gets the string form of the selected character
/// </summary>
public string SelectedString
{
get { return ((char)(_selectedChar + _typeSet * 256)).ToString(); }
}
#endregion
#region Protected Methods
/// <summary>
/// Handles the situation where a mouse up should show a magnified version of the character.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseUp(MouseEventArgs e)
{
if (_isPopup)
{
Rectangle pRect = GetPopupRectangle();
Rectangle cRect = DocumentToClient(pRect);
if (cRect.Contains(e.Location))
{
_isPopup = false; // make the popup vanish, but don't change the selection.
cRect.Inflate(CellSize);
Invalidate(cRect);
OnPopupClicked();
return;
}
}
if (e.X < 0) return;
if (e.Y < 0) return;
int col = (e.X + ControlRectangle.X) / _cellSize.Width;
int row = (e.Y + ControlRectangle.Y) / _cellSize.Height;
if ((_numColumns * row + col) < 256)
{
_isSelected = true;
_selectedChar = (byte)(_numColumns * row + col);
_isPopup = true;
}
Invalidate();
base.OnMouseUp(e);
}
/// <summary>
/// Fires the PopupClicked event args, and closes a drop down editor if it exists.
/// </summary>
protected virtual void OnPopupClicked()
{
if (_editorService != null)
{
_symbol.Code = SelectedChar;
_editorService.CloseDropDown();
}
if (PopupClicked != null) PopupClicked(this, EventArgs.Empty);
}
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected override void OnInitialize(PaintEventArgs e)
{
DocumentRectangle = new Rectangle(0, 0, _numColumns * _cellSize.Width + 1, NumRows * _cellSize.Height + 1);
if (_dynamicColumns)
{
int newColumns = (Width - 20) / _cellSize.Width;
if (newColumns != _numColumns)
{
e.Graphics.FillRectangle(Brushes.White, e.ClipRectangle);
_numColumns = newColumns;
Invalidate();
return;
}
}
if (_numColumns == 0) _numColumns = 1;
Font smallFont = new Font(Font.FontFamily, CellSize.Width * .8F, GraphicsUnit.Pixel);
for (int i = 0; i < 256; i++)
{
int row = i / _numColumns;
int col = i % _numColumns;
string text = ((char)(_typeSet * 256 + i)).ToString();
e.Graphics.DrawString(text, smallFont, Brushes.Black, new PointF(col * _cellSize.Width, row * _cellSize.Height));
}
for (int col = 0; col <= _numColumns; col++)
{
e.Graphics.DrawLine(Pens.Black, new PointF(col * _cellSize.Width, 0), new PointF(col * _cellSize.Width, NumRows * _cellSize.Height));
}
for (int row = 0; row <= NumRows; row++)
{
e.Graphics.DrawLine(Pens.Black, new PointF(0, row * _cellSize.Height), new PointF(NumColumns * _cellSize.Width, row * _cellSize.Height));
}
Brush backBrush = new SolidBrush(_selectionBackColor);
Brush foreBrush = new SolidBrush(_selectionForeColor);
if (_isSelected)
{
Rectangle sRect = GetSelectedRectangle();
e.Graphics.FillRectangle(backBrush, sRect);
e.Graphics.DrawString(SelectedString, smallFont, foreBrush, new PointF(sRect.X, sRect.Y));
}
if (_isPopup)
{
Rectangle pRect = GetPopupRectangle();
e.Graphics.FillRectangle(Brushes.Gray, new Rectangle(pRect.X + 2, pRect.Y + 2, pRect.Width, pRect.Height));
e.Graphics.FillRectangle(backBrush, pRect);
e.Graphics.DrawRectangle(Pens.Black, pRect);
Font bigFont = new Font(Font.FontFamily, CellSize.Width * 2.7F, GraphicsUnit.Pixel);
e.Graphics.DrawString(SelectedString, bigFont, foreBrush, new PointF(pRect.X, pRect.Y));
}
backBrush.Dispose();
foreBrush.Dispose();
}
/// <summary>
/// Occurs whenever this control is resized, and forces invalidation of the entire control because
/// we are completely changing how the paging works.
/// </summary>
/// <param name="e"></param>
protected override void OnResize(EventArgs e)
{
_isPopup = false;
base.OnResize(e);
Invalidate();
}
#endregion
#region Private Methods
private Rectangle GetPopupRectangle()
{
int pr = _selectedChar / _numColumns;
int pc = _selectedChar % _numColumns;
if (pc == 0) pc = 1;
if (pc == _numColumns - 1) pc = _numColumns - 2;
if (pr == 0) pr = 1;
if (pr == NumRows - 1) pr = NumRows - 2;
return new Rectangle((pc - 1) * CellSize.Width, (pr - 1) * CellSize.Height, CellSize.Width * 3, CellSize.Height * 3);
}
private Rectangle GetSelectedRectangle()
{
int row = _selectedChar / _numColumns;
int col = _selectedChar % _numColumns;
return new Rectangle(col * _cellSize.Width + 1, row * _cellSize.Height + 1, _cellSize.Width - 1, CellSize.Height - 1);
}
#endregion
}
}
| |
using System;
using GuruComponents.Netrix;
using GuruComponents.Netrix.ComInterop;
using GuruComponents.Netrix.WebEditing.Elements;
namespace GuruComponents.Netrix.WebEditing.Elements
{
/// <summary>
/// Gives direct access to the underlying DOM of any element.
/// </summary>
/// <remarks>
/// To access the document just query the ElementDom from body element.
/// </remarks>
public class ElementDom : IElementDom
{
Interop.IHTMLDOMNode node;
private IHtmlEditor htmlEditor;
private System.Xml.XmlNodeType nodeType;
public ElementDom(Interop.IHTMLDOMNode element, IHtmlEditor htmlEditor)
{
this.node = element;
this.htmlEditor = htmlEditor;
if (element.nodeType == 0)
{
nodeType = System.Xml.XmlNodeType.Attribute;
}
else
{
switch (element.nodeType)
{
case 1:
nodeType = System.Xml.XmlNodeType.Element;
break;
case 3:
nodeType = System.Xml.XmlNodeType.Text;
break;
default:
nodeType = System.Xml.XmlNodeType.None;
break;
}
}
}
/// <summary>
/// Exchanges the location of two objects in the document hierarchy.
/// </summary>
/// <remarks>If elements are removed at run time, before the closing tag is parsed, areas of the document might not render.</remarks>
/// <param name="node">Object that specifies the existing element.</param>
/// <returns>Returns a reference to the object that invoked the method.</returns>
public IElement SwapNode(IElement node)
{
Interop.IHTMLDOMNode newNode = (this.node).swapNode((Interop.IHTMLDOMNode) node);
return this.htmlEditor.GenericElementFactory.CreateElement(newNode as Interop.IHTMLElement) as IElement;
}
/// <overloads/>
/// <summary>
/// Returns the direct descendent children elements, including text nodes.
/// </summary>
/// <remarks>
/// This method returns text portions as <see cref="TextNodeElement"/> objects.
/// </remarks>
/// <param name="includeTextNodes">If <c>True</c> the collection will include text parts as <see cref="TextNodeElement"/> objects.</param>
/// <returns></returns>
public ElementCollection GetChildNodes(bool includeTextNodes)
{
Interop.IHTMLDOMChildrenCollection children = (Interop.IHTMLDOMChildrenCollection) node.childNodes;
ElementCollection ec = new ElementCollection();
int length = children.length;
for (int i = 0; i < length; i++)
{
Interop.IHTMLDOMNode element = children.item(i) as Interop.IHTMLDOMNode;
if (element != null && element != node)
{
if (element.nodeName.Equals("#text"))
{
ec.Add(new TextNodeElement(element, this.htmlEditor));
}
else
{
ec.Add(this.htmlEditor.GenericElementFactory.CreateElement(element as Interop.IHTMLElement));
}
}
}
return ec;
}
/// <summary>
/// Returns the direct descendent children elements.
/// </summary>
/// <remarks>
/// Does not returns any text nodes between the elements. They are stripped out from DOM tree before building the collection.
/// </remarks>
/// <returns></returns>
public ElementCollection GetChildNodes()
{
Interop.IHTMLDOMChildrenCollection children = (Interop.IHTMLDOMChildrenCollection) node.childNodes;
ElementCollection ec = new ElementCollection();
int length = children.length;
for (int i = 0; i < length; i++)
{
Interop.IHTMLDOMNode element = children.item(i) as Interop.IHTMLDOMNode;
if (element != null && element != node)
{
if (element.nodeName.Equals("#text")) continue;
ec.Add(this.htmlEditor.GenericElementFactory.CreateElement(element as Interop.IHTMLElement));
}
}
return ec;
}
/// <summary>
/// Returns the parent if there is any, or <c>null</c> otherwise.
/// </summary>
/// <returns>Returns the element as <see cref="IElement"/>, by forcing the cast to avoid access to non-native objects.</returns>
public IElement GetParent()
{
Interop.IHTMLElement parentNode = node.parentNode as Interop.IHTMLElement;
if (parentNode != null)
{
return htmlEditor.GenericElementFactory.CreateElement(parentNode) as IElement;
}
else
{
return null;
}
}
# region Explicit XmlNode implementation
public string LocalName
{
get
{
return ((Interop.IHTMLElement) node).GetTagName();
}
}
public string Name
{
get
{
string ns = (((Interop.IHTMLElement2) node).GetScopeName() == null) ? String.Empty : ((Interop.IHTMLElement2) node).GetScopeName();
if (ns.Length > 0) ns += ":";
return String.Concat(ns, LocalName);
}
}
public System.Xml.XmlNodeType NodeType
{
get
{
return nodeType;
}
}
public void WriteContentTo(System.Xml.XmlWriter w)
{
w.WriteRaw(((Interop.IHTMLElement) node).GetInnerHTML());
}
public void WriteTo(System.Xml.XmlWriter w)
{
w.WriteRaw(((Interop.IHTMLElement) node).GetInnerHTML());
}
# endregion
/// <summary>
/// Returns the last child of the current element.
/// </summary>
public IElement LastChild
{
get
{
Interop.IHTMLElement el = node.lastChild as Interop.IHTMLElement;
if (el != null)
{
return this.htmlEditor.GenericElementFactory.CreateElement(el) as IElement;
}
else
{
if (node.lastChild != null && node.lastChild.nodeName == "#text")
{
return new TextNodeElement(node.lastChild, this.htmlEditor);
}
return null;
}
}
}
/// <summary>
/// Returns the first child of the current element.
/// </summary>
public IElement FirstChild
{
get
{
Interop.IHTMLElement el = node.firstChild as Interop.IHTMLElement;
if (el != null)
{
return this.htmlEditor.GenericElementFactory.CreateElement(el) as IElement;
}
else
{
if (node.firstChild != null && node.firstChild.nodeName == "#text")
{
return new TextNodeElement(node.firstChild, this.htmlEditor);
}
return null;
}
}
}
/// <summary>
/// Gets <c>true</c>, if the element has child elements.
/// </summary>
public bool HasChildNodes
{
get
{
return node.hasChildNodes();
}
}
/// <summary>
/// Return the next sibling of this element.
/// </summary>
public IElement NextSibling
{
get
{
Interop.IHTMLElement el = node.nextSibling as Interop.IHTMLElement;
if (el != null)
{
return this.htmlEditor.GenericElementFactory.CreateElement(el) as IElement;
}
else
{
if (node.nextSibling != null && node.nextSibling.nodeName == "#text")
{
return new TextNodeElement(node.nextSibling, this.htmlEditor);
}
return null;
}
}
}
/// <summary>
/// Return the previous sibling of the element.
/// </summary>
public IElement PreviousSibling
{
get
{
Interop.IHTMLElement el = node.previousSibling as Interop.IHTMLElement;
if (el != null)
{
return this.htmlEditor.GenericElementFactory.CreateElement(el) as IElement;
}
else
{
if (node.previousSibling != null && node.previousSibling.nodeName == "#text")
{
return new TextNodeElement(node.previousSibling, this.htmlEditor);
}
return null;
}
}
}
/// <summary>
/// Return the previous sibling of the element.
/// </summary>
public IElement Parent
{
get
{
Interop.IHTMLElement el = node.parentNode as Interop.IHTMLElement;
if (el != null)
{
return this.htmlEditor.GenericElementFactory.CreateElement(el) as IElement;
}
else
{
if (node.parentNode != null && node.parentNode.nodeName == "#text")
{
return new TextNodeElement(node.parentNode, this.htmlEditor);
}
return null;
}
}
}
/// <summary>
/// Insert a new element before the current one.
/// </summary>
/// <param name="newChild">The new element, which has to be inserted.</param>
/// <param name="refChild">The element, before which the new element is inserted.</param>
/// <returns>The new element, if successful, <c>null</c> (<c>Nothing</c> in VB.NET) else.</returns>
public IElement InsertBefore (IElement newChild, IElement refChild)
{
Interop.IHTMLDOMNode nc, rc;
if (newChild is TextNodeElement)
{
nc = ((TextNodeElement) newChild).GetBaseElement() as Interop.IHTMLDOMNode;
}
else
{
nc = newChild.GetBaseElement() as Interop.IHTMLDOMNode;
}
if (refChild is TextNodeElement)
{
rc = ((TextNodeElement) refChild).GetBaseElement() as Interop.IHTMLDOMNode;
}
else
{
rc = refChild.GetBaseElement() as Interop.IHTMLDOMNode;
}
try
{
if (nc != null && rc != null)
{
return this.htmlEditor.GenericElementFactory.CreateElement((Interop.IHTMLElement) node.insertBefore(nc, rc)) as IElement;
}
else
{
return null;
}
}
catch
{
return null;
}
}
/// <summary>
/// Removes a child element from the collection of children.
/// </summary>
/// <param name="oldChild">The element which has to be removed.</param>
/// <returns>Returns the parent element.</returns>
public IElement RemoveChild (IElement oldChild)
{
Interop.IHTMLDOMNode oc;
if (oldChild is TextNodeElement)
{
oc = ((TextNodeElement) oldChild).GetBaseElement() as Interop.IHTMLDOMNode;
}
else
{
oc = ((IElement) oldChild).GetBaseElement() as Interop.IHTMLDOMNode;
}
try
{
Interop.IHTMLDOMNode parent = node.removeChild(oc);
return this.htmlEditor.GenericElementFactory.CreateElement((Interop.IHTMLElement) parent) as IElement;
}
catch
{
return null;
}
}
/// <summary>
/// Replaces an element in the children collection with a new one.
/// </summary>
/// <param name="oldChild">The child element which should be replaced.</param>
/// <param name="newChild">The new element which replaces the old one.</param>
/// <returns>The IElement object representing the new element.</returns>
public IElement ReplaceChild (IElement oldChild, IElement newChild)
{
Interop.IHTMLDOMNode nc, rc;
if (newChild is TextNodeElement)
{
nc = ((TextNodeElement) newChild).GetBaseElement() as Interop.IHTMLDOMNode;
}
else
{
nc = ((IElement) newChild).GetBaseElement() as Interop.IHTMLDOMNode;
}
if (oldChild is TextNodeElement)
{
rc = ((TextNodeElement) oldChild).GetBaseElement() as Interop.IHTMLDOMNode;
}
else
{
rc = ((IElement) oldChild).GetBaseElement() as Interop.IHTMLDOMNode;
}
try
{
if (rc != null && nc != null)
{
node.replaceChild(rc, nc);
return this.htmlEditor.GenericElementFactory.CreateElement((Interop.IHTMLElement) node) as IElement;
}
else
{
return null;
}
}
catch
{
return null;
}
}
/// <summary>
/// Appends a new child to the children collection.
/// </summary>
/// <param name="newChild"></param>
/// <returns></returns>
public IElement AppendChild (IElement newChild)
{
Interop.IHTMLDOMNode nc;
if (newChild is TextNodeElement)
{
nc = ((TextNodeElement) newChild).GetBaseElement() as Interop.IHTMLDOMNode;
}
else
{
nc = ((IElement) newChild).GetBaseElement() as Interop.IHTMLDOMNode;
}
try
{
if (nc != null)
{
return this.htmlEditor.GenericElementFactory.CreateElement((Interop.IHTMLElement) node.appendChild(nc)) as IElement;
}
else
{
return null;
}
}
catch
{
return null;
}
}
/// <summary>
/// Removes the current element from document
/// </summary>
/// <param name="deep">If <c>true</c>, all child element will be removed too. Otherwise the children will be preserved.</param>
public void RemoveElement(bool deep)
{
try
{
node.removeNode(deep);
((HtmlEditor)htmlEditor).InvokeHtmlElementChanged(((HtmlEditor)htmlEditor).CurrentScopeElement, GuruComponents.Netrix.Events.HtmlElementChangedType.Unknown);
}
catch
{
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.SpecifyStringComparisonAnalyzer,
Microsoft.NetCore.CSharp.Analyzers.Runtime.CSharpSpecifyStringComparisonFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.SpecifyStringComparisonAnalyzer,
Microsoft.NetCore.VisualBasic.Analyzers.Runtime.BasicSpecifyStringComparisonFixer>;
namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests
{
public class SpecifyStringComparisonTests
{
[Fact]
public async Task CA1307_StringCompareTests_CSharp()
{
#if !NETCOREAPP
const string StringArgType = "string";
#else
const string StringArgType = "string?";
#endif
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Globalization;
public class StringComparisonTests
{
public int StringCompare()
{
string strA = """";
string strB = """";
var x1 = String.Compare(strA, strB);
var x2 = String.Compare(strA, strB, true);
var x3 = String.Compare(strA, 0, strB, 0, 1);
var x4 = String.Compare(strA, 0, strB, 0, 1, true);
return 0;
}
}",
GetCA1307CSharpResultsAt(11, 18, $"string.Compare({StringArgType}, {StringArgType})",
"StringComparisonTests.StringCompare()",
$"string.Compare({StringArgType}, {StringArgType}, System.StringComparison)"),
GetCA1307CSharpResultsAt(12, 18, $"string.Compare({StringArgType}, {StringArgType}, bool)",
"StringComparisonTests.StringCompare()",
$"string.Compare({StringArgType}, {StringArgType}, System.StringComparison)"),
GetCA1307CSharpResultsAt(13, 18, $"string.Compare({StringArgType}, int, {StringArgType}, int, int)",
"StringComparisonTests.StringCompare()",
$"string.Compare({StringArgType}, int, {StringArgType}, int, int, System.StringComparison)"),
GetCA1307CSharpResultsAt(14, 18, $"string.Compare({StringArgType}, int, {StringArgType}, int, int, bool)",
"StringComparisonTests.StringCompare()",
$"string.Compare({StringArgType}, int, {StringArgType}, int, int, System.StringComparison)"));
}
[Fact]
public async Task CA1307_StringWithTests_CSharp()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Globalization;
public class StringComparisonTests
{
public bool StringWith()
{
string strA = """";
string strB = """";
var x = strA.EndsWith(strB);
return strA.StartsWith(strB);
}
}",
GetCA1307CSharpResultsAt(11, 17, "string.EndsWith(string)",
"StringComparisonTests.StringWith()",
"string.EndsWith(string, System.StringComparison)"),
GetCA1307CSharpResultsAt(12, 16, "string.StartsWith(string)",
"StringComparisonTests.StringWith()",
"string.StartsWith(string, System.StringComparison)"));
}
[Fact]
public async Task CA1307_StringIndexOfTests_CSharp()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Globalization;
public class StringComparisonTests
{
public int StringIndexOf()
{
string strA = """";
var x1 = strA.IndexOf("""");
var x2 = strA.IndexOf("""", 0);
return strA.IndexOf("""", 0, 1);
}
}",
GetCA1307CSharpResultsAt(10, 18, "string.IndexOf(string)",
"StringComparisonTests.StringIndexOf()",
"string.IndexOf(string, System.StringComparison)"),
GetCA1307CSharpResultsAt(11, 18, "string.IndexOf(string, int)",
"StringComparisonTests.StringIndexOf()",
"string.IndexOf(string, int, System.StringComparison)"),
GetCA1307CSharpResultsAt(12, 16, "string.IndexOf(string, int, int)",
"StringComparisonTests.StringIndexOf()",
"string.IndexOf(string, int, int, System.StringComparison)"));
}
[Fact]
public async Task CA1307_StringCompareToTests_CSharp()
{
#if !NETCOREAPP
const string ObjectArgType = "object";
const string StringArgType = "string";
#else
const string ObjectArgType = "object?";
const string StringArgType = "string?";
#endif
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Globalization;
public class StringComparisonTests
{
public int StringCompareTo()
{
string strA = """";
string strB = """";
var x1 = strA.CompareTo(strB);
return """".CompareTo(new object());
}
}",
GetCA1307CSharpResultsAt(11, 22, $"string.CompareTo({StringArgType})",
"StringComparisonTests.StringCompareTo()",
$"string.Compare({StringArgType}, {StringArgType}, System.StringComparison)"),
GetCA1307CSharpResultsAt(12, 20, $"string.CompareTo({ObjectArgType})",
"StringComparisonTests.StringCompareTo()",
$"string.Compare({StringArgType}, {StringArgType}, System.StringComparison)"));
}
[Fact]
public async Task CA1307_OverloadTests_CSharp()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Globalization;
public class StringComparisonTests
{
public void NonString()
{
DoNothing("""");
DoNothing<string>(""""); // No diagnostics since this is generics
}
public void DoNothing(string str)
{
}
public void DoNothing<T>(string str)
{
}
public void DoNothing<T>(string str, StringComparison strCompare)
{
}
}",
GetCA1307CSharpResultsAt(9, 9, "StringComparisonTests.DoNothing(string)",
"StringComparisonTests.NonString()",
"StringComparisonTests.DoNothing<T>(string, System.StringComparison)"));
}
[Fact]
public async Task CA1307_OverloadWithMismatchRefKind_CSharp()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Globalization;
public class StringComparisonTests
{
public void MyMethod()
{
M("""");
}
public void M(string str)
{
}
public void M(string str, out StringComparison strCompare)
{
strCompare = StringComparison.Ordinal;
}
public void M(ref StringComparison strCompare, string str)
{
strCompare = StringComparison.Ordinal;
}
public void M(ref string str, StringComparison strCompare)
{
}
}");
}
[Fact]
public async Task CA1307_StringCompareTests_VisualBasic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Imports System.Globalization
Public Class StringComparisonTests
Public Function StringCompare() As Integer
Dim strA As String = """"
Dim strB As String = """"
Dim x1 = [String].Compare(strA, strB)
Dim x2 = [String].Compare(strA, strB, True)
Dim x3 = [String].Compare(strA, 0, strB, 0, 1)
Dim x4 = [String].Compare(strA, 0, strB, 0, 1, True)
Return 0
End Function
End Class",
GetCA1307BasicResultsAt(9, 18, "String.Compare(String, String)",
"StringComparisonTests.StringCompare()",
"String.Compare(String, String, System.StringComparison)"),
GetCA1307BasicResultsAt(10, 18, "String.Compare(String, String, Boolean)",
"StringComparisonTests.StringCompare()",
"String.Compare(String, String, System.StringComparison)"),
GetCA1307BasicResultsAt(11, 18, "String.Compare(String, Integer, String, Integer, Integer)",
"StringComparisonTests.StringCompare()",
"String.Compare(String, Integer, String, Integer, Integer, System.StringComparison)"),
GetCA1307BasicResultsAt(12, 18, "String.Compare(String, Integer, String, Integer, Integer, Boolean)",
"StringComparisonTests.StringCompare()",
"String.Compare(String, Integer, String, Integer, Integer, System.StringComparison)"));
}
[Fact]
public async Task CA1307_StringWithTests_VisualBasic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Imports System.Globalization
Public Class StringComparisonTests
Public Function StringWith() As Boolean
Dim strA As String = """"
Dim strB As String = """"
Dim x = strA.EndsWith(strB)
Return strA.StartsWith(strB)
End Function
End Class",
GetCA1307BasicResultsAt(9, 17, "String.EndsWith(String)",
"StringComparisonTests.StringWith()",
"String.EndsWith(String, System.StringComparison)"),
GetCA1307BasicResultsAt(10, 16, "String.StartsWith(String)",
"StringComparisonTests.StringWith()",
"String.StartsWith(String, System.StringComparison)"));
}
[Fact]
public async Task CA1307_StringIndexOfTests_VisualBasic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Imports System.Globalization
Public Class StringComparisonTests
Public Function StringIndexOf() As Integer
Dim strA As String = """"
Dim x1 = strA.IndexOf("""")
Dim x2 = strA.IndexOf("""", 0)
Return strA.IndexOf("""", 0, 1)
End Function
End Class",
GetCA1307BasicResultsAt(8, 18, "String.IndexOf(String)",
"StringComparisonTests.StringIndexOf()",
"String.IndexOf(String, System.StringComparison)"),
GetCA1307BasicResultsAt(9, 18, "String.IndexOf(String, Integer)",
"StringComparisonTests.StringIndexOf()",
"String.IndexOf(String, Integer, System.StringComparison)"),
GetCA1307BasicResultsAt(10, 16, "String.IndexOf(String, Integer, Integer)",
"StringComparisonTests.StringIndexOf()",
"String.IndexOf(String, Integer, Integer, System.StringComparison)"));
}
[Fact]
public async Task CA1307_StringCompareToTests_VisualBasic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Imports System.Globalization
Public Class StringComparisonTests
Public Function StringCompareTo() As Integer
Dim strA As String = """"
Dim strB As String = """"
Dim x1 = strA.CompareTo(strB)
Return """".CompareTo(New Object())
End Function
End Class",
GetCA1307BasicResultsAt(9, 18, "String.CompareTo(String)",
"StringComparisonTests.StringCompareTo()",
"String.Compare(String, String, System.StringComparison)"),
GetCA1307BasicResultsAt(10, 16, "String.CompareTo(Object)",
"StringComparisonTests.StringCompareTo()",
"String.Compare(String, String, System.StringComparison)"));
}
[Fact]
public async Task CA1307_OverloadTests_VisualBasic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Imports System.Globalization
Public Class StringComparisonTests
Public Sub NonString()
DoNothing("")
' No diagnostics since this is generics
DoNothing(Of String)("")
End Sub
Public Sub DoNothing(str As String)
End Sub
Public Sub DoNothing(Of T)(str As String)
End Sub
Public Sub DoNothing(Of T)(str As String, strCompare As StringComparison)
End Sub
End Class",
GetCA1307BasicResultsAt(7, 9, "StringComparisonTests.DoNothing(String)",
"StringComparisonTests.NonString()",
"StringComparisonTests.DoNothing(Of T)(String, System.StringComparison)"));
}
private static DiagnosticResult GetCA1307CSharpResultsAt(int line, int column, string arg1, string arg2, string arg3) =>
VerifyCS.Diagnostic()
.WithLocation(line, column)
.WithArguments(arg1, arg2, arg3);
private static DiagnosticResult GetCA1307BasicResultsAt(int line, int column, string arg1, string arg2, string arg3) =>
VerifyVB.Diagnostic()
.WithLocation(line, column)
.WithArguments(arg1, arg2, arg3);
}
}
| |
//Copied and modified from SIL.Windows.Forms.Progress.ProgressDialog
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using L10NSharp;
using SIL.Progress;
using SIL.Reporting;
namespace Glyssen.Dialogs
{
/// <summary>
/// Provides a progress dialog which forces the user to acknowledge is complete by clicking OK
/// </summary>
public class ProgressDialogWithAcknowledgement : Form
{
public delegate void ProgressCallback(int progress);
private Label m_statusLabel;
private ProgressBar m_progressBar;
private Label m_progressLabel;
private Timer m_showWindowIfTakingLongTimeTimer;
private Timer m_progressTimer;
private Label m_overviewLabel;
private DateTime m_startTime;
private BackgroundWorker m_backgroundWorker;
private ProgressState m_progressState;
private TableLayoutPanel m_tableLayout;
private bool m_workerStarted;
private Button m_okButton;
private IContainer components;
private Button m_cancelButton;
private TableLayoutPanel m_buttonPanel;
private LinkLabel m_cancelLink;
private bool m_appUsingWaitCursor;
private Utilities.GlyssenColorPalette m_glyssenColorPalette;
private L10NSharp.UI.L10NSharpExtender l10NSharpExtender1;
private bool m_replaceCancelButtonWithLink;
/// <summary>
/// Standard constructor
/// </summary>
public ProgressDialogWithAcknowledgement()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
m_statusLabel.BackColor = Color.Transparent;
m_progressLabel.BackColor = Color.Transparent;
m_overviewLabel.BackColor = Color.Transparent;
m_startTime = default(DateTime);
Text = UsageReporter.AppNameToUseInDialogs;
m_statusLabel.Font = SystemFonts.MessageBoxFont;
m_progressLabel.Font = SystemFonts.MessageBoxFont;
m_overviewLabel.Font = SystemFonts.MessageBoxFont;
m_statusLabel.Text = string.Empty;
m_progressLabel.Text = string.Empty;
m_overviewLabel.Text = string.Empty;
m_cancelButton.MouseEnter += delegate
{
m_appUsingWaitCursor = Application.UseWaitCursor;
m_cancelButton.Cursor = Cursor = Cursors.Arrow;
Application.UseWaitCursor = false;
};
m_cancelButton.MouseLeave += delegate
{
Application.UseWaitCursor = m_appUsingWaitCursor;
};
}
private void HandleTableLayoutSizeChanged(object sender, EventArgs e)
{
if (!IsHandleCreated)
CreateHandle();
var desiredHeight = m_tableLayout.Height + Padding.Top + Padding.Bottom + (Height - ClientSize.Height);
var scn = Screen.FromControl(this);
Height = Math.Min(desiredHeight, scn.WorkingArea.Height - 20);
AutoScroll = (desiredHeight > scn.WorkingArea.Height - 20);
}
/// <summary>
/// Get / set the text to display in the first status panel
/// </summary>
public string StatusText
{
get
{
return m_statusLabel.Text;
}
set
{
m_statusLabel.Text = value;
}
}
/// <summary>
/// Description of why this dialog is even showing
/// </summary>
public string Overview
{
get
{
return m_overviewLabel.Text;
}
set
{
m_overviewLabel.Text = value;
}
}
/// <summary>
/// Get / set the minimum range of the progress bar
/// </summary>
public int ProgressRangeMinimum
{
get
{
return m_progressBar.Minimum;
}
set
{
if (m_backgroundWorker == null)
{
m_progressBar.Minimum = value;
}
}
}
/// <summary>
/// Get / set the maximum range of the progress bar
/// </summary>
public int ProgressRangeMaximum
{
get
{
return m_progressBar.Maximum;
}
set
{
if (m_backgroundWorker != null)
{
return;
}
if (InvokeRequired)
{
Invoke(new ProgressCallback(SetMaximumCrossThread), value);
}
else
{
m_progressBar.Maximum = value;
}
}
}
private void SetMaximumCrossThread(int amount)
{
ProgressRangeMaximum = amount;
}
/// <summary>
/// Get / set the current value of the progress bar
/// </summary>
public int Progress
{
get
{
return m_progressBar.Value;
}
set
{
/* these were causing weird, hard to debug (because of threads)
* failures. The debugger would report that value == max, so why fail?
* Debug.Assert(value <= _progressBar.Maximum);
*/
Debug.WriteLineIf(value > m_progressBar.Maximum,
"***Warning progress was " + value + " but max is " + m_progressBar.Maximum);
Debug.Assert(value >= m_progressBar.Minimum);
if (value > m_progressBar.Maximum)
{
m_progressBar.Maximum = value;//not worth crashing over in Release build
}
if (value < m_progressBar.Minimum)
{
return; //not worth crashing over in Release build
}
m_progressBar.Value = value;
}
}
/// <summary>
/// Get/set a boolean which determines whether the form
/// will show a cancel option (true) or not (false)
/// </summary>
public bool CanCancel
{
get
{
return m_cancelButton.Enabled || m_cancelLink.Enabled;
}
set
{
if (ReplaceCancelButtonWithLink)
{
m_cancelLink.Enabled = value;
m_cancelLink.Visible = value;
}
else
{
m_cancelButton.Enabled = value;
m_cancelButton.Visible = value;
}
}
}
/// <summary>
/// If this is set before showing, the dialog will run the worker and respond
/// to its events
/// </summary>
public BackgroundWorker BackgroundWorker
{
get
{
return m_backgroundWorker;
}
set
{
m_backgroundWorker = value;
m_progressBar.Minimum = 0;
m_progressBar.Maximum = 100;
}
}
public ProgressState ProgressStateResult
{
get
{
return m_progressState;
}
}
/// <summary>
/// Gets or sets the manner in which progress should be indicated on the progress bar.
/// </summary>
public ProgressBarStyle BarStyle { get { return m_progressBar.Style; } set { m_progressBar.Style = value; } }
/// <summary>
/// Optional; one will be created (of some class or subclass) if you don't set it.
/// E.g. dlg.ProgressState = new BackgroundWorkerState(dlg.BackgroundWorker);
/// Also, you can use the getter to gain access to the progressstate, in order to add arguments
/// which the worker method can get at.
/// </summary>
public ProgressState ProgressState
{
get
{
if(m_progressState ==null)
{
if(m_backgroundWorker == null)
{
throw new ArgumentException("You must set BackgroundWorker before accessing this property.");
}
ProgressState = new BackgroundWorkerState(m_backgroundWorker);
}
return m_progressState;
}
set
{
if (m_progressState!=null)
{
CancelRequested -= m_progressState.CancelRequested;
}
m_progressState = value;
CancelRequested += m_progressState.CancelRequested;
m_progressState.TotalNumberOfStepsChanged += OnTotalNumberOfStepsChanged;
}
}
public string CancelLinkText
{
get => m_cancelLink.Text;
set => m_cancelLink.Text = value;
}
public string ProgressLabelTextWhenComplete { get; set; }
public string OkButtonText { get; set; }
public bool ReplaceCancelButtonWithLink
{
get { return m_replaceCancelButtonWithLink; }
set
{
m_replaceCancelButtonWithLink = value;
m_cancelLink.Enabled = CanCancel && value;
m_cancelLink.Visible = CanCancel && value;
m_cancelButton.Enabled = CanCancel && !value;
m_cancelButton.Visible = CanCancel && !value;
}
}
protected virtual void OnBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled || (ProgressStateResult != null && ProgressStateResult.Cancel))
{
DialogResult = DialogResult.Cancel;
}
else if (ProgressStateResult != null && (ProgressStateResult.State == ProgressState.StateValue.StoppedWithError
|| ProgressStateResult.ExceptionThatWasEncountered != null))
{
//this dialog really can't know whether this was an unexpected exception or not
//so don't do this: Reporting.ErrorReporter.ReportException(ProgressStateResult.ExceptionThatWasEncountered, this, false);
DialogResult = DialogResult.Abort;//not really matching semantics
// _progressState.State = ProgressState.StateValue.StoppedWithError;
}
else
{
DialogResult = DialogResult.None;
m_progressBar.Maximum = 1;
m_progressBar.Value = 1;
m_progressBar.Style = ProgressBarStyle.Blocks;
m_progressLabel.Text = ProgressLabelTextWhenComplete;
AcceptButton = m_okButton;
m_okButton.Text = OkButtonText ?? LocalizationManager.GetString("Common.OK", "OK");
m_okButton.DialogResult = DialogResult.OK;
m_okButton.Enabled = true;
m_okButton.Visible = true;
}
}
void OnBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ProgressState state = e.UserState as ProgressState;
if (state != null)
{
StatusText = state.StatusLabel;
}
if (state == null
|| state is BackgroundWorkerState)
{
Progress = e.ProgressPercentage;
}
else
{
ProgressRangeMaximum = state.TotalNumberOfSteps;
Progress = state.NumberOfStepsCompleted;
}
}
/// <summary>
/// Raised when the cancel button is clicked
/// </summary>
public event EventHandler CancelRequested;
/// <summary>
/// Raises the cancelled event
/// </summary>
/// <param name="e">Event data</param>
protected virtual void OnCancelled( EventArgs e )
{
EventHandler cancelled = CancelRequested;
if( cancelled != null )
{
cancelled( this, e );
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (m_showWindowIfTakingLongTimeTimer != null)
{
m_showWindowIfTakingLongTimeTimer.Stop();
}
}
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();
this.m_statusLabel = new System.Windows.Forms.Label();
this.m_progressBar = new System.Windows.Forms.ProgressBar();
this.m_progressLabel = new System.Windows.Forms.Label();
this.m_showWindowIfTakingLongTimeTimer = new System.Windows.Forms.Timer(this.components);
this.m_progressTimer = new System.Windows.Forms.Timer(this.components);
this.m_overviewLabel = new System.Windows.Forms.Label();
this.m_tableLayout = new System.Windows.Forms.TableLayoutPanel();
this.m_buttonPanel = new System.Windows.Forms.TableLayoutPanel();
this.m_okButton = new System.Windows.Forms.Button();
this.m_cancelButton = new System.Windows.Forms.Button();
this.m_cancelLink = new System.Windows.Forms.LinkLabel();
this.m_glyssenColorPalette = new Glyssen.Utilities.GlyssenColorPalette();
this.l10NSharpExtender1 = new L10NSharp.UI.L10NSharpExtender(this.components);
this.m_tableLayout.SuspendLayout();
this.m_buttonPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.m_glyssenColorPalette)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.l10NSharpExtender1)).BeginInit();
this.SuspendLayout();
//
// m_statusLabel
//
this.m_statusLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_statusLabel.AutoSize = true;
this.m_statusLabel.BackColor = System.Drawing.SystemColors.Control;
this.m_glyssenColorPalette.SetBackColor(this.m_statusLabel, Glyssen.Utilities.GlyssenColors.BackColor);
this.m_tableLayout.SetColumnSpan(this.m_statusLabel, 2);
this.m_statusLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.m_glyssenColorPalette.SetForeColor(this.m_statusLabel, Glyssen.Utilities.GlyssenColors.ForeColor);
this.m_statusLabel.ForeColor = System.Drawing.SystemColors.WindowText;
this.l10NSharpExtender1.SetLocalizableToolTip(this.m_statusLabel, null);
this.l10NSharpExtender1.SetLocalizationComment(this.m_statusLabel, null);
this.l10NSharpExtender1.SetLocalizationPriority(this.m_statusLabel, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this.m_statusLabel, "ProgressDialogWithAcknowledgement.m_statusLabel");
this.m_statusLabel.Location = new System.Drawing.Point(0, 35);
this.m_statusLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 5);
this.m_statusLabel.Name = "m_statusLabel";
this.m_statusLabel.Size = new System.Drawing.Size(444, 15);
this.m_statusLabel.TabIndex = 12;
this.m_statusLabel.Text = "#";
this.m_statusLabel.UseMnemonic = false;
this.m_glyssenColorPalette.SetUsePaletteColors(this.m_statusLabel, true);
//
// m_progressBar
//
this.m_progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_glyssenColorPalette.SetBackColor(this.m_progressBar, Glyssen.Utilities.GlyssenColors.BackColor);
this.m_tableLayout.SetColumnSpan(this.m_progressBar, 2);
this.m_glyssenColorPalette.SetForeColor(this.m_progressBar, Glyssen.Utilities.GlyssenColors.ForeColor);
this.m_progressBar.Location = new System.Drawing.Point(0, 55);
this.m_progressBar.Margin = new System.Windows.Forms.Padding(0, 0, 0, 12);
this.m_progressBar.Name = "m_progressBar";
this.m_progressBar.Size = new System.Drawing.Size(444, 18);
this.m_progressBar.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
this.m_progressBar.TabIndex = 11;
this.m_glyssenColorPalette.SetUsePaletteColors(this.m_progressBar, false);
this.m_progressBar.Value = 1;
//
// m_progressLabel
//
this.m_progressLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_progressLabel.AutoEllipsis = true;
this.m_progressLabel.AutoSize = true;
this.m_progressLabel.BackColor = System.Drawing.SystemColors.Control;
this.m_glyssenColorPalette.SetBackColor(this.m_progressLabel, Glyssen.Utilities.GlyssenColors.BackColor);
this.m_glyssenColorPalette.SetForeColor(this.m_progressLabel, Glyssen.Utilities.GlyssenColors.ForeColor);
this.m_progressLabel.ForeColor = System.Drawing.SystemColors.WindowText;
this.l10NSharpExtender1.SetLocalizableToolTip(this.m_progressLabel, null);
this.l10NSharpExtender1.SetLocalizationComment(this.m_progressLabel, null);
this.l10NSharpExtender1.SetLocalizationPriority(this.m_progressLabel, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this.m_progressLabel, "ProgressDialogWithAcknowledgement.m_progressLabel");
this.m_progressLabel.Location = new System.Drawing.Point(0, 90);
this.m_progressLabel.Margin = new System.Windows.Forms.Padding(0, 5, 0, 0);
this.m_progressLabel.Name = "m_progressLabel";
this.m_progressLabel.Size = new System.Drawing.Size(314, 13);
this.m_progressLabel.TabIndex = 9;
this.m_progressLabel.Text = "#";
this.m_progressLabel.UseMnemonic = false;
this.m_glyssenColorPalette.SetUsePaletteColors(this.m_progressLabel, true);
//
// m_showWindowIfTakingLongTimeTimer
//
this.m_showWindowIfTakingLongTimeTimer.Interval = 2000;
this.m_showWindowIfTakingLongTimeTimer.Tick += new System.EventHandler(this.OnTakingLongTimeTimerClick);
//
// m_progressTimer
//
this.m_progressTimer.Enabled = true;
this.m_progressTimer.Interval = 1000;
this.m_progressTimer.Tick += new System.EventHandler(this.progressTimer_Tick);
//
// m_overviewLabel
//
this.m_overviewLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_overviewLabel.AutoSize = true;
this.m_overviewLabel.BackColor = System.Drawing.SystemColors.Control;
this.m_glyssenColorPalette.SetBackColor(this.m_overviewLabel, Glyssen.Utilities.GlyssenColors.BackColor);
this.m_tableLayout.SetColumnSpan(this.m_overviewLabel, 2);
this.m_overviewLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.m_glyssenColorPalette.SetForeColor(this.m_overviewLabel, Glyssen.Utilities.GlyssenColors.ForeColor);
this.m_overviewLabel.ForeColor = System.Drawing.SystemColors.WindowText;
this.l10NSharpExtender1.SetLocalizableToolTip(this.m_overviewLabel, null);
this.l10NSharpExtender1.SetLocalizationComment(this.m_overviewLabel, null);
this.l10NSharpExtender1.SetLocalizationPriority(this.m_overviewLabel, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this.m_overviewLabel, "ProgressDialogWithAcknowledgement.m_overviewLabel");
this.m_overviewLabel.Location = new System.Drawing.Point(0, 0);
this.m_overviewLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 20);
this.m_overviewLabel.Name = "m_overviewLabel";
this.m_overviewLabel.Size = new System.Drawing.Size(444, 15);
this.m_overviewLabel.TabIndex = 8;
this.m_overviewLabel.Text = "#";
this.m_overviewLabel.UseMnemonic = false;
this.m_glyssenColorPalette.SetUsePaletteColors(this.m_overviewLabel, true);
//
// m_tableLayout
//
this.m_tableLayout.AutoSize = true;
this.m_tableLayout.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.m_tableLayout.BackColor = System.Drawing.Color.Transparent;
this.m_glyssenColorPalette.SetBackColor(this.m_tableLayout, Glyssen.Utilities.GlyssenColors.BackColor);
this.m_tableLayout.ColumnCount = 2;
this.m_tableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.m_tableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.m_tableLayout.Controls.Add(this.m_buttonPanel, 1, 3);
this.m_tableLayout.Controls.Add(this.m_overviewLabel, 0, 0);
this.m_tableLayout.Controls.Add(this.m_progressLabel, 0, 3);
this.m_tableLayout.Controls.Add(this.m_progressBar, 0, 2);
this.m_tableLayout.Controls.Add(this.m_statusLabel, 0, 1);
this.m_tableLayout.Controls.Add(this.m_cancelLink, 0, 4);
this.m_tableLayout.Dock = System.Windows.Forms.DockStyle.Top;
this.m_glyssenColorPalette.SetForeColor(this.m_tableLayout, Glyssen.Utilities.GlyssenColors.Default);
this.m_tableLayout.Location = new System.Drawing.Point(12, 12);
this.m_tableLayout.Name = "m_tableLayout";
this.m_tableLayout.RowCount = 5;
this.m_tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.m_tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.m_tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.m_tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.m_tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.m_tableLayout.Size = new System.Drawing.Size(444, 121);
this.m_tableLayout.TabIndex = 13;
this.m_glyssenColorPalette.SetUsePaletteColors(this.m_tableLayout, false);
this.m_tableLayout.SizeChanged += new System.EventHandler(this.HandleTableLayoutSizeChanged);
//
// m_buttonPanel
//
this.m_buttonPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.m_buttonPanel.AutoSize = true;
this.m_buttonPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.m_glyssenColorPalette.SetBackColor(this.m_buttonPanel, Glyssen.Utilities.GlyssenColors.BackColor);
this.m_buttonPanel.ColumnCount = 2;
this.m_buttonPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.m_buttonPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.m_buttonPanel.Controls.Add(this.m_okButton, 0, 0);
this.m_buttonPanel.Controls.Add(this.m_cancelButton, 1, 0);
this.m_glyssenColorPalette.SetForeColor(this.m_buttonPanel, Glyssen.Utilities.GlyssenColors.Default);
this.m_buttonPanel.Location = new System.Drawing.Point(317, 95);
this.m_buttonPanel.Name = "m_buttonPanel";
this.m_buttonPanel.RowCount = 1;
this.m_tableLayout.SetRowSpan(this.m_buttonPanel, 2);
this.m_buttonPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.m_buttonPanel.Size = new System.Drawing.Size(124, 23);
this.m_buttonPanel.TabIndex = 14;
this.m_glyssenColorPalette.SetUsePaletteColors(this.m_buttonPanel, false);
//
// m_okButton
//
this.m_okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.m_okButton.AutoSize = true;
this.m_glyssenColorPalette.SetBackColor(this.m_okButton, Glyssen.Utilities.GlyssenColors.BackColor);
this.m_okButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.m_glyssenColorPalette.SetFlatAppearanceBorderColor(this.m_okButton, Glyssen.Utilities.GlyssenColors.ForeColor);
this.m_glyssenColorPalette.SetForeColor(this.m_okButton, Glyssen.Utilities.GlyssenColors.ForeColor);
this.l10NSharpExtender1.SetLocalizableToolTip(this.m_okButton, null);
this.l10NSharpExtender1.SetLocalizationComment(this.m_okButton, null);
this.l10NSharpExtender1.SetLocalizingId(this.m_okButton, "Common.OK");
this.m_okButton.Location = new System.Drawing.Point(8, 0);
this.m_okButton.Margin = new System.Windows.Forms.Padding(8, 0, 0, 0);
this.m_okButton.Name = "m_okButton";
this.m_okButton.Size = new System.Drawing.Size(50, 23);
this.m_okButton.TabIndex = 13;
this.m_okButton.Text = "&OK";
this.m_glyssenColorPalette.SetUsePaletteColors(this.m_okButton, false);
this.m_okButton.Visible = false;
//
// m_cancelButton
//
this.m_cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.m_cancelButton.AutoSize = true;
this.m_glyssenColorPalette.SetBackColor(this.m_cancelButton, Glyssen.Utilities.GlyssenColors.BackColor);
this.m_cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.m_glyssenColorPalette.SetFlatAppearanceBorderColor(this.m_cancelButton, Glyssen.Utilities.GlyssenColors.ForeColor);
this.m_glyssenColorPalette.SetForeColor(this.m_cancelButton, Glyssen.Utilities.GlyssenColors.ForeColor);
this.l10NSharpExtender1.SetLocalizableToolTip(this.m_cancelButton, null);
this.l10NSharpExtender1.SetLocalizationComment(this.m_cancelButton, null);
this.l10NSharpExtender1.SetLocalizingId(this.m_cancelButton, "Common.Cancel");
this.m_cancelButton.Location = new System.Drawing.Point(66, 0);
this.m_cancelButton.Margin = new System.Windows.Forms.Padding(8, 0, 0, 0);
this.m_cancelButton.Name = "m_cancelButton";
this.m_cancelButton.Size = new System.Drawing.Size(58, 23);
this.m_cancelButton.TabIndex = 10;
this.m_cancelButton.Text = "Cancel";
this.m_glyssenColorPalette.SetUsePaletteColors(this.m_cancelButton, false);
this.m_cancelButton.Click += new System.EventHandler(this.OnCancelButton_Click);
//
// m_cancelLink
//
this.m_cancelLink.ActiveLinkColor = System.Drawing.SystemColors.HotTrack;
this.m_glyssenColorPalette.SetActiveLinkColor(this.m_cancelLink, Glyssen.Utilities.GlyssenColors.ActiveLinkColor);
this.m_cancelLink.AutoSize = true;
this.m_glyssenColorPalette.SetBackColor(this.m_cancelLink, Glyssen.Utilities.GlyssenColors.BackColor);
this.m_cancelLink.BackColor = System.Drawing.SystemColors.Control;
this.m_cancelLink.DisabledLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(133)))), ((int)(((byte)(133)))), ((int)(((byte)(133)))));
this.m_glyssenColorPalette.SetDisabledLinkColor(this.m_cancelLink, Glyssen.Utilities.GlyssenColors.DisabledLinkColor);
this.m_cancelLink.ForeColor = System.Drawing.SystemColors.WindowText;
this.m_glyssenColorPalette.SetForeColor(this.m_cancelLink, Glyssen.Utilities.GlyssenColors.ForeColor);
this.m_cancelLink.LinkColor = System.Drawing.SystemColors.HotTrack;
this.m_glyssenColorPalette.SetLinkColor(this.m_cancelLink, Glyssen.Utilities.GlyssenColors.LinkColor);
this.m_cancelLink.Location = new System.Drawing.Point(25, 103);
this.m_cancelLink.Margin = new System.Windows.Forms.Padding(25, 0, 3, 0);
this.m_cancelLink.Name = "m_cancelLink";
this.m_cancelLink.Padding = new System.Windows.Forms.Padding(0, 5, 0, 0);
this.m_cancelLink.Size = new System.Drawing.Size(209, 18);
this.m_cancelLink.TabIndex = 15;
this.m_cancelLink.TabStop = true;
this.m_cancelLink.Text = "#";
this.m_glyssenColorPalette.SetUsePaletteColors(this.m_cancelLink, true);
this.m_cancelLink.Visible = false;
this.m_cancelLink.VisitedLinkColor = System.Drawing.SystemColors.HotTrack;
this.m_glyssenColorPalette.SetVisitedLinkColor(this.m_cancelLink, Glyssen.Utilities.GlyssenColors.VisitedLinkColor);
this.m_cancelLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.OnCancelLink_LinkClicked);
//
// l10NSharpExtender1
//
this.l10NSharpExtender1.LocalizationManagerId = "Glyssen";
this.l10NSharpExtender1.PrefixForNewItems = "DialogBoxes";
//
// ProgressDialogWithAcknowledgement
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.AutoSize = true;
this.m_glyssenColorPalette.SetBackColor(this, Glyssen.Utilities.GlyssenColors.BackColor);
this.ClientSize = new System.Drawing.Size(468, 139);
this.ControlBox = false;
this.Controls.Add(this.m_tableLayout);
this.m_glyssenColorPalette.SetForeColor(this, Glyssen.Utilities.GlyssenColors.Default);
this.ForeColor = System.Drawing.SystemColors.WindowText;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.l10NSharpExtender1.SetLocalizableToolTip(this, null);
this.l10NSharpExtender1.SetLocalizationComment(this, null);
this.l10NSharpExtender1.SetLocalizationPriority(this, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this, "ProgressDialogWithAcknowledgement.WindowTitle");
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ProgressDialogWithAcknowledgement";
this.Padding = new System.Windows.Forms.Padding(12);
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Palaso";
this.m_glyssenColorPalette.SetUsePaletteColors(this, true);
this.Load += new System.EventHandler(this.ProgressDialog_Load);
this.Shown += new System.EventHandler(this.ProgressDialog_Shown);
this.m_tableLayout.ResumeLayout(false);
this.m_tableLayout.PerformLayout();
this.m_buttonPanel.ResumeLayout(false);
this.m_buttonPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.m_glyssenColorPalette)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.l10NSharpExtender1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void OnTakingLongTimeTimerClick(object sender, EventArgs e)
{
// Show the window now the timer has elapsed, and stop the timer
m_showWindowIfTakingLongTimeTimer.Stop();
if (!Visible)
{
Show();
}
}
private void OnCancelButton_Click(object sender, EventArgs e)
{
m_showWindowIfTakingLongTimeTimer.Stop();
//Debug.WriteLine("Dialog:OnCancelButton_Click");
// Prevent further cancellation
m_cancelButton.Enabled = false;
m_progressTimer.Stop();
m_progressLabel.Text = LocalizationManager.GetString("DialogBoxes.ProgressDialogWithAcknowledgement.Canceling", "Canceling...");
// Tell people we're canceling
OnCancelled( e );
if (m_backgroundWorker != null && m_backgroundWorker.WorkerSupportsCancellation)
{
m_backgroundWorker.CancelAsync();
}
}
private void progressTimer_Tick(object sender, EventArgs e)
{
int range = m_progressBar.Maximum - m_progressBar.Minimum;
if( range <= 0 )
{
return;
}
if( m_progressBar.Value <= 0 )
{
return;
}
if (m_startTime != default(DateTime))
{
TimeSpan elapsed = DateTime.Now - m_startTime;
double estimatedSeconds = (elapsed.TotalSeconds * range) / m_progressBar.Value;
TimeSpan estimatedToGo = new TimeSpan(0, 0, 0, (int)(estimatedSeconds - elapsed.TotalSeconds), 0);
//_progressLabel.Text = String.Format(
// System.Globalization.CultureInfo.CurrentUICulture,
// "Elapsed: {0} Remaining: {1}",
// GetStringFor(elapsed),
// GetStringFor(estimatedToGo));
m_progressLabel.Text = String.Format(
CultureInfo.CurrentUICulture,
"{0}",
//GetStringFor(elapsed),
GetStringFor(estimatedToGo));
}
}
private static string GetStringFor( TimeSpan span )
{
if( span.TotalDays > 1 )
{
return string.Format(CultureInfo.CurrentUICulture, "{0} day {1} hour", span.Days, span.Hours);
}
else if( span.TotalHours > 1 )
{
return string.Format(CultureInfo.CurrentUICulture, "{0} hour {1} minutes", span.Hours, span.Minutes);
}
else if( span.TotalMinutes > 1 )
{
return string.Format(CultureInfo.CurrentUICulture, "{0} minutes {1} seconds", span.Minutes, span.Seconds);
}
return string.Format( CultureInfo.CurrentUICulture, "{0} seconds", span.Seconds );
}
public void OnNumberOfStepsCompletedChanged(object sender, EventArgs e)
{
Progress = ((ProgressState) sender).NumberOfStepsCompleted;
//in case there is no event pump showing us (mono-threaded)
progressTimer_Tick(this, null);
Refresh();
}
public void OnTotalNumberOfStepsChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new ProgressCallback(UpdateTotal), ((ProgressState)sender).TotalNumberOfSteps);
}
else
{
UpdateTotal(((ProgressState) sender).TotalNumberOfSteps);
}
}
private void UpdateTotal(int steps)
{
m_startTime = DateTime.Now;
ProgressRangeMaximum = steps;
Refresh();
}
public void OnStatusLabelChanged(object sender, EventArgs e)
{
StatusText = ((ProgressState)sender).StatusLabel;
Refresh();
}
private void OnStartWorker(object sender, EventArgs e)
{
m_workerStarted = true;
//Debug.WriteLine("Dialog:StartWorker");
if (m_backgroundWorker != null)
{
//BW uses percentages (unless it's using our custom ProgressState in the UserState member)
ProgressRangeMinimum = 0;
ProgressRangeMaximum = 100;
//if the actual task can't take cancelling, the caller of this should set CanCancel to false;
m_backgroundWorker.WorkerSupportsCancellation = CanCancel;
m_backgroundWorker.ProgressChanged += OnBackgroundWorker_ProgressChanged;
m_backgroundWorker.RunWorkerCompleted += OnBackgroundWorker_RunWorkerCompleted;
m_backgroundWorker.RunWorkerAsync(ProgressState);
}
}
//This is here, in addition to the OnShown handler, because of a weird bug where a certain,
//completely unrelated test (which doesn't use this class at all) can cause tests using this to
//fail because the OnShown event is never fired.
//I don't know why the orginal code we copied this from was using onshown instead of onload,
//but it may have something to do with its "delay show" feature (which I couldn't get to work,
//but which would be a terrific thing to have)
private void ProgressDialog_Load(object sender, EventArgs e)
{
if(!m_workerStarted)
{
OnStartWorker(this, null);
}
}
private void ProgressDialog_Shown(object sender, EventArgs e)
{
if(!m_workerStarted)
{
OnStartWorker(this, null);
}
}
private void OnCancelLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
m_cancelButton.Enabled = true;
m_cancelButton.Visible = true;
m_cancelButton.PerformClick();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.IO;
using System.Drawing.Internal;
namespace System.Drawing.Imaging
{
/// <summary>
/// Defines a graphic metafile. A metafile contains records that describe a sequence of graphics operations that
/// can be recorded and played back.
/// </summary>
public sealed partial class Metafile : Image
{
// GDI+ doesn't handle filenames over MAX_PATH very well
private const int MaxPath = 260;
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and
/// <see cref='WmfPlaceableFileHeader'/>.
/// </summary>
public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader) :
this(hmetafile, wmfHeader, false)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and
/// <see cref='WmfPlaceableFileHeader'/>.
/// </summary>
public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader, bool deleteWmf)
{
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromWmf(new HandleRef(null, hmetafile), deleteWmf, wmfHeader, out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and
/// <see cref='WmfPlaceableFileHeader'/>.
/// </summary>
public Metafile(IntPtr henhmetafile, bool deleteEmf)
{
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromEmf(new HandleRef(null, henhmetafile), deleteEmf, out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified filename.
/// </summary>
public Metafile(string filename)
{
// Called in order to emulate exception behavior from netfx related to invalid file paths.
Path.GetFullPath(filename);
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromFile(filename, out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified stream.
/// </summary>
public Metafile(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromStream(new GPStream(stream), out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle to a device context.
/// </summary>
public Metafile(IntPtr referenceHdc, EmfType emfType) :
this(referenceHdc, emfType, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle to a device context.
/// </summary>
public Metafile(IntPtr referenceHdc, EmfType emfType, String description)
{
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipRecordMetafile(new HandleRef(null, referenceHdc),
unchecked((int)emfType),
NativeMethods.NullHandleRef,
unchecked((int)MetafileFrameUnit.GdiCompatible),
description,
out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, RectangleF frameRect) :
this(referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit) :
this(referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type) :
this(referenceHdc, frameRect, frameUnit, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type, String description)
{
IntPtr metafile = IntPtr.Zero;
GPRECTF rectf = new GPRECTF(frameRect);
int status = SafeNativeMethods.Gdip.GdipRecordMetafile(new HandleRef(null, referenceHdc),
unchecked((int)type),
ref rectf,
unchecked((int)frameUnit),
description, out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, Rectangle frameRect) :
this(referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit) :
this(referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type) :
this(referenceHdc, frameRect, frameUnit, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string desc)
{
IntPtr metafile = IntPtr.Zero;
int status;
if (frameRect.IsEmpty)
{
status = SafeNativeMethods.Gdip.GdipRecordMetafile(new HandleRef(null, referenceHdc),
unchecked((int)type),
NativeMethods.NullHandleRef,
unchecked((int)MetafileFrameUnit.GdiCompatible),
desc,
out metafile);
}
else
{
GPRECT gprect = new GPRECT(frameRect);
status = SafeNativeMethods.Gdip.GdipRecordMetafileI(new HandleRef(null, referenceHdc),
unchecked((int)type),
ref gprect,
unchecked((int)frameUnit),
desc,
out metafile);
}
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc) :
this(fileName, referenceHdc, EmfType.EmfPlusDual, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, EmfType type) :
this(fileName, referenceHdc, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, EmfType type, String description)
{
// Called in order to emulate exception behavior from netfx related to invalid file paths.
Path.GetFullPath(fileName);
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipRecordMetafileFileName(fileName, new HandleRef(null, referenceHdc),
unchecked((int)type),
NativeMethods.NullHandleRef,
unchecked((int)MetafileFrameUnit.GdiCompatible),
description,
out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect) :
this(fileName, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit) :
this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit, EmfType type) :
this(fileName, referenceHdc, frameRect, frameUnit, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, string desc) :
this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, desc)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit, EmfType type, String description)
{
// Called in order to emulate exception behavior from netfx related to invalid file paths.
Path.GetFullPath(fileName);
if (fileName.Length > MaxPath)
{
throw new PathTooLongException();
}
IntPtr metafile = IntPtr.Zero;
GPRECTF rectf = new GPRECTF(frameRect);
int status = SafeNativeMethods.Gdip.GdipRecordMetafileFileName(fileName,
new HandleRef(null, referenceHdc),
unchecked((int)type),
ref rectf,
unchecked((int)frameUnit),
description,
out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect) :
this(fileName, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect,
MetafileFrameUnit frameUnit) :
this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect,
MetafileFrameUnit frameUnit, EmfType type) :
this(fileName, referenceHdc, frameRect, frameUnit, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, string description) :
this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, description)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string description)
{
// Called in order to emulate exception behavior from netfx related to invalid file paths.
Path.GetFullPath(fileName);
IntPtr metafile = IntPtr.Zero;
int status;
if (frameRect.IsEmpty)
{
status = SafeNativeMethods.Gdip.GdipRecordMetafileFileName(fileName,
new HandleRef(null, referenceHdc),
unchecked((int)type),
NativeMethods.NullHandleRef,
unchecked((int)frameUnit),
description,
out metafile);
}
else
{
GPRECT gprect = new GPRECT(frameRect);
status = SafeNativeMethods.Gdip.GdipRecordMetafileFileNameI(fileName,
new HandleRef(null, referenceHdc),
unchecked((int)type),
ref gprect,
unchecked((int)frameUnit),
description,
out metafile);
}
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc) :
this(stream, referenceHdc, EmfType.EmfPlusDual, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, EmfType type) :
this(stream, referenceHdc, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, EmfType type, string description)
{
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipRecordMetafileStream(new GPStream(stream),
new HandleRef(null, referenceHdc),
unchecked((int)type),
NativeMethods.NullHandleRef,
unchecked((int)MetafileFrameUnit.GdiCompatible),
description,
out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect) :
this(stream, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit) :
this(stream, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit, EmfType type) :
this(stream, referenceHdc, frameRect, frameUnit, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit, EmfType type, string description)
{
IntPtr metafile = IntPtr.Zero;
GPRECTF rectf = new GPRECTF(frameRect);
int status = SafeNativeMethods.Gdip.GdipRecordMetafileStream(new GPStream(stream),
new HandleRef(null, referenceHdc),
unchecked((int)type),
ref rectf,
unchecked((int)frameUnit),
description,
out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect) :
this(stream, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect,
MetafileFrameUnit frameUnit) :
this(stream, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect,
MetafileFrameUnit frameUnit, EmfType type) :
this(stream, referenceHdc, frameRect, frameUnit, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit,
EmfType type, string description)
{
IntPtr metafile = IntPtr.Zero;
int status;
if (frameRect.IsEmpty)
{
status = SafeNativeMethods.Gdip.GdipRecordMetafileStream(new GPStream(stream),
new HandleRef(null, referenceHdc),
unchecked((int)type),
NativeMethods.NullHandleRef,
unchecked((int)frameUnit),
description,
out metafile);
}
else
{
GPRECT gprect = new GPRECT(frameRect);
status = SafeNativeMethods.Gdip.GdipRecordMetafileStreamI(new GPStream(stream),
new HandleRef(null, referenceHdc),
unchecked((int)type),
ref gprect,
unchecked((int)frameUnit),
description,
out metafile);
}
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>.
/// </summary>
public static MetafileHeader GetMetafileHeader(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader)
{
MetafileHeader header = new MetafileHeader();
header.wmf = new MetafileHeaderWmf();
int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromWmf(new HandleRef(null, hmetafile), wmfHeader, header.wmf);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return header;
}
/// <summary>
/// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>.
/// </summary>
public static MetafileHeader GetMetafileHeader(IntPtr henhmetafile)
{
MetafileHeader header = new MetafileHeader();
header.emf = new MetafileHeaderEmf();
int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromEmf(new HandleRef(null, henhmetafile), header.emf);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return header;
}
/// <summary>
/// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>.
/// </summary>
public static MetafileHeader GetMetafileHeader(string fileName)
{
// Called in order to emulate exception behavior from netfx related to invalid file paths.
Path.GetFullPath(fileName);
MetafileHeader header = new MetafileHeader();
IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf)));
try
{
int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromFile(fileName, memory);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
int[] type = new int[] { 0 };
Marshal.Copy(memory, type, 0, 1);
MetafileType metafileType = (MetafileType)type[0];
if (metafileType == MetafileType.Wmf ||
metafileType == MetafileType.WmfPlaceable)
{
// WMF header
header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf));
header.emf = null;
}
else
{
// EMF header
header.wmf = null;
header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf));
}
}
finally
{
Marshal.FreeHGlobal(memory);
}
return header;
}
/// <summary>
/// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>.
/// </summary>
public static MetafileHeader GetMetafileHeader(Stream stream)
{
MetafileHeader header;
IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf)));
try
{
int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromStream(new GPStream(stream), memory);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
int[] type = new int[] { 0 };
Marshal.Copy(memory, type, 0, 1);
MetafileType metafileType = (MetafileType)type[0];
header = new MetafileHeader();
if (metafileType == MetafileType.Wmf ||
metafileType == MetafileType.WmfPlaceable)
{
// WMF header
header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf));
header.emf = null;
}
else
{
// EMF header
header.wmf = null;
header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf));
}
}
finally
{
Marshal.FreeHGlobal(memory);
}
return header;
}
/// <summary>
/// Returns the <see cref='MetafileHeader'/> associated with this <see cref='Metafile'/>.
/// </summary>
public MetafileHeader GetMetafileHeader()
{
MetafileHeader header;
IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf)));
try
{
int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromMetafile(new HandleRef(this, nativeImage), memory);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
int[] type = new int[] { 0 };
Marshal.Copy(memory, type, 0, 1);
MetafileType metafileType = (MetafileType)type[0];
header = new MetafileHeader();
if (metafileType == MetafileType.Wmf ||
metafileType == MetafileType.WmfPlaceable)
{
// WMF header
header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf));
header.emf = null;
}
else
{
// EMF header
header.wmf = null;
header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf));
}
}
finally
{
Marshal.FreeHGlobal(memory);
}
return header;
}
/// <summary>
/// Returns a Windows handle to an enhanced <see cref='Metafile'/>.
/// </summary>
public IntPtr GetHenhmetafile()
{
IntPtr hEmf = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipGetHemfFromMetafile(new HandleRef(this, nativeImage), out hEmf);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return hEmf;
}
/// <summary>
/// Plays an EMF+ file.
/// </summary>
public void PlayRecord(EmfPlusRecordType recordType,
int flags,
int dataSize,
byte[] data)
{
// Used in conjunction with Graphics.EnumerateMetafile to play an EMF+
// The data must be DWORD aligned if it's an EMF or EMF+. It must be
// WORD aligned if it's a WMF.
int status = SafeNativeMethods.Gdip.GdipPlayMetafileRecord(new HandleRef(this, nativeImage),
recordType,
flags,
dataSize,
data);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/*
* Create a new metafile object from a native metafile handle.
* This is only for internal purpose.
*/
internal static Metafile FromGDIplus(IntPtr nativeImage)
{
Metafile metafile = new Metafile();
metafile.SetNativeImage(nativeImage);
return metafile;
}
private Metafile()
{
}
}
}
| |
// 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;
namespace System.Text
{
public sealed class DecoderReplacementFallback : DecoderFallback
{
// Our variables
private String _strDefault;
// Construction. Default replacement fallback uses no best fit and ? replacement string
public DecoderReplacementFallback() : this("?")
{
}
public DecoderReplacementFallback(String replacement)
{
if (replacement == null)
throw new ArgumentNullException(nameof(replacement));
Contract.EndContractBlock();
// Make sure it doesn't have bad surrogate pairs
bool bFoundHigh = false;
for (int i = 0; i < replacement.Length; i++)
{
// Found a surrogate?
if (Char.IsSurrogate(replacement, i))
{
// High or Low?
if (Char.IsHighSurrogate(replacement, i))
{
// if already had a high one, stop
if (bFoundHigh)
break; // break & throw at the bFoundHIgh below
bFoundHigh = true;
}
else
{
// Low, did we have a high?
if (!bFoundHigh)
{
// Didn't have one, make if fail when we stop
bFoundHigh = true;
break;
}
// Clear flag
bFoundHigh = false;
}
}
// If last was high we're in trouble (not surrogate so not low surrogate, so break)
else if (bFoundHigh)
break;
}
if (bFoundHigh)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, nameof(replacement));
_strDefault = replacement;
}
public String DefaultString
{
get
{
return _strDefault;
}
}
public override DecoderFallbackBuffer CreateFallbackBuffer()
{
return new DecoderReplacementFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return _strDefault.Length;
}
}
public override bool Equals(Object value)
{
DecoderReplacementFallback that = value as DecoderReplacementFallback;
if (that != null)
{
return (_strDefault == that._strDefault);
}
return (false);
}
public override int GetHashCode()
{
return _strDefault.GetHashCode();
}
}
public sealed class DecoderReplacementFallbackBuffer : DecoderFallbackBuffer
{
// Store our default string
private String _strDefault;
private int _fallbackCount = -1;
private int _fallbackIndex = -1;
// Construction
public DecoderReplacementFallbackBuffer(DecoderReplacementFallback fallback)
{
_strDefault = fallback.DefaultString;
}
// Fallback Methods
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
// We can't call recursively but others might (note, we don't test on last char!!!)
if (_fallbackCount >= 1)
{
ThrowLastBytesRecursive(bytesUnknown);
}
// Go ahead and get our fallback
if (_strDefault.Length == 0)
return false;
_fallbackCount = _strDefault.Length;
_fallbackIndex = -1;
return true;
}
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
_fallbackCount--;
_fallbackIndex++;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (_fallbackCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (_fallbackCount == int.MaxValue)
{
_fallbackCount = -1;
return '\0';
}
// Now make sure its in the expected range
Debug.Assert(_fallbackIndex < _strDefault.Length && _fallbackIndex >= 0,
"Index exceeds buffer range");
return _strDefault[_fallbackIndex];
}
public override bool MovePrevious()
{
// Back up one, only if we just processed the last character (or earlier)
if (_fallbackCount >= -1 && _fallbackIndex >= 0)
{
_fallbackIndex--;
_fallbackCount++;
return true;
}
// Return false 'cause we couldn't do it.
return false;
}
// How many characters left to output?
public override int Remaining
{
get
{
// Our count is 0 for 1 character left.
return (_fallbackCount < 0) ? 0 : _fallbackCount;
}
}
// Clear the buffer
public override unsafe void Reset()
{
_fallbackCount = -1;
_fallbackIndex = -1;
byteStart = null;
}
// This version just counts the fallback and doesn't actually copy anything.
internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
{
// return our replacement string Length
return _strDefault.Length;
}
}
}
| |
namespace BooCompiler.Tests
{
using NUnit.Framework;
[TestFixture]
public class GenericsTestFixture : AbstractCompilerTestCase
{
override protected void RunCompilerTestCase(string name)
{
if (System.Environment.Version.Major < 2) Assert.Ignore("Test requires .net 2.");
System.ResolveEventHandler resolver = InstallAssemblyResolver(BaseTestCasesPath);
try
{
base.RunCompilerTestCase(name);
}
finally
{
RemoveAssemblyResolver(resolver);
}
}
override protected void CopyDependencies()
{
CopyAssembliesFromTestCasePath();
}
[Test]
public void ambiguous_1()
{
RunCompilerTestCase(@"ambiguous-1.boo");
}
[Test]
public void array_enumerable_1()
{
RunCompilerTestCase(@"array-enumerable-1.boo");
}
[Test]
public void array_enumerable_2()
{
RunCompilerTestCase(@"array-enumerable-2.boo");
}
[Test]
public void automatic_generic_method_stub()
{
RunCompilerTestCase(@"automatic-generic-method-stub.boo");
}
[Test]
public void callable_1()
{
RunCompilerTestCase(@"callable-1.boo");
}
[Test]
public void callable_2()
{
RunCompilerTestCase(@"callable-2.boo");
}
[Test]
public void collections_1()
{
RunCompilerTestCase(@"collections-1.boo");
}
[Test]
public void collections_2()
{
RunCompilerTestCase(@"collections-2.boo");
}
[Test]
public void enumerable_shorthand_1()
{
RunCompilerTestCase(@"enumerable-shorthand-1.boo");
}
[Test]
public void enumerable_type_inference_1()
{
RunCompilerTestCase(@"enumerable-type-inference-1.boo");
}
[Test]
public void enumerable_type_inference_2()
{
RunCompilerTestCase(@"enumerable-type-inference-2.boo");
}
[Test]
public void enumerable_type_inference_4()
{
RunCompilerTestCase(@"enumerable-type-inference-4.boo");
}
[Test]
public void enumerable_type_inference_5()
{
RunCompilerTestCase(@"enumerable-type-inference-5.boo");
}
[Test]
public void generator_with_type_constraint_1()
{
RunCompilerTestCase(@"generator-with-type-constraint-1.boo");
}
[Test]
public void generator_with_type_constraint_manually_expanded()
{
RunCompilerTestCase(@"generator-with-type-constraint-manually-expanded.boo");
}
[Test]
public void generators_1()
{
RunCompilerTestCase(@"generators-1.boo");
}
[Test]
public void generators_2()
{
RunCompilerTestCase(@"generators-2.boo");
}
[Test]
public void generators_3()
{
RunCompilerTestCase(@"generators-3.boo");
}
[Test]
public void generators_4()
{
RunCompilerTestCase(@"generators-4.boo");
}
[Test]
public void generators_5()
{
RunCompilerTestCase(@"generators-5.boo");
}
[Test]
public void generators_6()
{
RunCompilerTestCase(@"generators-6.boo");
}
[Test]
public void generators_7()
{
RunCompilerTestCase(@"generators-7.boo");
}
[Test]
public void generic_array_1()
{
RunCompilerTestCase(@"generic-array-1.boo");
}
[Test]
public void generic_array_2()
{
RunCompilerTestCase(@"generic-array-2.boo");
}
[Test]
public void generic_array_3()
{
RunCompilerTestCase(@"generic-array-3.boo");
}
[Test]
public void generic_closures()
{
RunCompilerTestCase(@"generic-closures.boo");
}
[Test]
public void generic_closures_2()
{
RunCompilerTestCase(@"generic-closures-2.boo");
}
[Test]
public void generic_closures_3()
{
RunCompilerTestCase(@"generic-closures-3.boo");
}
[Test]
public void generic_extension_1()
{
RunCompilerTestCase(@"generic-extension-1.boo");
}
[Test]
public void generic_extension_2()
{
RunCompilerTestCase(@"generic-extension-2.boo");
}
[Test]
public void generic_field_1()
{
RunCompilerTestCase(@"generic-field-1.boo");
}
[Test]
public void generic_generator_type_1()
{
RunCompilerTestCase(@"generic-generator-type-1.boo");
}
[Test]
public void generic_inheritance_1()
{
RunCompilerTestCase(@"generic-inheritance-1.boo");
}
[Test]
public void generic_instance_overload()
{
RunCompilerTestCase(@"generic-instance-overload.boo");
}
[Test]
public void generic_list_of_callable()
{
RunCompilerTestCase(@"generic-list-of-callable.boo");
}
[Test]
public void generic_matrix_1()
{
RunCompilerTestCase(@"generic-matrix-1.boo");
}
[Test]
public void generic_method_1()
{
RunCompilerTestCase(@"generic-method-1.boo");
}
[Test]
public void generic_method_2()
{
RunCompilerTestCase(@"generic-method-2.boo");
}
[Test]
public void generic_method_3()
{
RunCompilerTestCase(@"generic-method-3.boo");
}
[Test]
public void generic_method_4()
{
RunCompilerTestCase(@"generic-method-4.boo");
}
[Test]
public void generic_method_5()
{
RunCompilerTestCase(@"generic-method-5.boo");
}
[Test]
public void generic_method_invocation_1()
{
RunCompilerTestCase(@"generic-method-invocation-1.boo");
}
[Test]
public void generic_method_invocation_2()
{
RunCompilerTestCase(@"generic-method-invocation-2.boo");
}
[Test]
public void generic_overload_1()
{
RunCompilerTestCase(@"generic-overload-1.boo");
}
[Test]
public void generic_overload_2()
{
RunCompilerTestCase(@"generic-overload-2.boo");
}
[Test]
public void generic_overload_3()
{
RunCompilerTestCase(@"generic-overload-3.boo");
}
[Test]
public void generic_overload_4()
{
RunCompilerTestCase(@"generic-overload-4.boo");
}
[Test]
public void generic_overload_5()
{
RunCompilerTestCase(@"generic-overload-5.boo");
}
[Ignore("FIXME: Covariance support is incomplete, generates unverifiable IL (BOO-1155)")][Test]
public void generic_overload_6()
{
RunCompilerTestCase(@"generic-overload-6.boo");
}
[Test]
public void generic_overload_7()
{
RunCompilerTestCase(@"generic-overload-7.boo");
}
[Test]
public void generic_ref_parameter()
{
RunCompilerTestCase(@"generic-ref-parameter.boo");
}
[Test]
public void generic_type_resolution_1()
{
RunCompilerTestCase(@"generic-type-resolution-1.boo");
}
[Test]
public void generic_type_resolution_2()
{
RunCompilerTestCase(@"generic-type-resolution-2.boo");
}
[Test]
public void generic_type_resolution_3()
{
RunCompilerTestCase(@"generic-type-resolution-3.boo");
}
[Test]
public void inference_1()
{
RunCompilerTestCase(@"inference-1.boo");
}
[Test]
public void inference_10()
{
RunCompilerTestCase(@"inference-10.boo");
}
[Test]
public void inference_2()
{
RunCompilerTestCase(@"inference-2.boo");
}
[Test]
public void inference_3()
{
RunCompilerTestCase(@"inference-3.boo");
}
[Test]
public void inference_4()
{
RunCompilerTestCase(@"inference-4.boo");
}
[Test]
public void inference_5()
{
RunCompilerTestCase(@"inference-5.boo");
}
[Test]
public void inference_6()
{
RunCompilerTestCase(@"inference-6.boo");
}
[Test]
public void inference_7()
{
RunCompilerTestCase(@"inference-7.boo");
}
[Ignore("Anonymous callable types involving generic type arguments are not handled correctly yet (BOO-854)")][Test]
public void inference_8()
{
RunCompilerTestCase(@"inference-8.boo");
}
[Test]
public void inference_9()
{
RunCompilerTestCase(@"inference-9.boo");
}
[Test]
public void inheritance_1()
{
RunCompilerTestCase(@"inheritance-1.boo");
}
[Test]
public void inheritance_2()
{
RunCompilerTestCase(@"inheritance-2.boo");
}
[Test]
public void inheritance_3()
{
RunCompilerTestCase(@"inheritance-3.boo");
}
[Test]
public void interface_1()
{
RunCompilerTestCase(@"interface-1.boo");
}
[Test]
public void interface_with_generic_method()
{
RunCompilerTestCase(@"interface-with-generic-method.boo");
}
[Test]
public void internal_generic_callable_type_1()
{
RunCompilerTestCase(@"internal-generic-callable-type-1.boo");
}
[Test]
public void internal_generic_callable_type_2()
{
RunCompilerTestCase(@"internal-generic-callable-type-2.boo");
}
[Test]
public void internal_generic_callable_type_3()
{
RunCompilerTestCase(@"internal-generic-callable-type-3.boo");
}
[Test]
public void internal_generic_type_1()
{
RunCompilerTestCase(@"internal-generic-type-1.boo");
}
[Test]
public void internal_generic_type_10()
{
RunCompilerTestCase(@"internal-generic-type-10.boo");
}
[Test]
public void internal_generic_type_11()
{
RunCompilerTestCase(@"internal-generic-type-11.boo");
}
[Test]
public void internal_generic_type_2()
{
RunCompilerTestCase(@"internal-generic-type-2.boo");
}
[Test]
public void internal_generic_type_3()
{
RunCompilerTestCase(@"internal-generic-type-3.boo");
}
[Test]
public void internal_generic_type_4()
{
RunCompilerTestCase(@"internal-generic-type-4.boo");
}
[Test]
public void internal_generic_type_5()
{
RunCompilerTestCase(@"internal-generic-type-5.boo");
}
[Test]
public void internal_generic_type_6()
{
RunCompilerTestCase(@"internal-generic-type-6.boo");
}
[Test]
public void internal_generic_type_7()
{
RunCompilerTestCase(@"internal-generic-type-7.boo");
}
[Test]
public void internal_generic_type_8()
{
RunCompilerTestCase(@"internal-generic-type-8.boo");
}
[Test]
public void internal_generic_type_9()
{
RunCompilerTestCase(@"internal-generic-type-9.boo");
}
[Test]
public void method_ref_1()
{
RunCompilerTestCase(@"method-ref-1.boo");
}
[Test]
public void mixed_1()
{
RunCompilerTestCase(@"mixed-1.boo");
}
[Test]
public void mixed_2()
{
RunCompilerTestCase(@"mixed-2.boo");
}
[Test]
public void mixed_3()
{
RunCompilerTestCase(@"mixed-3.boo");
}
[Test]
public void mixed_4()
{
RunCompilerTestCase(@"mixed-4.boo");
}
[Test]
public void mixed_ref_parameter_1()
{
RunCompilerTestCase(@"mixed-ref-parameter-1.boo");
}
[Test]
public void mixed_ref_parameter_2()
{
RunCompilerTestCase(@"mixed-ref-parameter-2.boo");
}
[Test]
public void naked_type_constraints_1()
{
RunCompilerTestCase(@"naked-type-constraints-1.boo");
}
[Ignore("generics with nested types not supported yet")][Test]
public void nested_generic_type_1()
{
RunCompilerTestCase(@"nested-generic-type-1.boo");
}
[Test]
public void nullable_1()
{
RunCompilerTestCase(@"nullable-1.boo");
}
[Test]
public void nullable_2()
{
RunCompilerTestCase(@"nullable-2.boo");
}
[Test]
public void nullable_3()
{
RunCompilerTestCase(@"nullable-3.boo");
}
[Test]
public void nullable_4()
{
RunCompilerTestCase(@"nullable-4.boo");
}
[Test]
public void nullable_5()
{
RunCompilerTestCase(@"nullable-5.boo");
}
[Test]
public void nullable_6()
{
RunCompilerTestCase(@"nullable-6.boo");
}
[Test]
public void nullable_7()
{
RunCompilerTestCase(@"nullable-7.boo");
}
[Test]
public void override_1()
{
RunCompilerTestCase(@"override-1.boo");
}
[Test]
public void override_2()
{
RunCompilerTestCase(@"override-2.boo");
}
[Test]
public void override_3()
{
RunCompilerTestCase(@"override-3.boo");
}
[Test]
public void override_4()
{
RunCompilerTestCase(@"override-4.boo");
}
[Test]
public void override_5()
{
RunCompilerTestCase(@"override-5.boo");
}
[Test]
public void type_reference_1()
{
RunCompilerTestCase(@"type-reference-1.boo");
}
[Test]
public void type_reference_2()
{
RunCompilerTestCase(@"type-reference-2.boo");
}
[Test]
public void type_reference_3()
{
RunCompilerTestCase(@"type-reference-3.boo");
}
override protected string GetRelativeTestCasesPath()
{
return "net2/generics";
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Signum.Entities.Reflection;
using Signum.Utilities;
using Signum.Utilities.Reflection;
using Signum.Utilities.ExpressionTrees;
namespace Signum.Entities
{
[Serializable, DescriptionOptions(DescriptionOptions.Members), InTypeScript(false)]
public abstract class MixinEntity : ModifiableEntity
{
protected MixinEntity(ModifiableEntity mainEntity, MixinEntity? next)
{
this.mainEntity = mainEntity;
this.next = next;
}
[Ignore]
readonly MixinEntity? next;
[HiddenProperty]
public MixinEntity? Next
{
get { return next; }
}
[Ignore]
readonly ModifiableEntity mainEntity;
[HiddenProperty]
public ModifiableEntity MainEntity
{
get { return mainEntity; }
}
protected internal virtual void CopyFrom(MixinEntity mixin, object[] args)
{
}
}
public static class MixinDeclarations
{
public static readonly MethodInfo miMixin = ReflectionTools.GetMethodInfo((Entity i) => i.Mixin<CorruptMixin>()).GetGenericMethodDefinition();
public static ConcurrentDictionary<Type, HashSet<Type>> Declarations = new ConcurrentDictionary<Type, HashSet<Type>>();
public static ConcurrentDictionary<Type, Func<ModifiableEntity, MixinEntity?, MixinEntity>> Constructors = new ConcurrentDictionary<Type, Func<ModifiableEntity, MixinEntity?, MixinEntity>>();
public static Action<Type> AssertNotIncluded = t => { throw new NotImplementedException("Call MixinDeclarations.Register in the server, after the Connector is created."); };
public static void Register<T, M>()
where T : ModifiableEntity
where M : MixinEntity
{
Register(typeof(T), typeof(M));
}
public static void Register(Type mainEntity, Type mixinEntity)
{
if (!typeof(ModifiableEntity).IsAssignableFrom(mainEntity))
throw new InvalidOperationException("{0} is not a {1}".FormatWith(mainEntity.Name, typeof(Entity).Name));
if (mainEntity.IsAbstract)
throw new InvalidOperationException("{0} is abstract".FormatWith(mainEntity.Name));
if (!typeof(MixinEntity).IsAssignableFrom(mixinEntity))
throw new InvalidOperationException("{0} is not a {1}".FormatWith(mixinEntity.Name, typeof(MixinEntity).Name));
AssertNotIncluded(mainEntity);
GetMixinDeclarations(mainEntity).Add(mixinEntity);
AddConstructor(mixinEntity);
}
public static void Import(Dictionary<Type, HashSet<Type>> declarations)
{
Declarations = new ConcurrentDictionary<Type, HashSet<Type>>(declarations);
foreach (var t in declarations.SelectMany(d => d.Value).Distinct())
AddConstructor(t);
}
static void AddConstructor(Type mixinEntity)
{
Constructors.GetOrAdd(mixinEntity, me =>
{
var constructors = me.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (constructors.Length != 1)
throw new InvalidOperationException($"{me.Name} should have just one non-public construtor with parameters (ModifiableEntity mainEntity, MixinEntity next)"
.FormatWith(me.Name));
var ci = constructors.Single();
var pi = ci.GetParameters();
if (ci.IsPublic || pi.Length != 2 || pi[0].ParameterType != typeof(ModifiableEntity) || pi[1].ParameterType != typeof(MixinEntity))
throw new InvalidOperationException($"{me.Name} does not have a non-public construtor with parameters (ModifiableEntity mainEntity, MixinEntity next)." +
(pi[0].ParameterType == typeof(Entity) ? "\r\nBREAKING CHANGE: The first parameter has changed from Entity -> ModifiableEntity" : null)
);
return (Func<ModifiableEntity, MixinEntity?, MixinEntity>)Expression.Lambda(Expression.New(ci, pMainEntity, pNext), pMainEntity, pNext).Compile();
});
}
static readonly ParameterExpression pMainEntity = ParameterExpression.Parameter(typeof(ModifiableEntity));
static readonly ParameterExpression pNext = ParameterExpression.Parameter(typeof(MixinEntity));
public static HashSet<Type> GetMixinDeclarations(Type mainEntity)
{
if (!typeof(ModifiableEntity).IsAssignableFrom(mainEntity))
throw new InvalidOperationException($"Type {mainEntity.Name} is not a ModifiableEntity");
if (mainEntity.IsAbstract)
throw new InvalidOperationException($"{mainEntity.Name} is abstract");
return Declarations.GetOrAdd(mainEntity, me =>
{
var hs = new HashSet<Type>(me.GetCustomAttributes(typeof(MixinAttribute), inherit: false)
.Cast<MixinAttribute>()
.Select(t => t.MixinType));
foreach (var t in hs)
AddConstructor(t);
return hs;
});
}
public static bool IsDeclared(Type mainEntity, Type mixinType)
{
return GetMixinDeclarations(mainEntity).Contains(mixinType);
}
public static void AssertDeclared(Type mainEntity, Type mixinType)
{
if (!IsDeclared(mainEntity, mixinType))
throw new InvalidOperationException("Mixin {0} is not registered for {1}. Consider writing MixinDeclarations.Register<{1}, {0}>() at the beginning of Starter.Start".FormatWith(mixinType.TypeName(), mainEntity.TypeName()));
}
internal static MixinEntity? CreateMixins(ModifiableEntity mainEntity)
{
var types = GetMixinDeclarations(mainEntity.GetType());
MixinEntity? result = null;
foreach (var t in types)
result = Constructors[t](mainEntity, result);
return result;
}
public static T SetMixin<T, M, V>(this T entity, Expression<Func<M, V>> mixinProperty, V value)
where T : IModifiableEntity
where M : MixinEntity
{
M mixin = ((ModifiableEntity)(IModifiableEntity)entity).Mixin<M>();
var pi = ReflectionTools.BasePropertyInfo(mixinProperty);
var setter = MixinSetterCache<M>.Setter<V>(pi);
setter(mixin, value);
return entity;
}
static class MixinSetterCache<T> where T : MixinEntity
{
static ConcurrentDictionary<string, Delegate> cache = new ConcurrentDictionary<string, Delegate>();
internal static Action<T, V> Setter<V>(PropertyInfo pi)
{
return (Action<T, V>)cache.GetOrAdd(pi.Name, s => ReflectionTools.CreateSetter<T, V>(Reflector.FindFieldInfo(typeof(T), pi))!);
}
}
public static T CopyMixinsFrom<T>(this T newEntity, IModifiableEntity original, params object[] args)
where T: IModifiableEntity
{
var list = (from nm in ((ModifiableEntity)(IModifiableEntity)newEntity).Mixins
join om in ((ModifiableEntity)(IModifiableEntity)original).Mixins
on nm.GetType() equals om.GetType()
select new { nm, om });
foreach (var pair in list)
{
pair.nm!.CopyFrom(pair.om!, args); /*CSBUG*/
}
return newEntity;
}
}
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
public sealed class MixinAttribute : Attribute
{
readonly Type mixinType;
public MixinAttribute(Type mixinType)
{
this.mixinType = mixinType;
}
public Type MixinType
{
get { return this.mixinType; }
}
}
}
| |
using UnityEngine;
using Pathfinding.Serialization;
namespace Pathfinding {
public class PointNode : GraphNode {
public GraphNode[] connections;
public uint[] connectionCosts;
/** GameObject this node was created from (if any).
* \warning When loading a graph from a saved file or from cache, this field will be null.
*/
public GameObject gameObject;
/** Used for internal linked list structure.
* \warning Do not modify
*/
public PointNode next;
public void SetPosition (Int3 value) {
position = value;
}
public PointNode (AstarPath astar) : base(astar) {
}
public override void GetConnections (GraphNodeDelegate del) {
if (connections == null) return;
for (int i = 0; i < connections.Length; i++) del(connections[i]);
}
public override void ClearConnections (bool alsoReverse) {
if (alsoReverse && connections != null) {
for (int i = 0; i < connections.Length; i++) {
connections[i].RemoveConnection(this);
}
}
connections = null;
connectionCosts = null;
}
public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
UpdateG(path, pathNode);
handler.PushNode(pathNode);
for (int i = 0; i < connections.Length; i++) {
GraphNode other = connections[i];
PathNode otherPN = handler.GetPathNode(other);
if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) {
other.UpdateRecursiveG(path, otherPN, handler);
}
}
}
public override bool ContainsConnection (GraphNode node) {
for (int i = 0; i < connections.Length; i++) if (connections[i] == node) return true;
return false;
}
/** Add a connection from this node to the specified node.
* If the connection already exists, the cost will simply be updated and
* no extra connection added.
*
* \note Only adds a one-way connection. Consider calling the same function on the other node
* to get a two-way connection.
*/
public override void AddConnection (GraphNode node, uint cost) {
if (node == null) throw new System.ArgumentNullException();
if (connections != null) {
for (int i = 0; i < connections.Length; i++) {
if (connections[i] == node) {
connectionCosts[i] = cost;
return;
}
}
}
int connLength = connections != null ? connections.Length : 0;
var newconns = new GraphNode[connLength+1];
var newconncosts = new uint[connLength+1];
for (int i = 0; i < connLength; i++) {
newconns[i] = connections[i];
newconncosts[i] = connectionCosts[i];
}
newconns[connLength] = node;
newconncosts[connLength] = cost;
connections = newconns;
connectionCosts = newconncosts;
}
/** Removes any connection from this node to the specified node.
* If no such connection exists, nothing will be done.
*
* \note This only removes the connection from this node to the other node.
* You may want to call the same function on the other node to remove its eventual connection
* to this node.
*/
public override void RemoveConnection (GraphNode node) {
if (connections == null) return;
for (int i = 0; i < connections.Length; i++) {
if (connections[i] == node) {
int connLength = connections.Length;
var newconns = new GraphNode[connLength-1];
var newconncosts = new uint[connLength-1];
for (int j = 0; j < i; j++) {
newconns[j] = connections[j];
newconncosts[j] = connectionCosts[j];
}
for (int j = i+1; j < connLength; j++) {
newconns[j-1] = connections[j];
newconncosts[j-1] = connectionCosts[j];
}
connections = newconns;
connectionCosts = newconncosts;
return;
}
}
}
public override void Open (Path path, PathNode pathNode, PathHandler handler) {
if (connections == null) return;
for (int i = 0; i < connections.Length; i++) {
GraphNode other = connections[i];
if (path.CanTraverse(other)) {
PathNode pathOther = handler.GetPathNode(other);
if (pathOther.pathID != handler.PathID) {
pathOther.parent = pathNode;
pathOther.pathID = handler.PathID;
pathOther.cost = connectionCosts[i];
pathOther.H = path.CalculateHScore(other);
other.UpdateG(path, pathOther);
handler.PushNode(pathOther);
} else {
//If not we can test if the path from this node to the other one is a better one then the one already used
uint tmpCost = connectionCosts[i];
if (pathNode.G + tmpCost + path.GetTraversalCost(other) < pathOther.G) {
pathOther.cost = tmpCost;
pathOther.parent = pathNode;
other.UpdateRecursiveG(path, pathOther, handler);
} else if (pathOther.G+tmpCost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection(this)) {
//Or if the path from the other node to this one is better
pathNode.parent = pathOther;
pathNode.cost = tmpCost;
UpdateRecursiveG(path, pathNode, handler);
}
}
}
}
}
public override void SerializeNode (GraphSerializationContext ctx) {
base.SerializeNode(ctx);
ctx.SerializeInt3(position);
}
public override void DeserializeNode (GraphSerializationContext ctx) {
base.DeserializeNode(ctx);
position = ctx.DeserializeInt3();
}
public override void SerializeReferences (GraphSerializationContext ctx) {
if (connections == null) {
ctx.writer.Write(-1);
} else {
ctx.writer.Write(connections.Length);
for (int i = 0; i < connections.Length; i++) {
ctx.SerializeNodeReference(connections[i]);
ctx.writer.Write(connectionCosts[i]);
}
}
}
public override void DeserializeReferences (GraphSerializationContext ctx) {
int count = ctx.reader.ReadInt32();
if (count == -1) {
connections = null;
connectionCosts = null;
} else {
connections = new GraphNode[count];
connectionCosts = new uint[count];
for (int i = 0; i < count; i++) {
connections[i] = ctx.DeserializeNodeReference();
connectionCosts[i] = ctx.reader.ReadUInt32();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.ServiceModel;
using System.Collections;
namespace System.Runtime.Serialization.Json
{
#if USE_REFEMIT
public class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContextComplex
#else
internal class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContextComplex
#endif
{
EmitTypeInformation emitXsiType;
bool perCallXsiTypeAlreadyEmitted;
bool useSimpleDictionaryFormat;
public XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
: base(serializer,
serializer.MaxItemsInObjectGraph,
new StreamingContext(StreamingContextStates.All),
serializer.IgnoreExtensionDataObject)
{
this.emitXsiType = serializer.EmitTypeInformation;
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.knownTypeList;
this.dataContractSurrogate = serializer.DataContractSurrogate;
this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes;
this.useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
}
internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
{
return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract);
}
internal IList<Type> SerializerKnownTypeList
{
get
{
return this.serializerKnownTypeList;
}
}
public bool UseSimpleDictionaryFormat
{
get
{
return this.useSimpleDictionaryFormat;
}
}
internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName)
{
return false;
}
internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract)
{
return false;
}
internal override void WriteArraySize(XmlWriterDelegator xmlWriter, int size)
{
}
protected override void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace)
{
if (this.emitXsiType != EmitTypeInformation.Never)
{
if (string.IsNullOrEmpty(dataContractNamespace))
{
WriteTypeInfo(writer, dataContractName);
}
else
{
WriteTypeInfo(writer, string.Concat(dataContractName, JsonGlobals.NameValueSeparatorString, TruncateDefaultDataContractNamespace(dataContractNamespace)));
}
}
}
internal static string TruncateDefaultDataContractNamespace(string dataContractNamespace)
{
if (!string.IsNullOrEmpty(dataContractNamespace))
{
if (dataContractNamespace[0] == '#')
{
return string.Concat("\\", dataContractNamespace);
}
else if (dataContractNamespace[0] == '\\')
{
return string.Concat("\\", dataContractNamespace);
}
else if (dataContractNamespace.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal))
{
return string.Concat("#", dataContractNamespace.Substring(JsonGlobals.DataContractXsdBaseNamespaceLength));
}
}
return dataContractNamespace;
}
static bool RequiresJsonTypeInfo(DataContract contract)
{
return (contract is ClassDataContract);
}
void WriteTypeInfo(XmlWriterDelegator writer, string typeInformation)
{
writer.WriteAttributeString(null, JsonGlobals.serverTypeString, null, typeInformation);
}
protected override bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
{
if (!((object.ReferenceEquals(contract.Name, declaredContract.Name) &&
object.ReferenceEquals(contract.Namespace, declaredContract.Namespace)) ||
(contract.Name.Value == declaredContract.Name.Value &&
contract.Namespace.Value == declaredContract.Namespace.Value)) &&
(contract.UnderlyingType != Globals.TypeOfObjectArray) &&
(this.emitXsiType != EmitTypeInformation.Never))
{
// We always deserialize collections assigned to System.Object as object[]
// Because of its common and JSON-specific nature,
// we don't want to validate known type information for object[]
// Don't validate known type information when emitXsiType == Never because
// known types are not used without type information in the JSON
if (RequiresJsonTypeInfo(contract))
{
perCallXsiTypeAlreadyEmitted = true;
WriteTypeInfo(writer, contract.Name.Value, contract.Namespace.Value);
}
else
{
// check if the declared type is System.Enum and throw because
// __type information cannot be written for enums since it results in invalid JSON.
// Without __type, the resulting JSON cannot be deserialized since a number cannot be directly assigned to System.Enum.
if (declaredContract.UnderlyingType == typeof(Enum))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException
(SR.GetString(SR.EnumTypeNotSupportedByDataContractJsonSerializer, declaredContract.UnderlyingType)));
}
}
// Return true regardless of whether we actually wrote __type information
// E.g. We don't write __type information for enums, but we still want verifyKnownType
// to be true for them.
return true;
}
return false;
}
#if USE_REFEMIT
public void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
#else
internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
#endif
{
Type objType = obj.GetType();
SerializationInfo serInfo = new SerializationInfo(objType, XmlObjectSerializer.FormatterConverter);
GetObjectData(obj, serInfo, GetStreamingContext());
if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ChangingFullTypeNameNotSupported, serInfo.FullTypeName, DataContract.GetClrTypeFullName(objType))));
}
else
{
base.WriteSerializationInfo(xmlWriter, objType, serInfo);
}
}
#if USE_REFEMIT
public static DataContract GetRevisedItemContract(DataContract oldItemContract)
#else
internal static DataContract GetRevisedItemContract(DataContract oldItemContract)
#endif
{
if ((oldItemContract != null) &&
oldItemContract.UnderlyingType.IsGenericType &&
(oldItemContract.UnderlyingType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue))
{
return DataContract.GetDataContract(oldItemContract.UnderlyingType);
}
return oldItemContract;
}
protected override void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
{
JsonDataContract jsonDataContract = JsonDataContract.GetJsonDataContract(dataContract);
if (emitXsiType == EmitTypeInformation.Always && !perCallXsiTypeAlreadyEmitted && RequiresJsonTypeInfo(dataContract))
{
WriteTypeInfo(xmlWriter, jsonDataContract.TypeName);
}
perCallXsiTypeAlreadyEmitted = false;
DataContractJsonSerializer.WriteJsonValue(jsonDataContract, xmlWriter, obj, this, declaredTypeHandle);
}
protected override void WriteNull(XmlWriterDelegator xmlWriter)
{
DataContractJsonSerializer.WriteJsonNull(xmlWriter);
}
#if USE_REFEMIT
public XmlDictionaryString CollectionItemName
#else
internal XmlDictionaryString CollectionItemName
#endif
{
get { return JsonGlobals.itemDictionaryString; }
}
#if USE_REFEMIT
public static void WriteJsonNameWithMapping(XmlWriterDelegator xmlWriter, XmlDictionaryString[] memberNames, int index)
#else
internal static void WriteJsonNameWithMapping(XmlWriterDelegator xmlWriter, XmlDictionaryString[] memberNames, int index)
#endif
{
xmlWriter.WriteStartElement("a", JsonGlobals.itemString, JsonGlobals.itemString);
xmlWriter.WriteAttributeString(null, JsonGlobals.itemString, null, memberNames[index].Value);
}
internal override void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, IDataNode dataNode)
{
Type dataType = dataNode.DataType;
if (dataType == Globals.TypeOfClassDataNode ||
dataType == Globals.TypeOfISerializableDataNode)
{
xmlWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString);
base.WriteExtensionDataTypeInfo(xmlWriter, dataNode);
}
else if (dataType == Globals.TypeOfCollectionDataNode)
{
xmlWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.arrayString);
// Don't write __type for collections
}
else if (dataType == Globals.TypeOfXmlDataNode)
{
// Don't write type or __type for XML types because we serialize them to strings
}
else if ((dataType == Globals.TypeOfObject) && (dataNode.Value != null))
{
DataContract dc = GetDataContract(dataNode.Value.GetType());
if (RequiresJsonTypeInfo(dc))
{
base.WriteExtensionDataTypeInfo(xmlWriter, dataNode);
}
}
}
protected override void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
{
DataContract dataContract;
bool verifyKnownType = false;
bool isDeclaredTypeInterface = declaredType.IsInterface;
if (isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType))
{
dataContract = GetDataContract(declaredTypeHandle, declaredType);
}
else if (declaredType.IsArray) // If declared type is array do not write __serverType. Instead write__serverType for each item
{
dataContract = GetDataContract(declaredTypeHandle, declaredType);
}
else
{
dataContract = GetDataContract(objectTypeHandle, objectType);
DataContract declaredTypeContract = (declaredTypeID >= 0)
? GetDataContract(declaredTypeID, declaredTypeHandle)
: GetDataContract(declaredTypeHandle, declaredType);
verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract);
HandleCollectionAssignedToObject(declaredType, ref dataContract, ref obj, ref verifyKnownType);
}
if (isDeclaredTypeInterface)
{
VerifyObjectCompatibilityWithInterface(dataContract, obj, declaredType);
}
SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredType.TypeHandle, declaredType);
}
static void VerifyObjectCompatibilityWithInterface(DataContract contract, object graph, Type declaredType)
{
Type contractType = contract.GetType();
if ((contractType == typeof(XmlDataContract)) && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(declaredType))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.XmlObjectAssignedToIncompatibleInterface, graph.GetType(), declaredType)));
}
if ((contractType == typeof(CollectionDataContract)) && !CollectionDataContract.IsCollectionInterface(declaredType))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.CollectionAssignedToIncompatibleInterface, graph.GetType(), declaredType)));
}
}
void HandleCollectionAssignedToObject(Type declaredType, ref DataContract dataContract, ref object obj, ref bool verifyKnownType)
{
if ((declaredType != dataContract.UnderlyingType) && (dataContract is CollectionDataContract))
{
if (verifyKnownType)
{
VerifyType(dataContract, declaredType);
verifyKnownType = false;
}
if (((CollectionDataContract)dataContract).Kind == CollectionKind.Dictionary)
{
// Convert non-generic dictionary to generic dictionary
IDictionary dictionaryObj = obj as IDictionary;
Dictionary<object, object> genericDictionaryObj = new Dictionary<object, object>();
foreach (DictionaryEntry entry in dictionaryObj)
{
genericDictionaryObj.Add(entry.Key, entry.Value);
}
obj = genericDictionaryObj;
}
dataContract = GetDataContract(Globals.TypeOfIEnumerable);
}
}
internal override void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
{
bool verifyKnownType = false;
Type declaredType = rootTypeDataContract.UnderlyingType;
bool isDeclaredTypeInterface = declaredType.IsInterface;
if (!(isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType))
&& !declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item
{
verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract);
HandleCollectionAssignedToObject(declaredType, ref dataContract, ref obj, ref verifyKnownType);
}
if (isDeclaredTypeInterface)
{
VerifyObjectCompatibilityWithInterface(dataContract, obj, declaredType);
}
SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredType.TypeHandle, declaredType);
}
void VerifyType(DataContract dataContract, Type declaredType)
{
bool knownTypesAddedInCurrentScope = false;
if (dataContract.KnownDataContracts != null)
{
scopedKnownTypes.Push(dataContract.KnownDataContracts);
knownTypesAddedInCurrentScope = true;
}
if (!IsKnownType(dataContract, declaredType))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
}
if (knownTypesAddedInCurrentScope)
{
scopedKnownTypes.Pop();
}
}
internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
{
DataContract dataContract = base.GetDataContract(typeHandle, type);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type)
{
DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle)
{
DataContract dataContract = base.GetDataContract(id, typeHandle);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal static DataContract ResolveJsonDataContractFromRootDataContract(XmlObjectSerializerContext context, XmlQualifiedName typeQName, DataContract rootTypeDataContract)
{
if (rootTypeDataContract.StableName == typeQName)
return rootTypeDataContract;
CollectionDataContract collectionContract = rootTypeDataContract as CollectionDataContract;
while (collectionContract != null)
{
DataContract itemContract;
if (collectionContract.ItemType.IsGenericType
&& collectionContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>))
{
itemContract = context.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments()));
}
else
{
itemContract = context.GetDataContract(context.GetSurrogatedType(collectionContract.ItemType));
}
if (itemContract.StableName == typeQName)
{
return itemContract;
}
collectionContract = itemContract as CollectionDataContract;
}
return null;
}
protected override DataContract ResolveDataContractFromRootDataContract(XmlQualifiedName typeQName)
{
return XmlObjectSerializerWriteContextComplexJson.ResolveJsonDataContractFromRootDataContract(this, typeQName, rootTypeDataContract);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
public static partial class LoadBalancersOperationsExtensions
{
/// <summary>
/// The delete loadbalancer operation deletes the specified loadbalancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
public static void Delete(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName)
{
Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).DeleteAsync(resourceGroupName, loadBalancerName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete loadbalancer operation deletes the specified loadbalancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync( this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The delete loadbalancer operation deletes the specified loadbalancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
public static void BeginDelete(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName)
{
Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).BeginDeleteAsync(resourceGroupName, loadBalancerName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete loadbalancer operation deletes the specified loadbalancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync( this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The Get ntework interface operation retreives information about the
/// specified network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
public static LoadBalancer Get(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, string expand = default(string))
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).GetAsync(resourceGroupName, loadBalancerName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get ntework interface operation retreives information about the
/// specified network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LoadBalancer> GetAsync( this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<LoadBalancer> result = await operations.GetWithHttpMessagesAsync(resourceGroupName, loadBalancerName, expand, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The Put LoadBalancer operation creates/updates a LoadBalancer
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete LoadBalancer operation
/// </param>
public static LoadBalancer CreateOrUpdate(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters)
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).CreateOrUpdateAsync(resourceGroupName, loadBalancerName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put LoadBalancer operation creates/updates a LoadBalancer
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete LoadBalancer operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LoadBalancer> CreateOrUpdateAsync( this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<LoadBalancer> result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The Put LoadBalancer operation creates/updates a LoadBalancer
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete LoadBalancer operation
/// </param>
public static LoadBalancer BeginCreateOrUpdate(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters)
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, loadBalancerName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put LoadBalancer operation creates/updates a LoadBalancer
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete LoadBalancer operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LoadBalancer> BeginCreateOrUpdateAsync( this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<LoadBalancer> result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The List loadBalancer opertion retrieves all the loadbalancers in a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<LoadBalancer> ListAll(this ILoadBalancersOperations operations)
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List loadBalancer opertion retrieves all the loadbalancers in a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LoadBalancer>> ListAllAsync( this ILoadBalancersOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<IPage<LoadBalancer>> result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The List loadBalancer opertion retrieves all the loadbalancers in a
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<LoadBalancer> List(this ILoadBalancersOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List loadBalancer opertion retrieves all the loadbalancers in a
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LoadBalancer>> ListAsync( this ILoadBalancersOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<IPage<LoadBalancer>> result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The List loadBalancer opertion retrieves all the loadbalancers in a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<LoadBalancer> ListAllNext(this ILoadBalancersOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List loadBalancer opertion retrieves all the loadbalancers in a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LoadBalancer>> ListAllNextAsync( this ILoadBalancersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<IPage<LoadBalancer>> result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The List loadBalancer opertion retrieves all the loadbalancers in a
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<LoadBalancer> ListNext(this ILoadBalancersOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List loadBalancer opertion retrieves all the loadbalancers in a
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LoadBalancer>> ListNextAsync( this ILoadBalancersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<IPage<LoadBalancer>> result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Codecs.Lucene3x
{
using Lucene.Net.Util;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
/*
* 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 FieldInfos = Lucene.Net.Index.FieldInfos;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using Term = Lucene.Net.Index.Term;
/// <summary>
/// this stores a monotonically increasing set of <Term, TermInfo> pairs in a
/// Directory. Pairs are accessed either by Term or by ordinal position the
/// set </summary>
/// @deprecated (4.0) this class has been replaced by
/// FormatPostingsTermsDictReader, except for reading old segments.
/// @lucene.experimental
[Obsolete("(4.0) this class has been replaced by")]
public sealed class TermInfosReader : IDisposable
{
private readonly Directory Directory;
private readonly string Segment;
private readonly FieldInfos FieldInfos;
private readonly IDisposableThreadLocal<ThreadResources> threadResources = new IDisposableThreadLocal<ThreadResources>();
private readonly SegmentTermEnum OrigEnum;
private readonly long Size_Renamed;
private readonly TermInfosReaderIndex Index;
private readonly int IndexLength;
private readonly int TotalIndexInterval;
private const int DEFAULT_CACHE_SIZE = 1024;
// Just adds term's ord to TermInfo
public sealed class TermInfoAndOrd : TermInfo
{
internal readonly long TermOrd;
public TermInfoAndOrd(TermInfo ti, long termOrd)
: base(ti)
{
Debug.Assert(termOrd >= 0);
this.TermOrd = termOrd;
}
}
private class CloneableTerm : DoubleBarrelLRUCache.CloneableKey
{
internal Term Term;
public CloneableTerm(Term t)
{
this.Term = t;
}
public override bool Equals(object other)
{
CloneableTerm t = (CloneableTerm)other;
return this.Term.Equals(t.Term);
}
public override int GetHashCode()
{
return Term.GetHashCode();
}
public override DoubleBarrelLRUCache.CloneableKey Clone()
{
return new CloneableTerm(Term);
}
}
private readonly DoubleBarrelLRUCache<CloneableTerm, TermInfoAndOrd> TermsCache = new DoubleBarrelLRUCache<CloneableTerm, TermInfoAndOrd>(DEFAULT_CACHE_SIZE);
/// <summary>
/// Per-thread resources managed by ThreadLocal
/// </summary>
private sealed class ThreadResources
{
internal SegmentTermEnum TermEnum;
}
internal TermInfosReader(Directory dir, string seg, FieldInfos fis, IOContext context, int indexDivisor)
{
bool success = false;
if (indexDivisor < 1 && indexDivisor != -1)
{
throw new System.ArgumentException("indexDivisor must be -1 (don't load terms index) or greater than 0: got " + indexDivisor);
}
try
{
Directory = dir;
Segment = seg;
FieldInfos = fis;
OrigEnum = new SegmentTermEnum(Directory.OpenInput(IndexFileNames.SegmentFileName(Segment, "", Lucene3xPostingsFormat.TERMS_EXTENSION), context), FieldInfos, false);
Size_Renamed = OrigEnum.Size;
if (indexDivisor != -1)
{
// Load terms index
TotalIndexInterval = OrigEnum.IndexInterval * indexDivisor;
string indexFileName = IndexFileNames.SegmentFileName(Segment, "", Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION);
SegmentTermEnum indexEnum = new SegmentTermEnum(Directory.OpenInput(indexFileName, context), FieldInfos, true);
try
{
Index = new TermInfosReaderIndex(indexEnum, indexDivisor, dir.FileLength(indexFileName), TotalIndexInterval);
IndexLength = Index.Length();
}
finally
{
indexEnum.Dispose();
}
}
else
{
// Do not load terms index:
TotalIndexInterval = -1;
Index = null;
IndexLength = -1;
}
success = true;
}
finally
{
// With lock-less commits, it's entirely possible (and
// fine) to hit a FileNotFound exception above. In
// this case, we want to explicitly close any subset
// of things that were opened so that we don't have to
// wait for a GC to do so.
if (!success)
{
Dispose();
}
}
}
public int SkipInterval
{
get
{
return OrigEnum.SkipInterval;
}
}
public int MaxSkipLevels
{
get
{
return OrigEnum.MaxSkipLevels;
}
}
public void Dispose()
{
IOUtils.Close(OrigEnum, threadResources);
}
/// <summary>
/// Returns the number of term/value pairs in the set. </summary>
internal long Size()
{
return Size_Renamed;
}
private ThreadResources GetThreadResources
{
get
{
ThreadResources resources = threadResources.Get();
if (resources == null)
{
resources = new ThreadResources();
resources.TermEnum = Terms();
threadResources.Set(resources);
}
return resources;
}
}
private static readonly IComparer<BytesRef> LegacyComparator = BytesRef.UTF8SortedAsUTF16Comparer;
private int CompareAsUTF16(Term term1, Term term2)
{
if (term1.Field.Equals(term2.Field))
{
return LegacyComparator.Compare(term1.Bytes, term2.Bytes);
}
else
{
return term1.Field.CompareTo(term2.Field);
}
}
/// <summary>
/// Returns the TermInfo for a Term in the set, or null. </summary>
internal TermInfo Get(Term term)
{
return Get(term, false);
}
/// <summary>
/// Returns the TermInfo for a Term in the set, or null. </summary>
private TermInfo Get(Term term, bool mustSeekEnum)
{
if (Size_Renamed == 0)
{
return null;
}
EnsureIndexIsRead();
TermInfoAndOrd tiOrd = TermsCache.Get(new CloneableTerm(term));
ThreadResources resources = GetThreadResources;
if (!mustSeekEnum && tiOrd != null)
{
return tiOrd;
}
return SeekEnum(resources.TermEnum, term, tiOrd, true);
}
public void CacheCurrentTerm(SegmentTermEnum enumerator)
{
TermsCache.Put(new CloneableTerm(enumerator.Term()), new TermInfoAndOrd(enumerator.TermInfo_Renamed, enumerator.Position));
}
internal static Term DeepCopyOf(Term other)
{
return new Term(other.Field, BytesRef.DeepCopyOf(other.Bytes));
}
internal TermInfo SeekEnum(SegmentTermEnum enumerator, Term term, bool useCache)
{
if (useCache)
{
return SeekEnum(enumerator, term, TermsCache.Get(new CloneableTerm(DeepCopyOf(term))), useCache);
}
else
{
return SeekEnum(enumerator, term, null, useCache);
}
}
internal TermInfo SeekEnum(SegmentTermEnum enumerator, Term term, TermInfoAndOrd tiOrd, bool useCache)
{
if (Size_Renamed == 0)
{
return null;
}
// optimize sequential access: first try scanning cached enum w/o seeking
if (enumerator.Term() != null && ((enumerator.Prev() != null && CompareAsUTF16(term, enumerator.Prev()) > 0) || CompareAsUTF16(term, enumerator.Term()) >= 0)) // term is at or past current
{
int enumOffset = (int)(enumerator.Position / TotalIndexInterval) + 1;
if (IndexLength == enumOffset || Index.CompareTo(term, enumOffset) < 0) // but before end of block
{
// no need to seek
TermInfo ti;
int numScans = enumerator.ScanTo(term);
if (enumerator.Term() != null && CompareAsUTF16(term, enumerator.Term()) == 0)
{
ti = enumerator.TermInfo_Renamed;
if (numScans > 1)
{
// we only want to put this TermInfo into the cache if
// scanEnum skipped more than one dictionary entry.
// this prevents RangeQueries or WildcardQueries to
// wipe out the cache when they iterate over a large numbers
// of terms in order
if (tiOrd == null)
{
if (useCache)
{
TermsCache.Put(new CloneableTerm(DeepCopyOf(term)), new TermInfoAndOrd(ti, enumerator.Position));
}
}
else
{
Debug.Assert(SameTermInfo(ti, tiOrd, enumerator));
Debug.Assert(enumerator.Position == tiOrd.TermOrd);
}
}
}
else
{
ti = null;
}
return ti;
}
}
// random-access: must seek
int indexPos;
if (tiOrd != null)
{
indexPos = (int)(tiOrd.TermOrd / TotalIndexInterval);
}
else
{
// Must do binary search:
indexPos = Index.GetIndexOffset(term);
}
Index.SeekEnum(enumerator, indexPos);
enumerator.ScanTo(term);
TermInfo ti_;
if (enumerator.Term() != null && CompareAsUTF16(term, enumerator.Term()) == 0)
{
ti_ = enumerator.TermInfo_Renamed;
if (tiOrd == null)
{
if (useCache)
{
TermsCache.Put(new CloneableTerm(DeepCopyOf(term)), new TermInfoAndOrd(ti_, enumerator.Position));
}
}
else
{
Debug.Assert(SameTermInfo(ti_, tiOrd, enumerator));
Debug.Assert(enumerator.Position == tiOrd.TermOrd);
}
}
else
{
ti_ = null;
}
return ti_;
}
// called only from asserts
private bool SameTermInfo(TermInfo ti1, TermInfo ti2, SegmentTermEnum enumerator)
{
if (ti1.DocFreq != ti2.DocFreq)
{
return false;
}
if (ti1.FreqPointer != ti2.FreqPointer)
{
return false;
}
if (ti1.ProxPointer != ti2.ProxPointer)
{
return false;
}
// skipOffset is only valid when docFreq >= skipInterval:
if (ti1.DocFreq >= enumerator.SkipInterval && ti1.SkipOffset != ti2.SkipOffset)
{
return false;
}
return true;
}
private void EnsureIndexIsRead()
{
if (Index == null)
{
throw new InvalidOperationException("terms index was not loaded when this reader was created");
}
}
/// <summary>
/// Returns the position of a Term in the set or -1. </summary>
internal long GetPosition(Term term)
{
if (Size_Renamed == 0)
{
return -1;
}
EnsureIndexIsRead();
int indexOffset = Index.GetIndexOffset(term);
SegmentTermEnum enumerator = GetThreadResources.TermEnum;
Index.SeekEnum(enumerator, indexOffset);
while (CompareAsUTF16(term, enumerator.Term()) > 0 && enumerator.Next())
{
}
if (CompareAsUTF16(term, enumerator.Term()) == 0)
{
return enumerator.Position;
}
else
{
return -1;
}
}
/// <summary>
/// Returns an enumeration of all the Terms and TermInfos in the set. </summary>
public SegmentTermEnum Terms()
{
return (SegmentTermEnum)OrigEnum.Clone();
}
/// <summary>
/// Returns an enumeration of terms starting at or after the named term. </summary>
public SegmentTermEnum Terms(Term term)
{
Get(term, true);
return (SegmentTermEnum)GetThreadResources.TermEnum.Clone();
}
internal long RamBytesUsed()
{
return Index == null ? 0 : Index.RamBytesUsed();
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Scoring;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Ranking.Statistics
{
public class PerformanceBreakdownChart : Container
{
private readonly ScoreInfo score;
private readonly IBeatmap playableBeatmap;
private Drawable spinner;
private Drawable content;
private GridContainer chart;
private OsuSpriteText achievedPerformance;
private OsuSpriteText maximumPerformance;
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
[Resolved]
private ScorePerformanceCache performanceCache { get; set; }
[Resolved]
private BeatmapDifficultyCache difficultyCache { get; set; }
public PerformanceBreakdownChart(ScoreInfo score, IBeatmap playableBeatmap)
{
this.score = score;
this.playableBeatmap = playableBeatmap;
}
[BackgroundDependencyLoader]
private void load()
{
Children = new[]
{
spinner = new LoadingSpinner(true)
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre
},
content = new FillFlowContainer
{
Alpha = 0,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Width = 0.6f,
Origin = Anchor.TopCentre,
Anchor = Anchor.TopCentre,
Spacing = new Vector2(15, 15),
Children = new Drawable[]
{
new GridContainer
{
RelativeSizeAxes = Axes.X,
Width = 0.8f,
AutoSizeAxes = Axes.Y,
Origin = Anchor.TopCentre,
Anchor = Anchor.TopCentre,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize)
},
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.AutoSize)
},
Content = new[]
{
new Drawable[]
{
new OsuSpriteText
{
Origin = Anchor.CentreLeft,
Anchor = Anchor.CentreLeft,
Font = OsuFont.GetFont(weight: FontWeight.Regular, size: 18),
Text = "Achieved PP",
Colour = Color4Extensions.FromHex("#66FFCC")
},
achievedPerformance = new OsuSpriteText
{
Origin = Anchor.CentreRight,
Anchor = Anchor.CentreRight,
Font = OsuFont.GetFont(weight: FontWeight.SemiBold, size: 18),
Colour = Color4Extensions.FromHex("#66FFCC")
}
},
new Drawable[]
{
new OsuSpriteText
{
Origin = Anchor.CentreLeft,
Anchor = Anchor.CentreLeft,
Font = OsuFont.GetFont(weight: FontWeight.Regular, size: 18),
Text = "Maximum",
Colour = OsuColour.Gray(0.7f)
},
maximumPerformance = new OsuSpriteText
{
Origin = Anchor.CentreLeft,
Anchor = Anchor.CentreLeft,
Font = OsuFont.GetFont(weight: FontWeight.Regular, size: 18),
Colour = OsuColour.Gray(0.7f)
}
}
}
},
chart = new GridContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Origin = Anchor.TopCentre,
Anchor = Anchor.TopCentre,
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension(),
new Dimension(GridSizeMode.AutoSize)
}
}
}
}
};
spinner.Show();
new PerformanceBreakdownCalculator(playableBeatmap, difficultyCache, performanceCache)
.CalculateAsync(score, cancellationTokenSource.Token)
.ContinueWith(t => Schedule(() => setPerformanceValue(t.GetResultSafely())));
}
private void setPerformanceValue(PerformanceBreakdown breakdown)
{
spinner.Hide();
content.FadeIn(200);
var displayAttributes = breakdown.Performance.GetAttributesForDisplay();
var perfectDisplayAttributes = breakdown.PerfectPerformance.GetAttributesForDisplay();
setTotalValues(
displayAttributes.First(a => a.PropertyName == nameof(PerformanceAttributes.Total)),
perfectDisplayAttributes.First(a => a.PropertyName == nameof(PerformanceAttributes.Total))
);
var rowDimensions = new List<Dimension>();
var rows = new List<Drawable[]>();
foreach (PerformanceDisplayAttribute attr in displayAttributes)
{
if (attr.PropertyName == nameof(PerformanceAttributes.Total)) continue;
var row = createAttributeRow(attr, perfectDisplayAttributes.First(a => a.PropertyName == attr.PropertyName));
if (row != null)
{
rows.Add(row);
rowDimensions.Add(new Dimension(GridSizeMode.AutoSize));
}
}
chart.RowDimensions = rowDimensions.ToArray();
chart.Content = rows.ToArray();
}
private void setTotalValues(PerformanceDisplayAttribute attribute, PerformanceDisplayAttribute perfectAttribute)
{
achievedPerformance.Text = Math.Round(attribute.Value, MidpointRounding.AwayFromZero).ToLocalisableString();
maximumPerformance.Text = Math.Round(perfectAttribute.Value, MidpointRounding.AwayFromZero).ToLocalisableString();
}
[CanBeNull]
private Drawable[] createAttributeRow(PerformanceDisplayAttribute attribute, PerformanceDisplayAttribute perfectAttribute)
{
// Don't display the attribute if its maximum is 0
// For example, flashlight bonus would be zero if flashlight mod isn't on
if (Precision.AlmostEquals(perfectAttribute.Value, 0f))
return null;
float percentage = (float)(attribute.Value / perfectAttribute.Value);
return new Drawable[]
{
new OsuSpriteText
{
Origin = Anchor.CentreLeft,
Anchor = Anchor.CentreLeft,
Font = OsuFont.GetFont(weight: FontWeight.Regular),
Text = attribute.DisplayName,
Colour = Colour4.White
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Left = 10, Right = 10 },
Child = new Bar
{
RelativeSizeAxes = Axes.X,
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
CornerRadius = 2.5f,
Masking = true,
Height = 5,
BackgroundColour = Color4.White.Opacity(0.5f),
AccentColour = Color4Extensions.FromHex("#66FFCC"),
Length = percentage
}
},
new OsuSpriteText
{
Origin = Anchor.CentreRight,
Anchor = Anchor.CentreRight,
Font = OsuFont.GetFont(weight: FontWeight.SemiBold),
Text = percentage.ToLocalisableString("0%"),
Colour = Colour4.White
}
};
}
protected override void Dispose(bool isDisposing)
{
cancellationTokenSource?.Cancel();
base.Dispose(isDisposing);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Collections.Specialized
{
/// <devdoc>
/// <para>Represents a collection of strings.</para>
/// </devdoc>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class StringCollection : IList
{
private readonly ArrayList data = new ArrayList(); // Do not rename (binary serialization)
/// <devdoc>
/// <para>Represents the entry at the specified index of the <see cref='System.Collections.Specialized.StringCollection'/>.</para>
/// </devdoc>
public string this[int index]
{
get
{
return ((string)data[index]);
}
set
{
data[index] = value;
}
}
/// <devdoc>
/// <para>Gets the number of strings in the
/// <see cref='System.Collections.Specialized.StringCollection'/> .</para>
/// </devdoc>
public int Count
{
get
{
return data.Count;
}
}
bool IList.IsReadOnly
{
get
{
return false;
}
}
bool IList.IsFixedSize
{
get
{
return false;
}
}
/// <devdoc>
/// <para>Adds a string with the specified value to the
/// <see cref='System.Collections.Specialized.StringCollection'/> .</para>
/// </devdoc>
public int Add(string value)
{
return data.Add(value);
}
/// <devdoc>
/// <para>Copies the elements of a string array to the end of the <see cref='System.Collections.Specialized.StringCollection'/>.</para>
/// </devdoc>
public void AddRange(string[] value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
data.AddRange(value);
}
/// <devdoc>
/// <para>Removes all the strings from the
/// <see cref='System.Collections.Specialized.StringCollection'/> .</para>
/// </devdoc>
public void Clear()
{
data.Clear();
}
/// <devdoc>
/// <para>Gets a value indicating whether the
/// <see cref='System.Collections.Specialized.StringCollection'/> contains a string with the specified
/// value.</para>
/// </devdoc>
public bool Contains(string value)
{
return data.Contains(value);
}
/// <devdoc>
/// <para>Copies the <see cref='System.Collections.Specialized.StringCollection'/> values to a one-dimensional <see cref='System.Array'/> instance at the
/// specified index.</para>
/// </devdoc>
public void CopyTo(string[] array, int index)
{
data.CopyTo(array, index);
}
/// <devdoc>
/// <para>Returns an enumerator that can iterate through
/// the <see cref='System.Collections.Specialized.StringCollection'/> .</para>
/// </devdoc>
public StringEnumerator GetEnumerator()
{
return new StringEnumerator(this);
}
/// <devdoc>
/// <para>Returns the index of the first occurrence of a string in
/// the <see cref='System.Collections.Specialized.StringCollection'/> .</para>
/// </devdoc>
public int IndexOf(string value)
{
return data.IndexOf(value);
}
/// <devdoc>
/// <para>Inserts a string into the <see cref='System.Collections.Specialized.StringCollection'/> at the specified
/// index.</para>
/// </devdoc>
public void Insert(int index, string value)
{
data.Insert(index, value);
}
/// <devdoc>
/// <para>Gets a value indicating whether the <see cref='System.Collections.Specialized.StringCollection'/> is read-only.</para>
/// </devdoc>
public bool IsReadOnly
{
get
{
return false;
}
}
/// <devdoc>
/// <para>Gets a value indicating whether access to the
/// <see cref='System.Collections.Specialized.StringCollection'/>
/// is synchronized (thread-safe).</para>
/// </devdoc>
public bool IsSynchronized
{
get
{
return false;
}
}
/// <devdoc>
/// <para> Removes a specific string from the
/// <see cref='System.Collections.Specialized.StringCollection'/> .</para>
/// </devdoc>
public void Remove(string value)
{
data.Remove(value);
}
/// <devdoc>
/// <para>Removes the string at the specified index of the <see cref='System.Collections.Specialized.StringCollection'/>.</para>
/// </devdoc>
public void RemoveAt(int index)
{
data.RemoveAt(index);
}
/// <devdoc>
/// <para>Gets an object that can be used to synchronize access to the <see cref='System.Collections.Specialized.StringCollection'/>.</para>
/// </devdoc>
public object SyncRoot
{
get
{
return data.SyncRoot;
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = (string)value;
}
}
int IList.Add(object value)
{
return Add((string)value);
}
bool IList.Contains(object value)
{
return Contains((string)value);
}
int IList.IndexOf(object value)
{
return IndexOf((string)value);
}
void IList.Insert(int index, object value)
{
Insert(index, (string)value);
}
void IList.Remove(object value)
{
Remove((string)value);
}
void ICollection.CopyTo(Array array, int index)
{
data.CopyTo(array, index);
}
IEnumerator IEnumerable.GetEnumerator()
{
return data.GetEnumerator();
}
}
public class StringEnumerator
{
private System.Collections.IEnumerator _baseEnumerator;
private System.Collections.IEnumerable _temp;
internal StringEnumerator(StringCollection mappings)
{
_temp = (IEnumerable)(mappings);
_baseEnumerator = _temp.GetEnumerator();
}
public string Current
{
get
{
return (string)(_baseEnumerator.Current);
}
}
public bool MoveNext()
{
return _baseEnumerator.MoveNext();
}
public void Reset()
{
_baseEnumerator.Reset();
}
}
}
| |
// 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.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class BrotliEncoderTests : CompressionTestBase
{
protected override string CompressedTestFile(string uncompressedPath) => Path.Combine("BrotliTestData", Path.GetFileName(uncompressedPath) + ".br");
[Fact]
public void InvalidQuality()
{
Assert.Throws<ArgumentOutOfRangeException>("quality", () => new BrotliEncoder(-1, 11));
Assert.Throws<ArgumentOutOfRangeException>("quality", () => new BrotliEncoder(12, 11));
Assert.Throws<ArgumentOutOfRangeException>("quality", () => BrotliEncoder.TryCompress(new ReadOnlySpan<byte>(), new Span<byte>(), out int bytesWritten, -1, 13));
Assert.Throws<ArgumentOutOfRangeException>("quality", () => BrotliEncoder.TryCompress(new ReadOnlySpan<byte>(), new Span<byte>(), out int bytesWritten, 12, 13));
}
[Fact]
public void InvalidWindow()
{
Assert.Throws<ArgumentOutOfRangeException>("window", () => new BrotliEncoder(10, -1));
Assert.Throws<ArgumentOutOfRangeException>("window", () => new BrotliEncoder(10, 9));
Assert.Throws<ArgumentOutOfRangeException>("window", () => new BrotliEncoder(10, 25));
Assert.Throws<ArgumentOutOfRangeException>("window", () => BrotliEncoder.TryCompress(new ReadOnlySpan<byte>(), new Span<byte>(), out int bytesWritten, 6, -1));
Assert.Throws<ArgumentOutOfRangeException>("window", () => BrotliEncoder.TryCompress(new ReadOnlySpan<byte>(), new Span<byte>(), out int bytesWritten, 6, 9));
Assert.Throws<ArgumentOutOfRangeException>("window", () => BrotliEncoder.TryCompress(new ReadOnlySpan<byte>(), new Span<byte>(), out int bytesWritten, 6, 25));
}
[Fact]
public void GetMaxCompressedSize_Basic()
{
Assert.Throws<ArgumentOutOfRangeException>("inputSize", () => BrotliEncoder.GetMaxCompressedLength(-1));
Assert.Throws<ArgumentOutOfRangeException>("inputSize", () => BrotliEncoder.GetMaxCompressedLength(2147483133));
Assert.InRange(BrotliEncoder.GetMaxCompressedLength(2147483132), 0, int.MaxValue);
Assert.Equal(1, BrotliEncoder.GetMaxCompressedLength(0));
}
[Fact]
public void GetMaxCompressedSize()
{
string uncompressedFile = UncompressedTestFile();
string compressedFile = CompressedTestFile(uncompressedFile);
int maxCompressedSize = BrotliEncoder.GetMaxCompressedLength((int)new FileInfo(uncompressedFile).Length);
int actualCompressedSize = (int)new FileInfo(compressedFile).Length;
Assert.True(maxCompressedSize >= actualCompressedSize, $"MaxCompressedSize: {maxCompressedSize}, ActualCompressedSize: {actualCompressedSize}");
}
/// <summary>
/// Test to ensure that when given an empty Destination span, the decoder will consume no input and write no output.
/// </summary>
[Fact]
public void Decompress_WithEmptyDestination()
{
string testFile = UncompressedTestFile();
byte[] sourceBytes = File.ReadAllBytes(CompressedTestFile(testFile));
byte[] destinationBytes = new byte[0];
ReadOnlySpan<byte> source = new ReadOnlySpan<byte>(sourceBytes);
Span<byte> destination = new Span<byte>(destinationBytes);
Assert.False(BrotliDecoder.TryDecompress(source, destination, out int bytesWritten), "TryDecompress completed successfully but should have failed due to too short of a destination array");
Assert.Equal(0, bytesWritten);
BrotliDecoder decoder = default;
var result = decoder.Decompress(source, destination, out int bytesConsumed, out bytesWritten);
Assert.Equal(0, bytesWritten);
Assert.Equal(0, bytesConsumed);
Assert.Equal(OperationStatus.DestinationTooSmall, result);
}
/// <summary>
/// Test to ensure that when given an empty source span, the decoder will consume no input and write no output
/// </summary>
[Fact]
public void Decompress_WithEmptySource()
{
string testFile = UncompressedTestFile();
byte[] sourceBytes = new byte[0];
byte[] destinationBytes = new byte[100000];
ReadOnlySpan<byte> source = new ReadOnlySpan<byte>(sourceBytes);
Span<byte> destination = new Span<byte>(destinationBytes);
Assert.False(BrotliDecoder.TryDecompress(source, destination, out int bytesWritten), "TryDecompress completed successfully but should have failed due to too short of a source array");
Assert.Equal(0, bytesWritten);
BrotliDecoder decoder = default;
var result = decoder.Decompress(source, destination, out int bytesConsumed, out bytesWritten);
Assert.Equal(0, bytesWritten);
Assert.Equal(0, bytesConsumed);
Assert.Equal(OperationStatus.NeedMoreData, result);
}
/// <summary>
/// Test to ensure that when given an empty Destination span, the encoder consume no input and write no output
/// </summary>
[Fact]
public void Compress_WithEmptyDestination()
{
string testFile = UncompressedTestFile();
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = File.ReadAllBytes(CompressedTestFile(testFile));
byte[] empty = new byte[0];
ReadOnlySpan<byte> source = new ReadOnlySpan<byte>(correctUncompressedBytes);
Span<byte> destination = new Span<byte>(empty);
Assert.False(BrotliEncoder.TryCompress(source, destination, out int bytesWritten), "TryCompress completed successfully but should have failed due to too short of a destination array");
Assert.Equal(0, bytesWritten);
BrotliEncoder encoder = default;
var result = encoder.Compress(source, destination, out int bytesConsumed, out bytesWritten, false);
Assert.Equal(0, bytesWritten);
Assert.Equal(0, bytesConsumed);
Assert.Equal(OperationStatus.DestinationTooSmall, result);
result = encoder.Compress(source, destination, out bytesConsumed, out bytesWritten, isFinalBlock: true);
Assert.Equal(0, bytesWritten);
Assert.Equal(0, bytesConsumed);
Assert.Equal(OperationStatus.DestinationTooSmall, result);
}
/// <summary>
/// Test to ensure that when given an empty source span, the decoder will consume no input and write no output (until the finishing block)
/// </summary>
[Fact]
public void Compress_WithEmptySource()
{
string testFile = UncompressedTestFile();
byte[] sourceBytes = new byte[0];
byte[] destinationBytes = new byte[100000];
ReadOnlySpan<byte> source = new ReadOnlySpan<byte>(sourceBytes);
Span<byte> destination = new Span<byte>(destinationBytes);
Assert.True(BrotliEncoder.TryCompress(source, destination, out int bytesWritten));
// The only byte written should be the Brotli end of stream byte which varies based on the window/quality
Assert.Equal(1, bytesWritten);
BrotliEncoder encoder = default;
var result = encoder.Compress(source, destination, out int bytesConsumed, out bytesWritten, false);
Assert.Equal(0, bytesWritten);
Assert.Equal(0, bytesConsumed);
Assert.Equal(OperationStatus.Done, result);
result = encoder.Compress(source, destination, out bytesConsumed, out bytesWritten, isFinalBlock: true);
Assert.Equal(1, bytesWritten);
Assert.Equal(0, bytesConsumed);
Assert.Equal(OperationStatus.Done, result);
}
/// <summary>
/// Test that the decoder can handle partial chunks of flushed encoded data sent from the BrotliEncoder
/// </summary>
[Fact]
public void RoundTrip_Chunks()
{
int chunkSize = 100;
int totalSize = 20000;
BrotliEncoder encoder = default;
BrotliDecoder decoder = default;
for (int i = 0; i < totalSize; i += chunkSize)
{
byte[] uncompressed = new byte[chunkSize];
new Random().NextBytes(uncompressed);
byte[] compressed = new byte[BrotliEncoder.GetMaxCompressedLength(chunkSize)];
byte[] decompressed = new byte[chunkSize];
var uncompressedSpan = new ReadOnlySpan<byte>(uncompressed);
var compressedSpan = new Span<byte>(compressed);
var decompressedSpan = new Span<byte>(decompressed);
int totalWrittenThisIteration = 0;
var compress = encoder.Compress(uncompressedSpan, compressedSpan, out int bytesConsumed, out int bytesWritten, isFinalBlock: false);
totalWrittenThisIteration += bytesWritten;
compress = encoder.Flush(compressedSpan.Slice(bytesWritten), out bytesWritten);
totalWrittenThisIteration += bytesWritten;
var res = decoder.Decompress(compressedSpan.Slice(0, totalWrittenThisIteration), decompressedSpan, out int decompressbytesConsumed, out int decompressbytesWritten);
Assert.Equal(totalWrittenThisIteration, decompressbytesConsumed);
Assert.Equal(bytesConsumed, decompressbytesWritten);
Assert.Equal<byte>(uncompressed, decompressedSpan.ToArray());
}
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void ReadFully(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = File.ReadAllBytes(CompressedTestFile(testFile));
byte[] actualUncompressedBytes = new byte[correctUncompressedBytes.Length + 10000];
ReadOnlySpan<byte> source = new ReadOnlySpan<byte>(compressedBytes);
Span<byte> destination = new Span<byte>(actualUncompressedBytes);
Assert.True(BrotliDecoder.TryDecompress(source, destination, out int bytesWritten), "TryDecompress did not complete successfully");
Assert.Equal(correctUncompressedBytes.Length, bytesWritten);
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes.AsSpan(0, correctUncompressedBytes.Length).ToArray());
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void ReadWithState(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = File.ReadAllBytes(CompressedTestFile(testFile));
byte[] actualUncompressedBytes = new byte[correctUncompressedBytes.Length];
Decompress_WithState(compressedBytes, actualUncompressedBytes);
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes);
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void ReadWithoutState(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = File.ReadAllBytes(CompressedTestFile(testFile));
byte[] actualUncompressedBytes = new byte[correctUncompressedBytes.Length];
Decompress_WithoutState(compressedBytes, actualUncompressedBytes);
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes);
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void WriteFully(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = new byte[BrotliEncoder.GetMaxCompressedLength(correctUncompressedBytes.Length)];
byte[] actualUncompressedBytes = new byte[BrotliEncoder.GetMaxCompressedLength(correctUncompressedBytes.Length)];
Span<byte> destination = new Span<byte>(compressedBytes);
Assert.True(BrotliEncoder.TryCompress(correctUncompressedBytes, destination, out int bytesWritten));
Assert.True(BrotliDecoder.TryDecompress(destination, actualUncompressedBytes, out bytesWritten));
Assert.Equal(correctUncompressedBytes.Length, bytesWritten);
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes.AsSpan(0, correctUncompressedBytes.Length).ToArray());
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void WriteWithState(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = new byte[BrotliEncoder.GetMaxCompressedLength(correctUncompressedBytes.Length)];
byte[] actualUncompressedBytes = new byte[correctUncompressedBytes.Length];
Compress_WithState(correctUncompressedBytes, compressedBytes);
Decompress_WithState(compressedBytes, actualUncompressedBytes);
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes);
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void WriteWithoutState(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = new byte[BrotliEncoder.GetMaxCompressedLength(correctUncompressedBytes.Length)];
byte[] actualUncompressedBytes = new byte[correctUncompressedBytes.Length];
Compress_WithoutState(correctUncompressedBytes, compressedBytes);
Decompress_WithoutState(compressedBytes, actualUncompressedBytes);
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes);
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void WriteStream(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = Compress_Stream(correctUncompressedBytes, CompressionLevel.Optimal).ToArray();
byte[] actualUncompressedBytes = Decompress_Stream(compressedBytes).ToArray();
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes);
}
[OuterLoop("Full set of tests takes seconds to run")]
[Theory]
[InlineData(1, 0x400001, false)]
[InlineData(1, 0x400001, true)]
[InlineData(4, 0x800000, false)]
[InlineData(4, 0x800000, true)]
[InlineData(53, 12345, false)]
[InlineData(53, 12345, true)]
public static async Task Roundtrip_VaryingSizeReadsAndLengths_Success(int readSize, int totalLength, bool useAsync)
{
byte[] correctUncompressedBytes = Enumerable.Range(0, totalLength).Select(i => (byte)i).ToArray();
byte[] compressedBytes = Compress_Stream(correctUncompressedBytes, CompressionLevel.Fastest).ToArray();
byte[] actualBytes = new byte[correctUncompressedBytes.Length];
using (var s = new BrotliStream(new MemoryStream(compressedBytes), CompressionMode.Decompress))
{
int totalRead = 0;
while (totalRead < actualBytes.Length)
{
int numRead = useAsync ?
await s.ReadAsync(actualBytes, totalRead, Math.Min(readSize, actualBytes.Length - totalRead)) :
s.Read(actualBytes, totalRead, Math.Min(readSize, actualBytes.Length - totalRead));
totalRead += numRead;
}
Assert.Equal<byte>(correctUncompressedBytes, actualBytes);
}
}
[Theory]
[InlineData(1000, CompressionLevel.Fastest)]
[InlineData(1000, CompressionLevel.Optimal)]
[InlineData(1000, CompressionLevel.NoCompression)]
public static void Roundtrip_WriteByte_ReadByte_Success(int totalLength, CompressionLevel level)
{
byte[] correctUncompressedBytes = Enumerable.Range(0, totalLength).Select(i => (byte)i).ToArray();
byte[] compressedBytes;
using (var ms = new MemoryStream())
{
var bs = new BrotliStream(ms, level);
foreach (byte b in correctUncompressedBytes)
{
bs.WriteByte(b);
}
bs.Dispose();
compressedBytes = ms.ToArray();
}
byte[] decompressedBytes = new byte[correctUncompressedBytes.Length];
using (var ms = new MemoryStream(compressedBytes))
using (var bs = new BrotliStream(ms, CompressionMode.Decompress))
{
for (int i = 0; i < decompressedBytes.Length; i++)
{
int b = bs.ReadByte();
Assert.InRange(b, 0, 255);
decompressedBytes[i] = (byte)b;
}
Assert.Equal(-1, bs.ReadByte());
Assert.Equal(-1, bs.ReadByte());
}
Assert.Equal<byte>(correctUncompressedBytes, decompressedBytes);
}
private static void Compress_WithState(ReadOnlySpan<byte> input, Span<byte> output)
{
BrotliEncoder encoder = default;
while (!input.IsEmpty && !output.IsEmpty)
{
encoder.Compress(input, output, out int bytesConsumed, out int written, isFinalBlock: false);
input = input.Slice(bytesConsumed);
output = output.Slice(written);
}
encoder.Compress(ReadOnlySpan<byte>.Empty, output, out int bytesConsumed2, out int bytesWritten, isFinalBlock: true);
}
private static void Decompress_WithState(ReadOnlySpan<byte> input, Span<byte> output)
{
BrotliDecoder decoder = default;
while (!input.IsEmpty && !output.IsEmpty)
{
decoder.Decompress(input, output, out int bytesConsumed, out int written);
input = input.Slice(bytesConsumed);
output = output.Slice(written);
}
}
private static void Compress_WithoutState(ReadOnlySpan<byte> input, Span<byte> output)
{
BrotliEncoder.TryCompress(input, output, out int bytesWritten);
}
private static void Decompress_WithoutState(ReadOnlySpan<byte> input, Span<byte> output)
{
BrotliDecoder.TryDecompress(input, output, out int bytesWritten);
}
private static MemoryStream Compress_Stream(ReadOnlySpan<byte> input, CompressionLevel compressionLevel)
{
using (var inputStream = new MemoryStream(input.ToArray()))
{
var outputStream = new MemoryStream();
var compressor = new BrotliStream(outputStream, compressionLevel, true);
inputStream.CopyTo(compressor);
compressor.Dispose();
return outputStream;
}
}
private static MemoryStream Decompress_Stream(ReadOnlySpan<byte> input)
{
using (var inputStream = new MemoryStream(input.ToArray()))
{
var outputStream = new MemoryStream();
var decompressor = new BrotliStream(inputStream, CompressionMode.Decompress, true);
decompressor.CopyTo(outputStream);
decompressor.Dispose();
return outputStream;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal sealed class VisualStudioDocumentNavigationService : ForegroundThreadAffinitizedObject, IDocumentNavigationService
{
private readonly IServiceProvider _serviceProvider;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
public VisualStudioDocumentNavigationService(
SVsServiceProvider serviceProvider,
IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
{
_serviceProvider = serviceProvider;
_editorAdaptersFactoryService = editorAdaptersFactoryService;
}
public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan)
{
// Navigation should not change the context of linked files and Shared Projects.
documentId = workspace.GetDocumentIdInCurrentContext(documentId);
if (!IsSecondaryBuffer(workspace, documentId))
{
return true;
}
var document = workspace.CurrentSolution.GetDocument(documentId);
var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var vsTextSpan = text.GetVsTextSpanForSpan(textSpan);
return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan);
}
public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset)
{
// Navigation should not change the context of linked files and Shared Projects.
documentId = workspace.GetDocumentIdInCurrentContext(documentId);
if (!IsSecondaryBuffer(workspace, documentId))
{
return true;
}
var document = workspace.CurrentSolution.GetDocument(documentId);
var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset);
return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan);
}
public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0)
{
// Navigation should not change the context of linked files and Shared Projects.
documentId = workspace.GetDocumentIdInCurrentContext(documentId);
if (!IsSecondaryBuffer(workspace, documentId))
{
return true;
}
var document = workspace.CurrentSolution.GetDocument(documentId);
var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var vsTextSpan = text.GetVsTextSpanForPosition(position, virtualSpace);
return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan);
}
public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options)
{
// Navigation should not change the context of linked files and Shared Projects.
documentId = workspace.GetDocumentIdInCurrentContext(documentId);
if (!IsForeground())
{
throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread);
}
var document = OpenDocument(workspace, documentId, options);
if (document == null)
{
return false;
}
var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var textBuffer = text.Container.GetTextBuffer();
var vsTextSpan = text.GetVsTextSpanForSpan(textSpan);
if (IsSecondaryBuffer(workspace, documentId) &&
!vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan))
{
return false;
}
return NavigateTo(textBuffer, vsTextSpan);
}
public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options)
{
// Navigation should not change the context of linked files and Shared Projects.
documentId = workspace.GetDocumentIdInCurrentContext(documentId);
if (!IsForeground())
{
throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread);
}
var document = OpenDocument(workspace, documentId, options);
if (document == null)
{
return false;
}
var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var textBuffer = text.Container.GetTextBuffer();
var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset);
if (IsSecondaryBuffer(workspace, documentId) &&
!vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan))
{
return false;
}
return NavigateTo(textBuffer, vsTextSpan);
}
public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options)
{
// Navigation should not change the context of linked files and Shared Projects.
documentId = workspace.GetDocumentIdInCurrentContext(documentId);
if (!IsForeground())
{
throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread);
}
var document = OpenDocument(workspace, documentId, options);
if (document == null)
{
return false;
}
var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var textBuffer = text.Container.GetTextBuffer();
var vsTextSpan = text.GetVsTextSpanForPosition(position, virtualSpace);
if (IsSecondaryBuffer(workspace, documentId) &&
!vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan))
{
return false;
}
return NavigateTo(textBuffer, vsTextSpan);
}
private static Document OpenDocument(Workspace workspace, DocumentId documentId, OptionSet options)
{
options = options ?? workspace.Options;
// Always open the document again, even if the document is already open in the
// workspace. If a document is already open in a preview tab and it is opened again
// in a permanent tab, this allows the document to transition to the new state.
if (workspace.CanOpenDocuments)
{
if (options.GetOption(NavigationOptions.PreferProvisionalTab))
{
using (NewDocumentStateScope ndss = new NewDocumentStateScope(__VSNEWDOCUMENTSTATE.NDS_Provisional, VSConstants.NewDocumentStateReason.Navigation))
{
workspace.OpenDocument(documentId);
}
}
else
{
workspace.OpenDocument(documentId);
}
}
if (!workspace.IsDocumentOpen(documentId))
{
return null;
}
return workspace.CurrentSolution.GetDocument(documentId);
}
private bool NavigateTo(ITextBuffer textBuffer, VsTextSpan vsTextSpan)
{
using (Logger.LogBlock(FunctionId.NavigationService_VSDocumentNavigationService_NavigateTo, CancellationToken.None))
{
var vsTextBuffer = _editorAdaptersFactoryService.GetBufferAdapter(textBuffer);
if (vsTextBuffer == null)
{
Debug.Fail("Could not get IVsTextBuffer for document!");
return false;
}
var textManager = (IVsTextManager2)_serviceProvider.GetService(typeof(SVsTextManager));
if (textManager == null)
{
Debug.Fail("Could not get IVsTextManager service!");
return false;
}
return ErrorHandler.Succeeded(
textManager.NavigateToLineAndColumn2(
vsTextBuffer, VSConstants.LOGVIEWID.TextView_guid, vsTextSpan.iStartLine, vsTextSpan.iStartIndex, vsTextSpan.iEndLine, vsTextSpan.iEndIndex, (uint)_VIEWFRAMETYPE.vftCodeWindow));
}
}
private bool IsSecondaryBuffer(Workspace workspace, DocumentId documentId)
{
var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl;
if (visualStudioWorkspace == null)
{
return false;
}
var containedDocument = visualStudioWorkspace.GetHostDocument(documentId) as ContainedDocument;
if (containedDocument == null)
{
return false;
}
return true;
}
private bool CanMapFromSecondaryBufferToPrimaryBuffer(Workspace workspace, DocumentId documentId, VsTextSpan spanInSecondaryBuffer)
{
return spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out var spanInPrimaryBuffer);
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="MeshGeometry3D.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: 3D mesh implementation.
//
// See spec at http://avalon/medialayer/Specifications/Avalon3D%20API%20Spec.mht
//
// History:
// 06/10/2004 : [....] - Created from Mesh3D.cs (deprecated)
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.Media3D;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Diagnostics;
using System.Windows.Markup;
using System.Windows.Media.Composition;
namespace System.Windows.Media.Media3D
{
/// <summary>
/// MeshGeometry3D a straightforward triangle primitive.
/// </summary>
public sealed partial class MeshGeometry3D : Geometry3D
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Default Constructor.
/// </summary>
public MeshGeometry3D() {}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Get bounds for this MeshGeometry3D.
/// </summary>
public override Rect3D Bounds
{
get
{
ReadPreamble();
if (_cachedBounds.IsEmpty)
{
UpdateCachedBounds();
}
Debug_VerifyCachedBounds();
return _cachedBounds;
}
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Overriden to clear our bounds cache.
/// </summary>
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
if (e.IsAValueChange || e.IsASubPropertyChange)
{
DependencyProperty dp = e.Property;
// We invalidate the cache here rather than in the InvalidateResourcePositions method
// because the later is not invoked in the event that the Point3DCollection is swapped
// out from underneath us. (In that case, the resource invalidation takes a different
// code path.)
if (dp == MeshGeometry3D.PositionsProperty)
{
SetCachedBoundsDirty();
}
}
base.OnPropertyChanged(e);
}
#endregion Protected Methods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
internal Rect GetTextureCoordinateBounds()
{
PointCollection tx = TextureCoordinates;
int count = (tx == null) ? 0 : tx.Count;
if (count > 0)
{
Point ptMin = tx[0];
Point ptMax = tx[0];
for (int i = 1; i < count; i++)
{
Point txPt = tx.Internal_GetItem(i);
double txx = txPt.X;
if (ptMin.X > txx)
{
ptMin.X = txx;
}
else if (ptMax.X < txx)
{
ptMax.X = txx;
}
double txy = txPt.Y;
if (ptMin.Y > txy)
{
ptMin.Y = txy;
}
else if (ptMax.Y < txy)
{
ptMax.Y = txy;
}
}
return new Rect(ptMin, ptMax);
}
else
{
return Rect.Empty;
}
}
//
// Hits the ray against the mesh
//
internal override void RayHitTestCore(
RayHitTestParameters rayParams,
FaceType hitTestableFaces)
{
Debug.Assert(hitTestableFaces != FaceType.None,
"Caller should make sure we're trying to hit something");
Point3DCollection positions = Positions;
if (positions == null)
{
return;
}
Point3D origin;
Vector3D direction;
rayParams.GetLocalLine(out origin, out direction);
Int32Collection indices = TriangleIndices;
// In the line case, we want to hit test all faces because we don't
// have a direction. This may differ from what faces we want to
// accept.
FaceType facesToHit;
if (rayParams.IsRay)
{
facesToHit = hitTestableFaces;
}
else
{
facesToHit = FaceType.Front | FaceType.Back;
}
//
// This code duplication is unfortunate but necessary. Breaking it down into methods
// further significantly impacts performance. About 5% improvement could be made
// by unrolling this code below even more.
//
// If futher perf investigation is done with this code, be sure to test NGEN assemblies only
// as JIT produces different, faster code than NGEN.
//
if (indices == null || indices.Count == 0)
{
FrugalStructList<Point3D> ps = positions._collection;
int count = ps.Count - (ps.Count % 3);
for (int i = count - 1; i >= 2; i -= 3)
{
int i0 = i - 2;
int i1 = i - 1;
int i2 = i;
Point3D v0 = ps[i0];
Point3D v1 = ps[i1];
Point3D v2 = ps[i2];
double hitTime;
Point barycentric;
// The line hit test is equivalent to a double sided
// triangle hit because it doesn't cull triangles based
// on winding
if (LineUtil.ComputeLineTriangleIntersection(
facesToHit,
ref origin,
ref direction,
ref v0,
ref v1,
ref v2,
out barycentric,
out hitTime
)
)
{
if (rayParams.IsRay)
{
ValidateRayHit(
rayParams,
ref origin,
ref direction,
hitTime,
i0,
i1,
i2,
ref barycentric
);
}
else
{
ValidateLineHit(
rayParams,
hitTestableFaces,
i0,
i1,
i2,
ref v0,
ref v1,
ref v2,
ref barycentric
);
}
}
}
}
else // indexed mesh
{
FrugalStructList<Point3D> ps = positions._collection;
FrugalStructList<int> idcs = indices._collection;
int count = idcs.Count;
int limit = ps.Count;
for (int i = 2; i < count; i += 3)
{
int i0 = idcs[i - 2];
int i1 = idcs[i - 1];
int i2 = idcs[i];
// Quit if we encounter an index out of range.
// This is okay because the triangles we ignore are not rendered.
// (see: CMilMeshGeometry3DDuce::Realize)
if ((0 > i0 || i0 >= limit) ||
(0 > i1 || i1 >= limit) ||
(0 > i2 || i2 >= limit))
{
break;
}
Point3D v0 = ps[i0];
Point3D v1 = ps[i1];
Point3D v2 = ps[i2];
double hitTime;
Point barycentric;
if (LineUtil.ComputeLineTriangleIntersection(
facesToHit,
ref origin,
ref direction,
ref v0,
ref v1,
ref v2,
out barycentric,
out hitTime
)
)
{
if (rayParams.IsRay)
{
ValidateRayHit(
rayParams,
ref origin,
ref direction,
hitTime,
i0,
i1,
i2,
ref barycentric
);
}
else
{
ValidateLineHit(
rayParams,
hitTestableFaces,
i0,
i1,
i2,
ref v0,
ref v1,
ref v2,
ref barycentric
);
}
}
}
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
//
// Processes a ray-triangle intersection to see if it's a valid hit. Unnecessary faces
// have already been culled by the ray-triange intersection routines.
//
// Shares some code with ValidateLineHit
//
private void ValidateRayHit(
RayHitTestParameters rayParams,
ref Point3D origin,
ref Vector3D direction,
double hitTime,
int i0,
int i1,
int i2,
ref Point barycentric
)
{
if (hitTime > 0)
{
Matrix3D worldTransformMatrix = rayParams.HasWorldTransformMatrix ? rayParams.WorldTransformMatrix : Matrix3D.Identity;
Point3D pointHit = origin + hitTime * direction;
Point3D worldPointHit = pointHit;
worldTransformMatrix.MultiplyPoint(ref worldPointHit);
// If we have a HitTestProjectionMatrix than this hit test originated
// at a Viewport3DVisual.
if (rayParams.HasHitTestProjectionMatrix)
{
// To test if we are in front of the far clipping plane what we
// do conceptually is project our hit point in world space into
// homogenous space and verify that it is on the correct side of
// the Z=1 plane.
//
// To save some cycles we only bother computing Z and W of the
// projected point and use a simple Z/W > 1 test to see if we
// are past the far plane.
//
// NOTE: HitTestProjectionMatrix is not just the camera matrices.
// It has an additional translation to move the ray to the
// origin. This extra translation does not effect this test.
Matrix3D m = rayParams.HitTestProjectionMatrix;
// We directly substitute 1 for p.W below:
double pz = worldPointHit.X * m.M13 + worldPointHit.Y * m.M23 + worldPointHit.Z * m.M33 + m.OffsetZ;
double pw = worldPointHit.X * m.M14 + worldPointHit.Y * m.M24 + worldPointHit.Z * m.M34 + m.M44;
// Early exit if pz/pw > 1. The negated logic is to reject NaNs.
if (!(pz / pw <= 1))
{
return;
}
Debug.Assert(!double.IsInfinity(pz / pw) && !double.IsNaN(pz / pw),
"Expected near/far tests to cull -Inf/+Inf and NaN.");
}
double dist = (worldPointHit - rayParams.Origin).Length;
Debug.Assert(dist > 0, "Distance is negative: " + dist);
if (rayParams.HasModelTransformMatrix)
{
rayParams.ModelTransformMatrix.MultiplyPoint(ref pointHit);
}
rayParams.ReportResult(this, pointHit, dist, i0, i1, i2, barycentric);
}
}
//
// Processes a ray-line intersection to see if it's a valid hit.
//
// Shares some code with ValidateRayHit
//
private void ValidateLineHit(
RayHitTestParameters rayParams,
FaceType facesToHit,
int i0,
int i1,
int i2,
ref Point3D v0,
ref Point3D v1,
ref Point3D v2,
ref Point barycentric
)
{
Matrix3D worldTransformMatrix = rayParams.HasWorldTransformMatrix ? rayParams.WorldTransformMatrix : Matrix3D.Identity;
// OK, we have an intersection with the LINE but that could be wrong on three
// accounts:
// 1. We could have hit the line on the wrong side of the ray's origin.
// 2. We may need to cull the intersection if it's beyond the far clipping
// plane (only if the hit test originated from a Viewport3DVisual.)
// 3. We could have hit a back-facing triangle
// We will transform the hit point back into world space to check these
// things & compute the correct distance from the origin to the hit point.
// Hit point in model space
Point3D pointHit = M3DUtil.Interpolate(ref v0, ref v1, ref v2, ref barycentric);
Point3D worldPointHit = pointHit;
worldTransformMatrix.MultiplyPoint(ref worldPointHit);
// Vector from origin to hit point
Vector3D hitVector = worldPointHit - rayParams.Origin;
Vector3D originalDirection = rayParams.Direction;
double rayDistanceUnnormalized = Vector3D.DotProduct(originalDirection, hitVector);
if (rayDistanceUnnormalized > 0)
{
// If we have a HitTestProjectionMatrix than this hit test originated
// at a Viewport3DVisual.
if (rayParams.HasHitTestProjectionMatrix)
{
// To test if we are in front of the far clipping plane what we
// do conceptually is project our hit point in world space into
// homogenous space and verify that it is on the correct side of
// the Z=1 plane.
//
// To save some cycles we only bother computing Z and W of the
// projected point and use a simple Z/W > 1 test to see if we
// are past the far plane.
//
// NOTE: HitTestProjectionMatrix is not just the camera matrices.
// It has an additional translation to move the ray to the
// origin. This extra translation does not effect this test.
Matrix3D m = rayParams.HitTestProjectionMatrix;
// We directly substitute 1 for p.W below:
double pz = worldPointHit.X * m.M13 + worldPointHit.Y * m.M23 + worldPointHit.Z * m.M33 + m.OffsetZ;
double pw = worldPointHit.X * m.M14 + worldPointHit.Y * m.M24 + worldPointHit.Z * m.M34 + m.M44;
// Early exit if pz/pw > 1. The negated logic is to reject NaNs.
if (!(pz / pw <= 1))
{
return;
}
Debug.Assert(!double.IsInfinity(pz / pw) && !double.IsNaN(pz / pw),
"Expected near/far tests to cull -Inf/+Inf and NaN.");
}
Point3D a = v0, b = v1, c = v2;
worldTransformMatrix.MultiplyPoint(ref a);
worldTransformMatrix.MultiplyPoint(ref b);
worldTransformMatrix.MultiplyPoint(ref c);
Vector3D normal = Vector3D.CrossProduct(b - a, c - a);
double cullSign = -Vector3D.DotProduct(normal, hitVector);
double det = worldTransformMatrix.Determinant;
bool frontFace = (cullSign > 0) == (det >= 0);
if (((facesToHit & FaceType.Front) == FaceType.Front && frontFace) || ((facesToHit & FaceType.Back) == FaceType.Back && !frontFace))
{
double dist = hitVector.Length;
if (rayParams.HasModelTransformMatrix)
{
rayParams.ModelTransformMatrix.MultiplyPoint(ref pointHit);
}
rayParams.ReportResult(this, pointHit, dist, i0, i1, i2, barycentric);
}
}
}
// Updates the _cachedBounds member to the current bounds of the mesh.
// This method must be called before accessing _cachedBounds if
// _cachedBounds.IsEmpty is true. Otherwise the _cachedBounds are
// current and do not need to be recomputed. See also Debug_VerifyCachedBounds.
private void UpdateCachedBounds()
{
Debug.Assert(_cachedBounds.IsEmpty,
"PERF: Caller should verify that bounds are dirty before recomputing.");
_cachedBounds = M3DUtil.ComputeAxisAlignedBoundingBox(Positions);
}
// Sets _cachedBounds to Rect3D.Empty (indicating that the bounds are no
// longer valid.)
private void SetCachedBoundsDirty()
{
_cachedBounds = Rect3D.Empty;
}
#endregion Private Methods
//------------------------------------------------------
//
// DEBUG
//
//------------------------------------------------------
#region DEBUG
// Always call this method before accessing _cachedBounds. On
[Conditional("DEBUG")]
private void Debug_VerifyCachedBounds()
{
Rect3D actualBounds = M3DUtil.ComputeAxisAlignedBoundingBox(Positions);
// The funny boolean logic below avoids asserts when the cached
// bounds contain NaNs. (NaN != NaN)
bool areEqual =
!(_cachedBounds.X < actualBounds.X || _cachedBounds.X > actualBounds.X) &&
!(_cachedBounds.Y < actualBounds.Y || _cachedBounds.Y > actualBounds.Y) &&
!(_cachedBounds.Z < actualBounds.Z || _cachedBounds.Z > actualBounds.Z) &&
!(_cachedBounds.SizeX < actualBounds.SizeX || _cachedBounds.SizeX > actualBounds.SizeX) &&
!(_cachedBounds.SizeY < actualBounds.SizeY || _cachedBounds.SizeY > actualBounds.SizeY) &&
!(_cachedBounds.SizeZ < actualBounds.SizeZ || _cachedBounds.SizeZ > actualBounds.SizeZ);
if (!areEqual)
{
if (_cachedBounds == Rect3D.Empty)
{
Debug.Fail("Cached bounds are invalid. Caller needs to check for IsEmpty and call UpdateCachedBounds.");
}
else
{
Debug.Fail("Cached bounds are invalid. We missed a call to SetCachedBoundsDirty.");
}
}
}
#endregion DEBUG
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// If the _cachedBounds are empty it means that the cache is invalid. The user must
// check for this case and call UpdateCachedBounds if the cache is invalid. (There
// is no way to distinguish between actually caching "Empty" when there are no
// positions and the cache being invalid - but computing bounds in this case is
// very fast.)
private Rect3D _cachedBounds = Rect3D.Empty;
#endregion Private Fields
}
}
| |
// 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.Text;
using System;
using System.Collections;
namespace System.Collections.HashtableTests
{
public class RemoveTests
{
[Fact]
public void TestRemove()
{
Hashtable hash = null;
int ii;
HashConfuse hshcnf1;
string strValue;
ArrayList alst;
Boolean fRetValue;
int iCount;
Random rnd1;
int iElement;
#region "TestData"
string[] strSuperHeroes =
{
"Captain Marvel" , //0
"Batgirl" , //1
"Nightwing" , //2
"Green Lantern" , //3
"Robin" , //4
"Superman" , //5
"Black Canary" , //6
"Spiderman" , //7
"Iron Man" , //8
"Wonder Girl" , //9
"Batman" , //10
"Flash" , //11
"Green Arrow" , //12
"Atom" , //13
"Steel" , //14
"Powerman" , //15
};
string[] strSecretIdentities =
{
"Batson, Billy" , //0
"Gordan, Barbara" , //1
"Grayson, Dick" , //2
"Jordan, Hal" , //3
"Drake, Tim" , //4
"Kent, Clark" , //5
"Lance, Dinah" , //6
"Parker, Peter" , //7
"Stark, Tony" , //8
"Troy, Donna" , //9
"Wayne, Bruce" , //10
"West, Wally" , //11
"Queen, Oliver" , //12
"Palmer, Ray" , //13
"Irons, John Henry" , //14
"Cage, Luke" , //15
};
#endregion
// Allocate the hash table.
hash = new Hashtable();
Assert.NotNull(hash);
// Construct the hash table by adding items to the table.
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Add(strSuperHeroes[ii], strSecretIdentities[ii]);
}
// Validate additions to Hashtable.
Assert.Equal(strSuperHeroes.Length, hash.Count);
//
// [] Remove: Attempt to remove a bogus key entry from table.
//
hash.Remove("THIS IS A BOGUS KEY");
Assert.Equal(strSuperHeroes.Length, hash.Count);
//
// [] Remove: Attempt to remove a null key entry from table.
//
Assert.Throws<ArgumentNullException>(() =>
{
hash.Remove(null);
}
);
//
// [] Remove: Add key/value pair to Hashtable and remove items.
//
// Remove items from Hashtable.
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Remove(strSuperHeroes[ii]);
Assert.Equal(strSuperHeroes.Length - ii - 1, hash.Count);
}
//[]We want to add and delete items (with the same hashcode) to the hashtable in such a way that the hashtable
//does not expand but have to tread through collision bit set positions to insert the new elements. We do this
//by creating a default hashtable of size 11 (with the default load factor of 0.72), this should mean that
//the hashtable does not expand as long as we have at most 7 elements at any given time?
hash = new Hashtable();
alst = new ArrayList();
for (int i = 0; i < 7; i++)
{
strValue = "Test_" + i;
hshcnf1 = new HashConfuse(strValue);
alst.Add(hshcnf1);
hash.Add(hshcnf1, strValue);
}
//we will delete and add 3 new ones here and then compare
fRetValue = true;
iCount = 7;
rnd1 = new Random(-55);
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 7; j++)
{
if (!((string)hash[alst[j]]).Equals(((HashConfuse)alst[j]).Word))
{
fRetValue = false;
}
}
//we delete 3 elements from the hashtable
for (int j = 0; j < 3; j++)
{
iElement = rnd1.Next(6);
hash.Remove(alst[iElement]);
alst.RemoveAt(iElement);
strValue = "Test_" + iCount++;
hshcnf1 = new HashConfuse(strValue);
alst.Add(hshcnf1);
hash.Add(hshcnf1, strValue);
}
}
Assert.True(fRetValue);
}
[Fact]
public void TestRemove02()
{
Hashtable hash = null;
int ii;
#region "Test Data"
string[] strSuperHeroes = new string[]
{
"Captain Marvel" , //0
"Batgirl" , //1
"Nightwing" , //2
"Green Lantern" , //3
"Robin" , //4
"Superman" , //5
"Black Canary" , //6
"Spiderman" , //7
"Iron Man" , //8
"Wonder Girl" , //9
"Batman" , //10
"Flash" , //11
"Green Arrow" , //12
"Atom" , //13
"Steel" , //14
"Powerman" , //15
};
string[] strSecretIdentities = new string[]
{
"Batson, Billy" , //0
"Gordan, Barbara" , //1
"Grayson, Dick" , //2
"Jordan, Hal" , //3
"Drake, Tim" , //4
"Kent, Clark" , //5
"Lance, Dinah" , //6
"Parker, Peter" , //7
"Stark, Tony" , //8
"Troy, Donna" , //9
"Wayne, Bruce" , //10
"West, Wally" , //11
"Queen, Oliver" , //12
"Palmer, Ray" , //13
"Irons, John Henry" , //14
"Cage, Luke" , //15
};
#endregion
// Allocate the hash table.
hash = new Hashtable();
// Construct the hash table by adding items to the table.
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Add(strSuperHeroes[ii], strSecretIdentities[ii]);
}
// Validate additions to Hashtable.
Assert.Equal(strSuperHeroes.Length, hash.Count);
//
// []Remove: Attempt to remove a bogus key entry from table.
//
hash.Remove("THIS IS A BOGUS KEY");
Assert.Equal(hash.Count, strSuperHeroes.Length);
//
// [] Remove: Attempt to remove a null key entry from table.
//
Assert.Throws<ArgumentNullException>(() =>
{
hash.Remove(null);
}
);
//
// [] Remove: Add key/value pair to Hashtable and remove items.
//
// Remove items from Hashtable.
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Remove(strSuperHeroes[ii]);
Assert.Equal(strSuperHeroes.Length - ii - 1, hash.Count);
}
// now ADD ALL THE Entries the second time and remove them again
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Add(strSuperHeroes[ii], strSecretIdentities[ii]);
}
// remove elements
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Remove(strSuperHeroes[ii]);
Assert.Equal(hash.Count, strSuperHeroes.Length - ii - 1);
}
//[]Repeated removed
hash.Clear();
for (int iAnnoying = 0; iAnnoying < 10; iAnnoying++)
{
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Remove(strSuperHeroes[ii]);
Assert.Equal(0, hash.Count);
}
}
}
}
class HashConfuse
{
private string _strValue;
public HashConfuse(string val)
{
_strValue = val;
}
public string Word
{
get { return _strValue; }
set { _strValue = value; }
}
public override int GetHashCode()
{
return 5;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HoloJson.Core
{
// The purpose of this class is to implement "subarray" operation
// that does not require the content copy (which requires new memory allocation).
// This class is for wrapping "cyclic" arrays like CharQueue (ring buffer).
public sealed class CyclicCharArray
{
// backing array spec.
private readonly int arrayLength;
private readonly char[] backingArray;
// attrs to "define a subarray"
private int maxLength; // virtual array length == 2 * arrayLength;
private int offset;
private int length;
private int end; // "cache" == offset + length
// ????
public CyclicCharArray(char[] backingArray)
{
// backingArray cannot be null;
this.backingArray = backingArray;
this.arrayLength = this.backingArray.Length;
this.maxLength = 2 * this.arrayLength;
this.offset = 0;
this.length = 0;
ResetEnd();
}
private void ResetEnd()
{
this.end = this.offset + this.length;
}
// Read only.
public int MaxLength
{
get
{
return maxLength;
}
}
public int ArrayLength
{
get
{
return arrayLength;
}
}
// Convenience methods/builders.
public static CyclicCharArray Wrap(char[] backingArray)
{
CyclicCharArray charArray = new CyclicCharArray(backingArray);
return charArray;
}
public static CyclicCharArray Wrap(char[] backingArray, int offset, int length)
{
CyclicCharArray charArray = new CyclicCharArray(backingArray);
charArray.SetOffsetAndLength(offset, length);
return charArray;
}
//////////////////////////////////////////////////////////
// Usage:
// for(int i=caw.start; i<caw.end; i++) {
// char ch = caw.GetCharInArray(i);
// }
// or
// for(int i=0; i<caw.Length; i++) {
// char ch = caw.GetChar(i);
// }
// Note SetOffset() should be called before SetLength(), in the current implementation,
// if both values need to be set.
public int Offset
{
get
{
return offset;
}
set
{
// if(offset < 0) {
// this.offset = 0;
// } else if(offset > maxLength - 1) {
// this.offset = maxLength - 1;
// // } else if(offset > arrayLength - 1) { // Why is this causing errors???
// // this.offset = arrayLength - 1;
// } else {
// this.offset = offset;
// }
// if(this.offset + this.length > maxLength - 1) {
// this.length = (maxLength - 1) - this.offset;
// }
this.offset = value;
ResetEnd();
}
}
public int Length
{
get
{
return length;
}
set
{
// if(length < 0) {
// this.length = 0;
// } else if(this.offset + length > maxLength - 1) {
// this.length = (maxLength - 1) - this.offset;
// } else {
// this.length = length;
// }
this.length = value;
ResetEnd();
}
}
public void SetOffsetAndLength(int offset, int length)
{
// if(offset < 0) {
// this.offset = 0;
// } else if(offset > maxLength - 1) {
// this.offset = maxLength - 1;
// // } else if(offset > arrayLength - 1) { // Why is this causing errors???
// // this.offset = arrayLength - 1;
// } else {
// this.offset = offset;
// }
// if(length < 0) {
// this.length = 0;
// } else if(this.offset + length > maxLength - 1) {
// this.length = (maxLength - 1) - this.offset;
// } else {
// this.length = length;
// }
this.offset = offset;
this.length = length;
ResetEnd();
}
// vs. Offset???
public int Start
{
get
{
return offset;
}
}
public int End
{
get
{
return end;
}
}
public char[] BackingArray
{
get
{
return backingArray;
}
}
// offset <= index < offset + length
public char GetCharInArray()
{
return GetCharInArray(this.offset);
}
public char GetCharInArray(int index)
{
return this.backingArray[index % this.arrayLength];
}
public char GetCharInArrayBoundsCheck(int index)
{
if(index < this.offset || index >= this.offset + this.length) {
throw new ArgumentOutOfRangeException("Out of bound: index = " + index + ". offset = " + offset + "; length = " + length);
}
return this.backingArray[index % this.arrayLength];
}
public void SetCharInArray(char ch)
{
SetCharInArray(this.offset, ch);
}
public void SetCharInArray(int index, char ch)
{
this.backingArray[index % this.arrayLength] = ch;
}
public void SetCharInArrayBoundsCheck(int index, char ch)
{
if(index < this.offset || index >= this.offset + this.length) {
throw new ArgumentOutOfRangeException("Out of bound: index = " + index + ". offset = " + offset + "; length = " + length);
}
this.backingArray[index % this.arrayLength] = ch;
}
public void SetCharInArrays(params char[] c)
{
SetCharInArrays(this.offset, c);
}
public void SetCharInArrays(int index, params char[] c)
{
for(int i=0; i<c.Length; i++) {
this.backingArray[(index + i) % this.arrayLength] = c[i];
}
}
public void SetCharInArraysBoundsCheck(int index, params char[] c)
{
if(index < this.offset || index >= this.offset + this.length - c.Length) {
throw new ArgumentOutOfRangeException("Out of bound: index = " + index + ". offset = " + offset + "; length = " + length);
}
for(int i=0; i<c.Length; i++) {
this.backingArray[(index + i) % this.arrayLength] = c[i];
}
}
public char GetChar()
{
return GetChar(0);
}
public char GetChar(int index)
{
return this.backingArray[(this.offset + index) % this.arrayLength];
}
public char GetCharBoundsCheck(int index)
{
if(index < 0 || index >= this.length) {
throw new ArgumentOutOfRangeException("Out of bound: index = " + index + ". offset = " + offset + "; length = " + length);
}
return this.backingArray[(this.offset + index) % this.arrayLength];
}
// Make a copy and return the slice [index, index+length).
public char[] GetChars(int index, int length)
{
char[] copied = new char[length];
for(int i=0; i<length; i++) {
copied[i] = this.backingArray[(this.offset + index + i) % this.arrayLength];
}
return copied;
}
public void SetChar(char ch)
{
SetChar(0, ch);
}
public void SetChar(int index, char ch)
{
this.backingArray[(this.offset + index) % this.arrayLength] = ch;
}
public void SetCharBoundsCheck(int index, char ch)
{
if(index < 0 || index >= this.length) {
throw new ArgumentOutOfRangeException("Out of bound: index = " + index + ". offset = " + offset + "; length = " + length);
}
this.backingArray[(this.offset + index) % this.arrayLength] = ch;
}
public void SetChars(params char[] c)
{
SetChars(0, c);
}
public void SetChars(int index, params char[] c)
{
for(int i=0; i<c.Length; i++) {
this.backingArray[(this.offset + index + i) % this.arrayLength] = c[i];
}
}
public void SetCharsBoundsCheck(int index, params char[] c)
{
if(index < 0 || index >= this.length - c.Length) {
throw new ArgumentOutOfRangeException("Out of bound: index = " + index + ". offset = " + offset + "; length = " + length);
}
for(int i=0; i<c.Length; i++) {
this.backingArray[(this.offset + index + i) % this.arrayLength] = c[i];
}
}
// Returns the copied subarray from [offset to limit)
public char[] GetArray()
{
// which is better???
// [1] Using arraycopy.
// char[] copied = new char[length];
// if(offset + length < maxLength) {
// System.arraycopy(this.backingArray, offset, copied, 0, length);
// } else {
// // Note the arraycopy does memcopy/memomove.
// // Need a more efficient way to do this? (e.g., by returning a "ref" not copy???)
// int first = maxLength - offset;
// int second = length - first;
// System.arraycopy(this.backingArray, offset, copied, 0, first);
// System.arraycopy(this.backingArray, 0, copied, first, second);
// }
// [2] Just use a loop.
char[] copied = new char[length];
for(int i=0; i<length; i++) {
copied[i] = this.backingArray[(this.offset + i) % this.arrayLength];
}
return copied;
}
public override string ToString()
{
// return Arrays.ToString(this.GetArray());
return String.Join<char>(",", this.GetArray());
}
}
}
| |
// 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.Threading;
namespace System.Transactions
{
// Base class for all enlistment states
internal abstract class EnlistmentState
{
internal abstract void EnterState(InternalEnlistment enlistment);
// Double-checked locking pattern requires volatile for read/write synchronization
internal static volatile EnlistmentStatePromoted _enlistmentStatePromoted;
// Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) )
private static object s_classSyncObject;
// Helper object for static synchronization
private static object ClassSyncObject
{
get
{
if (s_classSyncObject == null)
{
object o = new object();
Interlocked.CompareExchange(ref s_classSyncObject, o, null);
}
return s_classSyncObject;
}
}
internal static EnlistmentStatePromoted EnlistmentStatePromoted
{
get
{
if (_enlistmentStatePromoted == null)
{
lock (ClassSyncObject)
{
if (_enlistmentStatePromoted == null)
{
EnlistmentStatePromoted temp = new EnlistmentStatePromoted();
_enlistmentStatePromoted = temp;
}
}
}
return _enlistmentStatePromoted;
}
}
internal virtual void EnlistmentDone(InternalEnlistment enlistment)
{
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void Prepared(InternalEnlistment enlistment)
{
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void ForceRollback(InternalEnlistment enlistment, Exception e)
{
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void Committed(InternalEnlistment enlistment)
{
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void Aborted(InternalEnlistment enlistment, Exception e)
{
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void InDoubt(InternalEnlistment enlistment, Exception e)
{
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual byte[] RecoveryInformation(InternalEnlistment enlistment)
{
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void InternalAborted(InternalEnlistment enlistment)
{
Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void InternalCommitted(InternalEnlistment enlistment)
{
Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void InternalIndoubt(InternalEnlistment enlistment)
{
Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void ChangeStateCommitting(InternalEnlistment enlistment)
{
Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void ChangeStatePromoted(InternalEnlistment enlistment, IPromotedEnlistment promotedEnlistment)
{
Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void ChangeStateDelegated(InternalEnlistment enlistment)
{
Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void ChangeStatePreparing(InternalEnlistment enlistment)
{
Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void ChangeStateSinglePhaseCommit(InternalEnlistment enlistment)
{
Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
throw TransactionException.CreateEnlistmentStateException(SR.TraceSourceLtm, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
}
internal class EnlistmentStatePromoted : EnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
enlistment.State = this;
}
internal override void EnlistmentDone(InternalEnlistment enlistment)
{
Monitor.Exit(enlistment.SyncRoot);
try
{
enlistment.PromotedEnlistment.EnlistmentDone();
}
finally
{
Monitor.Enter(enlistment.SyncRoot);
}
}
internal override void Prepared(InternalEnlistment enlistment)
{
Monitor.Exit(enlistment.SyncRoot);
try
{
enlistment.PromotedEnlistment.Prepared();
}
finally
{
Monitor.Enter(enlistment.SyncRoot);
}
}
internal override void ForceRollback(InternalEnlistment enlistment, Exception e)
{
Monitor.Exit(enlistment.SyncRoot);
try
{
enlistment.PromotedEnlistment.ForceRollback(e);
}
finally
{
Monitor.Enter(enlistment.SyncRoot);
}
}
internal override void Committed(InternalEnlistment enlistment)
{
Monitor.Exit(enlistment.SyncRoot);
try
{
enlistment.PromotedEnlistment.Committed();
}
finally
{
Monitor.Enter(enlistment.SyncRoot);
}
}
internal override void Aborted(InternalEnlistment enlistment, Exception e)
{
Monitor.Exit(enlistment.SyncRoot);
try
{
enlistment.PromotedEnlistment.Aborted(e);
}
finally
{
Monitor.Enter(enlistment.SyncRoot);
}
}
internal override void InDoubt(InternalEnlistment enlistment, Exception e)
{
Monitor.Exit(enlistment.SyncRoot);
try
{
enlistment.PromotedEnlistment.InDoubt(e);
}
finally
{
Monitor.Enter(enlistment.SyncRoot);
}
}
internal override byte[] RecoveryInformation(InternalEnlistment enlistment)
{
Monitor.Exit(enlistment.SyncRoot);
try
{
return enlistment.PromotedEnlistment.GetRecoveryInformation();
}
finally
{
Monitor.Enter(enlistment.SyncRoot);
}
}
}
}
| |
/*
Copyright 2001-2009 Markus Hahn
All rights reserved. See documentation for license details.
*/
using System;
namespace fxpa
{
/// <summary>Blowfish CBC implementation.</summary>
/// <remarks>Use this class to encrypt or decrypt byte arrays or a single blocks
/// with Blowfish in CBC (Cipher Block Block Chaining) mode. This is the recommended
/// way to use Blowfish.NET, unless certain requirements (e.g. moving block without
/// decryption) exist.
/// </remarks>
public class BlowfishCBC : BlowfishECB
{
// we store the IV as two 32bit integers, to void packing and
// unpacking inbetween the handling of data chunks
uint ivHi;
uint ivLo;
/// <summary>The current initialization vector (IV), which measures one block.</summary>
public byte[] IV
{
set
{
SetIV(value, 0);
}
get
{
byte[] result = new byte[BLOCK_SIZE];
GetIV(result, 0);
return result;
}
}
/// <summary>Sets the initialization vector (IV) with an offset.</summary>
/// <param name="buf">The buffer containing the new IV material.</param>
/// <param name="ofs">Where the IV material starts.</param>
public void SetIV(byte[] buf, int ofs)
{
this.ivHi = (((uint)buf[ofs ]) << 24) |
(((uint)buf[ofs + 1]) << 16) |
(((uint)buf[ofs + 2]) << 8) |
buf[ofs + 3];
this.ivLo = (((uint)buf[ofs + 4]) << 24) |
(((uint)buf[ofs + 5]) << 16) |
(((uint)buf[ofs + 6]) << 8) |
buf[ofs + 7];
}
/// <summary>Gets the current IV material (of the size of one block).</summary>
/// <param name="buf">The buffer to copy the IV to.</param>
/// <param name="ofs">Where to start copying.</param>
public void GetIV(byte[] buf, int ofs)
{
uint ivHi = this.ivHi;
uint ivLo = this.ivLo;
buf[ofs++] = (byte)(ivHi >> 24);
buf[ofs++] = (byte)(ivHi >> 16);
buf[ofs++] = (byte)(ivHi >> 8);
buf[ofs++] = (byte) ivHi;
buf[ofs++] = (byte)(ivLo >> 24);
buf[ofs++] = (byte)(ivLo >> 16);
buf[ofs++] = (byte)(ivLo >> 8);
buf[ofs ] = (byte) ivLo;
}
/// <summary>Default constructor.</summary>
/// <remarks>The IV needs to be assigned after the instance has been created!</remarks>
/// <see cref="BlowfishNET.BlowfishECB.Initialize"/>
public BlowfishCBC(byte[] key, int ofs, int len) : base(key, ofs, len)
{
}
/// <summary>Zero key constructor.</summary>
/// <remarks>After construction you need to initialize the instance and then apply the IV.</remarks>
public BlowfishCBC() : base(null, 0, 0)
{
}
/// <see cref="BlowfishNET.BlowfishECB.Invalidate"/>
public new void Invalidate()
{
base.Invalidate();
this.ivHi = this.ivLo = 0;
}
/// <see cref="BlowfishNET.BlowfishECB.EncryptBlock"/>
public new void EncryptBlock(
uint hi,
uint lo,
out uint outHi,
out uint outLo)
{
byte[] block = this.block;
block[0] = (byte)(hi >> 24);
block[1] = (byte)(hi >> 16);
block[2] = (byte)(hi >> 8);
block[3] = (byte) hi;
block[4] = (byte)(lo >> 24);
block[5] = (byte)(lo >> 16);
block[6] = (byte)(lo >> 8);
block[7] = (byte) lo;
Encrypt(block, 0, block, 0, BLOCK_SIZE);
outHi = (((uint)block[0]) << 24) |
(((uint)block[1]) << 16) |
(((uint)block[2]) << 8) |
block[3];
outLo = (((uint)block[4]) << 24) |
(((uint)block[5]) << 16) |
(((uint)block[6]) << 8) |
block[7];
}
/// <see cref="BlowfishNET.BlowfishECB.DecryptBlock"/>
public new void DecryptBlock(
uint hi,
uint lo,
out uint outHi,
out uint outLo)
{
byte[] block = this.block;
block[0] = (byte)(hi >> 24);
block[1] = (byte)(hi >> 16);
block[2] = (byte)(hi >> 8);
block[3] = (byte) hi;
block[4] = (byte)(lo >> 24);
block[5] = (byte)(lo >> 16);
block[6] = (byte)(lo >> 8);
block[7] = (byte) lo;
Decrypt(block, 0, block, 0, BLOCK_SIZE);
outHi = (((uint)block[0]) << 24) |
(((uint)block[1]) << 16) |
(((uint)block[2]) << 8) |
block[3];
outLo = (((uint)block[4]) << 24) |
(((uint)block[5]) << 16) |
(((uint)block[6]) << 8) |
block[7];
}
/// <see cref="BlowfishNET.BlowfishECB.Encrypt"/>
public new int Encrypt(
byte[] dataIn,
int posIn,
byte[] dataOut,
int posOut,
int count)
{
int end;
uint[] sbox1 = this.sbox1;
uint[] sbox2 = this.sbox2;
uint[] sbox3 = this.sbox3;
uint[] sbox4 = this.sbox4;
uint[] pbox = this.pbox;
uint pbox00 = pbox[ 0];
uint pbox01 = pbox[ 1];
uint pbox02 = pbox[ 2];
uint pbox03 = pbox[ 3];
uint pbox04 = pbox[ 4];
uint pbox05 = pbox[ 5];
uint pbox06 = pbox[ 6];
uint pbox07 = pbox[ 7];
uint pbox08 = pbox[ 8];
uint pbox09 = pbox[ 9];
uint pbox10 = pbox[10];
uint pbox11 = pbox[11];
uint pbox12 = pbox[12];
uint pbox13 = pbox[13];
uint pbox14 = pbox[14];
uint pbox15 = pbox[15];
uint pbox16 = pbox[16];
uint pbox17 = pbox[17];
uint hi = this.ivHi;
uint lo = this.ivLo;
count &= ~(BLOCK_SIZE - 1);
end = posIn + count;
while (posIn < end)
{
hi ^= (((uint)dataIn[posIn ]) << 24) |
(((uint)dataIn[posIn + 1]) << 16) |
(((uint)dataIn[posIn + 2]) << 8) |
dataIn[posIn + 3];
lo ^= (((uint)dataIn[posIn + 4]) << 24) |
(((uint)dataIn[posIn + 5]) << 16) |
(((uint)dataIn[posIn + 6]) << 8) |
dataIn[posIn + 7];
posIn += 8;
hi ^= pbox00;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox01;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox02;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox03;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox04;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox05;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox06;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox07;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox08;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox09;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox10;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox11;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox12;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox13;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox14;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox15;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox16;
uint swap = lo ^ pbox17;
lo = hi;
hi = swap;
dataOut[posOut ] = (byte)(hi >> 24);
dataOut[posOut + 1] = (byte)(hi >> 16);
dataOut[posOut + 2] = (byte)(hi >> 8);
dataOut[posOut + 3] = (byte) hi;
dataOut[posOut + 4] = (byte)(lo >> 24);
dataOut[posOut + 5] = (byte)(lo >> 16);
dataOut[posOut + 6] = (byte)(lo >> 8);
dataOut[posOut + 7] = (byte) lo;
posOut += 8;
}
this.ivHi = hi;
this.ivLo = lo;
return count;
}
/// <see cref="BlowfishNET.BlowfishECB.Decrypt"/>
public new int Decrypt(
byte[] dataIn,
int posIn,
byte[] dataOut,
int posOut,
int count)
{
int end;
uint hi, lo, hiBak, loBak;
uint[] sbox1 = this.sbox1;
uint[] sbox2 = this.sbox2;
uint[] sbox3 = this.sbox3;
uint[] sbox4 = this.sbox4;
uint[] pbox = this.pbox;
uint pbox00 = pbox[ 0];
uint pbox01 = pbox[ 1];
uint pbox02 = pbox[ 2];
uint pbox03 = pbox[ 3];
uint pbox04 = pbox[ 4];
uint pbox05 = pbox[ 5];
uint pbox06 = pbox[ 6];
uint pbox07 = pbox[ 7];
uint pbox08 = pbox[ 8];
uint pbox09 = pbox[ 9];
uint pbox10 = pbox[10];
uint pbox11 = pbox[11];
uint pbox12 = pbox[12];
uint pbox13 = pbox[13];
uint pbox14 = pbox[14];
uint pbox15 = pbox[15];
uint pbox16 = pbox[16];
uint pbox17 = pbox[17];
uint ivHi = this.ivHi;
uint ivLo = this.ivLo;
count &= ~(BLOCK_SIZE - 1);
end = posIn + count;
while (posIn < end)
{
hi = hiBak = (((uint)dataIn[posIn ]) << 24) |
(((uint)dataIn[posIn + 1]) << 16) |
(((uint)dataIn[posIn + 2]) << 8) |
dataIn[posIn + 3];
lo = loBak = (((uint)dataIn[posIn + 4]) << 24) |
(((uint)dataIn[posIn + 5]) << 16) |
(((uint)dataIn[posIn + 6]) << 8) |
dataIn[posIn + 7];
posIn += 8;
hi ^= pbox17;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox16;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox15;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox14;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox13;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox12;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox11;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox10;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox09;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox08;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox07;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox06;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox05;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox04;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox03;
lo ^= (((sbox1[(int)(hi >> 24)] + sbox2[(int)((hi >> 16) & 0x0ff)]) ^ sbox3[(int)((hi >> 8) & 0x0ff)]) + sbox4[(int)(hi & 0x0ff)]) ^ pbox02;
hi ^= (((sbox1[(int)(lo >> 24)] + sbox2[(int)((lo >> 16) & 0x0ff)]) ^ sbox3[(int)((lo >> 8) & 0x0ff)]) + sbox4[(int)(lo & 0x0ff)]) ^ pbox01;
lo ^= ivHi ^ pbox00;
hi ^= ivLo;
dataOut[posOut ] = (byte)(lo >> 24);
dataOut[posOut + 1] = (byte)(lo >> 16);
dataOut[posOut + 2] = (byte)(lo >> 8);
dataOut[posOut + 3] = (byte) lo;
dataOut[posOut + 4] = (byte)(hi >> 24);
dataOut[posOut + 5] = (byte)(hi >> 16);
dataOut[posOut + 6] = (byte)(hi >> 8);
dataOut[posOut + 7] = (byte) hi;
ivHi = hiBak;
ivLo = loBak;
posOut += 8;
}
this.ivHi = ivHi;
this.ivLo = ivLo;
return count;
}
/// <see cref="BlowfishNET.BlowfishECB.Clone"/>
public new object Clone()
{
BlowfishCBC result;
result = new BlowfishCBC();
result.pbox = (uint[]) this.pbox.Clone();
result.sbox1 = (uint[]) this.sbox1.Clone();
result.sbox2 = (uint[]) this.sbox2.Clone();
result.sbox3 = (uint[]) this.sbox3.Clone();
result.sbox4 = (uint[]) this.sbox4.Clone();
result.block = (byte[]) this.block.Clone();
result.isWeakKey = this.isWeakKey;
result.ivHi = this.ivHi;
result.ivLo = this.ivLo;
return result;
}
}
}
| |
using System;
using Csla;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERLevel;
namespace ParentLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// E03_Continent_Child (editable child object).<br/>
/// This is a generated base class of <see cref="E03_Continent_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="E02_Continent"/> collection.
/// </remarks>
[Serializable]
public partial class E03_Continent_Child : BusinessBase<E03_Continent_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "SubContinents Child Name");
/// <summary>
/// Gets or sets the SubContinents Child Name.
/// </summary>
/// <value>The SubContinents Child Name.</value>
public string Continent_Child_Name
{
get { return GetProperty(Continent_Child_NameProperty); }
set { SetProperty(Continent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="E03_Continent_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="E03_Continent_Child"/> object.</returns>
internal static E03_Continent_Child NewE03_Continent_Child()
{
return DataPortal.CreateChild<E03_Continent_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="E03_Continent_Child"/> object from the given E03_Continent_ChildDto.
/// </summary>
/// <param name="data">The <see cref="E03_Continent_ChildDto"/>.</param>
/// <returns>A reference to the fetched <see cref="E03_Continent_Child"/> object.</returns>
internal static E03_Continent_Child GetE03_Continent_Child(E03_Continent_ChildDto data)
{
E03_Continent_Child obj = new E03_Continent_Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="E03_Continent_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public E03_Continent_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="E03_Continent_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="E03_Continent_Child"/> object from the given <see cref="E03_Continent_ChildDto"/>.
/// </summary>
/// <param name="data">The E03_Continent_ChildDto to use.</param>
private void Fetch(E03_Continent_ChildDto data)
{
// Value properties
LoadProperty(Continent_Child_NameProperty, data.Continent_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="E03_Continent_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(E02_Continent parent)
{
var dto = new E03_Continent_ChildDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.Continent_Child_Name = Continent_Child_Name;
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IE03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="E03_Continent_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(E02_Continent parent)
{
if (!IsDirty)
return;
var dto = new E03_Continent_ChildDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.Continent_Child_Name = Continent_Child_Name;
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IE03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="E03_Continent_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(E02_Continent parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IE03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Continent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.IO;
using System.Text;
using BigMath;
using Raksha.Asn1.CryptoPro;
using Raksha.Asn1.X509;
using Raksha.Crypto;
using Raksha.Crypto.Parameters;
using Raksha.Math;
using Raksha.Security;
using Raksha.Utilities.Encoders;
using Raksha.Utilities.IO;
using Raksha.X509;
using Raksha.X509.Extension;
namespace Raksha.Tests.Cms
{
public class CmsTestUtil
{
public static SecureRandom rand;
private static IAsymmetricCipherKeyPairGenerator kpg;
private static IAsymmetricCipherKeyPairGenerator gostKpg;
private static IAsymmetricCipherKeyPairGenerator dsaKpg;
private static IAsymmetricCipherKeyPairGenerator ecGostKpg;
private static IAsymmetricCipherKeyPairGenerator ecDsaKpg;
public static CipherKeyGenerator aes192kg;
public static CipherKeyGenerator desede128kg;
public static CipherKeyGenerator desede192kg;
public static CipherKeyGenerator rc240kg;
public static CipherKeyGenerator rc264kg;
public static CipherKeyGenerator rc2128kg;
public static CipherKeyGenerator aesKg;
public static CipherKeyGenerator seedKg;
public static CipherKeyGenerator camelliaKg;
public static BigInteger serialNumber;
private static readonly byte[] attrCert = Base64.Decode(
"MIIHQDCCBqkCAQEwgZChgY2kgYowgYcxHDAaBgkqhkiG9w0BCQEWDW1sb3JjaEB2"
+ "dC5lZHUxHjAcBgNVBAMTFU1hcmt1cyBMb3JjaCAobWxvcmNoKTEbMBkGA1UECxMS"
+ "VmlyZ2luaWEgVGVjaCBVc2VyMRAwDgYDVQQLEwdDbGFzcyAyMQswCQYDVQQKEwJ2"
+ "dDELMAkGA1UEBhMCVVMwgYmkgYYwgYMxGzAZBgkqhkiG9w0BCQEWDHNzaGFoQHZ0"
+ "LmVkdTEbMBkGA1UEAxMSU3VtaXQgU2hhaCAoc3NoYWgpMRswGQYDVQQLExJWaXJn"
+ "aW5pYSBUZWNoIFVzZXIxEDAOBgNVBAsTB0NsYXNzIDExCzAJBgNVBAoTAnZ0MQsw"
+ "CQYDVQQGEwJVUzANBgkqhkiG9w0BAQQFAAIBBTAiGA8yMDAzMDcxODE2MDgwMloY"
+ "DzIwMDMwNzI1MTYwODAyWjCCBU0wggVJBgorBgEEAbRoCAEBMYIFORaCBTU8UnVs"
+ "ZSBSdWxlSWQ9IkZpbGUtUHJpdmlsZWdlLVJ1bGUiIEVmZmVjdD0iUGVybWl0Ij4K"
+ "IDxUYXJnZXQ+CiAgPFN1YmplY3RzPgogICA8U3ViamVjdD4KICAgIDxTdWJqZWN0"
+ "TWF0Y2ggTWF0Y2hJZD0idXJuOm9hc2lzOm5hbWVzOnRjOnhhY21sOjEuMDpmdW5j"
+ "dGlvbjpzdHJpbmctZXF1YWwiPgogICAgIDxBdHRyaWJ1dGVWYWx1ZSBEYXRhVHlw"
+ "ZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEjc3RyaW5nIj4KICAg"
+ "ICAgIENOPU1hcmt1cyBMb3JjaDwvQXR0cmlidXRlVmFsdWU+CiAgICAgPFN1Ympl"
+ "Y3RBdHRyaWJ1dGVEZXNpZ25hdG9yIEF0dHJpYnV0ZUlkPSJ1cm46b2FzaXM6bmFt"
+ "ZXM6dGM6eGFjbWw6MS4wOnN1YmplY3Q6c3ViamVjdC1pZCIgRGF0YVR5cGU9Imh0"
+ "dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hI3N0cmluZyIgLz4gCiAgICA8"
+ "L1N1YmplY3RNYXRjaD4KICAgPC9TdWJqZWN0PgogIDwvU3ViamVjdHM+CiAgPFJl"
+ "c291cmNlcz4KICAgPFJlc291cmNlPgogICAgPFJlc291cmNlTWF0Y2ggTWF0Y2hJ"
+ "ZD0idXJuOm9hc2lzOm5hbWVzOnRjOnhhY21sOjEuMDpmdW5jdGlvbjpzdHJpbmct"
+ "ZXF1YWwiPgogICAgIDxBdHRyaWJ1dGVWYWx1ZSBEYXRhVHlwZT0iaHR0cDovL3d3"
+ "dy53My5vcmcvMjAwMS9YTUxTY2hlbWEjYW55VVJJIj4KICAgICAgaHR0cDovL3p1"
+ "bmkuY3MudnQuZWR1PC9BdHRyaWJ1dGVWYWx1ZT4KICAgICA8UmVzb3VyY2VBdHRy"
+ "aWJ1dGVEZXNpZ25hdG9yIEF0dHJpYnV0ZUlkPSJ1cm46b2FzaXM6bmFtZXM6dGM6"
+ "eGFjbWw6MS4wOnJlc291cmNlOnJlc291cmNlLWlkIiBEYXRhVHlwZT0iaHR0cDov"
+ "L3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEjYW55VVJJIiAvPiAKICAgIDwvUmVz"
+ "b3VyY2VNYXRjaD4KICAgPC9SZXNvdXJjZT4KICA8L1Jlc291cmNlcz4KICA8QWN0"
+ "aW9ucz4KICAgPEFjdGlvbj4KICAgIDxBY3Rpb25NYXRjaCBNYXRjaElkPSJ1cm46"
+ "b2FzaXM6bmFtZXM6dGM6eGFjbWw6MS4wOmZ1bmN0aW9uOnN0cmluZy1lcXVhbCI+"
+ "CiAgICAgPEF0dHJpYnV0ZVZhbHVlIERhdGFUeXBlPSJodHRwOi8vd3d3LnczLm9y"
+ "Zy8yMDAxL1hNTFNjaGVtYSNzdHJpbmciPgpEZWxlZ2F0ZSBBY2Nlc3MgICAgIDwv"
+ "QXR0cmlidXRlVmFsdWU+CgkgIDxBY3Rpb25BdHRyaWJ1dGVEZXNpZ25hdG9yIEF0"
+ "dHJpYnV0ZUlkPSJ1cm46b2FzaXM6bmFtZXM6dGM6eGFjbWw6MS4wOmFjdGlvbjph"
+ "Y3Rpb24taWQiIERhdGFUeXBlPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hNTFNj"
+ "aGVtYSNzdHJpbmciIC8+IAogICAgPC9BY3Rpb25NYXRjaD4KICAgPC9BY3Rpb24+"
+ "CiAgPC9BY3Rpb25zPgogPC9UYXJnZXQ+CjwvUnVsZT4KMA0GCSqGSIb3DQEBBAUA"
+ "A4GBAGiJSM48XsY90HlYxGmGVSmNR6ZW2As+bot3KAfiCIkUIOAqhcphBS23egTr"
+ "6asYwy151HshbPNYz+Cgeqs45KkVzh7bL/0e1r8sDVIaaGIkjHK3CqBABnfSayr3"
+ "Rd1yBoDdEv8Qb+3eEPH6ab9021AsLEnJ6LWTmybbOpMNZ3tv");
private static IAsymmetricCipherKeyPairGenerator Kpg
{
get
{
if (kpg == null)
{
kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
kpg.Init(new RsaKeyGenerationParameters(
BigInteger.ValueOf(17), rand, 1024, 25));
}
return kpg;
}
}
private static IAsymmetricCipherKeyPairGenerator GostKpg
{
get
{
if (gostKpg == null)
{
gostKpg = GeneratorUtilities.GetKeyPairGenerator("GOST3410");
gostKpg.Init(
new Gost3410KeyGenerationParameters(
rand,
CryptoProObjectIdentifiers.GostR3410x94CryptoProA));
}
return gostKpg;
}
}
private static IAsymmetricCipherKeyPairGenerator DsaKpg
{
get
{
if (dsaKpg == null)
{
DsaParameters dsaSpec = new DsaParameters(
new BigInteger("7434410770759874867539421675728577177024889699586189000788950934679315164676852047058354758883833299702695428196962057871264685291775577130504050839126673"),
new BigInteger("1138656671590261728308283492178581223478058193247"),
new BigInteger("4182906737723181805517018315469082619513954319976782448649747742951189003482834321192692620856488639629011570381138542789803819092529658402611668375788410"));
dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA");
dsaKpg.Init(new DsaKeyGenerationParameters(rand, dsaSpec));
}
return dsaKpg;
}
}
private static IAsymmetricCipherKeyPairGenerator ECGostKpg
{
get
{
if (ecGostKpg == null)
{
ecGostKpg = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");
ecGostKpg.Init(
new ECKeyGenerationParameters(
CryptoProObjectIdentifiers.GostR3410x2001CryptoProA,
new SecureRandom()));
}
return ecGostKpg;
}
}
private static IAsymmetricCipherKeyPairGenerator ECDsaKpg
{
get
{
if (ecDsaKpg == null)
{
ecDsaKpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
ecDsaKpg.Init(new KeyGenerationParameters(rand, 239));
}
return ecDsaKpg;
}
}
static CmsTestUtil()
{
try
{
rand = new SecureRandom();
aes192kg = GeneratorUtilities.GetKeyGenerator("AES");
aes192kg.Init(new KeyGenerationParameters(rand, 192));
desede128kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
desede128kg.Init(new KeyGenerationParameters(rand, 112));
desede192kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
desede192kg.Init(new KeyGenerationParameters(rand, 168));
rc240kg = GeneratorUtilities.GetKeyGenerator("RC2");
rc240kg.Init(new KeyGenerationParameters(rand, 40));
rc264kg = GeneratorUtilities.GetKeyGenerator("RC2");
rc264kg.Init(new KeyGenerationParameters(rand, 64));
rc2128kg = GeneratorUtilities.GetKeyGenerator("RC2");
rc2128kg.Init(new KeyGenerationParameters(rand, 128));
aesKg = GeneratorUtilities.GetKeyGenerator("AES");
seedKg = GeneratorUtilities.GetKeyGenerator("SEED");
camelliaKg = GeneratorUtilities.GetKeyGenerator("Camellia");
serialNumber = BigInteger.One;
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
public static string DumpBase64(
byte[] data)
{
StringBuilder buf = new StringBuilder();
data = Base64.Encode(data);
for (int i = 0; i < data.Length; i += 64)
{
if (i + 64 < data.Length)
{
buf.Append(Encoding.Default.GetString(data, i, 64));
}
else
{
buf.Append(Encoding.Default.GetString(data, i, data.Length - i));
}
buf.Append('\n');
}
return buf.ToString();
}
public static IX509AttributeCertificate GetAttributeCertificate()
{
// X509StreamParser parser = X509StreamParser.GetInstance("AttributeCertificate");
// parser.Init(CmsTestUtil.attrCert);
// return (X509AttributeCertificate) parser.Read();
return new X509AttrCertParser().ReadAttrCert(attrCert);
}
public static AsymmetricCipherKeyPair MakeKeyPair()
{
return Kpg.GenerateKeyPair();
}
public static AsymmetricCipherKeyPair MakeGostKeyPair()
{
return GostKpg.GenerateKeyPair();
}
public static AsymmetricCipherKeyPair MakeDsaKeyPair()
{
return DsaKpg.GenerateKeyPair();
}
public static AsymmetricCipherKeyPair MakeECGostKeyPair()
{
return ECGostKpg.GenerateKeyPair();
}
public static AsymmetricCipherKeyPair MakeECDsaKeyPair()
{
return ECDsaKpg.GenerateKeyPair();
}
public static KeyParameter MakeDesEde128Key()
{
return ParameterUtilities.CreateKeyParameter("DESEDE", desede128kg.GenerateKey());
}
public static KeyParameter MakeAes192Key()
{
return ParameterUtilities.CreateKeyParameter("AES", aes192kg.GenerateKey());
}
public static KeyParameter MakeDesEde192Key()
{
return ParameterUtilities.CreateKeyParameter("DESEDE", desede192kg.GenerateKey());
}
public static KeyParameter MakeRC240Key()
{
return ParameterUtilities.CreateKeyParameter("RC2", rc240kg.GenerateKey());
}
public static KeyParameter MakeRC264Key()
{
return ParameterUtilities.CreateKeyParameter("RC2", rc264kg.GenerateKey());
}
public static KeyParameter MakeRC2128Key()
{
return ParameterUtilities.CreateKeyParameter("RC2", rc2128kg.GenerateKey());
}
public static KeyParameter MakeSeedKey()
{
return ParameterUtilities.CreateKeyParameter("SEED", seedKg.GenerateKey());
}
public static KeyParameter MakeAesKey(
int keySize)
{
aesKg.Init(new KeyGenerationParameters(rand, keySize));
return ParameterUtilities.CreateKeyParameter("AES", aesKg.GenerateKey());
}
public static KeyParameter MakeCamelliaKey(
int keySize)
{
camelliaKg.Init(new KeyGenerationParameters(rand, keySize));
return ParameterUtilities.CreateKeyParameter("CAMELLIA", camelliaKg.GenerateKey());
}
public static X509Certificate MakeCertificate(AsymmetricCipherKeyPair _subKP,
string _subDN, AsymmetricCipherKeyPair _issKP, string _issDN)
{
return MakeCertificate(_subKP, _subDN, _issKP, _issDN, false);
}
public static X509Certificate MakeCACertificate(AsymmetricCipherKeyPair _subKP,
string _subDN, AsymmetricCipherKeyPair _issKP, string _issDN)
{
return MakeCertificate(_subKP, _subDN, _issKP, _issDN, true);
}
public static X509Certificate MakeV1Certificate(AsymmetricCipherKeyPair subKP,
string _subDN, AsymmetricCipherKeyPair issKP, string _issDN)
{
AsymmetricKeyParameter subPub = subKP.Public;
AsymmetricKeyParameter issPriv = issKP.Private;
AsymmetricKeyParameter issPub = issKP.Public;
X509V1CertificateGenerator v1CertGen = new X509V1CertificateGenerator();
v1CertGen.Reset();
v1CertGen.SetSerialNumber(AllocateSerialNumber());
v1CertGen.SetIssuerDN(new X509Name(_issDN));
v1CertGen.SetNotBefore(DateTime.UtcNow);
v1CertGen.SetNotAfter(DateTime.UtcNow.AddDays(100));
v1CertGen.SetSubjectDN(new X509Name(_subDN));
v1CertGen.SetPublicKey(subPub);
if (issPub is RsaKeyParameters)
{
v1CertGen.SetSignatureAlgorithm("SHA1WithRSA");
}
else if (issPub is DsaPublicKeyParameters)
{
v1CertGen.SetSignatureAlgorithm("SHA1withDSA");
}
else if (issPub is ECPublicKeyParameters)
{
ECPublicKeyParameters ecPub = (ECPublicKeyParameters)issPub;
if (ecPub.AlgorithmName == "ECGOST3410")
{
v1CertGen.SetSignatureAlgorithm("GOST3411withECGOST3410");
}
else
{
v1CertGen.SetSignatureAlgorithm("SHA1withECDSA");
}
}
else
{
v1CertGen.SetSignatureAlgorithm("GOST3411WithGOST3410");
}
X509Certificate _cert = v1CertGen.Generate(issPriv);
_cert.CheckValidity(DateTime.UtcNow);
_cert.Verify(issPub);
return _cert;
}
public static X509Certificate MakeCertificate(
AsymmetricCipherKeyPair subKP, string _subDN,
AsymmetricCipherKeyPair issKP, string _issDN, bool _ca)
{
AsymmetricKeyParameter subPub = subKP.Public;
AsymmetricKeyParameter issPriv = issKP.Private;
AsymmetricKeyParameter issPub = issKP.Public;
X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
v3CertGen.Reset();
v3CertGen.SetSerialNumber(AllocateSerialNumber());
v3CertGen.SetIssuerDN(new X509Name(_issDN));
v3CertGen.SetNotBefore(DateTime.UtcNow);
v3CertGen.SetNotAfter(DateTime.UtcNow.AddDays(100));
v3CertGen.SetSubjectDN(new X509Name(_subDN));
v3CertGen.SetPublicKey(subPub);
if (issPub is RsaKeyParameters)
{
v3CertGen.SetSignatureAlgorithm("SHA1WithRSA");
}
else if (issPub is ECPublicKeyParameters)
{
ECPublicKeyParameters ecPub = (ECPublicKeyParameters) issPub;
if (ecPub.AlgorithmName == "ECGOST3410")
{
v3CertGen.SetSignatureAlgorithm("GOST3411withECGOST3410");
}
else
{
v3CertGen.SetSignatureAlgorithm("SHA1withECDSA");
}
}
else
{
v3CertGen.SetSignatureAlgorithm("GOST3411WithGOST3410");
}
v3CertGen.AddExtension(
X509Extensions.SubjectKeyIdentifier,
false,
CreateSubjectKeyId(subPub));
v3CertGen.AddExtension(
X509Extensions.AuthorityKeyIdentifier,
false,
CreateAuthorityKeyId(issPub));
v3CertGen.AddExtension(
X509Extensions.BasicConstraints,
false,
new BasicConstraints(_ca));
X509Certificate _cert = v3CertGen.Generate(issPriv);
_cert.CheckValidity();
_cert.Verify(issPub);
return _cert;
}
public static X509Crl MakeCrl(
AsymmetricCipherKeyPair pair)
{
X509V2CrlGenerator crlGen = new X509V2CrlGenerator();
DateTime now = DateTime.UtcNow;
crlGen.SetIssuerDN(new X509Name("CN=Test CA"));
crlGen.SetThisUpdate(now);
crlGen.SetNextUpdate(now.AddSeconds(100));
crlGen.SetSignatureAlgorithm("SHA256WithRSAEncryption");
crlGen.AddCrlEntry(BigInteger.One, now, CrlReason.PrivilegeWithdrawn);
crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.Public));
return crlGen.Generate(pair.Private);
}
/*
*
* INTERNAL METHODS
*
*/
private static AuthorityKeyIdentifier CreateAuthorityKeyId(
AsymmetricKeyParameter _pubKey)
{
SubjectPublicKeyInfo _info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_pubKey);
return new AuthorityKeyIdentifier(_info);
}
internal static SubjectKeyIdentifier CreateSubjectKeyId(
AsymmetricKeyParameter _pubKey)
{
SubjectPublicKeyInfo _info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_pubKey);
return new SubjectKeyIdentifier(_info);
}
private static BigInteger AllocateSerialNumber()
{
BigInteger _tmp = serialNumber;
serialNumber = serialNumber.Add(BigInteger.One);
return _tmp;
}
public static byte[] StreamToByteArray(
Stream inStream)
{
return Streams.ReadAll(inStream);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.