context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
/*****************************************************
*
* XMLRPCModule
*
* Module for accepting incoming communications from
* external XMLRPC client and calling a remote data
* procedure for a registered data channel/prim.
*
*
* 1. On module load, open a listener port
* 2. Attach an XMLRPC handler
* 3. When a request is received:
* 3.1 Parse into components: channel key, int, string
* 3.2 Look up registered channel listeners
* 3.3 Call the channel (prim) remote data method
* 3.4 Capture the response (llRemoteDataReply)
* 3.5 Return response to client caller
* 3.6 If no response from llRemoteDataReply within
* RemoteReplyScriptTimeout, generate script timeout fault
*
* Prims in script must:
* 1. Open a remote data channel
* 1.1 Generate a channel ID
* 1.2 Register primid,channelid pair with module
* 2. Implement the remote data procedure handler
*
* llOpenRemoteDataChannel
* llRemoteDataReply
* remote_data(integer type, key channel, key messageid, string sender, integer ival, string sval)
* llCloseRemoteDataChannel
*
* **************************************************/
namespace OpenSim.Region.CoreModules.Scripting.XMLRPC
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XMLRPCModule")]
public class XMLRPCModule : ISharedRegionModule, IXMLRPC
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_name = "XMLRPCModule";
// <channel id, RPCChannelInfo>
private ThreadedClasses.RwLockedDictionary<UUID, RPCChannelInfo> m_openChannels = new ThreadedClasses.RwLockedDictionary<UUID,RPCChannelInfo>();
private ThreadedClasses.RwLockedDictionary<UUID, SendRemoteDataRequest> m_pendingSRDResponses = new ThreadedClasses.RwLockedDictionary<UUID, SendRemoteDataRequest>();
private int m_remoteDataPort = 0;
public int Port
{
get { return m_remoteDataPort; }
}
private ThreadedClasses.RwLockedDictionary<UUID, RPCRequestInfo> m_rpcPending = new ThreadedClasses.RwLockedDictionary<UUID, RPCRequestInfo>();
private ThreadedClasses.RwLockedDictionary<UUID, RPCRequestInfo> m_rpcPendingResponses = new ThreadedClasses.RwLockedDictionary<UUID,RPCRequestInfo>();
private ThreadedClasses.RwLockedList<Scene> m_scenes = new ThreadedClasses.RwLockedList<Scene>();
private int RemoteReplyScriptTimeout = 9000;
private int RemoteReplyScriptWait = 300;
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
if (config.Configs["XMLRPC"] != null)
{
try
{
m_remoteDataPort = config.Configs["XMLRPC"].GetInt("XmlRpcPort", m_remoteDataPort);
}
catch (Exception)
{
}
}
}
public void PostInitialise()
{
if (IsEnabled())
{
// Start http server
// Attach xmlrpc handlers
// m_log.InfoFormat(
// "[XML RPC MODULE]: Starting up XMLRPC Server on port {0} for llRemoteData commands.",
// m_remoteDataPort);
IHttpServer httpServer = MainServer.GetHttpServer((uint)m_remoteDataPort);
httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData);
}
}
public void AddRegion(Scene scene)
{
if (!IsEnabled())
return;
m_scenes.Add(scene);
scene.RegisterModuleInterface<IXMLRPC>(this);
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (!IsEnabled())
return;
scene.UnregisterModuleInterface<IXMLRPC>(this);
m_scenes.Remove(scene);
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
#region IXMLRPC Members
public bool IsEnabled()
{
return (m_remoteDataPort > 0);
}
/**********************************************
* OpenXMLRPCChannel
*
* Generate a UUID channel key and add it and
* the prim id to dictionary <channelUUID, primUUID>
*
* A custom channel key can be proposed.
* Otherwise, passing UUID.Zero will generate
* and return a random channel
*
* First check if there is a channel assigned for
* this itemID. If there is, then someone called
* llOpenRemoteDataChannel twice. Just return the
* original channel. Other option is to delete the
* current channel and assign a new one.
*
* ********************************************/
public UUID OpenXMLRPCChannel(uint localID, UUID itemID, UUID channelID)
{
UUID newChannel = UUID.Zero;
//Is a dupe?
try
{
m_openChannels.ForEach(delegate(RPCChannelInfo ci)
{
if (ci.GetItemID().Equals(itemID))
{
// return the original channel ID for this item
throw new ThreadedClasses.ReturnValueException<UUID>(ci.GetChannelID());
}
});
}
catch(ThreadedClasses.ReturnValueException<UUID> e)
{
return e.Value;
}
newChannel = (channelID == UUID.Zero) ? UUID.Random() : channelID;
RPCChannelInfo rpcChanInfo = new RPCChannelInfo(localID, itemID, newChannel);
m_openChannels.Add(newChannel, rpcChanInfo);
return newChannel;
}
// Delete channels based on itemID
// for when a script is deleted
public void DeleteChannels(UUID itemID)
{
ArrayList tmp = new ArrayList();
m_openChannels.ForEach(delegate(RPCChannelInfo li)
{
if (li.GetItemID().Equals(itemID))
{
tmp.Add(itemID);
}
});
foreach (UUID uuid in tmp)
{
m_openChannels.Remove(uuid);
}
}
/**********************************************
* Remote Data Reply
*
* Response to RPC message
*
*********************************************/
public void RemoteDataReply(string channel, string message_id, string sdata, int idata)
{
UUID message_key = new UUID(message_id);
UUID channel_key = new UUID(channel);
RPCRequestInfo rpcInfo = null;
if (message_key == UUID.Zero)
{
m_rpcPendingResponses.ForEach(delegate(RPCRequestInfo oneRpcInfo)
{
if (oneRpcInfo.GetChannelKey() == channel_key)
rpcInfo = oneRpcInfo;
});
}
else
{
m_rpcPendingResponses.TryGetValue(message_key, out rpcInfo);
}
if (rpcInfo != null)
{
rpcInfo.SetStrRetval(sdata);
rpcInfo.SetIntRetval(idata);
rpcInfo.SetProcessed(true);
m_rpcPendingResponses.Remove(message_key);
}
else
{
m_log.Warn("[XML RPC MODULE]: Channel or message_id not found");
}
}
/**********************************************
* CloseXMLRPCChannel
*
* Remove channel from dictionary
*
*********************************************/
public void CloseXMLRPCChannel(UUID channelKey)
{
m_openChannels.Remove(channelKey);
}
public bool hasRequests()
{
return (m_rpcPending.Count > 0);
}
public IXmlRpcRequestInfo GetNextCompletedRequest()
{
try
{
m_rpcPending.ForEach(delegate(UUID luid)
{
RPCRequestInfo tmpReq;
if (m_rpcPending.TryGetValue(luid, out tmpReq))
{
if (!tmpReq.IsProcessed())
throw new ThreadedClasses.ReturnValueException<IXmlRpcRequestInfo>(tmpReq);
}
});
}
catch(ThreadedClasses.ReturnValueException<IXmlRpcRequestInfo> e)
{
return e.Value;
}
return null;
}
public void RemoveCompletedRequest(UUID id)
{
RPCRequestInfo tmp;
if (m_rpcPending.Remove(id, out tmp))
{
m_rpcPendingResponses.Add(id, tmp);
}
}
public UUID SendRemoteData(uint localID, UUID itemID, string channel, string dest, int idata, string sdata)
{
SendRemoteDataRequest req = new SendRemoteDataRequest(
localID, itemID, channel, dest, idata, sdata
);
m_pendingSRDResponses.Add(req.GetReqID(), req);
req.Process();
return req.ReqID;
}
public IServiceRequest GetNextCompletedSRDRequest()
{
try
{
m_pendingSRDResponses.ForEach(delegate(UUID luid)
{
SendRemoteDataRequest tmpReq;
if (m_pendingSRDResponses.TryGetValue(luid, out tmpReq))
{
if (tmpReq.Finished)
throw new ThreadedClasses.ReturnValueException<SendRemoteDataRequest>(tmpReq);
}
});
}
catch(ThreadedClasses.ReturnValueException<SendRemoteDataRequest> e)
{
return e.Value;
}
return null;
}
public void RemoveCompletedSRDRequest(UUID id)
{
m_pendingSRDResponses.Remove(id);
}
public void CancelSRDRequests(UUID itemID)
{
/* standard foreach makes a copy first on RwLockedDictionary */
foreach (SendRemoteDataRequest li in m_pendingSRDResponses.Values)
{
if (li.ItemID.Equals(itemID))
m_pendingSRDResponses.Remove(li.GetReqID());
}
}
#endregion
public XmlRpcResponse XmlRpcRemoteData(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable) request.Params[0];
bool GoodXML = (requestData.Contains("Channel") && requestData.Contains("IntValue") &&
requestData.Contains("StringValue"));
if (GoodXML)
{
UUID channel = new UUID((string) requestData["Channel"]);
RPCChannelInfo rpcChanInfo;
if (m_openChannels.TryGetValue(channel, out rpcChanInfo))
{
string intVal = Convert.ToInt32(requestData["IntValue"]).ToString();
string strVal = (string) requestData["StringValue"];
RPCRequestInfo rpcInfo;
rpcInfo =
new RPCRequestInfo(rpcChanInfo.GetLocalID(), rpcChanInfo.GetItemID(), channel, strVal,
intVal);
m_rpcPending.Add(rpcInfo.GetMessageID(), rpcInfo);
int timeoutCtr = 0;
while (!rpcInfo.IsProcessed() && (timeoutCtr < RemoteReplyScriptTimeout))
{
Thread.Sleep(RemoteReplyScriptWait);
timeoutCtr += RemoteReplyScriptWait;
}
if (rpcInfo.IsProcessed())
{
Hashtable param = new Hashtable();
param["StringValue"] = rpcInfo.GetStrRetval();
param["IntValue"] = rpcInfo.GetIntRetval();
ArrayList parameters = new ArrayList();
parameters.Add(param);
response.Value = parameters;
rpcInfo = null;
}
else
{
response.SetFault(-1, "Script timeout");
rpcInfo = null;
}
}
else
{
response.SetFault(-1, "Invalid channel");
}
}
return response;
}
}
public class RPCRequestInfo: IXmlRpcRequestInfo
{
private UUID m_ChannelKey;
private string m_IntVal;
private UUID m_ItemID;
private uint m_localID;
private UUID m_MessageID;
private bool m_processed;
private int m_respInt;
private string m_respStr;
private string m_StrVal;
public RPCRequestInfo(uint localID, UUID itemID, UUID channelKey, string strVal, string intVal)
{
m_localID = localID;
m_StrVal = strVal;
m_IntVal = intVal;
m_ItemID = itemID;
m_ChannelKey = channelKey;
m_MessageID = UUID.Random();
m_processed = false;
m_respStr = String.Empty;
m_respInt = 0;
}
public bool IsProcessed()
{
return m_processed;
}
public UUID GetChannelKey()
{
return m_ChannelKey;
}
public void SetProcessed(bool processed)
{
m_processed = processed;
}
public void SetStrRetval(string resp)
{
m_respStr = resp;
}
public string GetStrRetval()
{
return m_respStr;
}
public void SetIntRetval(int resp)
{
m_respInt = resp;
}
public int GetIntRetval()
{
return m_respInt;
}
public uint GetLocalID()
{
return m_localID;
}
public UUID GetItemID()
{
return m_ItemID;
}
public string GetStrVal()
{
return m_StrVal;
}
public int GetIntValue()
{
return int.Parse(m_IntVal);
}
public UUID GetMessageID()
{
return m_MessageID;
}
}
public class RPCChannelInfo
{
private UUID m_ChannelKey;
private UUID m_itemID;
private uint m_localID;
public RPCChannelInfo(uint localID, UUID itemID, UUID channelID)
{
m_ChannelKey = channelID;
m_localID = localID;
m_itemID = itemID;
}
public UUID GetItemID()
{
return m_itemID;
}
public UUID GetChannelID()
{
return m_ChannelKey;
}
public uint GetLocalID()
{
return m_localID;
}
}
public class SendRemoteDataRequest: IServiceRequest
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Channel;
public string DestURL;
private bool _finished;
public bool Finished
{
get { return _finished; }
set { _finished = value; }
}
private Thread httpThread;
public int Idata;
private UUID _itemID;
public UUID ItemID
{
get { return _itemID; }
set { _itemID = value; }
}
private uint _localID;
public uint LocalID
{
get { return _localID; }
set { _localID = value; }
}
private UUID _reqID;
public UUID ReqID
{
get { return _reqID; }
set { _reqID = value; }
}
public XmlRpcRequest Request;
public int ResponseIdata;
public string ResponseSdata;
public string Sdata;
public SendRemoteDataRequest(uint localID, UUID itemID, string channel, string dest, int idata, string sdata)
{
this.Channel = channel;
DestURL = dest;
this.Idata = idata;
this.Sdata = sdata;
ItemID = itemID;
LocalID = localID;
ReqID = UUID.Random();
}
public void Process()
{
httpThread = new Thread(SendRequest);
httpThread.Name = "HttpRequestThread";
httpThread.Priority = ThreadPriority.BelowNormal;
httpThread.IsBackground = true;
_finished = false;
httpThread.Start();
}
/*
* TODO: More work on the response codes. Right now
* returning 200 for success or 499 for exception
*/
public void SendRequest()
{
Hashtable param = new Hashtable();
// Check if channel is an UUID
// if not, use as method name
UUID parseUID;
string mName = "llRemoteData";
if (!string.IsNullOrEmpty(Channel))
if (!UUID.TryParse(Channel, out parseUID))
mName = Channel;
else
param["Channel"] = Channel;
param["StringValue"] = Sdata;
param["IntValue"] = Convert.ToString(Idata);
ArrayList parameters = new ArrayList();
parameters.Add(param);
XmlRpcRequest req = new XmlRpcRequest(mName, parameters);
try
{
XmlRpcResponse resp = req.Send(DestURL, 30000);
if (resp != null)
{
Hashtable respParms;
if (resp.Value.GetType().Equals(typeof(Hashtable)))
{
respParms = (Hashtable) resp.Value;
}
else
{
ArrayList respData = (ArrayList) resp.Value;
respParms = (Hashtable) respData[0];
}
if (respParms != null)
{
if (respParms.Contains("StringValue"))
{
Sdata = (string) respParms["StringValue"];
}
if (respParms.Contains("IntValue"))
{
Idata = Convert.ToInt32(respParms["IntValue"]);
}
if (respParms.Contains("faultString"))
{
Sdata = (string) respParms["faultString"];
}
if (respParms.Contains("faultCode"))
{
Idata = Convert.ToInt32(respParms["faultCode"]);
}
}
}
}
catch (Exception we)
{
Sdata = we.Message;
m_log.Warn("[SendRemoteDataRequest]: Request failed");
m_log.Warn(we.StackTrace);
}
_finished = true;
}
public void Stop()
{
try
{
httpThread.Abort();
}
catch (Exception)
{
}
}
public UUID GetReqID()
{
return ReqID;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Manifest;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.WebAssets;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.WebAssets
{
public class BackOfficeWebAssets
{
public const string UmbracoPreviewJsBundleName = "umbraco-preview-js";
public const string UmbracoPreviewCssBundleName = "umbraco-preview-css";
public const string UmbracoCssBundleName = "umbraco-backoffice-css";
public const string UmbracoInitCssBundleName = "umbraco-backoffice-init-css";
public const string UmbracoCoreJsBundleName = "umbraco-backoffice-js";
public const string UmbracoExtensionsJsBundleName = "umbraco-backoffice-extensions-js";
public const string UmbracoNonOptimizedPackageJsBundleName = "umbraco-backoffice-non-optimized-js";
public const string UmbracoNonOptimizedPackageCssBundleName = "umbraco-backoffice-non-optimized-css";
public const string UmbracoTinyMceJsBundleName = "umbraco-tinymce-js";
public const string UmbracoUpgradeCssBundleName = "umbraco-authorize-upgrade-css";
private readonly IRuntimeMinifier _runtimeMinifier;
private readonly IManifestParser _parser;
private readonly GlobalSettings _globalSettings;
private readonly CustomBackOfficeAssetsCollection _customBackOfficeAssetsCollection;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly PropertyEditorCollection _propertyEditorCollection;
public BackOfficeWebAssets(
IRuntimeMinifier runtimeMinifier,
IManifestParser parser,
PropertyEditorCollection propertyEditorCollection,
IHostingEnvironment hostingEnvironment,
IOptions<GlobalSettings> globalSettings,
CustomBackOfficeAssetsCollection customBackOfficeAssetsCollection)
{
_runtimeMinifier = runtimeMinifier;
_parser = parser;
_propertyEditorCollection = propertyEditorCollection;
_hostingEnvironment = hostingEnvironment;
_globalSettings = globalSettings.Value;
_customBackOfficeAssetsCollection = customBackOfficeAssetsCollection;
}
public void CreateBundles()
{
// Create bundles
_runtimeMinifier.CreateCssBundle(UmbracoInitCssBundleName,
BundlingOptions.NotOptimizedAndComposite,
FormatPaths(
"assets/css/umbraco.min.css",
"lib/bootstrap-social/bootstrap-social.css",
"lib/font-awesome/css/font-awesome.min.css"));
_runtimeMinifier.CreateCssBundle(UmbracoUpgradeCssBundleName,
BundlingOptions.NotOptimizedAndComposite,
FormatPaths(
"assets/css/umbraco.min.css",
"lib/bootstrap-social/bootstrap-social.css",
"lib/font-awesome/css/font-awesome.min.css"));
_runtimeMinifier.CreateCssBundle(UmbracoPreviewCssBundleName,
BundlingOptions.NotOptimizedAndComposite,
FormatPaths("assets/css/canvasdesigner.min.css"));
_runtimeMinifier.CreateJsBundle(UmbracoPreviewJsBundleName,
BundlingOptions.NotOptimizedAndComposite,
FormatPaths(GetScriptsForPreview()));
_runtimeMinifier.CreateJsBundle(UmbracoTinyMceJsBundleName,
BundlingOptions.NotOptimizedAndComposite,
FormatPaths(GetScriptsForTinyMce()));
_runtimeMinifier.CreateJsBundle(UmbracoCoreJsBundleName,
BundlingOptions.NotOptimizedAndComposite,
FormatPaths(GetScriptsForBackOfficeCore()));
// get the property editor assets
var propertyEditorAssets = ScanPropertyEditors()
.GroupBy(x => x.AssetType)
.ToDictionary(x => x.Key, x => x.Select(c => c.FilePath));
// get the back office custom assets
var customAssets = _customBackOfficeAssetsCollection.GroupBy(x => x.DependencyType).ToDictionary(x => x.Key, x => x.Select(c => c.FilePath));
// This bundle includes all scripts from property editor assets,
// custom back office assets, and any scripts found in package manifests
// that have the default bundle options.
IEnumerable<string> jsAssets = (customAssets.TryGetValue(AssetType.Javascript, out IEnumerable<string> customScripts) ? customScripts : Enumerable.Empty<string>())
.Union(propertyEditorAssets.TryGetValue(AssetType.Javascript, out IEnumerable<string> scripts) ? scripts : Enumerable.Empty<string>());
_runtimeMinifier.CreateJsBundle(
UmbracoExtensionsJsBundleName,
BundlingOptions.OptimizedAndComposite,
FormatPaths(
GetScriptsForBackOfficeExtensions(jsAssets)));
// Create a bundle per package manifest that is declaring an Independent bundle type
RegisterPackageBundlesForIndependentOptions(_parser.CombinedManifest.Scripts, AssetType.Javascript);
// Create a single non-optimized (no file processing) bundle for all manifests declaring None as a bundle option
RegisterPackageBundlesForNoneOption(_parser.CombinedManifest.Scripts, UmbracoNonOptimizedPackageJsBundleName);
// This bundle includes all CSS from property editor assets,
// custom back office assets, and any CSS found in package manifests
// that have the default bundle options.
IEnumerable<string> cssAssets = (customAssets.TryGetValue(AssetType.Css, out IEnumerable<string> customStyles) ? customStyles : Enumerable.Empty<string>())
.Union(propertyEditorAssets.TryGetValue(AssetType.Css, out IEnumerable<string> styles) ? styles : Enumerable.Empty<string>());
_runtimeMinifier.CreateCssBundle(
UmbracoCssBundleName,
BundlingOptions.OptimizedAndComposite,
FormatPaths(
GetStylesheetsForBackOffice(cssAssets)));
// Create a bundle per package manifest that is declaring an Independent bundle type
RegisterPackageBundlesForIndependentOptions(_parser.CombinedManifest.Stylesheets, AssetType.Css);
// Create a single non-optimized (no file processing) bundle for all manifests declaring None as a bundle option
RegisterPackageBundlesForNoneOption(_parser.CombinedManifest.Stylesheets, UmbracoNonOptimizedPackageCssBundleName);
}
public static string GetIndependentPackageBundleName(ManifestAssets manifestAssets, AssetType assetType)
=> $"{manifestAssets.PackageName.ToLowerInvariant()}-{(assetType == AssetType.Css ? "css" : "js")}";
private void RegisterPackageBundlesForNoneOption(
IReadOnlyDictionary<BundleOptions, IReadOnlyList<ManifestAssets>> combinedPackageManifestAssets,
string bundleName)
{
var assets = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
// Create a bundle per package manifest that is declaring the matching BundleOptions
if (combinedPackageManifestAssets.TryGetValue(BundleOptions.None, out IReadOnlyList<ManifestAssets> manifestAssetList))
{
foreach(var asset in manifestAssetList.SelectMany(x => x.Assets))
{
assets.Add(asset);
}
}
_runtimeMinifier.CreateJsBundle(
bundleName,
// no optimization, no composite files, just render individual files
BundlingOptions.NotOptimizedNotComposite,
FormatPaths(assets.ToArray()));
}
private void RegisterPackageBundlesForIndependentOptions(
IReadOnlyDictionary<BundleOptions, IReadOnlyList<ManifestAssets>> combinedPackageManifestAssets,
AssetType assetType)
{
// Create a bundle per package manifest that is declaring the matching BundleOptions
if (combinedPackageManifestAssets.TryGetValue(BundleOptions.Independent, out IReadOnlyList<ManifestAssets> manifestAssetList))
{
foreach (ManifestAssets manifestAssets in manifestAssetList)
{
string bundleName = GetIndependentPackageBundleName(manifestAssets, assetType);
string[] filePaths = FormatPaths(manifestAssets.Assets.ToArray());
switch (assetType)
{
case AssetType.Javascript:
_runtimeMinifier.CreateJsBundle(bundleName, BundlingOptions.OptimizedAndComposite, filePaths);
break;
case AssetType.Css:
_runtimeMinifier.CreateCssBundle(bundleName, BundlingOptions.OptimizedAndComposite, filePaths);
break;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Returns scripts used to load the back office
/// </summary>
/// <returns></returns>
private string[] GetScriptsForBackOfficeExtensions(IEnumerable<string> propertyEditorScripts)
{
var scripts = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
// only include scripts with the default bundle options here
if (_parser.CombinedManifest.Scripts.TryGetValue(BundleOptions.Default, out IReadOnlyList<ManifestAssets> manifestAssets))
{
foreach (string script in manifestAssets.SelectMany(x => x.Assets))
{
scripts.Add(script);
}
}
foreach (string script in propertyEditorScripts)
{
scripts.Add(script);
}
return scripts.ToArray();
}
/// <summary>
/// Returns the list of scripts for back office initialization
/// </summary>
/// <returns></returns>
private string[] GetScriptsForBackOfficeCore()
{
var resources = JsonConvert.DeserializeObject<JArray>(Resources.JsInitialize);
return resources.Where(x => x.Type == JTokenType.String).Select(x => x.ToString()).ToArray();
}
/// <summary>
/// Returns stylesheets used to load the back office
/// </summary>
/// <returns></returns>
private string[] GetStylesheetsForBackOffice(IEnumerable<string> propertyEditorStyles)
{
var stylesheets = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
// only include css with the default bundle options here
if (_parser.CombinedManifest.Stylesheets.TryGetValue(BundleOptions.Default, out IReadOnlyList<ManifestAssets> manifestAssets))
{
foreach (string script in manifestAssets.SelectMany(x => x.Assets))
{
stylesheets.Add(script);
}
}
foreach (string stylesheet in propertyEditorStyles)
{
stylesheets.Add(stylesheet);
}
return stylesheets.ToArray();
}
/// <summary>
/// Returns the scripts used for tinymce
/// </summary>
/// <returns></returns>
private string[] GetScriptsForTinyMce()
{
var resources = JsonConvert.DeserializeObject<JArray>(Resources.TinyMceInitialize);
return resources.Where(x => x.Type == JTokenType.String).Select(x => x.ToString()).ToArray();
}
/// <summary>
/// Returns the scripts used for preview
/// </summary>
/// <returns></returns>
private string[] GetScriptsForPreview()
{
var resources = JsonConvert.DeserializeObject<JArray>(Resources.PreviewInitialize);
return resources.Where(x => x.Type == JTokenType.String).Select(x => x.ToString()).ToArray();
}
/// <summary>
/// Re-format asset paths to be absolute paths
/// </summary>
/// <param name="assets"></param>
/// <returns></returns>
private string[] FormatPaths(params string[] assets)
{
var umbracoPath = _globalSettings.GetUmbracoMvcArea(_hostingEnvironment);
return assets
.Where(x => x.IsNullOrWhiteSpace() == false)
.Select(x => !x.StartsWith("/") && Uri.IsWellFormedUriString(x, UriKind.Relative)
// most declarations with be made relative to the /umbraco folder, so things
// like lib/blah/blah.js so we need to turn them into absolutes here
? umbracoPath.EnsureStartsWith('/').TrimEnd("/") + x.EnsureStartsWith('/')
: x).ToArray();
}
/// <summary>
/// Returns the web asset paths to load for property editors that have the <see cref="PropertyEditorAssetAttribute"/> attribute applied
/// </summary>
/// <returns></returns>
private IEnumerable<PropertyEditorAssetAttribute> ScanPropertyEditors()
{
return _propertyEditorCollection
.SelectMany(x => x.GetType().GetCustomAttributes<PropertyEditorAssetAttribute>(false));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Newtonsoft.Json.Linq;
using Mandrill.Model;
using Xunit;
namespace Tests
{
[Trait("Category", "messages")]
[Collection("messages")]
public class Messages : IntegrationTest
{
public Messages()
{
FromEmail = "mandrill.net@" +
(Environment.GetEnvironmentVariable("MANDRILL_SENDING_DOMAIN") ?? "test.mandrillapp.com");
}
public string FromEmail { get; set; }
static void AssertResults(IEnumerable<MandrillSendMessageResponse> result)
{
foreach (var response in result)
{
if (response.Status == MandrillSendMessageResponseStatus.Invalid)
{
Assert.True(false, "invalid email: " + response.RejectReason);
}
if (response.Status == MandrillSendMessageResponseStatus.Rejected &&
response.RejectReason == "unsigned")
{
Console.Error.WriteLine("unsigned sending domain");
break;
}
if (response.Status == MandrillSendMessageResponseStatus.Rejected)
{
Assert.True(false, "rejected email: " + response.RejectReason);
}
if (response.Status == MandrillSendMessageResponseStatus.Queued ||
response.Status == MandrillSendMessageResponseStatus.Sent)
{
break;
}
Assert.True(false, "Unexptected status:" + response.Status);
}
}
[Trait("Category", "messages/cancel_scheduled.json")]
public class CancelScheduled : Messages
{
[Fact]
public async Task Can_cancel_scheduled()
{
var list = await Api.Messages.ListScheduledAsync();
var schedule = list.LastOrDefault();
if (schedule != null)
{
var result = await Api.Messages.CancelScheduledAsync(schedule.Id);
result.Id.Should().Be(schedule.Id);
}
else
{
Console.Error.WriteLine("no scheduled results");
}
}
}
[Trait("Category", "messages/content.json")]
public class Content : Messages
{
[Fact]
public async Task Can_retrieve_content()
{
var results = await Api.Messages.SearchAsync(null, DateTime.Today.AddDays(-1));
//the api doesn't return results immediately, it may return no results.
//Also, the content may not be around > 24 hrs
var found = results.Where(x => x.Ts > DateTime.UtcNow.AddHours(-24))
.OrderBy(x => x.Ts)
.FirstOrDefault(x => x.State == MandrillMessageState.Sent);
if (found != null)
{
var result = await Api.Messages.ContentAsync(found.Id);
result.Should().NotBeNull();
var content = result.Html ?? result.Text;
content.Should().NotBeNullOrWhiteSpace();
}
else
{
Console.Error.WriteLine("no results were found yet, try again in a few minutes");
}
}
[Fact]
public async Task Throws_when_not_found()
{
var mandrillException = await Assert.ThrowsAsync<MandrillException>(() => Api.Messages.ContentAsync(Guid.NewGuid().ToString("N")));
mandrillException.Name.Should().Be("Unknown_Message");
}
[Fact]
public async Task Throws_when_not_found_sync()
{
var mandrillException = await Assert.ThrowsAsync<MandrillException>(() => Api.Messages.ContentAsync(Guid.NewGuid().ToString("N")));
mandrillException.Name.Should().Be("Unknown_Message");
Debug.WriteLine(mandrillException);
}
}
[Trait("Category", "messages/info.json")]
public class Info : Messages
{
[Fact]
public async Task Can_retrieve_info()
{
var results = await Api.Messages.SearchAsync("email:example.com");
//the api doesn't return results immediately, it may return no results
var found = results.OrderBy(x => x.Ts).FirstOrDefault();
if (found != null)
{
var result = await Api.Messages.InfoAsync(found.Id);
result.Should().NotBeNull();
result.Id.Should().Be(found.Id);
}
else
{
Console.Error.WriteLine("no results were found yet, try again in a few minutes");
}
}
[Fact]
public async Task Throws_when_not_found()
{
var mandrillException = await Assert.ThrowsAsync<MandrillException>(() => Api.Messages.InfoAsync(Guid.NewGuid().ToString("N")));
mandrillException.Name.Should().Be("Unknown_Message");
}
}
[Trait("Category", "messages/list_scheduled.json")]
public class ListScheduled : Messages
{
[Fact]
public async Task Can_list_scheduled()
{
var result = await Api.Messages.ListScheduledAsync();
result.Should().NotBeNull();
result.Count.Should().BeGreaterOrEqualTo(0);
}
}
[Trait("Category", "messages/parse.json")]
public class Parse : Messages
{
[Fact]
public async Task Can_parse_raw_message()
{
var rawMessage = $"From: {FromEmail}\nTo: [email protected]\nSubject: Some Subject\n\nSome content.";
var result = await Api.Messages.ParseAsync(rawMessage);
result.Should().NotBeNull();
result.FromEmail.Should().Be(FromEmail);
result.To[0].Email.Should().Be("[email protected]");
result.Subject.Should().Be("Some Subject");
result.Text.Should().Be("Some content.");
}
[Fact]
public async Task Can_parse_full_raw_message_headers()
{
var rawMessage = @"Delivered-To: [email protected]
Received: by 10.36.81.3 with SMTP id e3cs239nzb; Tue, 29 Mar 2005 15:11:47 -0800 (PST)
Return-Path:
Received: from mail.emailprovider.com (mail.emailprovider.com [111.111.11.111]) by mx.gmail.com with SMTP id h19si826631rnb.2005.03.29.15.11.46; Tue, 29 Mar 2005 15:11:47 -0800 (PST)
Message-ID: <[email protected]>
Reply-To: [email protected]
Received: from [11.11.111.111] by mail.emailprovider.com via HTTP; Tue, 29 Mar 2005 15:11:45 PST
Date: Tue, 29 Mar 2005 15:11:45 -0800 (PST)
From: Mr Jones
Subject: Hello
To: Mr Smith
";
var result = await Api.Messages.ParseAsync(rawMessage);
result.Should().NotBeNull();
result.Headers["Received"].Should().BeOfType<JArray>();
((JArray) result.Headers["Received"]).Count.Should().Be(3);
result.Headers["Delivered-To"].Should().BeOfType<string>();
result.Headers["Delivered-To"].Should().Be("[email protected]");
result.ReplyTo.Should().Be("[email protected]");
}
}
[Trait("Category", "messages/reschedule.json")]
public class Reschedule : Messages
{
[Fact]
public async Task Can_reschedule()
{
var list = await Api.Messages.ListScheduledAsync();
var schedule = list.LastOrDefault();
if (schedule != null)
{
var sendAtUtc = DateTime.UtcNow.AddHours(1);
sendAtUtc = new DateTime(sendAtUtc.Year, sendAtUtc.Month, sendAtUtc.Day, sendAtUtc.Hour, sendAtUtc.Minute, sendAtUtc.Second, 0, DateTimeKind.Utc);
var result = await Api.Messages.RescheduleAsync(schedule.Id, sendAtUtc);
result.SendAt.Should().Be(sendAtUtc);
}
else
{
Console.Error.WriteLine("no scheduled messages found.");
}
}
[Fact]
public async Task Throws_on_missing_args()
{
await Assert.ThrowsAsync<ArgumentNullException>(() => Api.Messages.RescheduleAsync(null, DateTime.UtcNow));
}
[Fact]
public async Task Throws_on_invalid_date()
{
await Assert.ThrowsAsync<ArgumentException>(() => Api.Messages.RescheduleAsync("foo", DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local)));
}
}
[Trait("Category", "messages/search.json")]
public class Search : Messages
{
[Fact]
public async Task Can_search_all_params()
{
var results = await Api.Messages.SearchAsync("email:example.com",
DateTime.Today.AddDays(-1),
DateTime.Today.AddDays(1),
new string[0],
new[] {FromEmail},
new[] {ApiKey},
10);
//the api doesn't return results immediately, it may return no results
results.Count.Should().BeLessOrEqualTo(10);
foreach (var result in results)
{
result.Id.Should().NotBeEmpty();
}
if (results.Count == 0)
{
Console.Error.WriteLine("no results were found yet, try again in a few minutes");
}
}
[Fact]
public async Task Can_search_query()
{
var results = await Api.Messages.SearchAsync("email:example.com", limit: 1);
//the api doesn't return results immediately, it may return no results
results.Count.Should().BeLessOrEqualTo(1);
foreach (var result in results)
{
result.Id.Should().NotBeEmpty();
}
if (results.Count == 0)
{
Console.Error.WriteLine("no results were found yet, try again in a few minutes");
}
}
}
[Trait("Category", "messages/search_time_series.json")]
public class SearchTimeSeries : Messages
{
[Fact]
public async Task Can_search_all_params()
{
var results = await Api.Messages.SearchTimeSeriesAsync("email:example.com",
DateTime.Today.AddDays(-1),
DateTime.Today.AddDays(1),
new string[0],
new[] {FromEmail});
foreach (var result in results)
{
result.Clicks.Should().BeGreaterOrEqualTo(0);
}
if (results.Count == 0)
{
Console.Error.WriteLine("no results were found yet, try again in a few minutes");
}
}
[Fact]
public async Task Can_search_open_query()
{
var results = await Api.Messages.SearchTimeSeriesAsync(null);
foreach (var result in results)
{
result.Clicks.Should().BeGreaterOrEqualTo(0);
}
if (results.Count == 0)
{
Console.Error.WriteLine("no results were found yet, try again in a few minutes");
}
}
}
[Trait("Category", "messages/send.json")]
public class Send : Messages
{
[Fact]
public async Task Can_send_message()
{
var message = new MandrillMessage
{
FromEmail = FromEmail,
Subject = "test",
Tags = new List<string>() {"test-send", "mandrill-net"},
To = new List<MandrillMailAddress>()
{
new MandrillMailAddress("[email protected]"),
new MandrillMailAddress("[email protected]", "A test")
},
Text = "This is a test",
Html = @"<html>
<head>
<title>a test</title>
</head>
<body>
<p>this is a test</p>
<img src=""cid:mandrill_logo"">
</body>
</html>"
};
message.Images.Add(new MandrillImage("image/png", "mandrill_logo", TestData.PngImage));
message.Attachments.Add(new MandrillAttachment("text/plain", "message.txt", Encoding.UTF8.GetBytes("This is an attachment.\n")));
var result = await Api.Messages.SendAsync(message);
result.Should().HaveCount(2);
AssertResults(result);
}
[Fact]
public async Task Can_throw_errors_when_error_response()
{
var invalidSubaccount = Guid.NewGuid().ToString("N");
var message = new MandrillMessage
{
FromEmail = FromEmail,
Subject = "test",
Tags = new List<string>() {"test-send-invalid"},
To = new List<MandrillMailAddress>()
{
new MandrillMailAddress("[email protected]")
},
Text = "This is a test",
Subaccount = invalidSubaccount
};
var result = await Assert.ThrowsAsync<MandrillException>(() => Api.Messages.SendAsync(message));
result.Should().NotBeNull();
result.Name.Should().Be("Unknown_Subaccount");
result.Message.Should().Contain(invalidSubaccount);
}
[Fact]
public async Task Can_send_async()
{
var message = new MandrillMessage
{
FromEmail = FromEmail,
Subject = "test",
Tags = new List<string> {"test-send", "mandrill-net"},
To = new List<MandrillMailAddress>()
{
new MandrillMailAddress("[email protected]")
},
Text = "This is a test",
};
var result = await Api.Messages.SendAsync(message, true);
result.Should().HaveCount(1);
AssertResults(result);
}
[Fact]
public async Task Throws_on_missing_args()
{
await Assert.ThrowsAsync<ArgumentNullException>(() => Api.Messages.SendAsync(null, true));
}
[Fact]
public async Task Can_send_scheduled()
{
var message = new MandrillMessage
{
FromEmail = FromEmail,
Subject = "test",
Tags = new List<string>() {"test-send", "mandrill-net"},
To = new List<MandrillMailAddress>()
{
new MandrillMailAddress("[email protected]")
},
Text = "This is a test",
};
var sendAtUtc = DateTime.UtcNow.AddHours(1);
var result = await Api.Messages.SendAsync(message, sendAtUtc: sendAtUtc);
result.Should().HaveCount(1);
result[0].Email.Should().Be("[email protected]");
result[0].Status.Should().Be(MandrillSendMessageResponseStatus.Scheduled);
}
[Fact]
public async Task Throws_if_scheduled_is_not_utc()
{
var message = new MandrillMessage();
var sendAtLocal = DateTime.SpecifyKind(DateTime.Now.AddHours(1), DateTimeKind.Local);
var result = await Assert.ThrowsAsync<ArgumentException>(() => Api.Messages.SendAsync(message, sendAtUtc: sendAtLocal));
result.ParamName.Should().Be("sendAtUtc");
}
}
[Trait("Category", "messages/send_raw.json")]
public class SendRaw : Messages
{
[Fact]
public async Task Can_send_raw_message()
{
var rawMessage = $"From: {FromEmail}\nTo: [email protected]\nSubject: Some Subject\n\nSome content.";
var fromEmail = FromEmail;
var fromName = "From Name";
var to = new[] {"[email protected]"};
bool async = false;
string ipPool = "Main Pool";
DateTime? sendAt = null;
string returnPathDomain = null;
var result = await Api.Messages.SendRawAsync(rawMessage, fromEmail, fromName, to, async, ipPool, sendAt, returnPathDomain);
result.Should().HaveCount(1);
AssertResults(result);
}
}
[Trait("Category", "messages/send_template.json")]
public class SendTemplate : Messages
{
protected string TestTemplateName;
public SendTemplate()
{
TestTemplateName = Guid.NewGuid().ToString();
var result = Api.Templates.AddAsync(TestTemplateName, TemplateContent.Code, TemplateContent.Text, true).GetAwaiter().GetResult();
result.Should().NotBeNull();
}
public override void Dispose()
{
var result = Api.Templates.DeleteAsync(TestTemplateName).GetAwaiter().GetResult();
result.Should().NotBeNull();
}
[Fact]
public async Task Can_send_template()
{
var message = new MandrillMessage
{
FromEmail = FromEmail,
Subject = "test",
Tags = new List<string>() {"test-send-template", "mandrill-net"},
To = new List<MandrillMailAddress>()
{
new MandrillMailAddress("[email protected]", "Test1 User"),
new MandrillMailAddress("[email protected]", "Test2 User")
},
};
message.AddGlobalMergeVars("ORDERDATE", string.Format("{0:d}", DateTime.UtcNow));
message.AddRcptMergeVars("[email protected]", "INVOICEDETAILS", "invoice for [email protected]");
message.AddRcptMergeVars("[email protected]", "INVOICEDETAILS", "invoice for [email protected]");
var result = await Api.Messages.SendTemplateAsync(message, TestTemplateName);
result.Should().HaveCount(2);
AssertResults(result);
}
[Fact]
public async Task Throws_on_missing_args0()
{
var result = await Assert.ThrowsAsync<ArgumentNullException>(() => Api.Messages.SendTemplateAsync(null, TestTemplateName));
}
[Fact]
public async Task Throws_on_missing_args1()
{
var result = await Assert.ThrowsAsync<ArgumentNullException>(() => Api.Messages.SendTemplateAsync(new MandrillMessage(), null));
}
[Fact]
public async Task Throws_on_invalid_date_type()
{
var result = await Assert.ThrowsAsync<ArgumentException>(() => Api.Messages.SendTemplateAsync(new MandrillMessage(), TestTemplateName, sendAtUtc:DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local)));
}
}
[Trait("Category", "messages/send_template.json"), Trait("Category", "handlebars")]
public class SendTemplate_Handlebars : Messages
{
protected string TestTemplateName;
public SendTemplate_Handlebars()
{
TestTemplateName = Guid.NewGuid().ToString();
var result = Api.Templates.AddAsync(TestTemplateName, TemplateContent.HandleBarCode, null, true).GetAwaiter().GetResult();
result.Should().NotBeNull();
}
public override void Dispose()
{
var result = Api.Templates.DeleteAsync(TestTemplateName).GetAwaiter().GetResult();
result.Should().NotBeNull();
base.Dispose();
}
[Fact]
public async Task Can_send_template_string_dictionary()
{
var message = new MandrillMessage
{
FromEmail = FromEmail,
Subject = "test",
Tags = new List<string>() { "test-send-template", "mandrill-net", "handlebars" },
MergeLanguage = MandrillMessageMergeLanguage.Handlebars,
To = new List<MandrillMailAddress>()
{
new MandrillMailAddress("[email protected]", "Test1 User"),
new MandrillMailAddress("[email protected]", "Test2 User")
},
};
var data1 = new[]
{
new Dictionary<string, object>
{
{"sku", "APL43"},
{"name", "apples"},
{"description", "Granny Smith Apples"},
{"price", "0.20"},
{"qty", "8"},
{"ordPrice", "1.60"},
},
new Dictionary<string, object>
{
{"sku", "ORA44"},
{"name", "Oranges"},
{"description", "Blood Oranges"},
{"price", "0.30"},
{"qty", "3"},
{"ordPrice", "0.93"},
}
};
var data2 = new[]
{
new Dictionary<string, object>
{
{"sku", "APL54"},
{"name", "apples"},
{"description", "Red Delicious Apples"},
{"price", "0.22"},
{"qty", "9"},
{"ordPrice", "1.98"},
},
new Dictionary<string, object>
{
{"sku", "ORA53"},
{"name", "Oranges"},
{"description", "Sunkist Oranges"},
{"price", "0.20"},
{"qty", "1"},
{"ordPrice", "0.20"},
}
};
message.AddGlobalMergeVars("ORDERDATE", DateTime.UtcNow.ToString("d"));
message.AddRcptMergeVars("[email protected]", "PRODUCTS", data1);
message.AddRcptMergeVars("[email protected]", "PRODUCTS", data2);
var result = await Api.Messages.SendTemplateAsync(message, TestTemplateName);
result.Should().HaveCount(2);
AssertResults(result);
}
[Fact]
public async Task Can_send_template_object_list()
{
var message = new MandrillMessage
{
FromEmail = FromEmail,
Subject = "test",
Tags = new List<string>() { "test-send-template", "mandrill-net", "handlebars" },
MergeLanguage = MandrillMessageMergeLanguage.Handlebars,
To = new List<MandrillMailAddress>()
{
new MandrillMailAddress("[email protected]", "Test1 User"),
new MandrillMailAddress("[email protected]", "Test2 User")
},
};
var data1 = new[]
{
new Dictionary<string, object>
{
{"sku", "APL43"},
{"name", "apples"},
{"description", "Granny Smith Apples"},
{"price", 0.20},
{"qty", 8},
{"ordPrice", 1.60},
},
new Dictionary<string, object>
{
{"sku", "ORA44"},
{"name", "Oranges"},
{"description", "Blood Oranges"},
{"price", 0.30},
{"qty", 3},
{"ordPrice", 0.93},
}
};
var data2 = new[]
{
new Dictionary<string, object>
{
{"sku", "APL54"},
{"name", "apples"},
{"description", "Red Delicious Apples"},
{"price", 0.22},
{"qty", 9},
{"ordPrice", 1.98},
},
new Dictionary<string, object>
{
{"sku", "ORA53"},
{"name", "Oranges"},
{"description", "Sunkist Oranges"},
{"price", 0.20},
{"qty", 1},
{"ordPrice", 0.20},
}
};
message.AddGlobalMergeVars("ORDERDATE", DateTime.UtcNow.ToString("d"));
message.AddRcptMergeVars("[email protected]", "PRODUCTS", data1);
message.AddRcptMergeVars("[email protected]", "PRODUCTS", data2);
var result = await Api.Messages.SendTemplateAsync(message, TestTemplateName);
result.Should().HaveCount(2);
AssertResults(result);
}
[Fact]
public async Task Can_send_template_dynamic()
{
var message = new MandrillMessage
{
FromEmail = FromEmail,
Subject = "test",
Tags = new List<string>() { "test-send-template", "mandrill-net", "handlebars" },
MergeLanguage = MandrillMessageMergeLanguage.Handlebars,
To = new List<MandrillMailAddress>()
{
new MandrillMailAddress("[email protected]", "Test1 User"),
new MandrillMailAddress("[email protected]", "Test2 User")
},
};
dynamic item1 = new ExpandoObject();
item1.sku = "APL54";
item1.name = "apples";
item1.description = "Red Dynamic Apples";
item1.price = 0.22;
item1.qty = 9;
item1.ordPrice = 1.98;
item1.tags = new {id = "tag1", enabled = true};
dynamic item2 = new ExpandoObject();
item2.sku = "ORA54";
item2.name = "oranges";
item2.description = "Dynamic Oranges";
item2.price = 0.33;
item2.qty = 8;
item2.ordPrice = 2.00;
item2.tags = new { id = "tag2", enabled = false };
message.AddGlobalMergeVars("ORDERDATE", DateTime.UtcNow.ToString("d"));
message.AddGlobalMergeVars("PRODUCTS", new [] { item1, item2 });
var result = await Api.Messages.SendTemplateAsync(message, TestTemplateName);
result.Should().HaveCount(2);
AssertResults(result);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.F1Help
{
public class F1HelpTests
{
private async Task TestAsync(string markup, string expectedText)
{
using (var workspace = await TestWorkspace.CreateCSharpAsync(markup))
{
var caret = workspace.Documents.First().CursorPosition;
var service = new CSharpHelpContextService();
var actualText = await service.GetHelpTermAsync(workspace.CurrentSolution.Projects.First().Documents.First(), workspace.Documents.First().SelectedSpans.First(), CancellationToken.None);
Assert.Equal(expectedText, actualText);
}
}
private async Task Test_KeywordAsync(string markup, string expectedText)
{
await TestAsync(markup, expectedText + "_CSharpKeyword");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestVoid()
{
await Test_KeywordAsync(
@"class C
{
vo[||]id foo()
{
}
}", "void");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestReturn()
{
await Test_KeywordAsync(
@"class C
{
void foo()
{
ret[||]urn;
}
}", "return");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestPartialType()
{
await Test_KeywordAsync(
@"part[||]ial class C
{
partial void foo();
}", "partialtype");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestPartialMethod()
{
await Test_KeywordAsync(
@"partial class C
{
par[||]tial void foo();
}", "partialmethod");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestWhereClause()
{
await Test_KeywordAsync(
@"using System.Linq;
class Program<T> where T : class
{
void foo(string[] args)
{
var x = from a in args
whe[||]re a.Length > 0
select a;
}
}", "whereclause");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestWhereConstraint()
{
await Test_KeywordAsync(
@"using System.Linq;
class Program<T> wh[||]ere T : class
{
void foo(string[] args)
{
var x = from a in args
where a.Length > 0
select a;
}
}", "whereconstraint");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestPreprocessor()
{
await TestAsync(
@"#regi[||]on
#endregion", "#region");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestConstructor()
{
await TestAsync(
@"namespace N
{
class C
{
void foo()
{
var x = new [|C|]();
}
}
}", "N.C.#ctor");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestGenericClass()
{
await TestAsync(
@"namespace N
{
class C<T>
{
void foo()
{
[|C|]<int> c;
}
}
}", "N.C`1");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestGenericMethod()
{
await TestAsync(
@"namespace N
{
class C<T>
{
void foo<T, U, V>(T t, U u, V v)
{
C<int> c;
c.f[|oo|](1, 1, 1);
}
}
}", "N.C`1.foo``3");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestOperator()
{
await TestAsync(
@"namespace N
{
class C
{
void foo()
{
var two = 1 [|+|] 1;
}
}", "+_CSharpKeyword");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestVar()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var[||] x = 3;
}
}", "var_CSharpKeyword");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestEquals()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var x =[||] 3;
}
}", "=_CSharpKeyword");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestFromIn()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var x = from n i[||]n {
1}
select n
}
}", "from_CSharpKeyword");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestProperty()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
new UriBuilder().Fragm[||]ent;
}
}", "System.UriBuilder.Fragment");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestForeachIn()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
foreach (var x in[||] {
1} )
{
}
}
}", "in_CSharpKeyword");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestRegionDescription()
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
#region Begin MyR[||]egion for testing
#endregion End
}
}", "#region");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestGenericAngle()
{
await TestAsync(
@"class Program
{
static void generic<T>(T t)
{
generic[||]<int>(0);
}
}", "Program.generic``1");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestLocalReferenceIsType()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
int x;
x[||];
}
}", "System.Int32");
}
[WorkItem(864266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864266")]
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestConstantField()
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
var i = int.Ma[||]xValue;
}
}", "System.Int32.MaxValue");
}
[WorkItem(862420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862420")]
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestParameter()
{
await TestAsync(
@"class Class2
{
void M1(int par[||]ameter) // 1
{
}
void M2()
{
int argument = 1;
M1(parameter: argument); // 2
}
}", "System.Int32");
}
[WorkItem(862420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862420")]
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestArgumentType()
{
await TestAsync(
@"class Class2
{
void M1(int pa[||]rameter) // 1
{
}
void M2()
{
int argument = 1;
M1(parameter: argument); // 2
}
}", "System.Int32");
}
[WorkItem(862396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862396")]
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestNoToken()
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
}
}[||]", "");
}
[WorkItem(862328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862328")]
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestLiteral()
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
Main(new string[] { ""fo[||]o"" });
}
}", "System.String");
}
[WorkItem(862478, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862478")]
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestColonColon()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
global:[||]:System.Console.Write("");
}
}", "::_CSharpKeyword");
}
[WorkItem(864658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864658")]
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestNullable()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
int?[||] a = int.MaxValue;
a.Value.GetHashCode();
}
}", "System.Nullable`1");
}
[WorkItem(863517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/863517")]
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestAfterLastToken()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
foreach (char var in ""!!!"")$$[||]
{
}
}
}", "");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestConditional()
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
var x = true [|?|] true : false;
}
}", "?_CSharpKeyword");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestLocalVar()
{
await TestAsync(
@"class C
{
void M()
{
var a = 0;
int v[||]ar = 1;
}
}", "System.Int32");
}
[WorkItem(867574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/867574")]
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestFatArrow()
{
await TestAsync(
@"class C
{
void M()
{
var a = new System.Action(() =[||]> {
});
}
}", "=>_CSharpKeyword");
}
[WorkItem(867572, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/867572")]
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestSubscription()
{
await TestAsync(
@"class CCC
{
event System.Action e;
void M()
{
e +[||]= () => {
};
}
}", "CCC.e.add");
}
[WorkItem(867554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/867554")]
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestComment()
{
await TestAsync(@"// some comm[||]ents here", "comments");
}
[WorkItem(867529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/867529")]
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestDynamic()
{
await TestAsync(
@"class C
{
void M()
{
dyna[||]mic d = 0;
}
}", "dynamic_CSharpKeyword");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestRangeVariable()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var zzz = from y in args
select [||]y;
}
}", "System.String");
}
}
}
| |
//TODO - add serializer (?)
//http://wiki.superfamicom.org/snes/show/Backgrounds
//TODO
//libsnes needs to be modified to support multiple instances - THIS IS NECESSARY - or else loading one game and then another breaks things
// edit - this is a lot of work
//wrap dll code around some kind of library-accessing interface so that it doesnt malfunction if the dll is unavailable
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using BizHawk.Common;
using BizHawk.Common.BufferExtensions;
using BizHawk.Emulation.Common;
namespace BizHawk.Emulation.Cores.Nintendo.SNES
{
[CoreAttributes(
"BSNES",
"byuu",
isPorted: true,
isReleased: true,
portedVersion: "v87",
portedUrl: "http://byuu.org/"
)]
[ServiceNotApplicable(typeof(IDriveLight))]
public unsafe class LibsnesCore : IEmulator, IVideoProvider, ISaveRam, IStatable, IInputPollable, IRegionable, ICodeDataLogger,
IDebuggable, ISettable<LibsnesCore.SnesSettings, LibsnesCore.SnesSyncSettings>
{
public LibsnesCore(GameInfo game, byte[] romData, bool deterministicEmulation, byte[] xmlData, CoreComm comm, object Settings, object SyncSettings)
{
ServiceProvider = new BasicServiceProvider(this);
MemoryCallbacks = new MemoryCallbackSystem();
Tracer = new TraceBuffer
{
Header = "65816: PC, mnemonic, operands, registers (A, X, Y, S, D, DB, flags (NVMXDIZC), V, H)"
};
(ServiceProvider as BasicServiceProvider).Register<ITraceable>(Tracer);
(ServiceProvider as BasicServiceProvider).Register<IDisassemblable>(new BizHawk.Emulation.Cores.Components.W65816.W65816_DisassemblerService());
_game = game;
CoreComm = comm;
byte[] sgbRomData = null;
if (game["SGB"])
{
if ((romData[0x143] & 0xc0) == 0xc0)
throw new CGBNotSupportedException();
sgbRomData = CoreComm.CoreFileProvider.GetFirmware("SNES", "Rom_SGB", true, "SGB Rom is required for SGB emulation.");
game.FirmwareHash = sgbRomData.HashSHA1();
}
this.Settings = (SnesSettings)Settings ?? new SnesSettings();
this.SyncSettings = (SnesSyncSettings)SyncSettings ?? new SnesSyncSettings();
api = new LibsnesApi(GetDllPath());
api.ReadHook = ReadHook;
api.ExecHook = ExecHook;
api.WriteHook = WriteHook;
ScanlineHookManager = new MyScanlineHookManager(this);
api.CMD_init();
api.QUERY_set_video_refresh(snes_video_refresh);
api.QUERY_set_input_poll(snes_input_poll);
api.QUERY_set_input_state(snes_input_state);
api.QUERY_set_input_notify(snes_input_notify);
api.QUERY_set_path_request(snes_path_request);
scanlineStart_cb = new LibsnesApi.snes_scanlineStart_t(snes_scanlineStart);
tracecb = new LibsnesApi.snes_trace_t(snes_trace);
soundcb = new LibsnesApi.snes_audio_sample_t(snes_audio_sample);
api.QUERY_set_audio_sample(soundcb);
RefreshPalette();
// start up audio resampler
InitAudio();
//strip header
if (romData != null)
if ((romData.Length & 0x7FFF) == 512)
{
var newData = new byte[romData.Length - 512];
Array.Copy(romData, 512, newData, 0, newData.Length);
romData = newData;
}
if (game["SGB"])
{
IsSGB = true;
SystemId = "SNES";
BoardName = "SGB";
CurrLoadParams = new LoadParams()
{
type = LoadParamType.SuperGameBoy,
rom_xml = null,
rom_data = sgbRomData,
rom_size = (uint)sgbRomData.Length,
dmg_xml = null,
dmg_data = romData,
dmg_size = (uint)romData.Length
};
if (!LoadCurrent())
throw new Exception("snes_load_cartridge_normal() failed");
}
else
{
//we may need to get some information out of the cart, even during the following bootup/load process
if (xmlData != null)
{
romxml = new System.Xml.XmlDocument();
romxml.Load(new MemoryStream(xmlData));
//bsnes wont inspect the xml to load the necessary sfc file.
//so, we have to do that here and pass it in as the romData :/
if (romxml["cartridge"] != null && romxml["cartridge"]["rom"] != null)
romData = File.ReadAllBytes(CoreComm.CoreFileProvider.PathSubfile(romxml["cartridge"]["rom"].Attributes["name"].Value));
else
throw new Exception("Could not find rom file specification in xml file. Please check the integrity of your xml file");
}
SystemId = "SNES";
CurrLoadParams = new LoadParams()
{
type = LoadParamType.Normal,
xml_data = xmlData,
rom_data = romData
};
if (!LoadCurrent())
throw new Exception("snes_load_cartridge_normal() failed");
}
if (api.QUERY_get_region() == LibsnesApi.SNES_REGION.NTSC)
{
//similar to what aviout reports from snes9x and seems logical from bsnes first principles. bsnes uses that numerator (ntsc master clockrate) for sure.
CoreComm.VsyncNum = 21477272;
CoreComm.VsyncDen = 4 * 341 * 262;
}
else
{
//http://forums.nesdev.com/viewtopic.php?t=5367&start=19
CoreComm.VsyncNum = 21281370;
CoreComm.VsyncDen = 4 * 341 * 312;
}
api.CMD_power();
SetupMemoryDomains(romData, sgbRomData);
DeterministicEmulation = deterministicEmulation;
if (DeterministicEmulation) // save frame-0 savestate now
{
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(CoreSaveState());
bw.Write(true); // framezero, so no controller follows and don't frameadvance on load
// hack: write fake dummy controller info
bw.Write(new byte[536]);
bw.Close();
savestatebuff = ms.ToArray();
}
}
CodeDataLog currCdl;
public void SetCDL(CodeDataLog cdl)
{
if(currCdl != null) currCdl.Unpin();
currCdl = cdl;
if(currCdl != null) currCdl.Pin();
//set it no matter what. if its null, the cdl will be unhooked from libsnes internally
api.QUERY_set_cdl(currCdl);
}
public void NewCDL(CodeDataLog cdl)
{
cdl["CARTROM"] = new byte[MemoryDomains["CARTROM"].Size];
if (MemoryDomains.Has("CARTRAM"))
cdl["CARTRAM"] = new byte[MemoryDomains["CARTRAM"].Size];
cdl["WRAM"] = new byte[MemoryDomains["WRAM"].Size];
cdl["APURAM"] = new byte[MemoryDomains["APURAM"].Size];
cdl.SubType = "SNES";
cdl.SubVer = 0;
}
public void DisassembleCDL(Stream s, CodeDataLog cdl)
{
//not supported yet
}
public IEmulatorServiceProvider ServiceProvider { get; private set; }
private GameInfo _game;
public string CurrentProfile
{
get
{
// TODO: This logic will only work until Accuracy is ready, would we really want to override the user's choice of Accuracy with Compatibility?
if (_game.OptionValue("profile") == "Compatibility")
{
return "Compatibility";
}
return SyncSettings.Profile;
}
}
public bool IsSGB { get; private set; }
/// <summary>disable all external callbacks. the front end should not even know the core is frame advancing</summary>
bool nocallbacks = false;
bool disposed = false;
public void Dispose()
{
if (disposed) return;
disposed = true;
api.CMD_unload_cartridge();
api.CMD_term();
resampler.Dispose();
api.Dispose();
if (currCdl != null) currCdl.Unpin();
}
public IDictionary<string, RegisterValue> GetCpuFlagsAndRegisters()
{
LibsnesApi.CpuRegs regs;
api.QUERY_peek_cpu_regs(out regs);
bool fn = (regs.p & 0x80)!=0;
bool fv = (regs.p & 0x40)!=0;
bool fm = (regs.p & 0x20)!=0;
bool fx = (regs.p & 0x10)!=0;
bool fd = (regs.p & 0x08)!=0;
bool fi = (regs.p & 0x04)!=0;
bool fz = (regs.p & 0x02)!=0;
bool fc = (regs.p & 0x01)!=0;
return new Dictionary<string, RegisterValue>
{
{ "PC", regs.pc },
{ "A", regs.a },
{ "X", regs.x },
{ "Y", regs.y },
{ "Z", regs.z },
{ "S", regs.s },
{ "D", regs.d },
{ "Vector", regs.vector },
{ "P", regs.p },
{ "AA", regs.aa },
{ "RD", regs.rd },
{ "SP", regs.sp },
{ "DP", regs.dp },
{ "DB", regs.db },
{ "MDR", regs.mdr },
{ "Flag N", fn },
{ "Flag V", fv },
{ "Flag M", fm },
{ "Flag X", fx },
{ "Flag D", fd },
{ "Flag I", fi },
{ "Flag Z", fz },
{ "Flag C", fc },
};
}
private readonly InputCallbackSystem _inputCallbacks = new InputCallbackSystem();
// TODO: optimize managed to unmanaged using the ActiveChanged event
public IInputCallbackSystem InputCallbacks { get { return _inputCallbacks; } }
public ITraceable Tracer { get; private set; }
public IMemoryCallbackSystem MemoryCallbacks { get; private set; }
public bool CanStep(StepType type) { return false; }
[FeatureNotImplemented]
public void Step(StepType type) { throw new NotImplementedException(); }
[FeatureNotImplemented]
public void SetCpuRegister(string register, int value)
{
throw new NotImplementedException();
}
public class MyScanlineHookManager : ScanlineHookManager
{
public MyScanlineHookManager(LibsnesCore core)
{
this.core = core;
}
LibsnesCore core;
public override void OnHooksChanged()
{
core.OnScanlineHooksChanged();
}
}
public MyScanlineHookManager ScanlineHookManager;
void OnScanlineHooksChanged()
{
if (disposed) return;
if (ScanlineHookManager.HookCount == 0) api.QUERY_set_scanlineStart(null);
else api.QUERY_set_scanlineStart(scanlineStart_cb);
}
void snes_scanlineStart(int line)
{
ScanlineHookManager.HandleScanline(line);
}
string snes_path_request(int slot, string hint)
{
//every rom requests msu1.rom... why? who knows.
//also handle msu-1 pcm files here
bool is_msu1_rom = hint == "msu1.rom";
bool is_msu1_pcm = Path.GetExtension(hint).ToLower() == ".pcm";
if (is_msu1_rom || is_msu1_pcm)
{
//well, check if we have an msu-1 xml
if (romxml != null && romxml["cartridge"] != null && romxml["cartridge"]["msu1"] != null)
{
var msu1 = romxml["cartridge"]["msu1"];
if (is_msu1_rom && msu1["rom"].Attributes["name"] != null)
return CoreComm.CoreFileProvider.PathSubfile(msu1["rom"].Attributes["name"].Value);
if (is_msu1_pcm)
{
//return @"D:\roms\snes\SuperRoadBlaster\SuperRoadBlaster-1.pcm";
//return "";
int wantsTrackNumber = int.Parse(hint.Replace("track-", "").Replace(".pcm", ""));
wantsTrackNumber++;
string wantsTrackString = wantsTrackNumber.ToString();
foreach (var child in msu1.ChildNodes.Cast<XmlNode>())
{
if (child.Name == "track" && child.Attributes["number"].Value == wantsTrackString)
return CoreComm.CoreFileProvider.PathSubfile(child.Attributes["name"].Value);
}
}
}
//not found.. what to do? (every rom will get here when msu1.rom is requested)
return "";
}
// not MSU-1. ok.
string firmwareID;
switch (hint)
{
case "cx4.rom": firmwareID = "CX4"; break;
case "dsp1.rom": firmwareID = "DSP1"; break;
case "dsp1b.rom": firmwareID = "DSP1b"; break;
case "dsp2.rom": firmwareID = "DSP2"; break;
case "dsp3.rom": firmwareID = "DSP3"; break;
case "dsp4.rom": firmwareID = "DSP4"; break;
case "st010.rom": firmwareID = "ST010"; break;
case "st011.rom": firmwareID = "ST011"; break;
case "st018.rom": firmwareID = "ST018"; break;
default:
CoreComm.ShowMessage(string.Format("Unrecognized SNES firmware request \"{0}\".", hint));
return "";
}
//build romfilename
string test = CoreComm.CoreFileProvider.GetFirmwarePath("SNES", firmwareID, false, "Game may function incorrectly without the requested firmware.");
//we need to return something to bsnes
test = test ?? "";
Console.WriteLine("Served libsnes request for firmware \"{0}\" with \"{1}\"", hint, test);
//return the path we built
return test;
}
void snes_trace(string msg)
{
// TODO: get them out of the core split up and remove this hackery
string splitStr = "A:";
var split = msg.Split(new[] {splitStr }, 2, StringSplitOptions.None);
Tracer.Put(new TraceInfo
{
Disassembly = split[0].PadRight(34),
RegisterInfo = splitStr + split[1]
});
}
public SnesColors.ColorType CurrPalette { get; private set; }
public void SetPalette(SnesColors.ColorType pal)
{
CurrPalette = pal;
int[] tmp = SnesColors.GetLUT(pal);
fixed (int* p = &tmp[0])
api.QUERY_set_color_lut((IntPtr)p);
}
public LibsnesApi api;
System.Xml.XmlDocument romxml;
string GetDllPath()
{
var exename = "libsneshawk-32-" + CurrentProfile.ToLower() + ".dll";
string dllPath = Path.Combine(CoreComm.CoreFileProvider.DllPath(), exename);
if (!File.Exists(dllPath))
throw new InvalidOperationException("Couldn't locate the DLL for SNES emulation for profile: " + CurrentProfile + ". Please make sure you're using a fresh dearchive of a BizHawk distribution.");
return dllPath;
}
void ReadHook(uint addr)
{
MemoryCallbacks.CallReads(addr);
//we RefreshMemoryCallbacks() after the trigger in case the trigger turns itself off at that point
//EDIT: for now, theres some IPC re-entrancy problem
//RefreshMemoryCallbacks();
api.SPECIAL_Resume();
}
void ExecHook(uint addr)
{
MemoryCallbacks.CallExecutes(addr);
//we RefreshMemoryCallbacks() after the trigger in case the trigger turns itself off at that point
//EDIT: for now, theres some IPC re-entrancy problem
//RefreshMemoryCallbacks();
api.SPECIAL_Resume();
}
void WriteHook(uint addr, byte val)
{
MemoryCallbacks.CallWrites(addr);
//we RefreshMemoryCallbacks() after the trigger in case the trigger turns itself off at that point
//EDIT: for now, theres some IPC re-entrancy problem
//RefreshMemoryCallbacks();
api.SPECIAL_Resume();
}
LibsnesApi.snes_scanlineStart_t scanlineStart_cb;
LibsnesApi.snes_trace_t tracecb;
LibsnesApi.snes_audio_sample_t soundcb;
enum LoadParamType
{
Normal, SuperGameBoy
}
struct LoadParams
{
public LoadParamType type;
public byte[] xml_data;
public string rom_xml;
public byte[] rom_data;
public uint rom_size;
public string dmg_xml;
public byte[] dmg_data;
public uint dmg_size;
}
LoadParams CurrLoadParams;
bool LoadCurrent()
{
bool result = false;
if (CurrLoadParams.type == LoadParamType.Normal)
result = api.CMD_load_cartridge_normal(CurrLoadParams.xml_data, CurrLoadParams.rom_data);
else result = api.CMD_load_cartridge_super_game_boy(CurrLoadParams.rom_xml, CurrLoadParams.rom_data, CurrLoadParams.rom_size, CurrLoadParams.dmg_xml, CurrLoadParams.dmg_data, CurrLoadParams.dmg_size);
mapper = api.QUERY_get_mapper();
return result;
}
/// <summary>
///
/// </summary>
/// <param name="port">0 or 1, corresponding to L and R physical ports on the snes</param>
/// <param name="device">LibsnesApi.SNES_DEVICE enum index specifying type of device</param>
/// <param name="index">meaningless for most controllers. for multitap, 0-3 for which multitap controller</param>
/// <param name="id">button ID enum; in the case of a regular controller, this corresponds to shift register position</param>
/// <returns>for regular controllers, one bit D0 of button status. for other controls, varying ranges depending on id</returns>
ushort snes_input_state(int port, int device, int index, int id)
{
// as this is implemented right now, only P1 and P2 normal controllers work
// port = 0, oninputpoll = 2: left port was strobed
// port = 1, oninputpoll = 3: right port was strobed
// InputCallbacks.Call();
//Console.WriteLine("{0} {1} {2} {3}", port, device, index, id);
string key = "P" + (1 + port) + " ";
if ((LibsnesApi.SNES_DEVICE)device == LibsnesApi.SNES_DEVICE.JOYPAD)
{
switch ((LibsnesApi.SNES_DEVICE_ID)id)
{
case LibsnesApi.SNES_DEVICE_ID.JOYPAD_A: key += "A"; break;
case LibsnesApi.SNES_DEVICE_ID.JOYPAD_B: key += "B"; break;
case LibsnesApi.SNES_DEVICE_ID.JOYPAD_X: key += "X"; break;
case LibsnesApi.SNES_DEVICE_ID.JOYPAD_Y: key += "Y"; break;
case LibsnesApi.SNES_DEVICE_ID.JOYPAD_UP: key += "Up"; break;
case LibsnesApi.SNES_DEVICE_ID.JOYPAD_DOWN: key += "Down"; break;
case LibsnesApi.SNES_DEVICE_ID.JOYPAD_LEFT: key += "Left"; break;
case LibsnesApi.SNES_DEVICE_ID.JOYPAD_RIGHT: key += "Right"; break;
case LibsnesApi.SNES_DEVICE_ID.JOYPAD_L: key += "L"; break;
case LibsnesApi.SNES_DEVICE_ID.JOYPAD_R: key += "R"; break;
case LibsnesApi.SNES_DEVICE_ID.JOYPAD_SELECT: key += "Select"; break;
case LibsnesApi.SNES_DEVICE_ID.JOYPAD_START: key += "Start"; break;
default: return 0;
}
return (ushort)(Controller[key] ? 1 : 0);
}
return 0;
}
void snes_input_poll()
{
// this doesn't actually correspond to anything in the underlying bsnes;
// it gets called once per frame with video_refresh() and has nothing to do with anything
}
void snes_input_notify(int index)
{
// gets called with the following numbers:
// 4xxx : lag frame related
// 0: signifies latch bit going to 0. should be reported as oninputpoll
// 1: signifies latch bit going to 1. should be reported as oninputpoll
if (index >= 0x4000)
IsLagFrame = false;
}
void snes_video_refresh(int* data, int width, int height)
{
bool doubleSize = Settings.AlwaysDoubleSize;
bool lineDouble = doubleSize, dotDouble = doubleSize;
vidWidth = width;
vidHeight = height;
int yskip = 1, xskip = 1;
//if we are in high-res mode, we get double width. so, lets double the height here to keep it square.
if (width == 512)
{
vidHeight *= 2;
yskip = 2;
lineDouble = true;
//we dont dot double here because the user wanted double res and the game provided double res
dotDouble = false;
}
else if (lineDouble)
{
vidHeight *= 2;
yskip = 2;
}
int srcPitch = 1024;
int srcStart = 0;
bool interlaced = (height == 478 || height == 448);
if (interlaced)
{
//from bsnes in interlaced mode we have each field side by side
//so we will come in with a dimension of 512x448, say
//but the fields are side by side, so it's actually 1024x224.
//copy the first scanline from row 0, then the 2nd scanline from row 0 (offset 512)
//EXAMPLE: yu yu hakushu legal screens
//EXAMPLE: World Class Service Super Nintendo Tester (double resolution vertically but not horizontally, in character test the stars should shrink)
lineDouble = false;
srcPitch = 512;
yskip = 1;
vidHeight = height;
}
if (dotDouble)
{
vidWidth *= 2;
xskip = 2;
}
int size = vidWidth * vidHeight;
if (vidBuffer.Length != size)
vidBuffer = new int[size];
for (int j = 0; j < 2; j++)
{
if (j == 1 && !dotDouble) break;
int xbonus = j;
for (int i = 0; i < 2; i++)
{
//potentially do this twice, if we need to line double
if (i == 1 && !lineDouble) break;
int bonus = i * vidWidth + xbonus;
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
int si = y * srcPitch + x + srcStart;
int di = y * vidWidth * yskip + x * xskip + bonus;
int rgb = data[si];
vidBuffer[di] = rgb;
}
}
}
}
public void FrameAdvance(bool render, bool rendersound)
{
api.MessageCounter = 0;
if(Settings.UseRingBuffer)
api.BeginBufferIO();
/* if the input poll callback is called, it will set this to false
* this has to be done before we save the per-frame state in deterministic
* mode, because in there, the core actually advances, and might advance
* through the point in time where IsLagFrame gets set to false. makes sense?
*/
IsLagFrame = true;
if (!nocallbacks && Tracer.Enabled)
api.QUERY_set_trace_callback(tracecb);
else
api.QUERY_set_trace_callback(null);
// for deterministic emulation, save the state we're going to use before frame advance
// don't do this during nocallbacks though, since it's already been done
if (!nocallbacks && DeterministicEmulation)
{
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(CoreSaveState());
bw.Write(false); // not framezero
SnesSaveController ssc = new SnesSaveController();
ssc.CopyFrom(Controller);
ssc.Serialize(bw);
bw.Close();
savestatebuff = ms.ToArray();
}
// speedup when sound rendering is not needed
if (!rendersound)
api.QUERY_set_audio_sample(null);
else
api.QUERY_set_audio_sample(soundcb);
bool resetSignal = Controller["Reset"];
if (resetSignal) api.CMD_reset();
bool powerSignal = Controller["Power"];
if (powerSignal) api.CMD_power();
//too many messages
api.QUERY_set_layer_enable(0, 0, Settings.ShowBG1_0);
api.QUERY_set_layer_enable(0, 1, Settings.ShowBG1_1);
api.QUERY_set_layer_enable(1, 0, Settings.ShowBG2_0);
api.QUERY_set_layer_enable(1, 1, Settings.ShowBG2_1);
api.QUERY_set_layer_enable(2, 0, Settings.ShowBG3_0);
api.QUERY_set_layer_enable(2, 1, Settings.ShowBG3_1);
api.QUERY_set_layer_enable(3, 0, Settings.ShowBG4_0);
api.QUERY_set_layer_enable(3, 1, Settings.ShowBG4_1);
api.QUERY_set_layer_enable(4, 0, Settings.ShowOBJ_0);
api.QUERY_set_layer_enable(4, 1, Settings.ShowOBJ_1);
api.QUERY_set_layer_enable(4, 2, Settings.ShowOBJ_2);
api.QUERY_set_layer_enable(4, 3, Settings.ShowOBJ_3);
RefreshMemoryCallbacks(false);
//apparently this is one frame?
timeFrameCounter++;
api.CMD_run();
while (api.QUERY_HasMessage)
Console.WriteLine(api.QUERY_DequeueMessage());
if (IsLagFrame)
LagCount++;
//diagnostics for IPC traffic
//Console.WriteLine(api.MessageCounter);
api.EndBufferIO();
}
void RefreshMemoryCallbacks(bool suppress)
{
var mcs = MemoryCallbacks;
api.QUERY_set_state_hook_exec(!suppress && mcs.HasExecutes);
api.QUERY_set_state_hook_read(!suppress && mcs.HasReads);
api.QUERY_set_state_hook_write(!suppress && mcs.HasWrites);
}
public DisplayType Region
{
get
{
if (api.QUERY_get_region() == LibsnesApi.SNES_REGION.NTSC)
return DisplayType.NTSC;
else
return DisplayType.PAL;
}
}
//video provider
int IVideoProvider.BackgroundColor { get { return 0; } }
int[] IVideoProvider.GetVideoBuffer() { return vidBuffer; }
int IVideoProvider.VirtualWidth { get { return (int)(vidWidth * 1.146); } }
public int VirtualHeight { get { return vidHeight; } }
int IVideoProvider.BufferWidth { get { return vidWidth; } }
int IVideoProvider.BufferHeight { get { return vidHeight; } }
int[] vidBuffer = new int[256 * 224];
int vidWidth = 256, vidHeight = 224;
public ControllerDefinition ControllerDefinition { get { return SNESController; } }
IController controller;
public IController Controller
{
get { return controller; }
set { controller = value; }
}
public static readonly ControllerDefinition SNESController =
new ControllerDefinition
{
Name = "SNES Controller",
BoolButtons = {
"Reset", "Power",
"P1 Up", "P1 Down", "P1 Left", "P1 Right", "P1 Select", "P1 Start", "P1 Y", "P1 B", "P1 X", "P1 A", "P1 L", "P1 R",
"P2 Up", "P2 Down", "P2 Left", "P2 Right", "P2 Select", "P2 Start", "P2 Y", "P2 B", "P2 X", "P2 A", "P2 L", "P2 R",
// adelikat: disabling these since they aren't hooked up
// "P3 Up", "P3 Down", "P3 Left", "P3 Right", "P3 Select", "P3 Start", "P3 Y", "P3 B", "P3 X", "P3 A", "P3 L", "P3 R",
// "P4 Up", "P4 Down", "P4 Left", "P4 Right", "P4 Select", "P4 Start", "P4 Y", "P4 B", "P4 X", "P4 A", "P4 L", "P4 R",
}
};
int timeFrameCounter;
public int Frame { get { return timeFrameCounter; } set { timeFrameCounter = value; } }
public int LagCount { get; set; }
public bool IsLagFrame { get; set; }
public string SystemId { get; private set; }
public string BoardName { get; private set; }
// adelikat: Nasty hack to force new business logic. Compatibility (and Accuracy when fully supported) will ALWAYS be in deterministic mode,
// a consequence is a permanent performance hit to the compatibility core
// Perormance will NEVER be in deterministic mode (and the client side logic will prohibit movie recording on it)
// feos: Nasty hack to a nasty hack. Allow user disable it with a strong warning.
public bool DeterministicEmulation
{
get
{
return Settings.ForceDeterminism &&
(CurrentProfile == "Compatibility" || CurrentProfile == "Accuracy");
}
private set { /* Do nothing */ }
}
public bool SaveRamModified
{
get
{
return api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM) != 0 || api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.SGB_CARTRAM) != 0;
}
}
public byte[] CloneSaveRam()
{
byte* buf = api.QUERY_get_memory_data(LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM);
var size = api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM);
if (buf == null)
{
buf = api.QUERY_get_memory_data(LibsnesApi.SNES_MEMORY.SGB_CARTRAM);
size = api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.SGB_CARTRAM);
}
var ret = new byte[size];
Marshal.Copy((IntPtr)buf, ret, 0, size);
return ret;
}
//public byte[] snes_get_memory_data_read(LibsnesApi.SNES_MEMORY id)
//{
// var size = (int)api.snes_get_memory_size(id);
// if (size == 0) return new byte[0];
// var ret = api.snes_get_memory_data(id);
// return ret;
//}
public void StoreSaveRam(byte[] data)
{
byte* buf = api.QUERY_get_memory_data(LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM);
var size = api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM);
if (buf == null)
{
buf = api.QUERY_get_memory_data(LibsnesApi.SNES_MEMORY.SGB_CARTRAM);
size = api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.SGB_CARTRAM);
}
if (size == 0) return;
if (size != data.Length) throw new InvalidOperationException("Somehow, we got a mismatch between saveram size and what bsnes says the saveram size is");
Marshal.Copy(data, 0, (IntPtr)buf, size);
}
public void ResetCounters()
{
timeFrameCounter = 0;
LagCount = 0;
IsLagFrame = false;
}
#region savestates
/// <summary>
/// can freeze a copy of a controller input set and serialize\deserialize it
/// </summary>
public class SnesSaveController : IController
{
// this is all rather general, so perhaps should be moved out of LibsnesCore
ControllerDefinition def;
public SnesSaveController()
{
this.def = null;
}
public SnesSaveController(ControllerDefinition def)
{
this.def = def;
}
WorkingDictionary<string, float> buttons = new WorkingDictionary<string,float>();
/// <summary>
/// invalid until CopyFrom has been called
/// </summary>
public ControllerDefinition Type
{
get { return def; }
}
public void Serialize(BinaryWriter b)
{
b.Write(buttons.Keys.Count);
foreach (var k in buttons.Keys)
{
b.Write(k);
b.Write(buttons[k]);
}
}
/// <summary>
/// no checking to see if the deserialized controls match any definition
/// </summary>
/// <param name="b"></param>
public void DeSerialize(BinaryReader b)
{
buttons.Clear();
int numbuttons = b.ReadInt32();
for (int i = 0; i < numbuttons; i++)
{
string k = b.ReadString();
float v = b.ReadSingle();
buttons.Add(k, v);
}
}
/// <summary>
/// this controller's definition changes to that of source
/// </summary>
/// <param name="source"></param>
public void CopyFrom(IController source)
{
this.def = source.Type;
buttons.Clear();
foreach (var k in def.BoolButtons)
buttons.Add(k, source.IsPressed(k) ? 1.0f : 0);
foreach (var k in def.FloatControls)
{
if (buttons.Keys.Contains(k))
throw new Exception("name collision between bool and float lists!");
buttons.Add(k, source.GetFloat(k));
}
}
public void Clear()
{
buttons.Clear();
}
public void Set(string button)
{
buttons[button] = 1.0f;
}
public bool this[string button]
{
get { return buttons[button] != 0; }
}
public bool IsPressed(string button)
{
return buttons[button] != 0;
}
public float GetFloat(string name)
{
return buttons[name];
}
}
public void SaveStateText(TextWriter writer)
{
var temp = SaveStateBinary();
temp.SaveAsHexFast(writer);
writer.WriteLine("Frame {0}", Frame); // we don't parse this, it's only for the client to use
writer.WriteLine("Profile {0}", CurrentProfile);
}
public void LoadStateText(TextReader reader)
{
string hex = reader.ReadLine();
byte[] state = new byte[hex.Length / 2];
state.ReadFromHexFast(hex);
LoadStateBinary(new BinaryReader(new MemoryStream(state)));
reader.ReadLine(); // Frame #
var profile = reader.ReadLine().Split(' ')[1];
ValidateLoadstateProfile(profile);
}
public void SaveStateBinary(BinaryWriter writer)
{
if (!DeterministicEmulation)
writer.Write(CoreSaveState());
else
writer.Write(savestatebuff);
// other variables
writer.Write(IsLagFrame);
writer.Write(LagCount);
writer.Write(Frame);
writer.Write(CurrentProfile);
writer.Flush();
}
public void LoadStateBinary(BinaryReader reader)
{
int size = api.QUERY_serialize_size();
byte[] buf = reader.ReadBytes(size);
CoreLoadState(buf);
if (DeterministicEmulation) // deserialize controller and fast-foward now
{
// reconstruct savestatebuff at the same time to avoid a costly core serialize
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(buf);
bool framezero = reader.ReadBoolean();
bw.Write(framezero);
if (!framezero)
{
SnesSaveController ssc = new SnesSaveController(ControllerDefinition);
ssc.DeSerialize(reader);
IController tmp = this.Controller;
this.Controller = ssc;
nocallbacks = true;
FrameAdvance(false, false);
nocallbacks = false;
this.Controller = tmp;
ssc.Serialize(bw);
}
else // hack: dummy controller info
{
bw.Write(reader.ReadBytes(536));
}
bw.Close();
savestatebuff = ms.ToArray();
}
// other variables
IsLagFrame = reader.ReadBoolean();
LagCount = reader.ReadInt32();
Frame = reader.ReadInt32();
var profile = reader.ReadString();
ValidateLoadstateProfile(profile);
}
void ValidateLoadstateProfile(string profile)
{
if (profile != CurrentProfile)
{
throw new InvalidOperationException(string.Format("You've attempted to load a savestate made using a different SNES profile ({0}) than your current configuration ({1}). We COULD automatically switch for you, but we havent done that yet. This error is to make sure you know that this isnt going to work right now.", profile, CurrentProfile));
}
}
public byte[] SaveStateBinary()
{
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
SaveStateBinary(bw);
bw.Flush();
return ms.ToArray();
}
public bool BinarySaveStatesPreferred { get { return true; } }
/// <summary>
/// handle the unmanaged part of loadstating
/// </summary>
void CoreLoadState(byte[] data)
{
int size = api.QUERY_serialize_size();
if (data.Length != size)
throw new Exception("Libsnes internal savestate size mismatch!");
api.CMD_init();
//zero 01-sep-2014 - this approach isn't being used anymore, it's too slow!
//LoadCurrent(); //need to make sure chip roms are reloaded
fixed (byte* pbuf = &data[0])
api.CMD_unserialize(new IntPtr(pbuf), size);
}
/// <summary>
/// handle the unmanaged part of savestating
/// </summary>
byte[] CoreSaveState()
{
int size = api.QUERY_serialize_size();
byte[] buf = new byte[size];
fixed (byte* pbuf = &buf[0])
api.CMD_serialize(new IntPtr(pbuf), size);
return buf;
}
/// <summary>
/// most recent internal savestate, for deterministic mode ONLY
/// </summary>
byte[] savestatebuff;
#endregion
public CoreComm CoreComm { get; private set; }
// works for WRAM, garbage for anything else
static int? FakeBusMap(int addr)
{
addr &= 0xffffff;
int bank = addr >> 16;
if (bank == 0x7e || bank == 0x7f)
return addr & 0x1ffff;
bank &= 0x7f;
int low = addr & 0xffff;
if (bank < 0x40 && low < 0x2000)
return low;
return null;
}
private LibsnesApi.SNES_MAPPER? mapper = null;
// works for ROM, garbage for anything else
byte FakeBusRead(int addr)
{
addr &= 0xffffff;
int bank = addr >> 16;
int low = addr & 0xffff;
if (!mapper.HasValue)
{
return 0;
}
switch (mapper)
{
case LibsnesApi.SNES_MAPPER.LOROM:
if (low >= 0x8000)
{
return api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.EXLOROM:
if ((bank >= 0x40 && bank <= 0x7f) || low >= 0x8000)
{
return api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.HIROM:
case LibsnesApi.SNES_MAPPER.EXHIROM:
if ((bank >= 0x40 && bank <= 0x7f) || bank >= 0xc0 || low >= 0x8000)
{
return api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.SUPERFXROM:
if ((bank >= 0x40 && bank <= 0x5f) || (bank >= 0xc0 && bank <= 0xdf) ||
(low >= 0x8000 && ((bank >= 0x00 && bank <= 0x3f) || (bank >= 0x80 && bank <= 0xbf))))
{
return api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.SA1ROM:
if (bank >= 0xc0 || (low >= 0x8000 && ((bank >= 0x00 && bank <= 0x3f) || (bank >= 0x80 && bank <= 0xbf))))
{
return api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.BSCLOROM:
if (low >= 0x8000 && ((bank >= 0x00 && bank <= 0x3f) || (bank >= 0x80 && bank <= 0xbf)))
{
return api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.BSCHIROM:
if ((bank >= 0x40 && bank <= 0x5f) || (bank >= 0xc0 && bank <= 0xdf) ||
(low >= 0x8000 && ((bank >= 0x00 && bank <= 0x1f) || (bank >= 0x80 && bank <= 0x9f))))
{
return api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.BSXROM:
if ((bank >= 0x40 && bank <= 0x7f) || bank >= 0xc0 ||
(low >= 0x8000 && ((bank >= 0x00 && bank <= 0x3f) || (bank >= 0x80 && bank <= 0xbf))) ||
(low >= 0x6000 && low <= 0x7fff && (bank >= 0x20 && bank <= 0x3f)))
{
return api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.STROM:
if (low >= 0x8000 && ((bank >= 0x00 && bank <= 0x5f) || (bank >= 0x80 && bank <= 0xdf)))
{
return api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
default:
throw new InvalidOperationException(string.Format("Unknown mapper: {0}", mapper));
}
return 0;
}
unsafe void MakeFakeBus()
{
int size = api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.WRAM);
if (size != 0x20000)
throw new InvalidOperationException();
byte* blockptr = api.QUERY_get_memory_data(LibsnesApi.SNES_MEMORY.WRAM);
var md = new MemoryDomainDelegate("System Bus", 0x1000000, MemoryDomain.Endian.Little,
(addr) =>
{
var a = FakeBusMap((int)addr);
if (a.HasValue)
return blockptr[a.Value];
else
return FakeBusRead((int)addr);
},
(addr, val) =>
{
var a = FakeBusMap((int)addr);
if (a.HasValue)
blockptr[a.Value] = val;
}, wordSize: 2);
_memoryDomains.Add(md);
}
// ----- Client Debugging API stuff -----
unsafe MemoryDomain MakeMemoryDomain(string name, LibsnesApi.SNES_MEMORY id, MemoryDomain.Endian endian, int byteSize = 1)
{
int size = api.QUERY_get_memory_size(id);
int mask = size - 1;
bool pow2 = Util.IsPowerOfTwo(size);
//if this type of memory isnt available, dont make the memory domain (most commonly save ram)
if (size == 0)
return null;
byte* blockptr = api.QUERY_get_memory_data(id);
MemoryDomain md;
if(id == LibsnesApi.SNES_MEMORY.OAM)
{
//OAM is actually two differently sized banks of memory which arent truly considered adjacent.
//maybe a better way to visualize it is with an empty bus and adjacent banks
//so, we just throw away everything above its size of 544 bytes
if (size != 544) throw new InvalidOperationException("oam size isnt 544 bytes.. wtf?");
md = new MemoryDomainDelegate(name, size, endian,
(addr) => (addr < 544) ? blockptr[addr] : (byte)0x00,
(addr, value) => { if (addr < 544) blockptr[addr] = value; },
byteSize);
}
else if(pow2)
md = new MemoryDomainDelegate(name, size, endian,
(addr) => blockptr[addr & mask],
(addr, value) => blockptr[addr & mask] = value, byteSize);
else
md = new MemoryDomainDelegate(name, size, endian,
(addr) => blockptr[addr % size],
(addr, value) => blockptr[addr % size] = value, byteSize);
_memoryDomains.Add(md);
return md;
}
void SetupMemoryDomains(byte[] romData, byte[] sgbRomData)
{
//lets just do this entirely differently for SGB
if (IsSGB)
{
//NOTE: CGB has 32K of wram, and DMG has 8KB of wram. Not sure how to control this right now.. bsnes might not have any ready way of doign that? I couldnt spot it.
//You wouldnt expect a DMG game to access excess wram, but what if it tried to? maybe an oversight in bsnes?
MakeMemoryDomain("SGB WRAM", LibsnesApi.SNES_MEMORY.SGB_WRAM, MemoryDomain.Endian.Little);
var romDomain = new MemoryDomainByteArray("SGB CARTROM", MemoryDomain.Endian.Little, romData, true, 1);
_memoryDomains.Add(romDomain);
//the last 1 byte of this is special.. its an interrupt enable register, instead of ram. weird. maybe its actually ram and just getting specially used?
MakeMemoryDomain("SGB HRAM", LibsnesApi.SNES_MEMORY.SGB_HRAM, MemoryDomain.Endian.Little);
MakeMemoryDomain("SGB CARTRAM", LibsnesApi.SNES_MEMORY.SGB_CARTRAM, MemoryDomain.Endian.Little);
MainMemory = MakeMemoryDomain("WRAM", LibsnesApi.SNES_MEMORY.WRAM, MemoryDomain.Endian.Little);
var sgbromDomain = new MemoryDomainByteArray("SGB.SFC ROM", MemoryDomain.Endian.Little, sgbRomData, true, 1);
_memoryDomains.Add(sgbromDomain);
}
else
{
MainMemory = MakeMemoryDomain("WRAM", LibsnesApi.SNES_MEMORY.WRAM, MemoryDomain.Endian.Little);
MakeMemoryDomain("CARTROM", LibsnesApi.SNES_MEMORY.CARTRIDGE_ROM, MemoryDomain.Endian.Little, byteSize: 2);
MakeMemoryDomain("CARTRAM", LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM, MemoryDomain.Endian.Little, byteSize: 2);
MakeMemoryDomain("VRAM", LibsnesApi.SNES_MEMORY.VRAM, MemoryDomain.Endian.Little, byteSize: 2);
MakeMemoryDomain("OAM", LibsnesApi.SNES_MEMORY.OAM, MemoryDomain.Endian.Little, byteSize: 2);
MakeMemoryDomain("CGRAM", LibsnesApi.SNES_MEMORY.CGRAM, MemoryDomain.Endian.Little, byteSize: 2);
MakeMemoryDomain("APURAM", LibsnesApi.SNES_MEMORY.APURAM, MemoryDomain.Endian.Little, byteSize: 2);
if (!DeterministicEmulation)
{
_memoryDomains.Add(new MemoryDomainDelegate("System Bus", 0x1000000, MemoryDomain.Endian.Little,
(addr) => api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr),
(addr, val) => api.QUERY_poke(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr, val), wordSize: 2));
}
else
{
// limited function bus
MakeFakeBus();
}
}
MemoryDomains = new MemoryDomainList(_memoryDomains);
(ServiceProvider as BasicServiceProvider).Register<IMemoryDomains>(MemoryDomains);
}
private MemoryDomain MainMemory;
private List<MemoryDomain> _memoryDomains = new List<MemoryDomain>();
private IMemoryDomains MemoryDomains;
#region audio stuff
SpeexResampler resampler;
void InitAudio()
{
resampler = new SpeexResampler(6, 64081, 88200, 32041, 44100);
}
void snes_audio_sample(ushort left, ushort right)
{
resampler.EnqueueSample((short)left, (short)right);
}
public ISoundProvider SoundProvider { get { return null; } }
public ISyncSoundProvider SyncSoundProvider { get { return resampler; } }
public bool StartAsyncSound() { return false; }
public void EndAsyncSound() { }
#endregion audio stuff
void RefreshPalette()
{
SetPalette((SnesColors.ColorType)Enum.Parse(typeof(SnesColors.ColorType), Settings.Palette, false));
}
SnesSettings Settings;
SnesSyncSettings SyncSettings;
public SnesSettings GetSettings() { return Settings.Clone(); }
public SnesSyncSettings GetSyncSettings() { return SyncSettings.Clone(); }
public bool PutSettings(SnesSettings o)
{
bool refreshneeded = o.Palette != Settings.Palette;
Settings = o;
if (refreshneeded)
RefreshPalette();
return false;
}
public bool PutSyncSettings(SnesSyncSettings o)
{
bool ret = o.Profile != SyncSettings.Profile;
SyncSettings = o;
return ret;
}
public class SnesSettings
{
public bool ShowBG1_0 = true;
public bool ShowBG2_0 = true;
public bool ShowBG3_0 = true;
public bool ShowBG4_0 = true;
public bool ShowBG1_1 = true;
public bool ShowBG2_1 = true;
public bool ShowBG3_1 = true;
public bool ShowBG4_1 = true;
public bool ShowOBJ_0 = true;
public bool ShowOBJ_1 = true;
public bool ShowOBJ_2 = true;
public bool ShowOBJ_3 = true;
public bool UseRingBuffer = true;
public bool AlwaysDoubleSize = false;
public bool ForceDeterminism = true;
public string Palette = "BizHawk";
public SnesSettings Clone()
{
return (SnesSettings)MemberwiseClone();
}
}
public class SnesSyncSettings
{
public string Profile = "Performance"; // "Accuracy", and "Compatibility" are the other choicec, todo: make this an enum
public SnesSyncSettings Clone()
{
return (SnesSyncSettings)MemberwiseClone();
}
}
}
public class ScanlineHookManager
{
public void Register(object tag, Action<int> callback)
{
var rr = new RegistrationRecord();
rr.tag = tag;
rr.callback = callback;
Unregister(tag);
records.Add(rr);
OnHooksChanged();
}
public int HookCount { get { return records.Count; } }
public virtual void OnHooksChanged() { }
public void Unregister(object tag)
{
records.RemoveAll((r) => r.tag == tag);
}
public void HandleScanline(int scanline)
{
foreach (var rr in records) rr.callback(scanline);
}
List<RegistrationRecord> records = new List<RegistrationRecord>();
class RegistrationRecord
{
public object tag;
public int scanline = 0;
public Action<int> callback;
}
}
}
| |
using System;
namespace jkEditor.Actions
{
/// <summary>
/// Summary description for SlideToGuidelineLeft.
/// </summary>
public class ZeroVerticalGuideline : IAction
{
#region IAction Members
public bool CanAct(object o)
{
return o is Fork.Layer;
}
public string Name()
{
return "Make v=0";
}
public void Act(ActionContext Context, object o)
{
Context.Vguide = 0;
}
#endregion
}
public class ZeroHorizontalGuideline : IAction
{
#region IAction Members
public bool CanAct(object o)
{
return o is Fork.Layer;
}
public string Name()
{
return "Make h=0";
}
public void Act(ActionContext Context, object o)
{
Context.Hguide = 0;
}
#endregion
}
public class InherGuideWH : IAction
{
#region IAction Members
public bool CanAct(object o)
{
return o is Fork.Control;
}
public string Name()
{
return "Make (h,v) <= (w,h)";
}
public void Act(ActionContext Context, object o)
{
Context.Hguide = (o as Fork.Control).Width;
Context.Vguide = (o as Fork.Control).Height;
}
#endregion
}
public class Guide2WH : IAction
{
#region IAction Members
public bool CanAct(object o)
{
return o is Fork.Control;
}
public string Name()
{
return "Make (w,h) <= (h,v)";
}
public void Act(ActionContext Context, object o)
{
(o as Fork.Control).Width = Context.Hguide;
(o as Fork.Control).Height = Context.Vguide;
}
#endregion
}
public class MinimizeLayer : IAction
{
public bool CanAct(object o)
{
return o is Fork.Layer;
}
public string Name()
{
return "Shrink Layer Bounds";
}
public void Act(ActionContext Context, object o)
{
if (Context.CurrentLayer == null) return;
if (Context.CurrentLayer.Controls == null) return;
int maxX = 0;
int maxY = 0;
foreach (Fork.Control C in Context.CurrentLayer.Controls)
{
maxX = Math.Max(C.X + C.Width, maxX);
maxY = Math.Max(C.Y + C.Height, maxY);
}
Context.CurrentLayer.Width = maxX;
Context.CurrentLayer.Height = maxY;
}
}
public class LockAll : IAction
{
public bool CanAct(object o)
{
return o is Fork.Layer;
}
public string Name()
{
return "Lock All";
}
public void Act(ActionContext Context, object o)
{
if (Context.CurrentLayer == null) return;
if (Context.CurrentLayer.Controls == null) return;
foreach (Fork.Control C in Context.CurrentLayer.Controls)
{
C.DesignLocked = true;
}
}
}
public class LockUnAll : IAction
{
public bool CanAct(object o)
{
return o is Fork.Layer;
}
public string Name()
{
return "Unlock All";
}
public void Act(ActionContext Context, object o)
{
if (Context.CurrentLayer == null) return;
if (Context.CurrentLayer.Controls == null) return;
foreach (Fork.Control C in Context.CurrentLayer.Controls)
{
C.DesignLocked = false;
}
}
}
public class TranslateAll : IAction
{
#region IAction Members
public bool CanAct(object o)
{
return o is Fork.Layer;
}
public string Name()
{
return "Translate to new Origin";
}
public void Act(ActionContext Context, object o)
{
if (Context.CurrentLayer == null) return;
if (Context.CurrentLayer.Controls == null) return;
int minX = 1000000;
int minY = 1000000;
bool AllLocked = false;
foreach (Fork.Control C in Context.CurrentLayer.Controls)
{
if (C.DesignLocked) AllLocked = true;
minX = Math.Min(C.X, minX);
minY = Math.Min(C.Y, minY);
}
if (AllLocked) return;
foreach (Fork.Control C in Context.CurrentLayer.Controls)
{
C.X -= minX;
C.X += Context.Hguide;
C.Y -= minY;
C.Y += Context.Vguide;
}
}
#endregion
}
/*
public class SlideToGuidelineLeft : IAction
{
#region IAction Members
public bool CanAct(object o)
{
if( o is Fork.Control ) return !(o as Fork.Control).DesignLocked;
return ! (o is Fork.Layer);
}
public string Name()
{
return "Slide Left to Guideline";
}
public void Act(ActionContext Context, object o)
{
Fork.Control C = o as Fork.Control;
C.X = Context.Hguide;
}
#endregion
}
public class SlideToGuidelineRight : IAction
{
#region IAction Members
public bool CanAct(object o)
{
if( o is Fork.Control ) return !(o as Fork.Control).DesignLocked;
return ! (o is Fork.Layer);
}
public string Name()
{
return "Slide Right to Guideline";
}
public void Act(ActionContext Context, object o)
{
Fork.Control C = o as Fork.Control;
C.X = Context.Hguide - C.Width;
}
#endregion
}
public class SlideToGuidelineTop : IAction
{
#region IAction Members
public bool CanAct(object o)
{
if( o is Fork.Control ) return !(o as Fork.Control).DesignLocked;
return ! (o is Fork.Layer);
}
public string Name()
{
return "Slide Top to Guideline";
}
public void Act(ActionContext Context, object o)
{
Fork.Control C = o as Fork.Control;
C.Y = Context.Vguide;
}
#endregion
}
public class SlideToGuidelineBottom : IAction
{
#region IAction Members
public bool CanAct(object o)
{
if( o is Fork.Control ) return !(o as Fork.Control).DesignLocked;
return ! (o is Fork.Layer);
}
public string Name()
{
return "Slide Bottom to Guideline";
}
public void Act(ActionContext Context, object o)
{
Fork.Control C = o as Fork.Control;
C.Y = Context.Vguide - C.Height;
}
#endregion
}
public class ObtainLeftGuideLine : IAction
{
#region IAction Members
public bool CanAct(object o)
{
return ! (o is Fork.Layer);
}
public string Name()
{
return "Inherit Left as Guideline";
}
public void Act(ActionContext Context, object o)
{
Fork.Control C = o as Fork.Control;
Context.Hguide = C.X;
}
#endregion
}
public class ObtainRightGuideLine : IAction
{
#region IAction Members
public bool CanAct(object o)
{
return ! ( o is Fork.Layer);
}
public string Name()
{
return "Inherit Right as Guideline";
}
public void Act(ActionContext Context, object o)
{
Fork.Control C = o as Fork.Control;
Context.Hguide = C.X + C.Width;
}
#endregion
}
public class ObtainTopGuideLine : IAction
{
#region IAction Members
public bool CanAct(object o)
{
return ! ( o is Fork.Layer);
}
public string Name()
{
return "Inherit Top as Guideline";
}
public void Act(ActionContext Context, object o)
{
Fork.Control C = o as Fork.Control;
Context.Vguide = C.Y;
}
#endregion
}
public class ObtainBottomGuideLine : IAction
{
#region IAction Members
public bool CanAct(object o)
{
return ! ( o is Fork.Layer);
}
public string Name()
{
return "Inherit Bottom as Guideline";
}
public void Act(ActionContext Context, object o)
{
Fork.Control C = o as Fork.Control;
Context.Vguide = C.Y + C.Height;
}
#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;
using System.IO;
using System.Runtime.CompilerServices;
namespace BadCheckedAdd1
{
internal enum SniContext
{
Undefined = 0,
Snix_Connect,
Snix_PreLoginBeforeSuccessfullWrite,
Snix_PreLogin,
Snix_LoginSspi,
Snix_ProcessSspi,
Snix_Login,
Snix_EnableMars,
Snix_AutoEnlist,
Snix_GetMarsSession,
Snix_Execute,
Snix_Read,
Snix_Close,
Snix_SendRows,
}
internal static class ADP
{
[MethodImpl(MethodImplOptions.NoInlining)]
static internal bool IsCatchableExceptionType(Exception e)
{
return false;
}
}
sealed internal class SQL
{
[MethodImpl(MethodImplOptions.NoInlining)]
static internal Exception InvalidSSPIPacketSize()
{
return null;
}
}
sealed internal class SqlLogin
{
internal int timeout; // login timeout
internal bool userInstance = false; // user instance
internal string hostName = ""; // client machine name
internal string userName = ""; // user id
internal string password = ""; // password
internal string applicationName = ""; // application name
internal string serverName = ""; // server name
internal string language = ""; // initial language
internal string database = ""; // initial database
internal string attachDBFilename = ""; // DB filename to be attached
internal string newPassword = ""; // new password for reset password
internal bool useReplication = false; // user login for replication
internal bool useSSPI = false; // use integrated security
internal int packetSize = 8000; // packet size
}
internal sealed class TdsParserStaticMethods
{
[MethodImpl(MethodImplOptions.NoInlining)]
static internal byte[] GetNetworkPhysicalAddressForTdsLoginOnly()
{
return new Byte[8];
}
[MethodImpl(MethodImplOptions.NoInlining)]
static internal Byte[] EncryptPassword(string password)
{
if (password == "")
{
return new Byte[0];
}
else
{
return new Byte[] {
0x86, 0xa5,
0x36, 0xa5, 0x22, 0xa5,
0x33, 0xa5, 0xb3, 0xa5,
0xb2, 0xa5, 0x77, 0xa5,
0xb6, 0xa5, 0x92, 0xa5
};
}
}
}
sealed internal class TdsParserStateObject
{
public uint ReadDwordFromPostHeaderContentAtByteOffset(int offset)
{
offset += 8;
using (var reader = new BinaryReader(new MemoryStream(this._outBuff, offset, 4)))
{
return reader.ReadUInt32();
}
}
internal byte[] _bTmp = new byte[8];
internal byte[] _outBuff = new Byte[1000];
internal int _outBytesUsed = 8;
internal readonly int _outputHeaderLen = 8;
internal byte _outputMessageType = 0;
internal byte _outputPacketNumber = 1;
internal bool _pendingData = false;
private int _timeoutSeconds;
private long _timeoutTime;
internal int _traceChangePasswordOffset = 0;
internal int _traceChangePasswordLength = 0;
internal int _tracePasswordOffset = 0;
internal int _tracePasswordLength = 0;
private SniContext _sniContext = SniContext.Undefined;
internal SniContext SniContext
{
get { return _sniContext; }
set { _sniContext = value; }
}
internal void SetTimeoutSeconds(int timeout)
{
_timeoutSeconds = timeout;
if (timeout == 0)
{
_timeoutTime = Int64.MaxValue;
}
}
internal void ResetBuffer()
{
this._outBytesUsed = this._outputHeaderLen;
return;
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal void WritePacket(byte flushMode)
{
return;
}
}
internal class TdsParser
{
internal TdsParserStateObject _physicalStateObj = new TdsParserStateObject();
private volatile static UInt32 s_maxSSPILength = 0;
private static byte[] s_nicAddress;
[MethodImpl(MethodImplOptions.NoInlining)]
private void SSPIData(byte[] receivedBuff, UInt32 receivedLength, byte[] sendBuff, ref UInt32 sendLength)
{
return;
}
internal void WriteByte(byte b, TdsParserStateObject stateObj)
{
if (stateObj._outBytesUsed == stateObj._outBuff.Length)
{
stateObj.WritePacket(0);
}
stateObj._outBuff[stateObj._outBytesUsed++] = b;
}
internal void WriteByteArray(Byte[] b, int len, int offsetBuffer, TdsParserStateObject stateObj)
{
int offset = offsetBuffer;
while (len > 0)
{
if ((stateObj._outBytesUsed + len) > stateObj._outBuff.Length)
{
int remainder = stateObj._outBuff.Length - stateObj._outBytesUsed;
Buffer.BlockCopy(b, offset, stateObj._outBuff, stateObj._outBytesUsed, remainder);
offset += remainder;
stateObj._outBytesUsed += remainder;
if (stateObj._outBytesUsed == stateObj._outBuff.Length)
{
stateObj.WritePacket(0);
}
len -= remainder;
}
else
{
Buffer.BlockCopy(b, offset, stateObj._outBuff, stateObj._outBytesUsed, len);
stateObj._outBytesUsed += len;
break;
}
}
}
internal void WriteShort(int v, TdsParserStateObject stateObj)
{
if ((stateObj._outBytesUsed + 2) > stateObj._outBuff.Length)
{
WriteByte((byte)(v & 0xff), stateObj);
WriteByte((byte)((v >> 8) & 0xff), stateObj);
}
else
{
stateObj._outBuff[stateObj._outBytesUsed++] = (byte)(v & 0xFF);
stateObj._outBuff[stateObj._outBytesUsed++] = (byte)((v >> 8) & 0xFF);
}
}
internal void WriteInt(int v, TdsParserStateObject stateObj)
{
WriteByteArray(BitConverter.GetBytes(v), 4, 0, stateObj);
}
private unsafe static void CopyStringToBytes(string source, int sourceOffset, byte[] dest, int destOffset, int charLength)
{
int byteLength = checked(charLength * 2);
fixed (char* sourcePtr = source)
{
char* srcPtr = sourcePtr;
srcPtr += sourceOffset;
fixed (byte* destinationPtr = dest)
{
byte* destPtr = destinationPtr;
destPtr += destOffset;
byte* destByteAddress = destPtr;
byte* srcByteAddress = (byte*)srcPtr;
for (int index = 0; index < byteLength; index++)
{
*destByteAddress = *srcByteAddress;
destByteAddress++;
srcByteAddress++;
}
}
}
}
internal void WriteString(string s, int length, int offset, TdsParserStateObject stateObj)
{
int cBytes = 2 * length;
if (cBytes < (stateObj._outBuff.Length - stateObj._outBytesUsed))
{
CopyStringToBytes(s, offset, stateObj._outBuff, stateObj._outBytesUsed, length);
stateObj._outBytesUsed += cBytes;
}
else
{
if (stateObj._bTmp == null || stateObj._bTmp.Length < cBytes)
{
stateObj._bTmp = new byte[cBytes];
}
CopyStringToBytes(s, offset, stateObj._bTmp, 0, length);
WriteByteArray(stateObj._bTmp, cBytes, 0, stateObj);
}
}
private void WriteString(string s, TdsParserStateObject stateObj)
{
WriteString(s, s.Length, 0, stateObj);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal void TdsLogin(SqlLogin rec)
{
_physicalStateObj.SetTimeoutSeconds(rec.timeout);
byte[] encryptedPassword = null;
encryptedPassword = TdsParserStaticMethods.EncryptPassword(rec.password);
byte[] encryptedChangePassword = null;
encryptedChangePassword = TdsParserStaticMethods.EncryptPassword(rec.newPassword);
_physicalStateObj._outputMessageType = 16;
int length = 0x5e;
string clientInterfaceName = ".Net SqlClient Data Provider";
checked
{
length += (rec.hostName.Length + rec.applicationName.Length +
rec.serverName.Length + clientInterfaceName.Length +
rec.language.Length + rec.database.Length +
rec.attachDBFilename.Length) * 2;
}
byte[] outSSPIBuff = null;
UInt32 outSSPILength = 0;
if (!rec.useSSPI)
{
checked
{
length += (rec.userName.Length * 2) + encryptedPassword.Length
+ encryptedChangePassword.Length;
}
}
else
{
if (rec.useSSPI)
{
outSSPIBuff = new byte[s_maxSSPILength];
outSSPILength = s_maxSSPILength;
_physicalStateObj.SniContext = SniContext.Snix_LoginSspi;
SSPIData(null, 0, outSSPIBuff, ref outSSPILength);
if (outSSPILength > Int32.MaxValue)
{
throw SQL.InvalidSSPIPacketSize(); // SqlBu 332503
}
_physicalStateObj.SniContext = SniContext.Snix_Login;
checked
{
length += (Int32)outSSPILength;
}
}
}
try
{
WriteInt(length, _physicalStateObj);
WriteInt(0x730a0003, _physicalStateObj);
WriteInt(rec.packetSize, _physicalStateObj);
WriteInt(0x06000000, _physicalStateObj);
WriteInt(0xa10, _physicalStateObj);
WriteInt(0, _physicalStateObj);
WriteByte(0xe0, _physicalStateObj);
WriteByte(0x3, _physicalStateObj);
WriteByte(0, _physicalStateObj);
WriteByte(0, _physicalStateObj);
WriteInt(0, _physicalStateObj);
WriteInt(0, _physicalStateObj);
int offset = 0x5e;
WriteShort(offset, _physicalStateObj);
WriteShort(rec.hostName.Length, _physicalStateObj);
offset += rec.hostName.Length * 2;
if (rec.useSSPI == false)
{
WriteShort(offset, _physicalStateObj);
WriteShort(rec.userName.Length, _physicalStateObj);
offset += rec.userName.Length * 2;
WriteShort(offset, _physicalStateObj);
WriteShort(encryptedPassword.Length / 2, _physicalStateObj);
offset += encryptedPassword.Length;
}
else
{
WriteShort(0, _physicalStateObj);
WriteShort(0, _physicalStateObj);
WriteShort(0, _physicalStateObj);
WriteShort(0, _physicalStateObj);
}
WriteShort(offset, _physicalStateObj);
WriteShort(rec.applicationName.Length, _physicalStateObj);
offset += rec.applicationName.Length * 2;
WriteShort(offset, _physicalStateObj);
WriteShort(rec.serverName.Length, _physicalStateObj);
offset += rec.serverName.Length * 2;
WriteShort(offset, _physicalStateObj);
WriteShort(0, _physicalStateObj);
WriteShort(offset, _physicalStateObj);
WriteShort(clientInterfaceName.Length, _physicalStateObj);
offset += clientInterfaceName.Length * 2;
WriteShort(offset, _physicalStateObj);
WriteShort(rec.language.Length, _physicalStateObj);
offset += rec.language.Length * 2;
WriteShort(offset, _physicalStateObj);
WriteShort(rec.database.Length, _physicalStateObj);
offset += rec.database.Length * 2;
if (null == s_nicAddress)
{
s_nicAddress = TdsParserStaticMethods.GetNetworkPhysicalAddressForTdsLoginOnly();
}
WriteByteArray(s_nicAddress, s_nicAddress.Length, 0, _physicalStateObj);
WriteShort(offset, _physicalStateObj);
if (rec.useSSPI)
{
WriteShort((int)outSSPILength, _physicalStateObj);
offset += (int)outSSPILength;
}
else
{
WriteShort(0, _physicalStateObj);
}
WriteShort(offset, _physicalStateObj);
WriteShort(rec.attachDBFilename.Length, _physicalStateObj);
offset += rec.attachDBFilename.Length * 2;
WriteShort(offset, _physicalStateObj);
WriteShort(encryptedChangePassword.Length / 2, _physicalStateObj);
WriteInt(0, _physicalStateObj);
WriteString(rec.hostName, _physicalStateObj);
if (!rec.useSSPI)
{
WriteString(rec.userName, _physicalStateObj);
_physicalStateObj._tracePasswordOffset = _physicalStateObj._outBytesUsed;
_physicalStateObj._tracePasswordLength = encryptedPassword.Length;
WriteByteArray(encryptedPassword, encryptedPassword.Length, 0, _physicalStateObj);
}
WriteString(rec.applicationName, _physicalStateObj);
WriteString(rec.serverName, _physicalStateObj);
WriteString(clientInterfaceName, _physicalStateObj);
WriteString(rec.language, _physicalStateObj);
WriteString(rec.database, _physicalStateObj);
if (rec.useSSPI)
{
WriteByteArray(outSSPIBuff, (int)outSSPILength, 0, _physicalStateObj);
}
WriteString(rec.attachDBFilename, _physicalStateObj);
if (!rec.useSSPI)
{
_physicalStateObj._traceChangePasswordOffset = _physicalStateObj._outBytesUsed;
_physicalStateObj._traceChangePasswordLength = encryptedChangePassword.Length;
WriteByteArray(encryptedChangePassword, encryptedChangePassword.Length, 0, _physicalStateObj);
}
}
catch (Exception e)
{
if (ADP.IsCatchableExceptionType(e))
{
_physicalStateObj._outputPacketNumber = 1;
_physicalStateObj.ResetBuffer();
}
throw;
}
_physicalStateObj.WritePacket(1);
_physicalStateObj._pendingData = true;
return;
}
}
internal static class App
{
private static SqlLogin MakeSqlLoginForRepro()
{
var login = new SqlLogin();
login.hostName = "CHRISAHNA1";
login.userName = "etcmuser";
login.password = "29xiaq-1s";
login.applicationName = ".Net SqlClient Data Provider";
login.serverName = "csetcmdb.redmond.corp.microsoft.com";
login.language = "";
login.database = "Tcm_Global";
login.attachDBFilename = "";
login.newPassword = "";
return login;
}
private static int Main()
{
var tdsParser = new TdsParser();
tdsParser.TdsLogin(App.MakeSqlLoginForRepro());
uint computedLengthValue = tdsParser._physicalStateObj.ReadDwordFromPostHeaderContentAtByteOffset(0x0);
if (computedLengthValue == 0x15e)
{
Console.WriteLine("Test passed.");
return 100;
}
else
{
Console.WriteLine("Test failed: ComputedLength=({0:x8})", computedLengthValue);
}
return 101;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole, Rob Prouse
//
// 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.Linq;
using System.Security.Principal;
using System.Threading;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
using NUnit.TestData.OneTimeSetUpTearDownData;
using NUnit.TestUtilities;
namespace NUnit.Framework.Attributes
{
[TestFixture]
public class OneTimeSetupTearDownTest
{
[Test]
public void MakeSureSetUpAndTearDownAreCalled()
{
SetUpAndTearDownFixture fixture = new SetUpAndTearDownFixture();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, fixture.SetUpCount, "SetUp");
Assert.AreEqual(1, fixture.TearDownCount, "TearDown");
}
[Test]
public void MakeSureSetUpAndTearDownAreCalledOnFixtureWithTestCases()
{
var fixture = new SetUpAndTearDownFixtureWithTestCases();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, fixture.SetUpCount, "SetUp");
Assert.AreEqual(1, fixture.TearDownCount, "TearDown");
}
[Test]
public void MakeSureSetUpAndTearDownAreCalledOnFixtureWithTheories()
{
var fixture = new SetUpAndTearDownFixtureWithTheories();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, fixture.SetUpCount, "SetUp");
Assert.AreEqual(1, fixture.TearDownCount, "TearDown");
}
[Test]
public void MakeSureSetUpAndTearDownAreNotCalledOnExplicitFixture()
{
ExplicitSetUpAndTearDownFixture fixture = new ExplicitSetUpAndTearDownFixture();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(0, fixture.SetUpCount, "SetUp");
Assert.AreEqual(0, fixture.TearDownCount, "TearDown");
}
[Test]
public void CheckInheritedSetUpAndTearDownAreCalled()
{
InheritSetUpAndTearDown fixture = new InheritSetUpAndTearDown();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, fixture.SetUpCount);
Assert.AreEqual(1, fixture.TearDownCount);
}
[Test]
public static void StaticSetUpAndTearDownAreCalled()
{
StaticSetUpAndTearDownFixture.SetUpCount = 0;
StaticSetUpAndTearDownFixture.TearDownCount = 0;
TestBuilder.RunTestFixture(typeof(StaticSetUpAndTearDownFixture));
Assert.AreEqual(1, StaticSetUpAndTearDownFixture.SetUpCount);
Assert.AreEqual(1, StaticSetUpAndTearDownFixture.TearDownCount);
}
[Test]
public static void StaticClassSetUpAndTearDownAreCalled()
{
StaticClassSetUpAndTearDownFixture.SetUpCount = 0;
StaticClassSetUpAndTearDownFixture.TearDownCount = 0;
TestBuilder.RunTestFixture(typeof(StaticClassSetUpAndTearDownFixture));
Assert.AreEqual(1, StaticClassSetUpAndTearDownFixture.SetUpCount);
Assert.AreEqual(1, StaticClassSetUpAndTearDownFixture.TearDownCount);
}
[Test]
public void OverriddenSetUpAndTearDownAreNotCalled()
{
OverrideSetUpAndTearDown fixture = new OverrideSetUpAndTearDown();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(0, fixture.SetUpCount);
Assert.AreEqual(0, fixture.TearDownCount);
Assert.AreEqual(1, fixture.DerivedSetUpCount);
Assert.AreEqual(1, fixture.DerivedTearDownCount);
}
[Test]
public void BaseSetUpCalledFirstAndTearDownCalledLast()
{
DerivedSetUpAndTearDownFixture fixture = new DerivedSetUpAndTearDownFixture();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, fixture.SetUpCount);
Assert.AreEqual(1, fixture.TearDownCount);
Assert.AreEqual(1, fixture.DerivedSetUpCount);
Assert.AreEqual(1, fixture.DerivedTearDownCount);
Assert.That(fixture.BaseSetUpCalledFirst, "Base SetUp called first");
Assert.That(fixture.BaseTearDownCalledLast, "Base TearDown called last");
}
[Test]
public void FailedBaseSetUpCausesDerivedSetUpAndTeardownToBeSkipped()
{
DerivedSetUpAndTearDownFixture fixture = new DerivedSetUpAndTearDownFixture();
fixture.ThrowInBaseSetUp = true;
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, fixture.SetUpCount);
Assert.AreEqual(1, fixture.TearDownCount);
Assert.AreEqual(0, fixture.DerivedSetUpCount);
Assert.AreEqual(0, fixture.DerivedTearDownCount);
}
[Test]
public void StaticBaseSetUpCalledFirstAndTearDownCalledLast()
{
StaticSetUpAndTearDownFixture.SetUpCount = 0;
StaticSetUpAndTearDownFixture.TearDownCount = 0;
DerivedStaticSetUpAndTearDownFixture.DerivedSetUpCount = 0;
DerivedStaticSetUpAndTearDownFixture.DerivedTearDownCount = 0;
DerivedStaticSetUpAndTearDownFixture fixture = new DerivedStaticSetUpAndTearDownFixture();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.SetUpCount);
Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.TearDownCount);
Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.DerivedSetUpCount);
Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.DerivedTearDownCount);
Assert.That(DerivedStaticSetUpAndTearDownFixture.BaseSetUpCalledFirst, "Base SetUp called first");
Assert.That(DerivedStaticSetUpAndTearDownFixture.BaseTearDownCalledLast, "Base TearDown called last");
}
[Test]
public void HandleErrorInFixtureSetup()
{
MisbehavingFixture fixture = new MisbehavingFixture();
fixture.BlowUpInSetUp = true;
ITestResult result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual( 1, fixture.SetUpCount, "setUpCount" );
Assert.AreEqual( 1, fixture.TearDownCount, "tearDownCount" );
Assert.AreEqual(ResultState.SetUpError, result.ResultState);
Assert.AreEqual("System.Exception : This was thrown from fixture setup", result.Message, "TestSuite Message");
Assert.IsNotNull(result.StackTrace, "TestSuite StackTrace should not be null");
Assert.AreEqual(1, result.Children.Count(), "Child result count");
Assert.AreEqual(1, result.FailCount, "Failure count");
}
[Test]
public void RerunFixtureAfterSetUpFixed()
{
MisbehavingFixture fixture = new MisbehavingFixture();
fixture.BlowUpInSetUp = true;
ITestResult result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(ResultState.SetUpError, result.ResultState);
//fix the blow up in setup
fixture.Reinitialize();
result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual( 1, fixture.SetUpCount, "setUpCount" );
Assert.AreEqual( 1, fixture.TearDownCount, "tearDownCount" );
Assert.AreEqual(ResultState.Success, result.ResultState);
}
[Test]
public void HandleIgnoreInFixtureSetup()
{
IgnoreInFixtureSetUp fixture = new IgnoreInFixtureSetUp();
ITestResult result = TestBuilder.RunTestFixture(fixture);
// should have one suite and one fixture
Assert.AreEqual(ResultState.Ignored.WithSite(FailureSite.SetUp), result.ResultState, "Suite should be ignored");
Assert.AreEqual("OneTimeSetUp called Ignore", result.Message);
Assert.IsNotNull(result.StackTrace, "StackTrace should not be null");
Assert.AreEqual(1, result.Children.Count(), "Child result count");
Assert.AreEqual(1, result.SkipCount, "SkipCount");
}
[Test]
public void HandleErrorInFixtureTearDown()
{
MisbehavingFixture fixture = new MisbehavingFixture();
fixture.BlowUpInTearDown = true;
ITestResult result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, result.Children.Count());
Assert.AreEqual(ResultState.TearDownError, result.ResultState);
Assert.AreEqual(1, fixture.SetUpCount, "setUpCount");
Assert.AreEqual(1, fixture.TearDownCount, "tearDownCount");
Assert.AreEqual("TearDown : System.Exception : This was thrown from fixture teardown", result.Message);
Assert.That(result.StackTrace, Does.Contain("--TearDown"));
}
[Test]
public void HandleErrorInFixtureTearDownAfterErrorInTest()
{
MisbehavingFixture fixture = new MisbehavingFixture();
fixture.BlowUpInTest = true;
fixture.BlowUpInTearDown = true;
ITestResult result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, result.Children.Count());
Assert.AreEqual(ResultState.TearDownError, result.ResultState);
Assert.AreEqual(1, fixture.SetUpCount, "setUpCount");
Assert.AreEqual(1, fixture.TearDownCount, "tearDownCount");
Assert.AreEqual(TestResult.CHILD_ERRORS_MESSAGE + Environment.NewLine + "TearDown : System.Exception : This was thrown from fixture teardown", result.Message);
Assert.That(result.ResultState.Site, Is.EqualTo(FailureSite.TearDown));
Assert.That(result.StackTrace, Does.Contain("--TearDown"));
}
[Test]
public void HandleErrorInFixtureTearDownAfterErrorInFixtureSetUp()
{
MisbehavingFixture fixture = new MisbehavingFixture();
fixture.BlowUpInSetUp = true;
fixture.BlowUpInTearDown = true;
ITestResult result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, result.Children.Count());
Assert.AreEqual(ResultState.TearDownError, result.ResultState);
Assert.AreEqual(1, fixture.SetUpCount, "setUpCount");
Assert.AreEqual(1, fixture.TearDownCount, "tearDownCount");
Assert.AreEqual("System.Exception : This was thrown from fixture setup" + Environment.NewLine +
"TearDown : System.Exception : This was thrown from fixture teardown", result.Message);
Assert.That(result.StackTrace, Does.Contain("--TearDown"));
}
[Test]
public void HandleExceptionInFixtureConstructor()
{
ITestResult result = TestBuilder.RunTestFixture( typeof( ExceptionInConstructor ) );
Assert.AreEqual(ResultState.SetUpError, result.ResultState);
Assert.AreEqual("System.Exception : This was thrown in constructor", result.Message, "TestSuite Message");
Assert.IsNotNull(result.StackTrace, "TestSuite StackTrace should not be null");
Assert.AreEqual(1, result.Children.Count(), "Child result count");
Assert.AreEqual(1, result.FailCount, "Failure count");
}
[Test]
public void RerunFixtureAfterTearDownFixed()
{
MisbehavingFixture fixture = new MisbehavingFixture();
fixture.BlowUpInTearDown = true;
ITestResult result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, result.Children.Count());
fixture.Reinitialize();
result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual( 1, fixture.SetUpCount, "setUpCount" );
Assert.AreEqual( 1, fixture.TearDownCount, "tearDownCount" );
}
[Test]
public void HandleSetUpAndTearDownWithTestInName()
{
SetUpAndTearDownWithTestInName fixture = new SetUpAndTearDownWithTestInName();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, fixture.SetUpCount);
Assert.AreEqual(1, fixture.TearDownCount);
}
//[Test]
//public void RunningSingleMethodCallsSetUpAndTearDown()
//{
// SetUpAndTearDownFixture fixture = new SetUpAndTearDownFixture();
// TestSuite suite = TestBuilder.MakeFixture(fixture.GetType());
// suite.Fixture = fixture;
// Test test = (Test)suite.Tests[0];
// suite.Run(TestListener.NULL, new NameFilter(test.TestName));
// Assert.AreEqual(1, fixture.SetUpCount);
// Assert.AreEqual(1, fixture.TearDownCount);
//}
[Test]
public void IgnoredFixtureShouldNotCallFixtureSetUpOrTearDown()
{
IgnoredFixture fixture = new IgnoredFixture();
TestSuite suite = new TestSuite("IgnoredFixtureSuite");
TestSuite fixtureSuite = TestBuilder.MakeFixture( fixture.GetType() );
TestMethod testMethod = (TestMethod)fixtureSuite.Tests[0];
suite.Add( fixtureSuite );
TestBuilder.RunTest(fixtureSuite, fixture);
Assert.IsFalse( fixture.SetupCalled, "OneTimeSetUp called running fixture");
Assert.IsFalse( fixture.TeardownCalled, "OneTimeSetUp called running fixture");
TestBuilder.RunTest(suite, fixture);
Assert.IsFalse( fixture.SetupCalled, "OneTimeSetUp called running enclosing suite");
Assert.IsFalse( fixture.TeardownCalled, "OneTimeTearDown called running enclosing suite");
TestBuilder.RunTest(testMethod, fixture);
Assert.IsFalse( fixture.SetupCalled, "OneTimeSetUp called running a test case");
Assert.IsFalse( fixture.TeardownCalled, "OneTimeTearDown called running a test case");
}
[Test]
public void FixtureWithNoTestsShouldNotCallFixtureSetUpOrTearDown()
{
FixtureWithNoTests fixture = new FixtureWithNoTests();
TestBuilder.RunTestFixture(fixture);
Assert.That( fixture.SetupCalled, Is.False, "OneTimeSetUp should not be called for a fixture with no tests" );
Assert.That( fixture.TeardownCalled, Is.False, "OneTimeTearDown should not be called for a fixture with no tests" );
}
[Test]
public void DisposeCalledOnceWhenFixtureImplementsIDisposable()
{
var fixture = new DisposableFixture();
TestBuilder.RunTestFixture(fixture);
Assert.That(fixture.DisposeCalled, Is.EqualTo(1));
Assert.That(fixture.Actions, Is.EqualTo(new object[] { "OneTimeSetUp", "OneTimeTearDown", "Dispose" }));
}
[Test]
public void DisposeCalledOnceWhenFixtureImplementsIDisposableAndHasTestCases()
{
var fixture = new DisposableFixtureWithTestCases();
TestBuilder.RunTestFixture(fixture);
Assert.That(fixture.DisposeCalled, Is.EqualTo(1));
}
}
#if !NETCOREAPP1_1
[TestFixture]
class ChangesMadeInFixtureSetUp
{
[OneTimeSetUp]
public void OneTimeSetUp()
{
// TODO: This test requires fixture setup and all tests to run on same thread
GenericIdentity identity = new GenericIdentity("foo");
Thread.CurrentPrincipal = new GenericPrincipal(identity, new string[0]);
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-GB");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
[Test]
public void TestThatChangesPersistUsingSameThread()
{
Assert.AreEqual("foo", Thread.CurrentPrincipal.Identity.Name);
Assert.AreEqual("en-GB", Thread.CurrentThread.CurrentCulture.Name);
Assert.AreEqual("en-GB", Thread.CurrentThread.CurrentUICulture.Name);
}
[Test, RequiresThread]
public void TestThatChangesPersistUsingSeparateThread()
{
Assert.AreEqual("foo", Thread.CurrentPrincipal.Identity.Name);
Assert.AreEqual("en-GB", Thread.CurrentThread.CurrentCulture.Name, "#CurrentCulture");
Assert.AreEqual("en-GB", Thread.CurrentThread.CurrentUICulture.Name, "#CurrentUICulture");
}
}
#endif
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.TeamFoundation.DistributedTask.Pipelines;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Agent.Worker;
using Microsoft.VisualStudio.Services.Agent.Worker.Build;
using Microsoft.VisualStudio.Services.Agent.Worker.Release;
using Microsoft.VisualStudio.Services.Agent.Worker.Telemetry;
using Microsoft.VisualStudio.Services.WebApi;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
namespace Microsoft.VisualStudio.Services.Agent.Tests.L1.Worker
{
public class TestResults
{
public int ReturnCode { get; internal set; }
public TaskResult Result { get; internal set; }
public bool TimedOut { get; internal set; }
}
public class L1TestBase : IDisposable
{
protected TimeSpan ChannelTimeout = TimeSpan.FromSeconds(100);
protected TimeSpan JobTimeout = TimeSpan.FromSeconds(100);
private List<IAgentService> _mockedServices = new List<IAgentService>();
protected List<Timeline> GetTimelines()
{
return GetMockedService<FakeJobServer>().Timelines.Values.ToList();
}
protected IList<TimelineRecord> GetSteps()
{
var timeline = GetTimelines()[0];
return timeline.Records.Where(x => x.RecordType == "Task").ToList();
}
protected T GetMockedService<T>()
{
return _mockedServices.Where(x => x is T).Cast<T>().Single();
}
protected IList<string> GetTimelineLogLines(TimelineRecord record)
{
var jobService = GetMockedService<FakeJobServer>();
var lines = jobService.LogLines.GetValueOrDefault(record.Log.Id).ToList();
if (lines.Count <= 0)
{
lines = new List<string>();
// Fall back to blobstore
foreach (var blobId in jobService.IdToBlobMapping.GetValueOrDefault(record.Log.Id))
{
lines.AddRange(jobService.UploadedLogBlobs.GetValueOrDefault(blobId));
}
}
return lines;
}
protected void AssertJobCompleted(int buildCount = 1)
{
Assert.Equal(buildCount, GetMockedService<FakeJobServer>().RecordedEvents.Where(x => x is JobCompletedEvent).Count());
}
protected static Pipelines.AgentJobRequestMessage LoadTemplateMessage(string jobId = "12f1170f-54f2-53f3-20dd-22fc7dff55f9", string jobName = "__default", string jobDisplayName = "Job", string checkoutRepoAlias = "self", int additionalRepos = 1)
{
var template = JobMessageTemplate;
template = template.Replace("$$PLANID$$", Guid.NewGuid().ToString());
template = template.Replace("$$JOBID$$", jobId, StringComparison.OrdinalIgnoreCase);
template = template.Replace("$$JOBNAME$$", jobName, StringComparison.OrdinalIgnoreCase);
template = template.Replace("$$JOBDISPLAYNAME$$", jobDisplayName, StringComparison.OrdinalIgnoreCase);
template = template.Replace("$$CHECKOUTREPOALIAS$$", checkoutRepoAlias, StringComparison.OrdinalIgnoreCase);
var sb = new StringBuilder();
for (int i = 0; i < additionalRepos; i++)
{
sb.Append(GetRepoJson("Repo" + (i + 2)));
}
template = template.Replace("$$ADDITIONALREPOS$$", sb.ToString(), StringComparison.OrdinalIgnoreCase);
return LoadJobMessageFromJSON(template);
}
private static string GetRepoJson(string repoAlias)
{
return String.Format(@",
{{
'properties': {{
'id': '{0}',
'type': 'Git',
'version': 'cf64a69d29ae2e01a655956f67ee0332ffb730a3',
'name': '{1}',
'project': '6302cb6f-c9d9-44c2-ae60-84eff8845059',
'defaultBranch': 'refs/heads/master',
'ref': 'refs/heads/master',
'url': 'https://[email protected]/alpeck/MyFirstProject/_git/{1}',
'versionInfo': {{
'author': '[PII]'
}},
'checkoutOptions': {{ }}
}},
'alias': '{1}',
'endpoint': {{
'name': 'SystemVssConnection'
}}
}}",
Guid.NewGuid(), repoAlias);
}
protected static Pipelines.AgentJobRequestMessage LoadJobMessageFromJSON(string message)
{
return JsonUtility.FromString<Pipelines.AgentJobRequestMessage>(message);
}
protected static TaskStep CreateScriptTask(string script)
{
var step = new TaskStep
{
Reference = new TaskStepDefinitionReference
{
Id = Guid.Parse("d9bafed4-0b18-4f58-968d-86655b4d2ce9"),
Name = "CmdLine",
Version = "2.164.0"
},
Name = "CmdLine",
DisplayName = "CmdLine",
Id = Guid.NewGuid()
};
step.Inputs.Add("script", script);
return step;
}
protected static TaskStep CreateNode10ScriptTask(string script)
{
var step = new TaskStep
{
Reference = new TaskStepDefinitionReference
{
Id = Guid.Parse("e9bafed4-0b18-4f58-968d-86655b4d2ce9"),
Name = "CmdLine",
Version = "2.177.3"
},
Name = "CmdLine",
DisplayName = "CmdLine",
Id = Guid.NewGuid()
};
step.Inputs.Add("script", script);
return step;
}
protected static TaskStep CreateCheckoutTask(string repoAlias)
{
var step = new TaskStep
{
Reference = new TaskStepDefinitionReference
{
Id = Guid.Parse("6d15af64-176c-496d-b583-fd2ae21d4df4"),
Name = "Checkout",
Version = "1.0.0"
},
Name = "Checkout",
DisplayName = "Checkout",
Id = Guid.NewGuid()
};
step.Inputs.Add("repository", repoAlias);
return step;
}
public void SetupL1([CallerMemberName] string testName = "")
{
// Clear working directory
string path = GetWorkingDirectory(testName);
if (File.Exists(path))
{
File.Delete(path);
}
// Fix localization
var assemblyLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var stringFile = Path.Combine(assemblyLocation, "en-US", "strings.json");
StringUtil.LoadExternalLocalization(stringFile);
_l1HostContext = new L1HostContext("Agent", GetLogFile(this, testName));
SetupMocks(_l1HostContext);
// Use different working directories for each test
var config = GetMockedService<FakeConfigurationStore>(); // TODO: Need to update this. can hack it for now.
config.WorkingDirectoryName = testName;
}
public string GetWorkingDirectory([CallerMemberName] string testName = "")
{
return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/TestRuns/" + testName + "/w";
}
public TrackingConfig GetTrackingConfig(Pipelines.AgentJobRequestMessage message, [CallerMemberName] string testName = "")
{
message.Variables.TryGetValue("system.collectionId", out VariableValue collectionIdVar);
message.Variables.TryGetValue("system.definitionId", out VariableValue definitionIdVar);
string filename;
if (message.Variables.TryGetValue("agent.useWorkspaceId", out _))
{
var repoTrackingInfos = message.Resources.Repositories.Select(repo => new RepositoryTrackingInfo(repo, "/")).ToList();
var workspaceIdentifier = TrackingConfigHashAlgorithm.ComputeHash(collectionIdVar?.Value, definitionIdVar?.Value, repoTrackingInfos);
filename = Path.Combine(GetWorkingDirectory(testName),
Constants.Build.Path.SourceRootMappingDirectory,
collectionIdVar.Value,
definitionIdVar.Value,
workspaceIdentifier,
Constants.Build.Path.TrackingConfigFile);
}
else
{
filename = Path.Combine(GetWorkingDirectory(testName),
Constants.Build.Path.SourceRootMappingDirectory,
collectionIdVar.Value,
definitionIdVar.Value,
Constants.Build.Path.TrackingConfigFile);
}
string content = File.ReadAllText(filename);
return JsonConvert.DeserializeObject<TrackingConfig>(content);
}
protected L1HostContext _l1HostContext;
protected async Task<TestResults> RunWorker(Pipelines.AgentJobRequestMessage message)
{
if (_l1HostContext == null)
{
throw new InvalidOperationException("Must call SetupL1() to initialize L1HostContext before calling RunWorker()");
}
await SetupMessage(_l1HostContext, message);
using (var cts = new CancellationTokenSource())
{
cts.CancelAfter((int)JobTimeout.TotalMilliseconds);
return await RunWorker(_l1HostContext, message, cts.Token);
}
}
private void SetupMocks(L1HostContext context)
{
_mockedServices.Add(context.SetupService<IConfigurationStore>(typeof(FakeConfigurationStore)));
_mockedServices.Add(context.SetupService<IJobServer>(typeof(FakeJobServer)));
_mockedServices.Add(context.SetupService<ITaskServer>(typeof(FakeTaskServer)));
_mockedServices.Add(context.SetupService<IBuildServer>(typeof(FakeBuildServer)));
_mockedServices.Add(context.SetupService<IReleaseServer>(typeof(FakeReleaseServer)));
_mockedServices.Add(context.SetupService<IAgentPluginManager>(typeof(FakeAgentPluginManager)));
_mockedServices.Add(context.SetupService<ITaskManager>(typeof(FakeTaskManager)));
_mockedServices.Add(context.SetupService<ICustomerIntelligenceServer>(typeof(FakeCustomerIntelligenceServer)));
}
private string GetLogFile(object testClass, string testMethod)
{
// Trim the test assembly's root namespace from the test class's full name.
var suiteName = testClass.GetType().FullName.Substring(
startIndex: typeof(Tests.TestHostContext).FullName.LastIndexOf(nameof(TestHostContext)));
var testName = testMethod.Replace(".", "_");
return Path.Combine(
Path.Combine(TestUtil.GetSrcPath(), "Test", "TestLogs"),
$"trace_{suiteName}_{testName}.log");
}
private async Task SetupMessage(HostContext context, Pipelines.AgentJobRequestMessage message)
{
// The agent assumes the server creates this
var jobServer = context.GetService<IJobServer>();
await jobServer.CreateTimelineAsync(message.Plan.ScopeIdentifier, message.Plan.PlanType, message.Plan.PlanId, message.Timeline.Id, default(CancellationToken));
}
private async Task<TestResults> RunWorker(HostContext HostContext, Pipelines.AgentJobRequestMessage message, CancellationToken jobRequestCancellationToken)
{
var worker = HostContext.GetService<IWorker>();
Task<int> workerTask = null;
// Setup the anonymous pipes to use for communication with the worker.
using (var processChannel = HostContext.CreateService<IProcessChannel>())
{
processChannel.StartServer(startProcess: (string pipeHandleOut, string pipeHandleIn) =>
{
// Run the worker
// Note: this happens on the same process as the test
workerTask = worker.RunAsync(
pipeIn: pipeHandleOut,
pipeOut: pipeHandleIn);
}, disposeClient: false); // Don't dispose the client because our process is both the client and the server
// Send the job request message to the worker
var body = JsonUtility.ToString(message);
using (var csSendJobRequest = new CancellationTokenSource(ChannelTimeout))
{
await processChannel.SendAsync(
messageType: MessageType.NewJobRequest,
body: body,
cancellationToken: csSendJobRequest.Token);
}
// wait for worker process or cancellation token been fired.
var completedTask = await Task.WhenAny(workerTask, Task.Delay(-1, jobRequestCancellationToken));
if (completedTask == workerTask)
{
int returnCode = await workerTask;
TaskResult result = TaskResultUtil.TranslateFromReturnCode(returnCode);
return new TestResults
{
ReturnCode = returnCode,
Result = result
};
}
else
{
return new TestResults
{
TimedOut = true
};
}
}
}
protected void TearDown()
{
this._l1HostContext?.Dispose();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this._l1HostContext?.Dispose();
}
}
protected static readonly String JobMessageTemplate = @"
{
'mask': [
{
'type': 'regex',
'value': 'accessTokenSecret'
},
{
'type': 'regex',
'value': 'accessTokenSecret'
}
],
'steps': [
{
'inputs': {
'repository': '$$CHECKOUTREPOALIAS$$'
},
'type': 'task',
'reference': {
'id': '6d15af64-176c-496d-b583-fd2ae21d4df4',
'name': 'Checkout',
'version': '1.0.0'
},
'condition': 'true',
'id': 'af08acd5-c28a-5b03-f5a9-06f9a40627bb',
'name': 'Checkout',
'displayName': 'Checkout'
},
{
'inputs': {
'script': 'echo Hello World!'
},
'type': 'task',
'reference': {
'id': 'd9bafed4-0b18-4f58-968d-86655b4d2ce9',
'name': 'CmdLine',
'version': '2.164.0'
},
'id': '9c939e41-62c2-5605-5e05-fc3554afc9f5',
'name': 'CmdLine',
'displayName': 'CmdLine'
}
],
'variables': {
'system': {
'value': 'build',
'isReadOnly': true
},
'system.hosttype': {
'value': 'build',
'isReadOnly': true
},
'system.servertype': {
'value': 'Hosted',
'isReadOnly': true
},
'system.culture': {
'value': 'en-US',
'isReadOnly': true
},
'system.collectionId': {
'value': '297a3210-e711-4ddf-857a-1df14915bb29',
'isReadOnly': true
},
'system.debug': {
'value': 'true',
'isReadOnly': true
},
'system.collectionUri': {
'value': 'https://codedev.ms/alpeck/',
'isReadOnly': true
},
'system.teamFoundationCollectionUri': {
'value': 'https://codedev.ms/alpeck/',
'isReadOnly': true
},
'system.taskDefinitionsUri': {
'value': 'https://codedev.ms/alpeck/',
'isReadOnly': true
},
'system.pipelineStartTime': {
'value': '2020-02-10 13:29:58-05:00',
'isReadOnly': true
},
'system.teamProject': {
'value': 'MyFirstProject',
'isReadOnly': true
},
'system.teamProjectId': {
'value': '6302cb6f-c9d9-44c2-ae60-84eff8845059',
'isReadOnly': true
},
'system.definitionId': {
'value': '2',
'isReadOnly': true
},
'build.definitionName': {
'value': 'MyFirstProject (1)',
'isReadOnly': true
},
'build.definitionVersion': {
'value': '1',
'isReadOnly': true
},
'build.queuedBy': {
'value': '[PII]',
'isReadOnly': true
},
'build.queuedById': {
'value': '00000002-0000-8888-8000-000000000000',
'isReadOnly': true
},
'build.requestedFor': {
'value': '[PII]',
'isReadOnly': true
},
'build.requestedForId': {
'value': '8546ffd5-88f3-69c1-ad8f-30c41e8ce5ad',
'isReadOnly': true
},
'build.requestedForEmail': {
'value': '[PII]',
'isReadOnly': true
},
'build.sourceVersion': {
'value': '[PII]',
'isReadOnly': true
},
'build.sourceBranch': {
'value': '[PII]',
'isReadOnly': true
},
'build.sourceBranchName': {
'value': '[PII]',
'isReadOnly': true
},
'build.reason': {
'value': 'IndividualCI',
'isReadOnly': true
},
'system.pullRequest.isFork': {
'value': 'False',
'isReadOnly': true
},
'system.jobParallelismTag': {
'value': 'Private',
'isReadOnly': true
},
'system.enableAccessToken': {
'value': 'SecretVariable',
'isReadOnly': true
},
'MSDEPLOY_HTTP_USER_AGENT': {
'value': 'VSTS_297a3210-e711-4ddf-857a-1df14915bb29_build_2_0',
'isReadOnly': true
},
'AZURE_HTTP_USER_AGENT': {
'value': 'VSTS_297a3210-e711-4ddf-857a-1df14915bb29_build_2_0',
'isReadOnly': true
},
'build.buildId': {
'value': '5',
'isReadOnly': true
},
'build.buildUri': {
'value': 'vstfs:///Build/Build/5',
'isReadOnly': true
},
'build.buildNumber': {
'value': '20200210.2',
'isReadOnly': true
},
'build.containerId': {
'value': '12',
'isReadOnly': true
},
'system.isScheduled': {
'value': 'False',
'isReadOnly': true
},
'system.definitionName': {
'value': 'MyFirstProject (1)',
'isReadOnly': true
},
'system.planId': {
'value': '$$PLANID$$',
'isReadOnly': true
},
'system.timelineId': {
'value': '$$PLANID$$',
'isReadOnly': true
},
'system.stageDisplayName': {
'value': '__default',
'isReadOnly': true
},
'system.stageId': {
'value': '96ac2280-8cb4-5df5-99de-dd2da759617d',
'isReadOnly': true
},
'system.stageName': {
'value': '__default',
'isReadOnly': true
},
'system.stageAttempt': {
'value': '1',
'isReadOnly': true
},
'system.phaseDisplayName': {
'value': 'Job',
'isReadOnly': true
},
'system.phaseId': {
'value': '3a3a2a60-14c7-570b-14a4-fa42ad92f52a',
'isReadOnly': true
},
'system.phaseName': {
'value': 'Job',
'isReadOnly': true
},
'system.phaseAttempt': {
'value': '1',
'isReadOnly': true
},
'system.jobIdentifier': {
'value': 'Job.$$JOBNAME$$',
'isReadOnly': true
},
'system.jobAttempt': {
'value': '1',
'isReadOnly': true
},
'System.JobPositionInPhase': {
'value': '1',
'isReadOnly': true
},
'System.TotalJobsInPhase': {
'value': '1',
'isReadOnly': true
},
'system.jobDisplayName': {
'value': 'Job',
'isReadOnly': true
},
'system.jobId': {
'value': '$$JOBID$$',
'isReadOnly': true
},
'system.jobName': {
'value': '$$JOBNAME$$',
'isReadOnly': true
},
'system.accessToken': {
'value': 'thisisanaccesstoken',
'isSecret': true
},
'agent.retainDefaultEncoding': {
'value': 'false',
'isReadOnly': true
},
'agent.readOnlyVariables': {
'value': 'true',
'isReadOnly': true
},
'agent.disablelogplugin.TestResultLogPlugin': {
'value': 'true',
'isReadOnly': true
},
'agent.disablelogplugin.TestFilePublisherPlugin': {
'value': 'true',
'isReadOnly': true
},
'build.repository.id': {
'value': '05bbff1a-ac43-4a40-a1c1-99f4e17e61dd',
'isReadOnly': true
},
'build.repository.name': {
'value': 'MyFirstProject',
'isReadOnly': true
},
'build.repository.uri': {
'value': 'https://[email protected]/alpeck/MyFirstProject/_git/MyFirstProject',
'isReadOnly': true
},
'build.sourceVersionAuthor': {
'value': '[PII]',
'isReadOnly': true
},
'build.sourceVersionMessage': {
'value': 'Update azure-pipelines-1.yml for Azure Pipelines',
'isReadOnly': true
}
},
'messageType': 'PipelineAgentJobRequest',
'plan': {
'scopeIdentifier': '6302cb6f-c9d9-44c2-ae60-84eff8845059',
'planType': 'Build',
'version': 9,
'planId': '$$PLANID$$',
'planGroup': 'Build:6302cb6f-c9d9-44c2-ae60-84eff8845059:5',
'artifactUri': 'vstfs:///Build/Build/5',
'artifactLocation': null,
'definition': {
'_links': {
'web': {
'href': 'https://codedev.ms/alpeck/6302cb6f-c9d9-44c2-ae60-84eff8845059/_build/definition?definitionId=2'
},
'self': {
'href': 'https://codedev.ms/alpeck/6302cb6f-c9d9-44c2-ae60-84eff8845059/_apis/build/Definitions/2'
}
},
'id': 2,
'name': 'MyFirstProject (1)'
},
'owner': {
'_links': {
'web': {
'href': 'https://codedev.ms/alpeck/6302cb6f-c9d9-44c2-ae60-84eff8845059/_build/results?buildId=5'
},
'self': {
'href': 'https://codedev.ms/alpeck/6302cb6f-c9d9-44c2-ae60-84eff8845059/_apis/build/Builds/5'
}
},
'id': 5,
'name': '20200210.2'
}
},
'timeline': {
'id': '$$PLANID$$',
'changeId': 5,
'location': null
},
'jobId': '$$JOBID$$',
'jobDisplayName': 'Job',
'jobName': '$$JOBNAME$$',
'jobContainer': null,
'requestId': 0,
'lockedUntil': '0001-01-01T00:00:00',
'resources': {
'endpoints': [
{
'data': {
'ServerId': '297a3210-e711-4ddf-857a-1df14915bb29',
'ServerName': 'alpeck'
},
'name': 'SystemVssConnection',
'url': 'https://codedev.ms/alpeck/',
'authorization': {
'parameters': {
'AccessToken': 'access'
},
'scheme': 'OAuth'
},
'isShared': false,
'isReady': true
}
],
'repositories': [
{
'properties': {
'id': '05bbff1a-ac43-4a40-a1c1-99f4e17e61dd',
'type': 'Git',
'version': 'cf64a69d29ae2e01a655956f67ee0332ffb730a3',
'name': 'MyFirstProject',
'project': '6302cb6f-c9d9-44c2-ae60-84eff8845059',
'defaultBranch': 'refs/heads/master',
'ref': 'refs/heads/master',
'url': 'https://[email protected]/alpeck/MyFirstProject/_git/MyFirstProject',
'versionInfo': {
'author': '[PII]'
},
'checkoutOptions': {}
},
'alias': 'self',
'endpoint': {
'name': 'SystemVssConnection'
}
}
$$ADDITIONALREPOS$$
]
},
'workspace': {}
}
".Replace("'", "\"");
}
}
| |
using System;
namespace PCSComUtils.Framework.TableFrame.DS
{
[Serializable]
public class sys_TableFieldVO
{
private int mTableFieldID;
private int mTableID;
private string mFieldName;
private string mCaptionJP;
private string mCaptionVN;
private string mCaptionEN;
private string mCaption;
private bool mInvisible;
private int mCharacterCase;
private int mAlign;
private int mWidth;
private int mSortType;
private string mFormats;
private bool mReadOnly;
private bool mNotAllowNull;
private bool mIdentityColumn;
private bool mUniqueColumn;
private string mItems;
private string mFromTable;
private string mFromField;
private string mFilterField1;
private string mFilterField2;
private string mFilterField3;
private int mFieldOrder;
private string mCaptionJP1;
private string mCaptionVN1;
private string mCaptionEN1;
private int mAlign1;
private int mWidth1;
private string mFormats1;
private string mCaptionJP2;
private string mCaptionVN2;
private string mCaptionEN2;
private int mAlign2;
private int mWidth2;
private string mFormats2;
private string mCaptionJP3;
private string mCaptionVN3;
private string mCaptionEN3;
private int mAlign3;
private int mWidth3;
private string mFormats3;
public int TableFieldID
{ set { mTableFieldID = value; }
get { return mTableFieldID; }
}
public int TableID
{ set { mTableID = value; }
get { return mTableID; }
}
public string FieldName
{ set { mFieldName = value; }
get { return mFieldName; }
}
public string CaptionJP
{ set { mCaptionJP = value; }
get { return mCaptionJP; }
}
public string CaptionVN
{ set { mCaptionVN = value; }
get { return mCaptionVN; }
}
public string CaptionEN
{ set { mCaptionEN = value; }
get { return mCaptionEN; }
}
public string Caption
{ set { mCaption = value; }
get { return mCaption; }
}
public bool Invisible
{ set { mInvisible = value; }
get { return mInvisible; }
}
public int CharacterCase
{ set { mCharacterCase = value; }
get { return mCharacterCase; }
}
public int Align
{ set { mAlign = value; }
get { return mAlign; }
}
public int Width
{ set { mWidth = value; }
get { return mWidth; }
}
public int SortType
{ set { mSortType = value; }
get { return mSortType; }
}
public string Formats
{ set { mFormats = value; }
get { return mFormats; }
}
public bool ReadOnly
{ set { mReadOnly = value; }
get { return mReadOnly; }
}
public bool NotAllowNull
{ set { mNotAllowNull = value; }
get { return mNotAllowNull; }
}
public bool IdentityColumn
{ set { mIdentityColumn = value; }
get { return mIdentityColumn; }
}
public bool UniqueColumn
{ set { mUniqueColumn = value; }
get { return mUniqueColumn; }
}
public string Items
{ set { mItems = value; }
get { return mItems; }
}
public string FromTable
{ set { mFromTable = value; }
get { return mFromTable; }
}
public string FromField
{ set { mFromField = value; }
get { return mFromField; }
}
public string FilterField1
{ set { mFilterField1 = value; }
get { return mFilterField1; }
}
public string FilterField2
{ set { mFilterField2 = value; }
get { return mFilterField2; }
}
public string FilterField3
{
set { mFilterField3 = value; }
get { return mFilterField3; }
}
public int FieldOrder
{ set { mFieldOrder = value; }
get { return mFieldOrder; }
}
public string CaptionJP1
{
set { mCaptionJP1 = value; }
get { return mCaptionJP1; }
}
public string CaptionVN1
{
set { mCaptionVN1 = value; }
get { return mCaptionVN1; }
}
public string CaptionEN1
{
set { mCaptionEN1 = value; }
get { return mCaptionEN1; }
}
public int Align1
{
set { mAlign1 = value; }
get { return mAlign1; }
}
public int Width1
{
set { mWidth1 = value; }
get { return mWidth1; }
}
public string Formats1
{
set { mFormats1 = value; }
get { return mFormats1; }
}
public string CaptionJP2
{
set { mCaptionJP2 = value; }
get { return mCaptionJP2; }
}
public string CaptionVN2
{
set { mCaptionVN2 = value; }
get { return mCaptionVN2; }
}
public string CaptionEN2
{
set { mCaptionEN2 = value; }
get { return mCaptionEN2; }
}
public int Align2
{
set { mAlign2 = value; }
get { return mAlign2; }
}
public int Width2
{
set { mWidth2 = value; }
get { return mWidth2; }
}
public string Formats2
{
set { mFormats2 = value; }
get { return mFormats2; }
}
public string CaptionJP3
{
set { mCaptionJP3 = value; }
get { return mCaptionJP3; }
}
public string CaptionVN3
{
set { mCaptionVN3 = value; }
get { return mCaptionVN3; }
}
public string CaptionEN3
{
set { mCaptionEN3 = value; }
get { return mCaptionEN3; }
}
public int Align3
{
set { mAlign3 = value; }
get { return mAlign3; }
}
public int Width3
{
set { mWidth3 = value; }
get { return mWidth3; }
}
public string Formats3
{
set { mFormats3 = value; }
get { return mFormats3; }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApiControllers.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tasks.Tests
{
public static class CancellationTokenTests
{
[Fact]
public static void CancellationTokenRegister_Exceptions()
{
CancellationToken token = new CancellationToken();
Assert.Throws<ArgumentNullException>(() => token.Register(null));
Assert.Throws<ArgumentNullException>(() => token.Register(null, false));
Assert.Throws<ArgumentNullException>(() => token.Register(null, null));
}
[Fact]
public static void CancellationTokenEquality()
{
//simple empty token comparisons
Assert.Equal(new CancellationToken(), new CancellationToken());
//inflated empty token comparisons
CancellationToken inflated_empty_CT1 = new CancellationToken();
bool temp1 = inflated_empty_CT1.CanBeCanceled; // inflate the CT
CancellationToken inflated_empty_CT2 = new CancellationToken();
bool temp2 = inflated_empty_CT2.CanBeCanceled; // inflate the CT
Assert.Equal(inflated_empty_CT1, new CancellationToken());
Assert.Equal(new CancellationToken(), inflated_empty_CT1);
Assert.Equal(inflated_empty_CT1, inflated_empty_CT2);
// inflated pre-set token comparisons
CancellationToken inflated_defaultSet_CT1 = new CancellationToken(true);
bool temp3 = inflated_defaultSet_CT1.CanBeCanceled; // inflate the CT
CancellationToken inflated_defaultSet_CT2 = new CancellationToken(true);
bool temp4 = inflated_defaultSet_CT2.CanBeCanceled; // inflate the CT
Assert.Equal(inflated_defaultSet_CT1, new CancellationToken(true));
Assert.Equal(inflated_defaultSet_CT1, inflated_defaultSet_CT2);
// Things that are not equal
Assert.NotEqual(inflated_empty_CT1, inflated_defaultSet_CT2);
Assert.NotEqual(inflated_empty_CT1, new CancellationToken(true));
Assert.NotEqual(new CancellationToken(true), inflated_empty_CT1);
}
[Fact]
public static void CancellationToken_GetHashCode()
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
int hash1 = cts.GetHashCode();
int hash2 = cts.Token.GetHashCode();
int hash3 = ct.GetHashCode();
Assert.Equal(hash1, hash2);
Assert.Equal(hash2, hash3);
CancellationToken defaultUnsetToken1 = new CancellationToken();
CancellationToken defaultUnsetToken2 = new CancellationToken();
int hashDefaultUnset1 = defaultUnsetToken1.GetHashCode();
int hashDefaultUnset2 = defaultUnsetToken2.GetHashCode();
Assert.Equal(hashDefaultUnset1, hashDefaultUnset2);
CancellationToken defaultSetToken1 = new CancellationToken(true);
CancellationToken defaultSetToken2 = new CancellationToken(true);
int hashDefaultSet1 = defaultSetToken1.GetHashCode();
int hashDefaultSet2 = defaultSetToken2.GetHashCode();
Assert.Equal(hashDefaultSet1, hashDefaultSet2);
Assert.NotEqual(hash1, hashDefaultUnset1);
Assert.NotEqual(hash1, hashDefaultSet1);
Assert.NotEqual(hashDefaultUnset1, hashDefaultSet1);
}
[Fact]
public static void CancellationToken_EqualityAndDispose()
{
//hashcode.
Assert.Throws<ObjectDisposedException>(
() =>
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.Dispose();
cts.Token.GetHashCode();
});
//x.Equals(y)
Assert.Throws<ObjectDisposedException>(
() =>
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.Dispose();
cts.Token.Equals(new CancellationToken());
});
//x.Equals(y)
Assert.Throws<ObjectDisposedException>(
() =>
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.Dispose();
new CancellationToken().Equals(cts.Token);
});
//x==y
Assert.Throws<ObjectDisposedException>(
() =>
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.Dispose();
bool result = cts.Token == new CancellationToken();
});
//x==y
Assert.Throws<ObjectDisposedException>(
() =>
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.Dispose();
bool result = new CancellationToken() == cts.Token;
});
//x!=y
Assert.Throws<ObjectDisposedException>(
() =>
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.Dispose();
bool result = cts.Token != new CancellationToken();
});
//x!=y
Assert.Throws<ObjectDisposedException>(
() =>
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.Dispose();
bool result = new CancellationToken() != cts.Token;
});
}
[Fact]
public static void TokenSourceDispose()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
CancellationTokenRegistration preDisposeRegistration = token.Register(() => { });
//WaitHandle and Dispose
WaitHandle wh = token.WaitHandle; //ok
Assert.NotNull(wh);
tokenSource.Dispose();
// Regression test: allow ctr.Dispose() to succeed when the backing cts has already been disposed.
try
{
preDisposeRegistration.Dispose();
}
catch
{
Assert.True(false, string.Format("TokenSourceDispose: > ctr.Dispose() failed when referring to a disposed CTS"));
}
bool cr = tokenSource.IsCancellationRequested; //this is ok after dispose.
tokenSource.Dispose(); //Repeat calls to Dispose should be ok.
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Relies on quirked behavior to not throw in token.Register when already disposed")]
[Fact]
public static void TokenSourceDispose_Negative()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
CancellationTokenRegistration preDisposeRegistration = token.Register(() => { });
//WaitHandle and Dispose
tokenSource.Dispose();
Assert.Throws<ObjectDisposedException>(() => token.WaitHandle);
Assert.Throws<ObjectDisposedException>(() =>tokenSource.Token);
//shouldn't throw
token.Register(() => { });
// Allow ctr.Dispose() to succeed when the backing cts has already been disposed.
preDisposeRegistration.Dispose();
//shouldn't throw
CancellationTokenSource.CreateLinkedTokenSource(new[] { token, token });
}
/// <summary>
/// Test passive signalling.
///
/// Gets a token, then polls on its ThrowIfCancellationRequested property.
/// </summary>
/// <returns></returns>
[Fact]
public static void CancellationTokenPassiveListening()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Assert.False(token.IsCancellationRequested,
"CancellationTokenPassiveListening: Cancellation should not have occurred yet.");
tokenSource.Cancel();
Assert.True(token.IsCancellationRequested,
"CancellationTokenPassiveListening: Cancellation should now have occurred.");
}
/// <summary>
/// Test active signalling.
///
/// Gets a token, registers a notification callback and ensure it is called.
/// </summary>
/// <returns></returns>
[Fact]
public static void CancellationTokenActiveListening()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
bool signalReceived = false;
token.Register(() => signalReceived = true);
Assert.False(signalReceived,
"CancellationTokenActiveListening: Cancellation should not have occurred yet.");
tokenSource.Cancel();
Assert.True(signalReceived,
"CancellationTokenActiveListening: Cancellation should now have occurred and caused a signal.");
}
private static event EventHandler AddAndRemoveDelegates_TestEvent;
[Fact]
public static void AddAndRemoveDelegates()
{
//Test various properties of callbacks:
// 1. the same handler can be added multiple times
// 2. removing a handler only removes one instance of a repeat
// 3. after some add and removes, everything appears to be correct
// 4. The behaviour matches the behaviour of a regular Event(Multicast-delegate).
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
List<string> output = new List<string>();
Action action1 = () => output.Add("action1");
Action action2 = () => output.Add("action2");
CancellationTokenRegistration reg1 = token.Register(action1);
CancellationTokenRegistration reg2 = token.Register(action2);
CancellationTokenRegistration reg3 = token.Register(action2);
CancellationTokenRegistration reg4 = token.Register(action1);
reg2.Dispose();
reg3.Dispose();
reg4.Dispose();
tokenSource.Cancel();
Assert.Equal(1, output.Count);
Assert.Equal("action1", output[0]);
// and prove this is what normal events do...
output.Clear();
EventHandler handler1 = (sender, obj) => output.Add("handler1");
EventHandler handler2 = (sender, obj) => output.Add("handler2");
AddAndRemoveDelegates_TestEvent += handler1;
AddAndRemoveDelegates_TestEvent += handler2;
AddAndRemoveDelegates_TestEvent += handler2;
AddAndRemoveDelegates_TestEvent += handler1;
AddAndRemoveDelegates_TestEvent -= handler2;
AddAndRemoveDelegates_TestEvent -= handler2;
AddAndRemoveDelegates_TestEvent -= handler1;
AddAndRemoveDelegates_TestEvent(null, EventArgs.Empty);
Assert.Equal(1, output.Count);
Assert.Equal("handler1", output[0]);
}
/// <summary>
/// Test late enlistment.
///
/// If a handler is added to a 'canceled' cancellation token, the handler is called immediately.
/// </summary>
/// <returns></returns>
[Fact]
public static void CancellationTokenLateEnlistment()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
bool signalReceived = false;
tokenSource.Cancel(); //Signal
//Late enlist.. should fire the delegate synchronously
token.Register(() => signalReceived = true);
Assert.True(signalReceived,
"CancellationTokenLateEnlistment: The signal should have been received even after late enlistment.");
}
/// <summary>
/// Test the wait handle exposed by the cancellation token
///
/// The signal occurs on a separate thread, and should happen after the wait begins.
/// </summary>
/// <returns></returns>
[Fact]
public static void CancellationTokenWaitHandle_SignalAfterWait()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task.Run(
() =>
{
tokenSource.Cancel(); //Signal
});
token.WaitHandle.WaitOne();
Assert.True(token.IsCancellationRequested,
"CancellationTokenWaitHandle_SignalAfterWait: the token should have been canceled.");
}
/// <summary>
/// Test the wait handle exposed by the cancellation token
///
/// The signal occurs on a separate thread, and should happen after the wait begins.
/// </summary>
/// <returns></returns>
[Fact]
public static void CancellationTokenWaitHandle_SignalBeforeWait()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
tokenSource.Cancel();
token.WaitHandle.WaitOne(); // the wait handle should already be set.
Assert.True(token.IsCancellationRequested,
"CancellationTokenWaitHandle_SignalBeforeWait: the token should have been canceled.");
}
/// <summary>
/// Test that WaitAny can be used with a CancellationToken.WaitHandle
/// </summary>
/// <returns></returns>
[Fact]
public static void CancellationTokenWaitHandle_WaitAny()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
CancellationToken tokenNoSource = new CancellationToken();
tokenSource.Cancel();
WaitHandle.WaitAny(new[] { token.WaitHandle, tokenNoSource.WaitHandle }); //make sure the dummy tokens has a valid WaitHanle
Assert.True(token.IsCancellationRequested,
"CancellationTokenWaitHandle_WaitAny: The token should have been canceled.");
}
[Fact]
public static void CreateLinkedTokenSource_Simple_TwoToken()
{
CancellationTokenSource signal1 = new CancellationTokenSource();
CancellationTokenSource signal2 = new CancellationTokenSource();
//Neither token is signalled.
CancellationTokenSource combined = CancellationTokenSource.CreateLinkedTokenSource(signal1.Token, signal2.Token);
Assert.False(combined.IsCancellationRequested,
"CreateLinkedToken_Simple_TwoToken: The combined token should start unsignalled");
signal1.Cancel();
Assert.True(combined.IsCancellationRequested,
"CreateLinkedToken_Simple_TwoToken: The combined token should now be signalled");
}
[Fact]
public static void CreateLinkedTokenSource_Simple_MultiToken()
{
CancellationTokenSource signal1 = new CancellationTokenSource();
CancellationTokenSource signal2 = new CancellationTokenSource();
CancellationTokenSource signal3 = new CancellationTokenSource();
//Neither token is signalled.
CancellationTokenSource combined = CancellationTokenSource.CreateLinkedTokenSource(new[] { signal1.Token, signal2.Token, signal3.Token });
Assert.False(combined.IsCancellationRequested,
"CreateLinkedToken_Simple_MultiToken: The combined token should start unsignalled");
signal1.Cancel();
Assert.True(combined.IsCancellationRequested,
"CreateLinkedToken_Simple_MultiToken: The combined token should now be signalled");
}
[Fact]
public static void CreateLinkedToken_SourceTokenAlreadySignalled()
{
//creating a combined token, when a source token is already signalled.
CancellationTokenSource signal1 = new CancellationTokenSource();
CancellationTokenSource signal2 = new CancellationTokenSource();
signal1.Cancel(); //early signal.
CancellationTokenSource combined = CancellationTokenSource.CreateLinkedTokenSource(signal1.Token, signal2.Token);
Assert.True(combined.IsCancellationRequested,
"CreateLinkedToken_SourceTokenAlreadySignalled: The combined token should immediately be in the signalled state.");
}
[Fact]
public static void CreateLinkedToken_MultistepComposition_SourceTokenAlreadySignalled()
{
//two-step composition
CancellationTokenSource signal1 = new CancellationTokenSource();
signal1.Cancel(); //early signal.
CancellationTokenSource signal2 = new CancellationTokenSource();
CancellationTokenSource combined1 = CancellationTokenSource.CreateLinkedTokenSource(signal1.Token, signal2.Token);
CancellationTokenSource signal3 = new CancellationTokenSource();
CancellationTokenSource combined2 = CancellationTokenSource.CreateLinkedTokenSource(signal3.Token, combined1.Token);
Assert.True(combined2.IsCancellationRequested,
"CreateLinkedToken_MultistepComposition_SourceTokenAlreadySignalled: The 2-step combined token should immediately be in the signalled state.");
}
[Fact]
public static void CallbacksOrderIsLifo()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
List<string> callbackOutput = new List<string>();
token.Register(() => callbackOutput.Add("Callback1"));
token.Register(() => callbackOutput.Add("Callback2"));
tokenSource.Cancel();
Assert.Equal("Callback2", callbackOutput[0]);
Assert.Equal("Callback1", callbackOutput[1]);
}
[Fact]
public static void Enlist_EarlyAndLate()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
CancellationTokenSource earlyEnlistedTokenSource = new CancellationTokenSource();
token.Register(() => earlyEnlistedTokenSource.Cancel());
tokenSource.Cancel();
Assert.Equal(true, earlyEnlistedTokenSource.IsCancellationRequested);
CancellationTokenSource lateEnlistedTokenSource = new CancellationTokenSource();
token.Register(() => lateEnlistedTokenSource.Cancel());
Assert.Equal(true, lateEnlistedTokenSource.IsCancellationRequested);
}
/// <summary>
/// This test from donnya. Thanks Donny.
/// </summary>
/// <returns></returns>
[Fact]
public static void WaitAll()
{
Debug.WriteLine("WaitAll: Testing CancellationTokenTests.WaitAll, If Join does not work, then a deadlock will occur.");
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationTokenSource signal2 = new CancellationTokenSource();
ManualResetEvent mre = new ManualResetEvent(false);
ManualResetEvent mre2 = new ManualResetEvent(false);
Task t = new Task(() =>
{
WaitHandle.WaitAll(new WaitHandle[] { tokenSource.Token.WaitHandle, signal2.Token.WaitHandle, mre });
mre2.Set();
});
t.Start();
tokenSource.Cancel();
signal2.Cancel();
mre.Set();
mre2.WaitOne();
t.Wait();
//true if the Join succeeds.. otherwise a deadlock will occur.
}
[Fact]
public static void BehaviourAfterCancelSignalled()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
token.Register(() => { });
tokenSource.Cancel();
}
[Fact]
public static void Cancel_ThrowOnFirstException()
{
ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false);
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
// Main test body
ArgumentException caughtException = null;
token.Register(() =>
{
throw new InvalidOperationException();
});
token.Register(() =>
{
throw new ArgumentException();
}); // !!NOTE: Due to LIFO ordering, this delegate should be the only one to run.
Task.Run(() =>
{
try
{
tokenSource.Cancel(true);
}
catch (ArgumentException ex)
{
caughtException = ex;
}
catch (Exception ex)
{
Assert.True(false, string.Format("Cancel_ThrowOnFirstException: The wrong exception type was thrown. ex=" + ex));
}
mre_CancelHasBeenEnacted.Set();
});
mre_CancelHasBeenEnacted.WaitOne();
Assert.NotNull(caughtException);
}
[Fact]
public static void Cancel_DontThrowOnFirstException()
{
ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false);
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
// Main test body
AggregateException caughtException = null;
token.Register(() => { throw new ArgumentException(); });
token.Register(() => { throw new InvalidOperationException(); });
Task.Run(
() =>
{
try
{
tokenSource.Cancel(false);
}
catch (AggregateException ex)
{
caughtException = ex;
}
mre_CancelHasBeenEnacted.Set();
}
);
mre_CancelHasBeenEnacted.WaitOne();
Assert.NotNull(caughtException);
Assert.Equal(2, caughtException.InnerExceptions.Count);
Assert.True(caughtException.InnerExceptions[0] is InvalidOperationException,
"Cancel_ThrowOnFirstException: Due to LIFO call order, the first inner exception should be an InvalidOperationException.");
Assert.True(caughtException.InnerExceptions[1] is ArgumentException,
"Cancel_ThrowOnFirstException: Due to LIFO call order, the second inner exception should be an ArgumentException.");
}
[Fact]
public static void CancellationRegistration_RepeatDispose()
{
Exception caughtException = null;
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
CancellationTokenRegistration registration = ct.Register(() => { });
try
{
registration.Dispose();
registration.Dispose();
}
catch (Exception ex)
{
caughtException = ex;
}
Assert.Null(caughtException);
}
[Fact]
public static void CancellationTokenRegistration_EqualityAndHashCode()
{
CancellationTokenSource outerCTS = new CancellationTokenSource();
{
// different registrations on 'different' default tokens
CancellationToken ct1 = new CancellationToken();
CancellationToken ct2 = new CancellationToken();
CancellationTokenRegistration ctr1 = ct1.Register(() => outerCTS.Cancel());
CancellationTokenRegistration ctr2 = ct2.Register(() => outerCTS.Cancel());
Assert.True(ctr1.Equals(ctr2),
"CancellationTokenRegistration_EqualityAndHashCode: [1]The two registrations should compare equal, as they are both dummies.");
Assert.True(ctr1 == ctr2,
"CancellationTokenRegistration_EqualityAndHashCode: [2]The two registrations should compare equal, as they are both dummies.");
Assert.False(ctr1 != ctr2,
"CancellationTokenRegistration_EqualityAndHashCode: [3]The two registrations should compare equal, as they are both dummies.");
Assert.True(ctr1.GetHashCode() == ctr2.GetHashCode(),
"CancellationTokenRegistration_EqualityAndHashCode: [4]The two registrations should have the same hashcode, as they are both dummies.");
}
{
// different registrations on the same already cancelled token
CancellationTokenSource cts = new CancellationTokenSource();
cts.Cancel();
CancellationToken ct = cts.Token;
CancellationTokenRegistration ctr1 = ct.Register(() => outerCTS.Cancel());
CancellationTokenRegistration ctr2 = ct.Register(() => outerCTS.Cancel());
Assert.True(ctr1.Equals(ctr2),
"CancellationTokenRegistration_EqualityAndHashCode: [1]The two registrations should compare equal, as they are both dummies due to CTS being already canceled.");
Assert.True(ctr1 == ctr2,
"CancellationTokenRegistration_EqualityAndHashCode: [2]The two registrations should compare equal, as they are both dummies due to CTS being already canceled.");
Assert.False(ctr1 != ctr2,
"CancellationTokenRegistration_EqualityAndHashCode: [3]The two registrations should compare equal, as they are both dummies due to CTS being already canceled.");
Assert.True(ctr1.GetHashCode() == ctr2.GetHashCode(),
"CancellationTokenRegistration_EqualityAndHashCode: [4]The two registrations should have the same hashcode, as they are both dummies due to CTS being already canceled.");
}
{
// different registrations on one real token
CancellationTokenSource cts1 = new CancellationTokenSource();
CancellationTokenRegistration ctr1 = cts1.Token.Register(() => outerCTS.Cancel());
CancellationTokenRegistration ctr2 = cts1.Token.Register(() => outerCTS.Cancel());
Assert.False(ctr1.Equals(ctr2),
"CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal.");
Assert.False(ctr1 == ctr2,
"CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal.");
Assert.True(ctr1 != ctr2,
"CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal.");
Assert.False(ctr1.GetHashCode() == ctr2.GetHashCode(),
"CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not have the same hashcode.");
CancellationTokenRegistration ctr1copy = ctr1;
Assert.True(ctr1 == ctr1copy, "The two registrations should be equal.");
}
{
// registrations on different real tokens.
// different registrations on one token
CancellationTokenSource cts1 = new CancellationTokenSource();
CancellationTokenSource cts2 = new CancellationTokenSource();
CancellationTokenRegistration ctr1 = cts1.Token.Register(() => outerCTS.Cancel());
CancellationTokenRegistration ctr2 = cts2.Token.Register(() => outerCTS.Cancel());
Assert.False(ctr1.Equals(ctr2),
"CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal.");
Assert.False(ctr1 == ctr2,
"CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal.");
Assert.True(ctr1 != ctr2,
"CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal.");
Assert.False(ctr1.GetHashCode() == ctr2.GetHashCode(),
"CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not have the same hashcode.");
CancellationTokenRegistration ctr1copy = ctr1;
Assert.True(ctr1.Equals(ctr1copy), "The two registrations should be equal.");
}
}
[Fact]
public static void CancellationTokenLinking_ODEinTarget()
{
CancellationTokenSource cts1 = new CancellationTokenSource();
CancellationTokenSource cts2 = CancellationTokenSource.CreateLinkedTokenSource(cts1.Token, new CancellationToken());
Exception caughtException = null;
cts2.Token.Register(() => { throw new ObjectDisposedException("myException"); });
try
{
cts1.Cancel(true);
}
catch (Exception ex)
{
caughtException = ex;
}
Assert.True(
caughtException is AggregateException
&& caughtException.InnerException is ObjectDisposedException
&& caughtException.InnerException.Message.Contains("myException"),
"CancellationTokenLinking_ODEinTarget: The users ODE should be caught. Actual:" + caughtException);
}
[Fact]
public static void ThrowIfCancellationRequested()
{
OperationCanceledException caughtEx = null;
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
ct.ThrowIfCancellationRequested();
// no exception should occur
cts.Cancel();
try
{
ct.ThrowIfCancellationRequested();
}
catch (OperationCanceledException oce)
{
caughtEx = oce;
}
Assert.NotNull(caughtEx);
Assert.Equal(ct, caughtEx.CancellationToken);
}
/// <summary>
/// ensure that calling ctr.Dipose() from within a cancellation callback will not deadlock.
/// </summary>
/// <returns></returns>
[Fact]
public static void DeregisterFromWithinACallbackIsSafe_BasicTest()
{
Debug.WriteLine("CancellationTokenTests.Bug720327_DeregisterFromWithinACallbackIsSafe_BasicTest()");
Debug.WriteLine(" - this method should complete immediately. Delay to complete indicates a deadlock failure.");
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
CancellationTokenRegistration ctr1 = ct.Register(() => { });
ct.Register(() => { ctr1.Dispose(); });
cts.Cancel();
Debug.WriteLine(" - Completed OK.");
}
// regression test
// Disposing a linkedCTS would previously throw if a source CTS had been
// disposed already. (it is an error for a user to get in this situation, but we decided to allow it to work).
[Fact]
public static void ODEWhenDisposingLinkedCTS()
{
try
{
// User passes a cancellation token (CT) to component A.
CancellationTokenSource userTokenSource = new CancellationTokenSource();
CancellationToken userToken = userTokenSource.Token;
// Component A implements "timeout", by creating its own cancellation token source (CTS) and invoking cts.Cancel() when the timeout timer fires.
CancellationTokenSource cts2 = new CancellationTokenSource();
CancellationToken cts2Token = cts2.Token;
// Component A creates a linked token source representing the CT from the user and the "timeout" CT.
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cts2Token, userToken);
// User calls Cancel() on his CTS and then Dispose()
userTokenSource.Cancel();
userTokenSource.Dispose();
// Component B correctly cancels the operation, returns to component A.
// ...
// Component A now disposes the linked CTS => ObjectDisposedException is thrown by cts.Dispose() because the user CTS was already disposed.
linkedTokenSource.Dispose();
}
catch (Exception ex)
{
if (ex is ObjectDisposedException)
{
Assert.True(false, string.Format("Bug901737_ODEWhenDisposingLinkedCTS: - ODE Occurred!"));
}
else
{
Assert.True(false, string.Format("Bug901737_ODEWhenDisposingLinkedCTS: - Exception Occurred (not an ODE!!): " + ex));
}
}
}
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
static void FinalizeHelper(DisposeTracker disposeTracker)
{
new DerivedCTS(disposeTracker);
}
// Several tests for deriving custom user types from CancellationTokenSource
[Fact]
public static void DerivedCancellationTokenSource()
{
// Verify that a derived CTS is functional
{
CancellationTokenSource c = new DerivedCTS(null);
CancellationToken token = c.Token;
var task = Task.Factory.StartNew(() => c.Cancel());
task.Wait();
Assert.True(token.IsCancellationRequested,
"DerivedCancellationTokenSource: The token should have been cancelled.");
}
// Verify that callback list on a derived CTS is functional
{
CancellationTokenSource c = new DerivedCTS(null);
CancellationToken token = c.Token;
int callbackRan = 0;
token.Register(() => Interlocked.Increment(ref callbackRan));
var task = Task.Factory.StartNew(() => c.Cancel());
task.Wait();
SpinWait.SpinUntil(() => callbackRan > 0, 1000);
Assert.True(callbackRan == 1,
"DerivedCancellationTokenSource: Expected the callback to run once. Instead, it ran " + callbackRan + " times.");
}
// Test the Dispose path for a class derived from CancellationTokenSource
{
var disposeTracker = new DisposeTracker();
CancellationTokenSource c = new DerivedCTS(disposeTracker);
Assert.True(c.Token.CanBeCanceled,
"DerivedCancellationTokenSource: The token should be cancellable.");
c.Dispose();
// Dispose() should have prevented the finalizer from running. Give the finalizer a chance to run. If this
// results in Dispose(false) getting called, we'll catch the issue.
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(disposeTracker.DisposeTrueCalled,
"DerivedCancellationTokenSource: Dispose(true) should have been called.");
Assert.False(disposeTracker.DisposeFalseCalled,
"DerivedCancellationTokenSource: Dispose(false) should not have been called.");
}
// Test the finalization code path for a class derived from CancellationTokenSource
{
var disposeTracker = new DisposeTracker();
FinalizeHelper(disposeTracker);
// Wait until the DerivedCTS object is finalized
SpinWait.SpinUntil(() =>
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
return disposeTracker.DisposeTrueCalled;
}, 500);
Assert.False(disposeTracker.DisposeTrueCalled,
"DerivedCancellationTokenSource: Dispose(true) should not have been called.");
Assert.True(disposeTracker.DisposeFalseCalled,
"DerivedCancellationTokenSource: Dispose(false) should have been called.");
}
// Verify that Dispose(false) is a no-op on the CTS. Dispose(false) should only release any unmanaged resources, and
// CTS does not currently hold any unmanaged resources.
{
var disposeTracker = new DisposeTracker();
DerivedCTS c = new DerivedCTS(disposeTracker);
c.DisposeUnmanaged();
// No exception expected - the CancellationTokenSource should be valid
Assert.True(c.Token.CanBeCanceled,
"DerivedCancellationTokenSource: The token should still be cancellable.");
Assert.False(disposeTracker.DisposeTrueCalled,
"DerivedCancellationTokenSource: Dispose(true) should not have been called.");
Assert.True(disposeTracker.DisposeFalseCalled,
"DerivedCancellationTokenSource: Dispose(false) should have run.");
}
}
// Several tests for deriving custom user types from CancellationTokenSource
[Fact]
public static void DerivedCancellationTokenSource_Negative()
{
// Test the Dispose path for a class derived from CancellationTokenSource
{
var disposeTracker = new DisposeTracker();
CancellationTokenSource c = new DerivedCTS(disposeTracker);
c.Dispose();
// Dispose() should have prevented the finalizer from running. Give the finalizer a chance to run. If this
// results in Dispose(false) getting called, we'll catch the issue.
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.Throws<ObjectDisposedException>(
() =>
{
// Accessing the Token property should throw an ObjectDisposedException
if (c.Token.CanBeCanceled)
Assert.True(false, string.Format("DerivedCancellationTokenSource: Accessing the Token property should throw an ObjectDisposedException, but it did not."));
else
Assert.True(false, string.Format("DerivedCancellationTokenSource: Accessing the Token property should throw an ObjectDisposedException, but it did not."));
});
}
}
[Fact]
public static void CancellationTokenSourceWithTimer()
{
TimeSpan bigTimeSpan = new TimeSpan(2000, 0, 0, 0, 0);
TimeSpan reasonableTimeSpan = new TimeSpan(0, 0, 1);
CancellationTokenSource cts = new CancellationTokenSource();
cts.Dispose();
//
// Test out some int-based timeout logic
//
cts = new CancellationTokenSource(-1); // should be an infinite timeout
CancellationToken token = cts.Token;
ManualResetEventSlim mres = new ManualResetEventSlim(false);
CancellationTokenRegistration ctr = token.Register(() => mres.Set());
Assert.False(token.IsCancellationRequested,
"CancellationTokenSourceWithTimer: Cancellation signaled on infinite timeout (int)!");
cts.CancelAfter(1000000);
Assert.False(token.IsCancellationRequested,
"CancellationTokenSourceWithTimer: Cancellation signaled on super-long timeout (int) !");
cts.CancelAfter(1);
Debug.WriteLine("CancellationTokenSourceWithTimer: > About to wait on cancellation that should occur soon (int)... if we hang, something bad happened");
mres.Wait();
cts.Dispose();
//
// Test out some TimeSpan-based timeout logic
//
TimeSpan prettyLong = new TimeSpan(1, 0, 0);
cts = new CancellationTokenSource(prettyLong);
token = cts.Token;
mres = new ManualResetEventSlim(false);
ctr = token.Register(() => mres.Set());
Assert.False(token.IsCancellationRequested,
"CancellationTokenSourceWithTimer: Cancellation signaled on super-long timeout (TimeSpan,1)!");
cts.CancelAfter(prettyLong);
Assert.False(token.IsCancellationRequested,
"CancellationTokenSourceWithTimer: Cancellation signaled on super-long timeout (TimeSpan,2) !");
cts.CancelAfter(new TimeSpan(1000));
Debug.WriteLine("CancellationTokenSourceWithTimer: > About to wait on cancellation that should occur soon (TimeSpan)... if we hang, something bad happened");
mres.Wait();
cts.Dispose();
}
[Fact]
public static void CancellationTokenSourceWithTimer_Negative()
{
TimeSpan bigTimeSpan = new TimeSpan(2000, 0, 0, 0, 0);
TimeSpan reasonableTimeSpan = new TimeSpan(0, 0, 1);
//
// Test exception logic
//
Assert.Throws<ArgumentOutOfRangeException>(
() => { new CancellationTokenSource(-2); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { new CancellationTokenSource(bigTimeSpan); });
CancellationTokenSource cts = new CancellationTokenSource();
Assert.Throws<ArgumentOutOfRangeException>(
() => { cts.CancelAfter(-2); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { cts.CancelAfter(bigTimeSpan); });
cts.Dispose();
Assert.Throws<ObjectDisposedException>(
() => { cts.CancelAfter(1); });
Assert.Throws<ObjectDisposedException>(
() => { cts.CancelAfter(reasonableTimeSpan); });
}
[Fact]
public static void EnlistWithSyncContext_BeforeCancel()
{
ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); //synchronization helper
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
// Install a SynchronizationContext...
SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current;
TestingSynchronizationContext testContext = new TestingSynchronizationContext();
SetSynchronizationContext(testContext);
// Main test body
// register a null delegate, but use the currently registered syncContext.
// the testSyncContext will track that it was used when the delegate is invoked.
token.Register(() => { }, true);
Task.Run(
() =>
{
tokenSource.Cancel();
mre_CancelHasBeenEnacted.Set();
}
);
mre_CancelHasBeenEnacted.WaitOne();
Assert.True(testContext.DidSendOccur,
"EnlistWithSyncContext_BeforeCancel: the delegate should have been called via Send to SyncContext.");
//Cleanup.
SetSynchronizationContext(prevailingSyncCtx);
}
[Fact]
public static void EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate()
{
ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); //synchronization helper
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
// Install a SynchronizationContext...
SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current;
TestingSynchronizationContext testContext = new TestingSynchronizationContext();
SetSynchronizationContext(testContext);
// Main test body
AggregateException caughtException = null;
// register a null delegate, but use the currently registered syncContext.
// the testSyncContext will track that it was used when the delegate is invoked.
token.Register(() => { throw new ArgumentException(); }, true);
Task.Run(
() =>
{
try
{
tokenSource.Cancel();
}
catch (AggregateException ex)
{
caughtException = ex;
}
mre_CancelHasBeenEnacted.Set();
}
);
mre_CancelHasBeenEnacted.WaitOne();
Assert.True(testContext.DidSendOccur,
"EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate: the delegate should have been called via Send to SyncContext.");
Assert.NotNull(caughtException);
Assert.Equal(1, caughtException.InnerExceptions.Count);
Assert.True(caughtException.InnerExceptions[0] is ArgumentException,
"EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate: The inner exception should be an ArgumentException.");
//Cleanup.
SetSynchronizationContext(prevailingSyncCtx);
}
[Fact]
public static void EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate_ThrowOnFirst()
{
ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); //synchronization helper
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
// Install a SynchronizationContext...
SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current;
TestingSynchronizationContext testContext = new TestingSynchronizationContext();
SetSynchronizationContext(testContext);
// Main test body
ArgumentException caughtException = null;
// register a null delegate, but use the currently registered syncContext.
// the testSyncContext will track that it was used when the delegate is invoked.
token.Register(() => { throw new ArgumentException(); }, true);
Task.Run(
() =>
{
try
{
tokenSource.Cancel(true);
}
catch (ArgumentException ex)
{
caughtException = ex;
}
mre_CancelHasBeenEnacted.Set();
}
);
mre_CancelHasBeenEnacted.WaitOne();
Assert.True(testContext.DidSendOccur,
"EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate_ThrowOnFirst: the delegate should have been called via Send to SyncContext.");
Assert.NotNull(caughtException);
//Cleanup
SetSynchronizationContext(prevailingSyncCtx);
}
// Test that we marshal exceptions back if we run callbacks on a sync context.
// (This assumes that a syncContext.Send() may not be doing the marshalling itself).
[Fact]
public static void SyncContextWithExceptionThrowingCallback()
{
Exception caughtEx1 = null;
AggregateException caughtEx2 = null;
SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current;
SetSynchronizationContext(new ThreadCrossingSynchronizationContext());
// -- Test 1 -- //
CancellationTokenSource cts = new CancellationTokenSource();
cts.Token.Register(
() => { throw new Exception("testEx1"); }, true);
try
{
cts.Cancel(true); //throw on first exception
}
catch (Exception ex)
{
caughtEx1 = (AggregateException)ex;
}
Assert.NotNull(caughtEx1);
// -- Test 2 -- //
cts = new CancellationTokenSource();
cts.Token.Register(
() => { throw new ArgumentException("testEx2"); }, true);
try
{
cts.Cancel(false); //do not throw on first exception
}
catch (AggregateException ex)
{
caughtEx2 = (AggregateException)ex;
}
Assert.NotNull(caughtEx2);
Assert.Equal(1, caughtEx2.InnerExceptions.Count);
// clean up
SetSynchronizationContext(prevailingSyncCtx);
}
[Fact]
public static void Bug720327_DeregisterFromWithinACallbackIsSafe_SyncContextTest()
{
Debug.WriteLine("* CancellationTokenTests.Bug720327_DeregisterFromWithinACallbackIsSafe_SyncContextTest()");
Debug.WriteLine(" - this method should complete immediately. Delay to complete indicates a deadlock failure.");
//Install our syncContext.
SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current;
ThreadCrossingSynchronizationContext threadCrossingSyncCtx = new ThreadCrossingSynchronizationContext();
SetSynchronizationContext(threadCrossingSyncCtx);
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
CancellationTokenRegistration ctr1 = ct.Register(() => { });
CancellationTokenRegistration ctr2 = ct.Register(() => { });
CancellationTokenRegistration ctr3 = ct.Register(() => { });
CancellationTokenRegistration ctr4 = ct.Register(() => { });
ct.Register(() => { ctr1.Dispose(); }, true); // with a custom syncContext
ct.Register(() => { ctr2.Dispose(); }, false); // without
ct.Register(() => { ctr3.Dispose(); }, true); // with a custom syncContext
ct.Register(() => { ctr4.Dispose(); }, false); // without
cts.Cancel();
Debug.WriteLine(" - Completed OK.");
//cleanup
SetSynchronizationContext(prevailingSyncCtx);
}
#region Helper Classes and Methods
private class TestingSynchronizationContext : SynchronizationContext
{
public bool DidSendOccur = false;
override public void Send(SendOrPostCallback d, Object state)
{
//Note: another idea was to install this syncContext on the executing thread.
//unfortunately, the ExecutionContext business gets in the way and reestablishes a default SyncContext.
DidSendOccur = true;
base.Send(d, state); // call the delegate with our syncContext installed.
}
}
/// <summary>
/// This syncContext uses a different thread to run the work
/// This is similar to how WindowsFormsSynchronizationContext works.
/// </summary>
private class ThreadCrossingSynchronizationContext : SynchronizationContext
{
public bool DidSendOccur = false;
override public void Send(SendOrPostCallback d, Object state)
{
Exception marshalledException = null;
Task t = new Task(
(passedInState) =>
{
//Debug.WriteLine(" threadCrossingSyncContext..running callback delegate on threadID = " + Thread.CurrentThread.ManagedThreadId);
try
{
d(passedInState);
}
catch (Exception e)
{
marshalledException = e;
}
}, state);
t.Start();
t.Wait();
//t.Start(state);
//t.Join();
if (marshalledException != null)
throw new AggregateException("DUMMY: ThreadCrossingSynchronizationContext.Send captured and propogated an exception",
marshalledException);
}
}
/// <summary>
/// A test class derived from CancellationTokenSource
/// </summary>
internal class DerivedCTS : CancellationTokenSource
{
private DisposeTracker _disposeTracker;
public DerivedCTS(DisposeTracker disposeTracker)
{
_disposeTracker = disposeTracker;
}
protected override void Dispose(bool disposing)
{
// Dispose any derived class state. DerivedCTS simply records that Dispose() has been called.
if (_disposeTracker != null)
{
if (disposing) { _disposeTracker.DisposeTrueCalled = true; }
else { _disposeTracker.DisposeFalseCalled = true; }
}
// Dispose the state in the CancellationTokenSource base class
base.Dispose(disposing);
}
/// <summary>
/// A helper method to call Dispose(false). That allows us to easily simulate finalization of CTS, while still maintaining
/// a reference to the CTS.
/// </summary>
public void DisposeUnmanaged()
{
Dispose(false);
}
~DerivedCTS()
{
Dispose(false);
}
}
/// <summary>
/// A simple class to track whether Dispose(bool) method has been called and if so, what was the bool flag.
/// </summary>
internal class DisposeTracker
{
public bool DisposeTrueCalled = false;
public bool DisposeFalseCalled = false;
}
public static void SetSynchronizationContext(SynchronizationContext sc)
{
SynchronizationContext.SetSynchronizationContext(sc);
}
#endregion
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* 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 ReaderException = com.google.zxing.ReaderException;
using ResultPoint = com.google.zxing.ResultPoint;
using ResultPointCallback = com.google.zxing.ResultPointCallback;
using BitMatrix = com.google.zxing.common.BitMatrix;
using System.Collections.Generic;
namespace com.google.zxing.qrcode.detector
{
/// <summary> <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder
/// patterns but are smaller and appear at regular intervals throughout the image.</p>
///
/// <p>At the moment this only looks for the bottom-right alignment pattern.</p>
///
/// <p>This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied,
/// pasted and stripped down here for maximum performance but does unfortunately duplicate
/// some code.</p>
///
/// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source
/// </author>
sealed class AlignmentPatternFinder
{
//UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private BitMatrix image;
//UPGRADE_NOTE: Final was removed from the declaration of 'possibleCenters '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private List<object> possibleCenters;
//UPGRADE_NOTE: Final was removed from the declaration of 'startX '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private int startX;
//UPGRADE_NOTE: Final was removed from the declaration of 'startY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private int startY;
//UPGRADE_NOTE: Final was removed from the declaration of 'width '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private int width;
//UPGRADE_NOTE: Final was removed from the declaration of 'height '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private int height;
//UPGRADE_NOTE: Final was removed from the declaration of 'moduleSize '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private float moduleSize;
//UPGRADE_NOTE: Final was removed from the declaration of 'crossCheckStateCount '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private int[] crossCheckStateCount;
//UPGRADE_NOTE: Final was removed from the declaration of 'resultPointCallback '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private ResultPointCallback resultPointCallback;
/// <summary> <p>Creates a finder that will look in a portion of the whole image.</p>
///
/// </summary>
/// <param name="image">image to search
/// </param>
/// <param name="startX">left column from which to start searching
/// </param>
/// <param name="startY">top row from which to start searching
/// </param>
/// <param name="width">width of region to search
/// </param>
/// <param name="height">height of region to search
/// </param>
/// <param name="moduleSize">estimated module size so far
/// </param>
internal AlignmentPatternFinder(BitMatrix image, int startX, int startY, int width, int height, float moduleSize, ResultPointCallback resultPointCallback)
{
this.image = image;
this.possibleCenters = new List<object>();
this.startX = startX;
this.startY = startY;
this.width = width;
this.height = height;
this.moduleSize = moduleSize;
this.crossCheckStateCount = new int[3];
this.resultPointCallback = resultPointCallback;
}
/// <summary> <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since
/// it's pretty performance-critical and so is written to be fast foremost.</p>
///
/// </summary>
/// <returns> {@link AlignmentPattern} if found
/// </returns>
/// <throws> ReaderException if not found </throws>
internal AlignmentPattern find()
{
int startX = this.startX;
int height = this.height;
int maxJ = startX + width;
int middleI = startY + (height >> 1);
// We are looking for black/white/black modules in 1:1:1 ratio;
// this tracks the number of black/white/black modules seen so far
int[] stateCount = new int[3];
for (int iGen = 0; iGen < height; iGen++)
{
// Search from middle outwards
int i = middleI + ((iGen & 0x01) == 0?((iGen + 1) >> 1):- ((iGen + 1) >> 1));
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
int j = startX;
// Burn off leading white pixels before anything else; if we start in the middle of
// a white run, it doesn't make sense to count its length, since we don't know if the
// white run continued to the left of the start point
while (j < maxJ && !image.get_Renamed(j, i))
{
j++;
}
int currentState = 0;
while (j < maxJ)
{
if (image.get_Renamed(j, i))
{
// Black pixel
if (currentState == 1)
{
// Counting black pixels
stateCount[currentState]++;
}
else
{
// Counting white pixels
if (currentState == 2)
{
// A winner?
if (foundPatternCross(stateCount))
{
// Yes
AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j);
if (confirmed != null)
{
return confirmed;
}
}
stateCount[0] = stateCount[2];
stateCount[1] = 1;
stateCount[2] = 0;
currentState = 1;
}
else
{
stateCount[++currentState]++;
}
}
}
else
{
// White pixel
if (currentState == 1)
{
// Counting black pixels
currentState++;
}
stateCount[currentState]++;
}
j++;
}
if (foundPatternCross(stateCount))
{
AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ);
if (confirmed != null)
{
return confirmed;
}
}
}
// Hmm, nothing we saw was observed and confirmed twice. If we had
// any guess at all, return it.
if (!(possibleCenters.Count == 0))
{
return (AlignmentPattern) possibleCenters[0];
}
throw ReaderException.Instance;
}
/// <summary> Given a count of black/white/black pixels just seen and an end position,
/// figures the location of the center of this black/white/black run.
/// </summary>
private static float centerFromEnd(int[] stateCount, int end)
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
return (float) (end - stateCount[2]) - stateCount[1] / 2.0f;
}
/// <param name="stateCount">count of black/white/black pixels just read
/// </param>
/// <returns> true iff the proportions of the counts is close enough to the 1/1/1 ratios
/// used by alignment patterns to be considered a match
/// </returns>
private bool foundPatternCross(int[] stateCount)
{
float moduleSize = this.moduleSize;
float maxVariance = moduleSize / 2.0f;
for (int i = 0; i < 3; i++)
{
if (System.Math.Abs(moduleSize - stateCount[i]) >= maxVariance)
{
return false;
}
}
return true;
}
/// <summary> <p>After a horizontal scan finds a potential alignment pattern, this method
/// "cross-checks" by scanning down vertically through the center of the possible
/// alignment pattern to see if the same proportion is detected.</p>
///
/// </summary>
/// <param name="startI">row where an alignment pattern was detected
/// </param>
/// <param name="centerJ">center of the section that appears to cross an alignment pattern
/// </param>
/// <param name="maxCount">maximum reasonable number of modules that should be
/// observed in any reading state, based on the results of the horizontal scan
/// </param>
/// <returns> vertical center of alignment pattern, or {@link Float#NaN} if not found
/// </returns>
private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal)
{
BitMatrix image = this.image;
int maxI = image.Height;
int[] stateCount = crossCheckStateCount;
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
// Start counting up from center
int i = startI;
while (i >= 0 && image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount)
{
stateCount[1]++;
i--;
}
// If already too many modules in this state or ran off the edge:
if (i < 0 || stateCount[1] > maxCount)
{
return System.Single.NaN;
}
while (i >= 0 && !image.get_Renamed(centerJ, i) && stateCount[0] <= maxCount)
{
stateCount[0]++;
i--;
}
if (stateCount[0] > maxCount)
{
return System.Single.NaN;
}
// Now also count down from center
i = startI + 1;
while (i < maxI && image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount)
{
stateCount[1]++;
i++;
}
if (i == maxI || stateCount[1] > maxCount)
{
return System.Single.NaN;
}
while (i < maxI && !image.get_Renamed(centerJ, i) && stateCount[2] <= maxCount)
{
stateCount[2]++;
i++;
}
if (stateCount[2] > maxCount)
{
return System.Single.NaN;
}
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
{
return System.Single.NaN;
}
return foundPatternCross(stateCount)?centerFromEnd(stateCount, i):System.Single.NaN;
}
/// <summary> <p>This is called when a horizontal scan finds a possible alignment pattern. It will
/// cross check with a vertical scan, and if successful, will see if this pattern had been
/// found on a previous horizontal scan. If so, we consider it confirmed and conclude we have
/// found the alignment pattern.</p>
///
/// </summary>
/// <param name="stateCount">reading state module counts from horizontal scan
/// </param>
/// <param name="i">row where alignment pattern may be found
/// </param>
/// <param name="j">end of possible alignment pattern in row
/// </param>
/// <returns> {@link AlignmentPattern} if we have found the same pattern twice, or null if not
/// </returns>
private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j)
{
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
float centerJ = centerFromEnd(stateCount, j);
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
float centerI = crossCheckVertical(i, (int) centerJ, 2 * stateCount[1], stateCountTotal);
if (!System.Single.IsNaN(centerI))
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
float estimatedModuleSize = (float) (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f;
int max = possibleCenters.Count;
for (int index = 0; index < max; index++)
{
AlignmentPattern center = (AlignmentPattern) possibleCenters[index];
// Look for about the same center and module size:
if (center.aboutEquals(estimatedModuleSize, centerI, centerJ))
{
return new AlignmentPattern(centerJ, centerI, estimatedModuleSize);
}
}
// Hadn't found this before; save it
ResultPoint point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize);
possibleCenters.Add(point);
if (resultPointCallback != null)
{
resultPointCallback.foundPossibleResultPoint(point);
}
}
return null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Collections;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Utils;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Interactivity;
using Avalonia.Threading;
using Avalonia.VisualTree;
namespace Avalonia.Controls
{
/// <summary>
/// Displays a hierarchical tree of data.
/// </summary>
public class TreeView : ItemsControl, ICustomKeyboardNavigation
{
/// <summary>
/// Defines the <see cref="AutoScrollToSelectedItem"/> property.
/// </summary>
public static readonly StyledProperty<bool> AutoScrollToSelectedItemProperty =
SelectingItemsControl.AutoScrollToSelectedItemProperty.AddOwner<TreeView>();
/// <summary>
/// Defines the <see cref="SelectedItem"/> property.
/// </summary>
public static readonly DirectProperty<TreeView, object?> SelectedItemProperty =
SelectingItemsControl.SelectedItemProperty.AddOwner<TreeView>(
o => o.SelectedItem,
(o, v) => o.SelectedItem = v);
/// <summary>
/// Defines the <see cref="SelectedItems"/> property.
/// </summary>
public static readonly DirectProperty<TreeView, IList> SelectedItemsProperty =
AvaloniaProperty.RegisterDirect<TreeView, IList>(
nameof(SelectedItems),
o => o.SelectedItems,
(o, v) => o.SelectedItems = v);
/// <summary>
/// Defines the <see cref="SelectionMode"/> property.
/// </summary>
public static readonly StyledProperty<SelectionMode> SelectionModeProperty =
ListBox.SelectionModeProperty.AddOwner<TreeView>();
private static readonly IList Empty = Array.Empty<object>();
private object? _selectedItem;
private IList? _selectedItems;
private bool _syncingSelectedItems;
/// <summary>
/// Initializes static members of the <see cref="TreeView"/> class.
/// </summary>
static TreeView()
{
// HACK: Needed or SelectedItem property will not be found in Release build.
}
/// <summary>
/// Occurs when the control's selection changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs>? SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
/// <summary>
/// Gets the <see cref="ITreeItemContainerGenerator"/> for the tree view.
/// </summary>
public new ITreeItemContainerGenerator ItemContainerGenerator =>
(ITreeItemContainerGenerator)base.ItemContainerGenerator;
/// <summary>
/// Gets or sets a value indicating whether to automatically scroll to newly selected items.
/// </summary>
public bool AutoScrollToSelectedItem
{
get => GetValue(AutoScrollToSelectedItemProperty);
set => SetValue(AutoScrollToSelectedItemProperty, value);
}
/// <summary>
/// Gets or sets the selection mode.
/// </summary>
public SelectionMode SelectionMode
{
get => GetValue(SelectionModeProperty);
set => SetValue(SelectionModeProperty, value);
}
/// <summary>
/// Gets or sets the selected item.
/// </summary>
/// <remarks>
/// Note that setting this property only currently works if the item is expanded to be visible.
/// To select non-expanded nodes use `Selection.SelectedIndex`.
/// </remarks>
public object? SelectedItem
{
get => _selectedItem;
set
{
var selectedItems = SelectedItems;
SetAndRaise(SelectedItemProperty, ref _selectedItem, value);
if (value != null)
{
if (selectedItems.Count != 1 || selectedItems[0] != value)
{
SelectSingleItem(value);
}
}
else if (SelectedItems.Count > 0)
{
SelectedItems.Clear();
}
}
}
/// <summary>
/// Gets or sets the selected items.
/// </summary>
public IList SelectedItems
{
get
{
if (_selectedItems == null)
{
_selectedItems = new AvaloniaList<object>();
SubscribeToSelectedItems();
}
return _selectedItems;
}
set
{
if (value?.IsFixedSize == true || value?.IsReadOnly == true)
{
throw new NotSupportedException(
"Cannot use a fixed size or read-only collection as SelectedItems.");
}
UnsubscribeFromSelectedItems();
_selectedItems = value ?? new AvaloniaList<object>();
SubscribeToSelectedItems();
}
}
/// <summary>
/// Expands the specified <see cref="TreeViewItem"/> all descendent <see cref="TreeViewItem"/>s.
/// </summary>
/// <param name="item">The item to expand.</param>
public void ExpandSubTree(TreeViewItem item)
{
item.IsExpanded = true;
if (item.Presenter?.Panel != null)
{
foreach (var child in item.Presenter.Panel.Children)
{
if (child is TreeViewItem treeViewItem)
{
ExpandSubTree(treeViewItem);
}
}
}
}
/// <summary>
/// Selects all items in the <see cref="TreeView"/>.
/// </summary>
/// <remarks>
/// Note that this method only selects nodes currently visible due to their parent nodes
/// being expanded: it does not expand nodes.
/// </remarks>
public void SelectAll()
{
SynchronizeItems(SelectedItems, ItemContainerGenerator.Index!.Items);
}
/// <summary>
/// Deselects all items in the <see cref="TreeView"/>.
/// </summary>
public void UnselectAll()
{
SelectedItems.Clear();
}
/// <summary>
/// Subscribes to the <see cref="SelectedItems"/> CollectionChanged event, if any.
/// </summary>
private void SubscribeToSelectedItems()
{
if (_selectedItems is INotifyCollectionChanged incc)
{
incc.CollectionChanged += SelectedItemsCollectionChanged;
}
SelectedItemsCollectionChanged(
_selectedItems,
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
private void SelectSingleItem(object item)
{
_syncingSelectedItems = true;
SelectedItems.Clear();
SelectedItems.Add(item);
_syncingSelectedItems = false;
SetAndRaise(SelectedItemProperty, ref _selectedItem, item);
}
/// <summary>
/// Called when the <see cref="SelectedItems"/> CollectionChanged event is raised.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void SelectedItemsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
IList? added = null;
IList? removed = null;
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
SelectedItemsAdded(e.NewItems!.Cast<object>().ToArray());
if (AutoScrollToSelectedItem)
{
var container = ItemContainerGenerator.Index!.ContainerFromItem(e.NewItems![0]!);
container?.BringIntoView();
}
added = e.NewItems;
break;
case NotifyCollectionChangedAction.Remove:
if (!_syncingSelectedItems)
{
if (SelectedItems.Count == 0)
{
SelectedItem = null;
}
else
{
var selectedIndex = SelectedItems.IndexOf(_selectedItem);
if (selectedIndex == -1)
{
var old = _selectedItem;
_selectedItem = SelectedItems[0];
RaisePropertyChanged(SelectedItemProperty, old, _selectedItem);
}
}
}
foreach (var item in e.OldItems!)
{
MarkItemSelected(item, false);
}
removed = e.OldItems;
break;
case NotifyCollectionChangedAction.Reset:
foreach (IControl container in ItemContainerGenerator.Index!.Containers)
{
MarkContainerSelected(container, false);
}
if (SelectedItems.Count > 0)
{
SelectedItemsAdded(SelectedItems);
added = SelectedItems;
}
else if (!_syncingSelectedItems)
{
SelectedItem = null;
}
break;
case NotifyCollectionChangedAction.Replace:
foreach (var item in e.OldItems!)
{
MarkItemSelected(item, false);
}
foreach (var item in e.NewItems!)
{
MarkItemSelected(item, true);
}
if (SelectedItem != SelectedItems[0] && !_syncingSelectedItems)
{
var oldItem = SelectedItem;
var item = SelectedItems[0];
_selectedItem = item;
RaisePropertyChanged(SelectedItemProperty, oldItem, item);
}
added = e.NewItems;
removed = e.OldItems;
break;
}
if (added?.Count > 0 || removed?.Count > 0)
{
var changed = new SelectionChangedEventArgs(
SelectingItemsControl.SelectionChangedEvent,
removed ?? Empty,
added ?? Empty);
RaiseEvent(changed);
}
}
private void MarkItemSelected(object item, bool selected)
{
var container = ItemContainerGenerator.Index!.ContainerFromItem(item)!;
MarkContainerSelected(container, selected);
}
private void SelectedItemsAdded(IList items)
{
if (items.Count == 0)
{
return;
}
foreach (object item in items)
{
MarkItemSelected(item, true);
}
if (SelectedItem == null && !_syncingSelectedItems)
{
SetAndRaise(SelectedItemProperty, ref _selectedItem, items[0]);
}
}
/// <summary>
/// Unsubscribes from the <see cref="SelectedItems"/> CollectionChanged event, if any.
/// </summary>
private void UnsubscribeFromSelectedItems()
{
if (_selectedItems is INotifyCollectionChanged incc)
{
incc.CollectionChanged -= SelectedItemsCollectionChanged;
}
}
(bool handled, IInputElement? next) ICustomKeyboardNavigation.GetNext(IInputElement element,
NavigationDirection direction)
{
if (direction == NavigationDirection.Next || direction == NavigationDirection.Previous)
{
if (!this.IsVisualAncestorOf(element))
{
var result = _selectedItem != null ?
ItemContainerGenerator.Index!.ContainerFromItem(_selectedItem) :
ItemContainerGenerator.ContainerFromIndex(0);
return (result != null, result); // SelectedItem may not be in the treeview.
}
return (true, null);
}
return (false, null);
}
/// <inheritdoc/>
protected override IItemContainerGenerator CreateItemContainerGenerator()
{
var result = CreateTreeItemContainerGenerator();
result.Index!.Materialized += ContainerMaterialized;
return result;
}
protected virtual ITreeItemContainerGenerator CreateTreeItemContainerGenerator() =>
CreateTreeItemContainerGenerator<TreeViewItem>();
protected virtual ITreeItemContainerGenerator CreateTreeItemContainerGenerator<TVItem>() where TVItem: TreeViewItem, new()
{
return new TreeItemContainerGenerator<TVItem>(
this,
TreeViewItem.HeaderProperty,
TreeViewItem.ItemTemplateProperty,
TreeViewItem.ItemsProperty,
TreeViewItem.IsExpandedProperty);
}
/// <inheritdoc/>
protected override void OnGotFocus(GotFocusEventArgs e)
{
if (e.NavigationMethod == NavigationMethod.Directional)
{
e.Handled = UpdateSelectionFromEventSource(
e.Source!,
true,
e.KeyModifiers.HasAllFlags(KeyModifiers.Shift));
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
var direction = e.Key.ToNavigationDirection();
if (direction?.IsDirectional() == true && !e.Handled)
{
if (SelectedItem != null)
{
var next = GetContainerInDirection(
GetContainerFromEventSource(e.Source!),
direction.Value,
true);
if (next != null)
{
FocusManager.Instance?.Focus(next, NavigationMethod.Directional);
e.Handled = true;
}
}
else
{
SelectedItem = ElementAt(Items, 0);
}
}
if (!e.Handled)
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
bool Match(List<KeyGesture>? gestures) => gestures?.Any(g => g.Matches(e)) ?? false;
if (this.SelectionMode == SelectionMode.Multiple && Match(keymap?.SelectAll))
{
SelectAll();
e.Handled = true;
}
}
}
private TreeViewItem? GetContainerInDirection(
TreeViewItem? from,
NavigationDirection direction,
bool intoChildren)
{
IItemContainerGenerator? parentGenerator = GetParentContainerGenerator(from);
if (parentGenerator == null)
{
return null;
}
var index = from is not null ? parentGenerator.IndexFromContainer(from) : -1;
var parent = from?.Parent as ItemsControl;
TreeViewItem? result = null;
switch (direction)
{
case NavigationDirection.Up:
if (index > 0)
{
var previous = (TreeViewItem)parentGenerator.ContainerFromIndex(index - 1)!;
result = previous.IsExpanded && previous.ItemCount > 0 ?
(TreeViewItem)previous.ItemContainerGenerator.ContainerFromIndex(previous.ItemCount - 1)! :
previous;
}
else
{
result = from?.Parent as TreeViewItem;
}
break;
case NavigationDirection.Down:
if (from?.IsExpanded == true && intoChildren && from.ItemCount > 0)
{
result = (TreeViewItem)from.ItemContainerGenerator.ContainerFromIndex(0)!;
}
else if (index < parent?.ItemCount - 1)
{
result = (TreeViewItem)parentGenerator.ContainerFromIndex(index + 1)!;
}
else if (parent is TreeViewItem parentItem)
{
return GetContainerInDirection(parentItem, direction, false);
}
break;
}
return result;
}
/// <inheritdoc/>
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (e.Source is IVisual source)
{
var point = e.GetCurrentPoint(source);
if (point.Properties.IsLeftButtonPressed || point.Properties.IsRightButtonPressed)
{
e.Handled = UpdateSelectionFromEventSource(
e.Source,
true,
e.KeyModifiers.HasAllFlags(KeyModifiers.Shift),
e.KeyModifiers.HasAllFlags(KeyModifiers.Control),
point.Properties.IsRightButtonPressed);
}
}
}
/// <summary>
/// Updates the selection for an item based on user interaction.
/// </summary>
/// <param name="container">The container.</param>
/// <param name="select">Whether the item should be selected or unselected.</param>
/// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param>
/// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param>
/// <param name="rightButton">Whether the event is a right-click.</param>
protected void UpdateSelectionFromContainer(
IControl container,
bool select = true,
bool rangeModifier = false,
bool toggleModifier = false,
bool rightButton = false)
{
var item = ItemContainerGenerator.Index!.ItemFromContainer(container);
if (item == null)
{
return;
}
IControl? selectedContainer = null;
if (SelectedItem != null)
{
selectedContainer = ItemContainerGenerator.Index!.ContainerFromItem(SelectedItem);
}
var mode = SelectionMode;
var toggle = toggleModifier || mode.HasAllFlags(SelectionMode.Toggle);
var multi = mode.HasAllFlags(SelectionMode.Multiple);
var range = multi && rangeModifier && selectedContainer != null;
if (rightButton)
{
if (!SelectedItems.Contains(item))
{
SelectSingleItem(item);
}
}
else if (!toggle && !range)
{
SelectSingleItem(item);
}
else if (multi && range)
{
SynchronizeItems(
SelectedItems,
GetItemsInRange(selectedContainer as TreeViewItem, container as TreeViewItem));
}
else
{
var i = SelectedItems.IndexOf(item);
if (i != -1)
{
SelectedItems.Remove(item);
}
else
{
if (multi)
{
SelectedItems.Add(item);
}
else
{
SelectedItem = item;
}
}
}
}
private static IItemContainerGenerator? GetParentContainerGenerator(TreeViewItem? item)
{
if (item == null)
{
return null;
}
switch (item.Parent)
{
case TreeView treeView:
return treeView.ItemContainerGenerator;
case TreeViewItem treeViewItem:
return treeViewItem.ItemContainerGenerator;
default:
return null;
}
}
/// <summary>
/// Find which node is first in hierarchy.
/// </summary>
/// <param name="treeView">Search root.</param>
/// <param name="nodeA">Nodes to find.</param>
/// <param name="nodeB">Node to find.</param>
/// <returns>Found first node.</returns>
private static TreeViewItem? FindFirstNode(TreeView treeView, TreeViewItem nodeA, TreeViewItem nodeB)
{
return FindInContainers(treeView.ItemContainerGenerator, nodeA, nodeB);
}
private static TreeViewItem? FindInContainers(ITreeItemContainerGenerator containerGenerator,
TreeViewItem nodeA,
TreeViewItem nodeB)
{
IEnumerable<ItemContainerInfo> containers = containerGenerator.Containers;
foreach (ItemContainerInfo container in containers)
{
TreeViewItem? node = FindFirstNode(container.ContainerControl as TreeViewItem, nodeA, nodeB);
if (node != null)
{
return node;
}
}
return null;
}
private static TreeViewItem? FindFirstNode(TreeViewItem? node, TreeViewItem nodeA, TreeViewItem nodeB)
{
if (node == null)
{
return null;
}
TreeViewItem? match = node == nodeA ? nodeA : node == nodeB ? nodeB : null;
if (match != null)
{
return match;
}
return FindInContainers(node.ItemContainerGenerator, nodeA, nodeB);
}
/// <summary>
/// Returns all items that belong to containers between <paramref name="from"/> and <paramref name="to"/>.
/// The range is inclusive.
/// </summary>
/// <param name="from">From container.</param>
/// <param name="to">To container.</param>
private List<object> GetItemsInRange(TreeViewItem? from, TreeViewItem? to)
{
var items = new List<object>();
if (from == null || to == null)
{
return items;
}
TreeViewItem? firstItem = FindFirstNode(this, from, to);
if (firstItem == null)
{
return items;
}
bool wasReversed = false;
if (firstItem == to)
{
var temp = from;
from = to;
to = temp;
wasReversed = true;
}
TreeViewItem? node = from;
while (node != to)
{
var item = ItemContainerGenerator.Index!.ItemFromContainer(node);
if (item != null)
{
items.Add(item);
}
node = GetContainerInDirection(node, NavigationDirection.Down, true);
}
var toItem = ItemContainerGenerator.Index!.ItemFromContainer(to);
if (toItem != null)
{
items.Add(toItem);
}
if (wasReversed)
{
items.Reverse();
}
return items;
}
/// <summary>
/// Updates the selection based on an event that may have originated in a container that
/// belongs to the control.
/// </summary>
/// <param name="eventSource">The control that raised the event.</param>
/// <param name="select">Whether the container should be selected or unselected.</param>
/// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param>
/// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param>
/// <param name="rightButton">Whether the event is a right-click.</param>
/// <returns>
/// True if the event originated from a container that belongs to the control; otherwise
/// false.
/// </returns>
protected bool UpdateSelectionFromEventSource(
IInteractive eventSource,
bool select = true,
bool rangeModifier = false,
bool toggleModifier = false,
bool rightButton = false)
{
var container = GetContainerFromEventSource(eventSource);
if (container != null)
{
UpdateSelectionFromContainer(container, select, rangeModifier, toggleModifier, rightButton);
return true;
}
return false;
}
/// <summary>
/// Tries to get the container that was the source of an event.
/// </summary>
/// <param name="eventSource">The control that raised the event.</param>
/// <returns>The container or null if the event did not originate in a container.</returns>
protected TreeViewItem? GetContainerFromEventSource(IInteractive eventSource)
{
var item = ((IVisual)eventSource).GetSelfAndVisualAncestors()
.OfType<TreeViewItem>()
.FirstOrDefault();
if (item != null)
{
if (item.ItemContainerGenerator.Index == ItemContainerGenerator.Index)
{
return item;
}
}
return null;
}
/// <summary>
/// Called when a new item container is materialized, to set its selected state.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void ContainerMaterialized(object? sender, ItemContainerEventArgs e)
{
var selectedItem = SelectedItem;
if (selectedItem == null)
{
return;
}
foreach (var container in e.Containers)
{
if (container.Item == selectedItem)
{
((TreeViewItem)container.ContainerControl).IsSelected = true;
if (AutoScrollToSelectedItem)
{
Dispatcher.UIThread.Post(container.ContainerControl.BringIntoView);
}
break;
}
}
}
/// <summary>
/// Sets a container's 'selected' class or <see cref="ISelectable.IsSelected"/>.
/// </summary>
/// <param name="container">The container.</param>
/// <param name="selected">Whether the control is selected</param>
private void MarkContainerSelected(IControl container, bool selected)
{
if (container == null)
{
return;
}
if (container is ISelectable selectable)
{
selectable.IsSelected = selected;
}
else
{
container.Classes.Set(":selected", selected);
}
}
/// <summary>
/// Makes a list of objects equal another (though doesn't preserve order).
/// </summary>
/// <param name="items">The items collection.</param>
/// <param name="desired">The desired items.</param>
private static void SynchronizeItems(IList items, IEnumerable<object> desired)
{
var list = items.Cast<object>().ToList();
var toRemove = list.Except(desired).ToList();
var toAdd = desired.Except(list).ToList();
foreach (var i in toRemove)
{
items.Remove(i);
}
foreach (var i in toAdd)
{
items.Add(i);
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ContainsSearchOperator.cs
//
// <OWNER>[....]</OWNER>
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// Contains is quite similar to the any/all operator above. Each partition searches a
/// subset of elements for a match, and the first one to find a match signals to the rest
/// of the partititons to stop searching.
/// </summary>
/// <typeparam name="TInput"></typeparam>
internal sealed class ContainsSearchOperator<TInput> : UnaryQueryOperator<TInput, bool>
{
private readonly TInput m_searchValue; // The value for which we are searching.
private readonly IEqualityComparer<TInput> m_comparer; // The comparer to use for equality tests.
//---------------------------------------------------------------------------------------
// Constructs a new instance of the contains search operator.
//
// Arguments:
// child - the child tree to enumerate.
// searchValue - value we are searching for.
// comparer - a comparison routine used to test equality.
//
internal ContainsSearchOperator(IEnumerable<TInput> child, TInput searchValue, IEqualityComparer<TInput> comparer)
:base(child)
{
Contract.Assert(child != null, "child data source cannot be null");
m_searchValue = searchValue;
if (comparer == null)
{
m_comparer = EqualityComparer<TInput>.Default;
}
else
{
m_comparer = comparer;
}
}
//---------------------------------------------------------------------------------------
// Executes the entire query tree, and aggregates the individual partition results to
// form an overall answer to the search operation.
//
internal bool Aggregate()
{
// Because the final reduction is typically much cheaper than the intermediate
// reductions over the individual partitions, and because each parallel partition
// could do a lot of work to produce a single output element, we prefer to turn off
// pipelining, and process the final reductions serially.
using (IEnumerator<bool> enumerator = GetEnumerator(ParallelMergeOptions.FullyBuffered, true))
{
// Any value of true means the element was found. We needn't consult all partitions
while (enumerator.MoveNext())
{
if (enumerator.Current)
{
return true;
}
}
}
return false;
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<bool> Open(QuerySettings settings, bool preferStriping)
{
QueryResults<TInput> childQueryResults = Child.Open(settings, preferStriping);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TInput, TKey> inputStream, IPartitionedStreamRecipient<bool> recipient, bool preferStriping, QuerySettings settings)
{
int partitionCount = inputStream.PartitionCount;
PartitionedStream<bool, int> outputStream = new PartitionedStream<bool, int>(partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Correct);
// Create a shared cancelation variable
Shared<bool> resultFoundFlag = new Shared<bool>(false);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new ContainsSearchOperatorEnumerator<TKey>(inputStream[i], m_searchValue, m_comparer, i, resultFoundFlag,
settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<bool> AsSequentialQuery(CancellationToken token)
{
Contract.Assert(false, "This method should never be called as it is an ending operator with LimitsParallelism=false.");
throw new NotSupportedException();
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
//---------------------------------------------------------------------------------------
// This enumerator performs the search over its input data source. It also cancels peer
// enumerators when an answer was found, and polls this cancelation flag to stop when
// requested.
//
class ContainsSearchOperatorEnumerator<TKey> : QueryOperatorEnumerator<bool, int>
{
private readonly QueryOperatorEnumerator<TInput, TKey> m_source; // The source data.
private readonly TInput m_searchValue; // The value for which we are searching.
private readonly IEqualityComparer<TInput> m_comparer; // The comparer to use for equality tests.
private readonly int m_partitionIndex; // This partition's unique index.
private readonly Shared<bool> m_resultFoundFlag; // Whether to cancel the operation.
private CancellationToken m_cancellationToken;
//---------------------------------------------------------------------------------------
// Instantiates a new any/all search operator.
//
internal ContainsSearchOperatorEnumerator(QueryOperatorEnumerator<TInput, TKey> source, TInput searchValue,
IEqualityComparer<TInput> comparer, int partitionIndex, Shared<bool> resultFoundFlag,
CancellationToken cancellationToken)
{
Contract.Assert(source != null);
Contract.Assert(comparer != null);
Contract.Assert(resultFoundFlag != null);
m_source = source;
m_searchValue = searchValue;
m_comparer = comparer;
m_partitionIndex = partitionIndex;
m_resultFoundFlag = resultFoundFlag;
m_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// This enumerates the entire input source to perform the search. If another peer
// partition finds an answer before us, we will voluntarily return (propagating the
// peer's result).
//
internal override bool MoveNext(ref bool currentElement, ref int currentKey)
{
Contract.Assert(m_comparer != null);
// Avoid enumerating if we've already found an answer.
if (m_resultFoundFlag.Value)
return false;
// We just scroll through the enumerator and accumulate the result.
TInput element = default(TInput);
TKey keyUnused = default(TKey);
if (m_source.MoveNext(ref element, ref keyUnused))
{
currentElement = false;
currentKey = m_partitionIndex;
// Continue walking the data so long as we haven't found an item that satisfies
// the condition we are searching for.
int i = 0;
do
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(m_cancellationToken);
if (m_resultFoundFlag.Value)
{
// If cancelation occurred, it's because a successful answer was found.
return false;
}
if (m_comparer.Equals(element, m_searchValue))
{
// We have found an item that satisfies the search. Cancel other
// workers that are concurrently searching, and return.
m_resultFoundFlag.Value = true;
currentElement = true;
break;
}
}
while (m_source.MoveNext(ref element, ref keyUnused));
return true;
}
return false;
}
protected override void Dispose(bool disposing)
{
Contract.Assert(m_source != null);
m_source.Dispose();
}
}
}
}
| |
//
// X509CertificateStore.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013-2015 Xamarin Inc. (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.
//
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
namespace MimeKit.Cryptography {
/// <summary>
/// A store for X.509 certificates and keys.
/// </summary>
/// <remarks>
/// A store for X.509 certificates and keys.
/// </remarks>
public class X509CertificateStore : IX509Store
{
readonly Dictionary<X509Certificate, AsymmetricKeyParameter> keys;
readonly HashSet<X509Certificate> unique;
readonly List<X509Certificate> certs;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.X509CertificateStore"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="X509CertificateStore"/>.
/// </remarks>
public X509CertificateStore ()
{
keys = new Dictionary<X509Certificate, AsymmetricKeyParameter> ();
unique = new HashSet<X509Certificate> ();
certs = new List<X509Certificate> ();
}
/// <summary>
/// Enumerates the certificates currently in the store.
/// </summary>
/// <remarks>
/// Enumerates the certificates currently in the store.
/// </remarks>
/// <value>The certificates.</value>
public IEnumerable<X509Certificate> Certificates {
get { return certs; }
}
/// <summary>
/// Gets the private key for the specified certificate.
/// </summary>
/// <remarks>
/// Gets the private key for the specified certificate, if it exists.
/// </remarks>
/// <returns>The private key on success; otherwise <c>null</c>.</returns>
/// <param name="certificate">The certificate.</param>
public AsymmetricKeyParameter GetPrivateKey (X509Certificate certificate)
{
AsymmetricKeyParameter key;
if (!keys.TryGetValue (certificate, out key))
return null;
return key;
}
/// <summary>
/// Adds the specified certificate to the store.
/// </summary>
/// <remarks>
/// Adds the specified certificate to the store.
/// </remarks>
/// <param name="certificate">The certificate.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="certificate"/> is <c>null</c>.
/// </exception>
public void Add (X509Certificate certificate)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
if (unique.Add (certificate))
certs.Add (certificate);
}
/// <summary>
/// Adds the specified range of certificates to the store.
/// </summary>
/// <remarks>
/// Adds the specified range of certificates to the store.
/// </remarks>
/// <param name="certificates">The certificates.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="certificates"/> is <c>null</c>.
/// </exception>
public void AddRange (IEnumerable<X509Certificate> certificates)
{
if (certificates == null)
throw new ArgumentNullException ("certificates");
foreach (var certificate in certificates) {
if (unique.Add (certificate))
certs.Add (certificate);
}
}
/// <summary>
/// Removes the specified certificate from the store.
/// </summary>
/// <remarks>
/// Removes the specified certificate from the store.
/// </remarks>
/// <param name="certificate">The certificate.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="certificate"/> is <c>null</c>.
/// </exception>
public void Remove (X509Certificate certificate)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
if (unique.Remove (certificate))
certs.Remove (certificate);
}
/// <summary>
/// Removes the specified range of certificates from the store.
/// </summary>
/// <remarks>
/// Removes the specified range of certificates from the store.
/// </remarks>
/// <param name="certificates">The certificates.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="certificates"/> is <c>null</c>.
/// </exception>
public void RemoveRange (IEnumerable<X509Certificate> certificates)
{
if (certificates == null)
throw new ArgumentNullException ("certificates");
foreach (var certificate in certificates) {
if (unique.Remove (certificate))
certs.Remove (certificate);
}
}
/// <summary>
/// Imports the certificate(s) from the specified stream.
/// </summary>
/// <remarks>
/// Imports the certificate(s) from the specified stream.
/// </remarks>
/// <param name="stream">The stream to import.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="stream"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An error occurred reading the stream.
/// </exception>
public void Import (Stream stream)
{
if (stream == null)
throw new ArgumentNullException ("stream");
var parser = new X509CertificateParser ();
foreach (X509Certificate certificate in parser.ReadCertificates (stream)) {
if (unique.Add (certificate))
certs.Add (certificate);
}
}
/// <summary>
/// Imports the certificate(s) from the specified file.
/// </summary>
/// <remarks>
/// Imports the certificate(s) from the specified file.
/// </remarks>
/// <param name="fileName">The name of the file to import.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="fileName"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.IO.FileNotFoundException">
/// The specified file could not be found.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An error occurred reading the file.
/// </exception>
public void Import (string fileName)
{
if (fileName == null)
throw new ArgumentNullException ("fileName");
using (var stream = File.OpenRead (fileName))
Import (stream);
}
/// <summary>
/// Imports the certificate(s) from the specified byte array.
/// </summary>
/// <remarks>
/// Imports the certificate(s) from the specified byte array.
/// </remarks>
/// <param name="rawData">The raw certificate data.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="rawData"/> is <c>null</c>.
/// </exception>
public void Import (byte[] rawData)
{
if (rawData == null)
throw new ArgumentNullException ("rawData");
using (var stream = new MemoryStream (rawData, false))
Import (stream);
}
/// <summary>
/// Imports certificates and private keys from the specified stream.
/// </summary>
/// <remarks>
/// <para>Imports certificates and private keys from the specified pkcs12 stream.</para>
/// </remarks>
/// <param name="stream">The stream to import.</param>
/// <param name="password">The password to unlock the stream.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="stream"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="password"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.IO.IOException">
/// An error occurred reading the stream.
/// </exception>
public void Import (Stream stream, string password)
{
if (stream == null)
throw new ArgumentNullException ("stream");
if (password == null)
throw new ArgumentNullException ("password");
var pkcs12 = new Pkcs12Store (stream, password.ToCharArray ());
foreach (string alias in pkcs12.Aliases) {
if (pkcs12.IsKeyEntry (alias)) {
var chain = pkcs12.GetCertificateChain (alias);
var entry = pkcs12.GetKey (alias);
for (int i = 0; i < chain.Length; i++) {
if (unique.Add (chain[i].Certificate))
certs.Add (chain[i].Certificate);
}
if (entry.Key.IsPrivate)
keys.Add (chain[0].Certificate, entry.Key);
} else if (pkcs12.IsCertificateEntry (alias)) {
var entry = pkcs12.GetCertificate (alias);
if (unique.Add (entry.Certificate))
certs.Add (entry.Certificate);
}
}
}
/// <summary>
/// Imports certificates and private keys from the specified file.
/// </summary>
/// <remarks>
/// <para>Imports certificates and private keys from the specified pkcs12 stream.</para>
/// </remarks>
/// <param name="fileName">The name of the file to import.</param>
/// <param name="password">The password to unlock the file.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="fileName"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="password"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// The specified file path is empty.
/// </exception>
/// <exception cref="System.IO.FileNotFoundException">
/// The specified file could not be found.
/// </exception>
/// <exception cref="System.UnauthorizedAccessException">
/// The user does not have access to read the specified file.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An error occurred reading the file.
/// </exception>
public void Import (string fileName, string password)
{
if (fileName == null)
throw new ArgumentNullException ("fileName");
if (string.IsNullOrEmpty (fileName))
throw new ArgumentException ("The specified path is empty.", "fileName");
using (var stream = File.OpenRead (fileName))
Import (stream, password);
}
/// <summary>
/// Imports certificates and private keys from the specified byte array.
/// </summary>
/// <remarks>
/// <para>Imports certificates and private keys from the specified pkcs12 stream.</para>
/// </remarks>
/// <param name="rawData">The raw certificate data.</param>
/// <param name="password">The password to unlock the raw data.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="rawData"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="password"/> is <c>null</c>.</para>
/// </exception>
public void Import (byte[] rawData, string password)
{
if (rawData == null)
throw new ArgumentNullException ("rawData");
using (var stream = new MemoryStream (rawData, false))
Import (stream, password);
}
/// <summary>
/// Exports the certificates to an unencrypted stream.
/// </summary>
/// <remarks>
/// Exports the certificates to an unencrypted stream.
/// </remarks>
/// <param name="stream">The output stream.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="stream"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An error occurred while writing to the stream.
/// </exception>
public void Export (Stream stream)
{
if (stream == null)
throw new ArgumentNullException ("stream");
foreach (var certificate in certs) {
var encoded = certificate.GetEncoded ();
stream.Write (encoded, 0, encoded.Length);
}
}
/// <summary>
/// Exports the certificates to an unencrypted file.
/// </summary>
/// <remarks>
/// Exports the certificates to an unencrypted file.
/// </remarks>
/// <param name="fileName">The file path to write to.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="fileName"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The specified file path is empty.
/// </exception>
/// <exception cref="System.IO.PathTooLongException">
/// The specified path exceeds the maximum allowed path length of the system.
/// </exception>
/// <exception cref="System.IO.DirectoryNotFoundException">
/// A directory in the specified path does not exist.
/// </exception>
/// <exception cref="System.UnauthorizedAccessException">
/// The user does not have access to create the specified file.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An error occurred while writing to the stream.
/// </exception>
public void Export (string fileName)
{
if (fileName == null)
throw new ArgumentNullException ("fileName");
if (string.IsNullOrEmpty (fileName))
throw new ArgumentException ("The specified path is empty.", "fileName");
using (var file = File.Create (fileName))
Export (file);
}
/// <summary>
/// Exports the specified stream and password to a pkcs12 encrypted file.
/// </summary>
/// <remarks>
/// Exports the specified stream and password to a pkcs12 encrypted file.
/// </remarks>
/// <param name="stream">The output stream.</param>
/// <param name="password">The password to use to lock the private keys.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="stream"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="password"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.IO.IOException">
/// An error occurred while writing to the stream.
/// </exception>
public void Export (Stream stream, string password)
{
if (stream == null)
throw new ArgumentNullException ("stream");
if (password == null)
throw new ArgumentNullException ("password");
var store = new Pkcs12Store ();
foreach (var certificate in certs) {
if (keys.ContainsKey (certificate))
continue;
var alias = certificate.GetCommonName ();
if (alias == null)
continue;
var entry = new X509CertificateEntry (certificate);
store.SetCertificateEntry (alias, entry);
}
foreach (var kvp in keys) {
var alias = kvp.Key.GetCommonName ();
if (alias == null)
continue;
var entry = new AsymmetricKeyEntry (kvp.Value);
var cert = new X509CertificateEntry (kvp.Key);
var chain = new List<X509CertificateEntry> ();
chain.Add (cert);
store.SetKeyEntry (alias, entry, chain.ToArray ());
}
store.Save (stream, password.ToCharArray (), new SecureRandom ());
}
/// <summary>
/// Exports the specified stream and password to a pkcs12 encrypted file.
/// </summary>
/// <remarks>
/// Exports the specified stream and password to a pkcs12 encrypted file.
/// </remarks>
/// <param name="fileName">The file path to write to.</param>
/// <param name="password">The password to use to lock the private keys.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="fileName"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="password"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// The specified file path is empty.
/// </exception>
/// <exception cref="System.IO.PathTooLongException">
/// The specified path exceeds the maximum allowed path length of the system.
/// </exception>
/// <exception cref="System.IO.DirectoryNotFoundException">
/// A directory in the specified path does not exist.
/// </exception>
/// <exception cref="System.UnauthorizedAccessException">
/// The user does not have access to create the specified file.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An error occurred while writing to the stream.
/// </exception>
public void Export (string fileName, string password)
{
if (fileName == null)
throw new ArgumentNullException ("fileName");
if (string.IsNullOrEmpty (fileName))
throw new ArgumentException ("The specified path is empty.", "fileName");
if (password == null)
throw new ArgumentNullException ("password");
using (var file = File.Create (fileName))
Export (file, password);
}
/// <summary>
/// Gets an enumerator of matching X.509 certificates based on the specified selector.
/// </summary>
/// <remarks>
/// Gets an enumerator of matching X.509 certificates based on the specified selector.
/// </remarks>
/// <returns>The matching certificates.</returns>
/// <param name="selector">The match criteria.</param>
public IEnumerable<X509Certificate> GetMatches (IX509Selector selector)
{
foreach (var certificate in certs) {
if (selector == null || selector.Match (certificate))
yield return certificate;
}
yield break;
}
#region IX509Store implementation
/// <summary>
/// Gets a collection of matching X.509 certificates based on the specified selector.
/// </summary>
/// <remarks>
/// Gets a collection of matching X.509 certificates based on the specified selector.
/// </remarks>
/// <returns>The matching certificates.</returns>
/// <param name="selector">The match criteria.</param>
ICollection IX509Store.GetMatches (IX509Selector selector)
{
var matches = new List<X509Certificate> ();
foreach (var certificate in GetMatches (selector))
matches.Add (certificate);
return matches;
}
#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;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace System.Globalization
{
internal partial class CultureData
{
// ICU constants
const int ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY = 100; // max size of keyword or value
const int ICU_ULOC_FULLNAME_CAPACITY = 157; // max size of locale name
const string ICU_COLLATION_KEYWORD = "@collation=";
/// <summary>
/// This method uses the sRealName field (which is initialized by the constructor before this is called) to
/// initialize the rest of the state of CultureData based on the underlying OS globalization library.
/// </summary>
[SecuritySafeCritical]
private unsafe bool InitCultureData()
{
Contract.Assert(_sRealName != null);
string alternateSortName = string.Empty;
string realNameBuffer = _sRealName;
// Basic validation
if (realNameBuffer.Contains("@"))
{
return false; // don't allow ICU variants to come in directly
}
// Replace _ (alternate sort) with @collation= for ICU
int index = realNameBuffer.IndexOf('_');
if (index > 0)
{
if (index >= (realNameBuffer.Length - 1) // must have characters after _
|| realNameBuffer.Substring(index + 1).Contains("_")) // only one _ allowed
{
return false; // fail
}
alternateSortName = realNameBuffer.Substring(index + 1);
realNameBuffer = realNameBuffer.Substring(0, index) + ICU_COLLATION_KEYWORD + alternateSortName;
}
// Get the locale name from ICU
if (!GetLocaleName(realNameBuffer, out _sWindowsName))
{
return false; // fail
}
// Replace the ICU collation keyword with an _
index = _sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal);
if (index >= 0)
{
_sName = _sWindowsName.Substring(0, index) + "_" + alternateSortName;
}
else
{
_sName = _sWindowsName;
}
_sRealName = _sName;
_sSpecificCulture = _sRealName; // we don't attempt to find a non-neutral locale if a neutral is passed in (unlike win32)
_iLanguage = this.ILANGUAGE;
if (_iLanguage == 0)
{
_iLanguage = CultureInfo.LOCALE_CUSTOM_UNSPECIFIED;
}
_bNeutral = (this.SISO3166CTRYNAME.Length == 0);
// Remove the sort from sName unless custom culture
if (index>0 && !_bNeutral && !IsCustomCultureId(_iLanguage))
{
_sName = _sWindowsName.Substring(0, index);
}
return true;
}
[SecuritySafeCritical]
internal static bool GetLocaleName(string localeName, out string windowsName)
{
// Get the locale name from ICU
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
if (!Interop.GlobalizationInterop.GetLocaleName(localeName, sb, sb.Capacity))
{
StringBuilderCache.Release(sb);
windowsName = null;
return false; // fail
}
// Success - use the locale name returned which may be different than realNameBuffer (casing)
windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls
return true;
}
[SecuritySafeCritical]
internal static bool GetDefaultLocaleName(out string windowsName)
{
// Get the default (system) locale name from ICU
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
if (!Interop.GlobalizationInterop.GetDefaultLocaleName(sb, sb.Capacity))
{
StringBuilderCache.Release(sb);
windowsName = null;
return false; // fail
}
// Success - use the locale name returned which may be different than realNameBuffer (casing)
windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls
return true;
}
private string GetLocaleInfo(LocaleStringData type)
{
Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already");
return GetLocaleInfo(_sWindowsName, type);
}
// For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
// "windows" name, which can be specific for downlevel (< windows 7) os's.
[SecuritySafeCritical]
private string GetLocaleInfo(string localeName, LocaleStringData type)
{
Contract.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
switch (type)
{
case LocaleStringData.NegativeInfinitySymbol:
// not an equivalent in ICU; prefix the PositiveInfinitySymbol with NegativeSign
return GetLocaleInfo(localeName, LocaleStringData.NegativeSign) +
GetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol);
}
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
bool result = Interop.GlobalizationInterop.GetLocaleInfoString(localeName, (uint)type, sb, sb.Capacity);
if (!result)
{
// Failed, just use empty string
StringBuilderCache.Release(sb);
Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
return String.Empty;
}
return StringBuilderCache.GetStringAndRelease(sb);
}
[SecuritySafeCritical]
private int GetLocaleInfo(LocaleNumberData type)
{
Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
switch (type)
{
case LocaleNumberData.CalendarType:
// returning 0 will cause the first supported calendar to be returned, which is the preferred calendar
return 0;
}
int value = 0;
bool result = Interop.GlobalizationInterop.GetLocaleInfoInt(_sWindowsName, (uint)type, ref value);
if (!result)
{
// Failed, just use 0
Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
}
return value;
}
[SecuritySafeCritical]
private int[] GetLocaleInfo(LocaleGroupingData type)
{
Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
int primaryGroupingSize = 0;
int secondaryGroupingSize = 0;
bool result = Interop.GlobalizationInterop.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize);
if (!result)
{
Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
}
if (secondaryGroupingSize == 0)
{
return new int[] { primaryGroupingSize };
}
return new int[] { primaryGroupingSize, secondaryGroupingSize };
}
private string GetTimeFormatString()
{
return GetTimeFormatString(false);
}
[SecuritySafeCritical]
private string GetTimeFormatString(bool shortFormat)
{
Contract.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
bool result = Interop.GlobalizationInterop.GetLocaleTimeFormat(_sWindowsName, shortFormat, sb, sb.Capacity);
if (!result)
{
// Failed, just use empty string
StringBuilderCache.Release(sb);
Contract.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
return String.Empty;
}
return ConvertIcuTimeFormatString(StringBuilderCache.GetStringAndRelease(sb));
}
private int GetFirstDayOfWeek()
{
return this.GetLocaleInfo(LocaleNumberData.FirstDayOfWeek);
}
private String[] GetTimeFormats()
{
string format = GetTimeFormatString(false);
return new string[] { format };
}
private String[] GetShortTimeFormats()
{
string format = GetTimeFormatString(true);
return new string[] { format };
}
private static CultureData GetCultureDataFromRegionName(String regionName)
{
// no support to lookup by region name, other than the hard-coded list in CultureData
return null;
}
private static string GetLanguageDisplayName(string cultureName)
{
return new CultureInfo(cultureName).m_cultureData.GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName);
}
private static string GetRegionDisplayName(string isoCountryCode)
{
// use the fallback which is to return NativeName
return null;
}
private static CultureInfo GetUserDefaultCulture()
{
return CultureInfo.GetUserDefaultCulture();
}
private static string ConvertIcuTimeFormatString(string icuFormatString)
{
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
bool amPmAdded = false;
for (int i = 0; i < icuFormatString.Length; i++)
{
switch(icuFormatString[i])
{
case ':':
case '.':
case 'H':
case 'h':
case 'm':
case 's':
sb.Append(icuFormatString[i]);
break;
case ' ':
case '\u00A0':
// Convert nonbreaking spaces into regular spaces
sb.Append(' ');
break;
case 'a': // AM/PM
if (!amPmAdded)
{
amPmAdded = true;
sb.Append("tt");
}
break;
}
}
return StringBuilderCache.GetStringAndRelease(sb);
}
private static string LCIDToLocaleName(int culture)
{
return LocaleData.LCIDToLocaleName(culture);
}
private static int LocaleNameToLCID(string cultureName)
{
int lcid = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.Lcid);
return lcid == -1 ? CultureInfo.LOCALE_CUSTOM_UNSPECIFIED : lcid;
}
private static int GetAnsiCodePage(string cultureName)
{
int ansiCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.AnsiCodePage);
return ansiCodePage == -1 ? CultureData.Invariant.IDEFAULTANSICODEPAGE : ansiCodePage;
}
private static int GetOemCodePage(string cultureName)
{
int oemCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.OemCodePage);
return oemCodePage == -1 ? CultureData.Invariant.IDEFAULTOEMCODEPAGE : oemCodePage;
}
private static int GetMacCodePage(string cultureName)
{
int macCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.MacCodePage);
return macCodePage == -1 ? CultureData.Invariant.IDEFAULTMACCODEPAGE : macCodePage;
}
private static int GetEbcdicCodePage(string cultureName)
{
int ebcdicCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.EbcdicCodePage);
return ebcdicCodePage == -1 ? CultureData.Invariant.IDEFAULTEBCDICCODEPAGE : ebcdicCodePage;
}
private static int GetGeoId(string cultureName)
{
int geoId = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.GeoId);
return geoId == -1 ? CultureData.Invariant.IGEOID : geoId;
}
}
}
| |
/// Refly License
///
/// Copyright (c) 2004 Jonathan de Halleux, http://www.dotnetwiki.org
///
/// This software is provided 'as-is', without any express or implied warranty.
/// In no event will the authors be held liable for any damages arising from
/// the use of this software.
///
/// Permission is granted to anyone to use this software for any purpose,
/// including commercial applications, and to alter it and redistribute it
/// freely, subject to the following restrictions:
///
/// 1. The origin of this software must not be misrepresented;
/// you must not claim that you wrote the original software.
/// If you use this software in a product, an acknowledgment in the product
/// documentation would be appreciated but is not required.
///
/// 2. Altered source versions must be plainly marked as such,
/// and must not be misrepresented as being the original software.
///
///3. This notice may not be removed or altered from any source distribution.
using System;
using System.CodeDom;
namespace Refly.CodeDom
{
using Refly.CodeDom.Expressions;
using Refly.CodeDom.Statements;
/// <summary>
/// Helper class containing static methods to create <see cref="Expression"/>
/// instances.
/// </summary>
public sealed class Expr
{
#region Constructors
private Expr(){}
#endregion
#region Keywords
/// <summary>
/// Create a <c>this</c> reference expression
/// </summary>
/// <remarks>
/// Generated code:
/// <code>
/// [C#]
/// this
/// </code>
/// </remarks>
public static ThisReferenceExpression This
{
get
{
return new ThisReferenceExpression();
}
}
/// <summary>
/// Create a <c>base</c> reference expression
/// </summary>
/// <remarks>
/// Generated code:
/// <code>
/// [C#]
/// base
/// </code>
/// </remarks>
public static BaseReferenceExpression Base
{
get
{
return new BaseReferenceExpression();
}
}
/// <summary>
/// Create a <c>value</c> reference expression of a
/// <c>set</c> section inside a property
/// </summary>
/// <remarks>
/// Generated code:
/// <code>
/// [C#]
/// value
/// </code>
/// </remarks>
public static PropertySetValueReferenceExpression Value
{
get
{
return new PropertySetValueReferenceExpression();
}
}
/// <summary>
/// Create a <c>null</c> expression
/// </summary>
/// <remarks>
/// Generated code:
/// <code>
/// [C#]
/// null
/// </code>
/// </remarks>
public static NativeExpression Null
{
get
{
return new NativeExpression(
new CodePrimitiveExpression(null)
);
}
}
/// <summary>
/// Create a <c>true</c> expression
/// </summary>
/// <remarks>
/// Generated code:
/// <code>
/// [C#]
/// true
/// </code>
/// </remarks>
public static PrimitiveExpression True
{
get
{
return Prim(true);
}
}
/// <summary>
/// Create a <c>false</c> expression
/// </summary>
/// <remarks>
/// Generated code:
/// <code>
/// [C#]
/// false
/// </code>
/// </remarks>
public static PrimitiveExpression False
{
get
{
return Prim(false);
}
}
#endregion
#region New
/// <summary>
/// Creates a <c>new type(...)</c> expression.
/// </summary>
/// <param name="type">
/// Target <see cref="Type"/> name.
/// </param>
/// <param name="parameters">
/// Parameters of the construcotr.
/// </param>
/// <include file='Refly.CodeDom.Doc.xml' path='doc/remarkss/remark[@name="Expr.New"]'/>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is a null reference (Noting in Visual Basic)
/// </exception>
public static ObjectCreationExpression New(
String type,
params Expression[] parameters)
{
if (type==null)
throw new ArgumentNullException("type");
return New(new StringTypeDeclaration(type),parameters);
}
/// <summary>
/// Creates a <c>new type(...)</c> expression.
/// </summary>
/// <param name="type">
/// Target <see cref="Type"/>.
/// </param>
/// <param name="parameters">
/// Parameters of the construcotr.
/// </param>
/// <include file='Refly.CodeDom.Doc.xml' path='doc/remarkss/remark[@name="Expr.New"]'/>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is a null reference (Noting in Visual Basic)
/// </exception>
public static ObjectCreationExpression New(
Type type,
params Expression[] parameters)
{
if (type==null)
throw new ArgumentNullException("type");
return New(new TypeTypeDeclaration(type),parameters);
}
/// <summary>
/// Creates a <c>new t(...)</c> expression.
/// </summary>
/// <param name="type">
/// Target <see cref="Type"/>.
/// </param>
/// <param name="parameters">
/// Parameters of the construcotr.
/// </param>
/// <include file='Refly.CodeDom.Doc.xml' path='doc/remarkss/remark[@name="Expr.New"]'/>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is a null reference (Noting in Visual Basic)
/// </exception>
public static ObjectCreationExpression New(
ITypeDeclaration type,
params Expression[] parameters)
{
if (type==null)
throw new ArgumentNullException("type");
return new ObjectCreationExpression(type,parameters);
}
#endregion
#region NewArray (size)
/// <summary>
/// Creates a <c>new type[size]</c> expression
/// </summary>
/// <param name="type">Array item type</param>
/// <param name="size">Array size</param>
/// <returns>A <see cref="ArrayCreationWithSizeExpression"/> instance</returns>
/// <include file='Refly.CodeDom.Doc.xml' path='doc/remarkss/remark[@name="Expr.NewArray"]'/>
/// <exception cref="ArgumentNullExpression">
/// <paramref name="type"/> is a null reference.
/// </exception>
public static ArrayCreationWithSizeExpression NewArray(
Type type,
int size
)
{
if (type == null)
throw new ArgumentNullException("type");
return new ArrayCreationWithSizeExpression(
new TypeTypeDeclaration(type),
Expr.Prim(size));
}
/// <summary>
/// Creates a <c>new type[size]</c> expression
/// </summary>
/// <param name="type">Array item type</param>
/// <param name="size">Array size</param>
/// <returns>A <see cref="ArrayCreationWithSizeExpression"/> instance</returns>
/// <include file='Refly.CodeDom.Doc.xml' path='doc/remarkss/remark[@name="Expr.NewArray"]'/>
/// <exception cref="ArgumentNullExpression">
/// <paramref name="type"/> is a null reference.
/// </exception>
public static ArrayCreationWithSizeExpression NewArray(
String type,
int size
)
{
if (type == null)
throw new ArgumentNullException("type");
return new ArrayCreationWithSizeExpression(
new StringTypeDeclaration(type),
Expr.Prim(size));
}
/// <summary>
/// Creates a <c>new type[size]</c> expression
/// </summary>
/// <param name="type">Array item type</param>
/// <param name="size">Array size</param>
/// <returns>A <see cref="ArrayCreationWithSizeExpression"/> instance</returns>
/// <include file='Refly.CodeDom.Doc.xml' path='doc/remarkss/remark[@name="Expr.NewArray"]'/>
/// <exception cref="ArgumentNullExpression">
/// <paramref name="type"/> is a null reference.
/// </exception>
public static ArrayCreationWithSizeExpression NewArray(
ITypeDeclaration type,
int size
)
{
if (type == null)
throw new ArgumentNullException("type");
return new ArrayCreationWithSizeExpression(type,
Expr.Prim(size));
}
/// <summary>
/// Creates a <c>new type[expression]</c> expression
/// </summary>
/// <param name="type">Array item type</param>
/// <param name="sizeExpression">Array size <see cref="Expression"/></param>
/// <returns>A <see cref="ArrayCreationWithSizeExpression"/> instance</returns>
/// <include file='Refly.CodeDom.Doc.xml' path='doc/remarkss/remark[@name="Expr.NewArray"]'/>
/// <exception cref="ArgumentNullExpression">
/// <paramref name="type"/> or <paramref name="sizeExpression"/>
/// is a null reference.
/// </exception>
public static ArrayCreationWithSizeExpression NewArray(
Type type,
Expression sizeExpression
)
{
if (type == null)
throw new ArgumentNullException("type");
return new ArrayCreationWithSizeExpression(
new TypeTypeDeclaration(type), sizeExpression);
}
/// <summary>
/// Creates a <c>new type[expression]</c> expression
/// </summary>
/// <param name="type">Array item type</param>
/// <param name="sizeExpression">Array size <see cref="Expression"/></param>
/// <returns>A <see cref="ArrayCreationWithSizeExpression"/> instance</returns>
/// <include file='Refly.CodeDom.Doc.xml' path='doc/remarkss/remark[@name="Expr.NewArray"]'/>
/// <exception cref="ArgumentNullExpression">
/// <paramref name="type"/> or <paramref name="sizeExpression"/>
/// is a null reference.
/// </exception>
public static ArrayCreationWithSizeExpression NewArray(
String type,
Expression sizeExpression
)
{
if (type == null)
throw new ArgumentNullException("type");
return new ArrayCreationWithSizeExpression(
new StringTypeDeclaration(type), sizeExpression);
}
/// <summary>
/// Creates a <c>new type[expression]</c> expression
/// </summary>
/// <param name="type">Array item type</param>
/// <param name="sizeExpression">Array size <see cref="Expression"/></param>
/// <returns>A <see cref="ArrayCreationWithSizeExpression"/> instance</returns>
/// <include file='Refly.CodeDom.Doc.xml' path='doc/remarkss/remark[@name="Expr.NewArray"]'/>
/// <exception cref="ArgumentNullExpression">
/// <paramref name="type"/> or <paramref name="sizeExpression"/>
/// is a null reference.
/// </exception>
public static ArrayCreationWithSizeExpression NewArray(
ITypeDeclaration type,
Expression sizeExpression
)
{
if (type == null)
throw new ArgumentNullException("type");
if (sizeExpression == null)
throw new ArgumentNullException("sizeExpression");
return new ArrayCreationWithSizeExpression(type, sizeExpression);
}
#endregion
#region NewArray (initializers)
/// <summary>
/// Creates a <c>new type[] { initializers }</c> expression
/// </summary>
/// <param name="type">Array item type</param>
/// <param name="initializers">Array items</param>
/// <returns>A <see cref="ArrayCreationWithInitializersExpression"/> instance</returns>
/// <include file='Refly.CodeDom.Doc.xml' path='doc/remarkss/remark[@name="Expr.NewArray"]'/>
/// <exception cref="ArgumentNullExpression">
/// <paramref name="type"/> is a null reference.
/// </exception>
public static ArrayCreationWithInitializersExpression NewArray(
Type type,
params Expression[] initialiers
)
{
if (type == null)
throw new ArgumentNullException("type");
return new ArrayCreationWithInitializersExpression(
new TypeTypeDeclaration(type),
initialiers);
}
/// <summary>
/// Creates a <c>new type[] { initializers }</c> expression
/// </summary>
/// <param name="type">Array item type</param>
/// <param name="initializers">Array items</param>
/// <returns>A <see cref="ArrayCreationWithInitializersExpression"/> instance</returns>
/// <include file='Refly.CodeDom.Doc.xml' path='doc/remarkss/remark[@name="Expr.NewArray"]'/>
/// <exception cref="ArgumentNullExpression">
/// <paramref name="type"/> is a null reference.
/// </exception>
public static ArrayCreationWithInitializersExpression NewArray(
String type,
params Expression[] initialiers
)
{
if (type == null)
throw new ArgumentNullException("type");
return new ArrayCreationWithInitializersExpression(
new StringTypeDeclaration(type),
initialiers);
}
/// <summary>
/// Creates a <c>new type[] { initializers }</c> expression
/// </summary>
/// <param name="type">Array item type</param>
/// <param name="initializers">Array items</param>
/// <returns>A <see cref="ArrayCreationWithInitializersExpression"/> instance</returns>
/// <include file='Refly.CodeDom.Doc.xml' path='doc/remarkss/remark[@name="Expr.NewArray"]'/>
/// <exception cref="ArgumentNullExpression">
/// <paramref name="type"/> is a null reference.
/// </exception>
public static ArrayCreationWithInitializersExpression NewArray(
ITypeDeclaration type,
params Expression[] initialiers
)
{
if (type == null)
throw new ArgumentNullException("type");
return new ArrayCreationWithInitializersExpression(
type,
initialiers);
}
#endregion
#region Arg, Var
/// <summary>
/// Creates a reference to a given argument
/// </summary>
/// <param name="p">
/// The <see cref="ParameterDeclaration"/> instance to reference.
/// </param>
/// <returns>
/// A <see cref="ArgumentReferenceExpression"/> instance referencing
/// <paramref name="p"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="p"/> is a null reference (Noting in Visual Basic)
/// </exception>
public static ArgumentReferenceExpression Arg(
ParameterDeclaration p)
{
if (p==null)
throw new ArgumentNullException("p");
return new ArgumentReferenceExpression(p);
}
/// <summary>
/// Creates a reference to a given variable
/// </summary>
/// <param name="p">
/// The <see cref="VariableDeclarationStatement"/> instance to reference.
/// </param>
/// <returns>
/// A <see cref="VariableReferenceExpression"/> instance referencing
/// <paramref name="v"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="v"/> is a null reference (Noting in Visual Basic)
/// </exception>
public static VariableReferenceExpression Var(
VariableDeclarationStatement v)
{
if (v==null)
throw new ArgumentNullException("v");
return new VariableReferenceExpression(v);
}
#endregion
#region Prim
/// <summary>
/// Creates a primitive <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">
/// <see cref="Boolean"/> value to generate.
/// </param>
/// <returns>
/// A <see cref="PrimitiveExpression"/> instance that
/// will generate the value.
/// </returns>
public static PrimitiveExpression Prim(bool value)
{
return new PrimitiveExpression(value);
}
/// <summary>
/// Creates a primitive <see cref="String"/> value.
/// </summary>
/// <param name="value">
/// <see cref="String"/> value to generate.
/// </param>
/// <returns>
/// A <see cref="PrimitiveExpression"/> instance that
/// will generate the value.
/// </returns>
public static PrimitiveExpression Prim(string value)
{
return new PrimitiveExpression(value);
}
/// <summary>
/// Creates a primitive <see cref="int"/> value.
/// </summary>
/// <param name="value">
/// <see cref="int"/> value to generate.
/// </param>
/// <returns>
/// A <see cref="PrimitiveExpression"/> instance that
/// will generate the value.
/// </returns>
public static PrimitiveExpression Prim(int value)
{
return new PrimitiveExpression(value);
}
/// <summary>
/// Creates a primitive <see cref="long"/> value.
/// </summary>
/// <param name="value">
/// <see cref="long"/> value to generate.
/// </param>
/// <returns>
/// A <see cref="PrimitiveExpression"/> instance that
/// will generate the value.
/// </returns>
public static PrimitiveExpression Prim(long value)
{
return new PrimitiveExpression(value);
}
/// <summary>
/// Creates a primitive <see cref="decimal"/> value.
/// </summary>
/// <param name="value">
/// <see cref="decimal"/> value to generate.
/// </param>
/// <returns>
/// A <see cref="PrimitiveExpression"/> instance that
/// will generate the value.
/// </returns>
public static PrimitiveExpression Prim(decimal value)
{
return new PrimitiveExpression(value);
}
/// <summary>
/// Creates a primitive <see cref="double"/> value.
/// </summary>
/// <param name="value">
/// <see cref="double"/> value to generate.
/// </param>
/// <returns>
/// A <see cref="PrimitiveExpression"/> instance that
/// will generate the value.
/// </returns>
public static PrimitiveExpression Prim(double value)
{
return new PrimitiveExpression(value);
}
/// <summary>
/// Creates a primitive <see cref="short"/> value.
/// </summary>
/// <param name="value">
/// <see cref="short"/> value to generate.
/// </param>
/// <returns>
/// A <see cref="PrimitiveExpression"/> instance that
/// will generate the value.
/// </returns>
public static PrimitiveExpression Prim(short value)
{
return new PrimitiveExpression(value);
}
/// <summary>
/// Creates a primitive <see cref="byte"/> value.
/// </summary>
/// <param name="value">
/// <see cref="byte"/> value to generate.
/// </param>
/// <returns>
/// A <see cref="PrimitiveExpression"/> instance that
/// will generate the value.
/// </returns>
public static PrimitiveExpression Prim(byte value)
{
return new PrimitiveExpression(value);
}
/// <summary>
/// Creates a primitive <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">
/// <see cref="DateTime"/> value to generate.
/// </param>
/// <returns>
/// A <see cref="PrimitiveExpression"/> instance that
/// will generate the value.
/// </returns>
public static PrimitiveExpression Prim(DateTime value)
{
return new PrimitiveExpression(value);
}
#endregion
#region Cast
/// <summary>
/// Creates a case of the <see cref="Expression"/>
/// <paramref name="e"/> to the <see cref="Type"/>
/// <paramref name="type"/>.
/// </summary>
/// <param name="type">Target <see cref="Type"/></param>
/// <param name="e"><see cref="Expression"/> instance to case</param>
/// <returns>
/// A <see cref="CastExpressoin"/> that will generate the cast.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is a null reference (Noting in Visual Basic)
/// </exception>
public static CastExpression Cast(String type, Expression e)
{
if (type==null)
throw new ArgumentNullException("type");
return Cast(new StringTypeDeclaration(type),e);
}
/// <summary>
/// Creates a case of the <see cref="Expression"/>
/// <paramref name="e"/> to the <see cref="Type"/>
/// <paramref name="type"/>.
/// </summary>
/// <param name="type">Target <see cref="Type"/></param>
/// <param name="e"><see cref="Expression"/> instance to case</param>
/// <returns>
/// A <see cref="CastExpressoin"/> that will generate the cast.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is a null reference (Noting in Visual Basic)
/// </exception>
public static CastExpression Cast(Type type, Expression e)
{
if (type==null)
throw new ArgumentNullException("type");
return Cast(new TypeTypeDeclaration(type),e);
}
/// <summary>
/// Creates a case of the <see cref="Expression"/>
/// <paramref name="e"/> to the <see cref="Type"/>
/// <paramref name="type"/>.
/// </summary>
/// <param name="type">Target <see cref="Type"/></param>
/// <param name="e"><see cref="Expression"/> instance to case</param>
/// <returns>
/// A <see cref="CastExpressoin"/> that will generate the cast.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is a null reference (Noting in Visual Basic)
/// </exception>
public static CastExpression Cast(ITypeDeclaration type, Expression e)
{
return new CastExpression(type,e);
}
#endregion
#region Snippet
/// <summary>
/// Creates a snippet of code that will be outputed as such.
/// </summary>
/// <param name="snippet">
/// Snippet of code
/// </param>
/// <remarks>
/// <para>
/// Try not to use this type of generators because you will not be
/// able to output different languages. This one is for the lazy users!
/// </para>
/// </remarks>
/// <returns>
/// A <see cref="NativeExpression"/> instance that will output the snippet.
/// </returns>
public static NativeExpression Snippet(string snippet)
{
return new NativeExpression(
new CodeSnippetExpression(snippet)
);
}
#endregion
#region TypeOf
/// <summary>
/// Creates a <c>typeof(type)</c> expression.
/// </summary>
/// <param name="type">
/// Target <see cref="Type"/> name.
/// </param>
/// <returns>
/// A <see cref="NativeExpression"/> that will generate the expression.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is a null reference (Nothing in Visual Basic)
/// </exception>
public static NativeExpression TypeOf(String type)
{
if (type==null)
throw new ArgumentNullException("type");
return TypeOf(new StringTypeDeclaration(type));
}
/// <summary>
/// Creates a <c>typeof(type)</c> expression.
/// </summary>
/// <param name="type">
/// Target <see cref="Type"/>
/// </param>
/// <returns>
/// A <see cref="NativeExpression"/> that will generate the expression.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is a null reference (Nothing in Visual Basic)
/// </exception>
public static NativeExpression TypeOf(Type type)
{
if (type==null)
throw new ArgumentNullException("type");
return TypeOf(new TypeTypeDeclaration(type));
}
/// <summary>
/// Creates a <c>typeof(type)</c> expression.
/// </summary>
/// <param name="type">
/// Target <see cref="Type"/>
/// </param>
/// <returns>
/// A <see cref="NativeExpression"/> that will generate the expression.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is a null reference (Nothing in Visual Basic)
/// </exception>
public static NativeExpression TypeOf(ITypeDeclaration type)
{
if (type==null)
throw new ArgumentNullException("type");
return new NativeExpression(
new CodeTypeOfExpression(type.TypeReference)
);
}
#endregion
#region Type
/// <summary>
/// Creates a reference expression to a given <see cref="Type"/>.
/// </summary>
/// <param name="type">
/// Target <see cref="Type"/> name
/// </param>
/// <returns>
/// A <see cref="NativeExpression"/> that will generate the expression.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is a null reference (Nothing in Visual Basic)
/// </exception>
public static TypeReferenceExpression Type(String type)
{
if (type==null)
throw new ArgumentNullException("type");
return Type(new StringTypeDeclaration(type));
}
/// <summary>
/// Creates a reference expression to a given <see cref="Type"/>.
/// </summary>
/// <param name="type">
/// Target <see cref="Type"/> name
/// </param>
/// <returns>
/// A <see cref="NativeExpression"/> that will generate the expression.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is a null reference (Nothing in Visual Basic)
/// </exception>
public static TypeReferenceExpression Type(Type type)
{
if (type==null)
throw new ArgumentNullException("type");
return Type(new TypeTypeDeclaration(type));
}
/// <summary>
/// Creates a reference expression to a given <see cref="Type"/>.
/// </summary>
/// <param name="type">
/// Target <see cref="Type"/> name
/// </param>
/// <returns>
/// A <see cref="NativeExpression"/> that will generate the expression.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is a null reference (Nothing in Visual Basic)
/// </exception>
public static TypeReferenceExpression Type(ITypeDeclaration type)
{
if (type==null)
throw new ArgumentNullException("type");
return new TypeReferenceExpression(type);
}
#endregion
#region Delegate
/// <summary>
/// Creates a delegate constructr
/// </summary>
/// <param name="delegateType">
/// The delegate type
/// </param>
/// <param name="method">
/// The listener method
/// </param>
/// <returns>
/// A <see cref="DelegateCreateExpression"/> representing the
/// delegate creation.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="delegateType"/> or <paramref name="method"/>
/// is a null reference (Nothing in Visual Basic)
/// </exception>
public static DelegateCreateExpression Delegate(
ITypeDeclaration delegateType,
MethodReferenceExpression method)
{
if (delegateType==null)
throw new ArgumentNullException("delegateType");
if (method==null)
throw new ArgumentNullException("method");
return new DelegateCreateExpression(delegateType,method);
}
/// <summary>
/// Creates a delegate constructr
/// </summary>
/// <param name="delegateType">
/// The delegate type
/// </param>
/// <param name="method">
/// The listener method
/// </param>
/// <returns>
/// A <see cref="DelegateCreateExpression"/> representing the
/// delegate creation.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="delegateType"/> or <paramref name="method"/>
/// is a null reference (Nothing in Visual Basic)
/// </exception>
public static DelegateCreateExpression Delegate(
string delegateType,
MethodReferenceExpression method)
{
if (delegateType==null)
throw new ArgumentNullException("delegateType");
if (method==null)
throw new ArgumentNullException("method");
return new DelegateCreateExpression(new StringTypeDeclaration(delegateType),method);
}
/// <summary>
/// Creates a delegate constructr
/// </summary>
/// <param name="delegateType">
/// The delegate type
/// </param>
/// <param name="method">
/// The listener method
/// </param>
/// <returns>
/// A <see cref="DelegateCreateExpression"/> representing the
/// delegate creation.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="delegateType"/> or <paramref name="method"/>
/// is a null reference (Nothing in Visual Basic)
/// </exception>
public static DelegateCreateExpression Delegate(
Type delegateType,
MethodReferenceExpression method)
{
if (delegateType==null)
throw new ArgumentNullException("delegateType");
if (method==null)
throw new ArgumentNullException("method");
return new DelegateCreateExpression(new TypeTypeDeclaration(delegateType),method);
}
#endregion
#region DelegateInvoke
/// <summary>
/// Create a <c>firedEvent(parameters)</c> invocation.</c>
/// </summary>
/// <param name="firedEvent">Delegate to invoke</param>
/// <param name="parameters">Delegate arguments</param>
/// <returns></returns>
public static DelegateInvokeExpression DelegateInvoke(
EventReferenceExpression firedEvent,
params Expression[] parameters
)
{
if (firedEvent == null)
throw new ArgumentNullException("firedEvent");
DelegateInvokeExpression expr = new DelegateInvokeExpression(firedEvent, parameters);
return expr;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using EffectEditor.EffectComponents.HLSLInformation;
using EffectEditor.EffectComponents;
using System.Collections;
namespace EffectEditor.Controls
{
public partial class ComponentParameterList : UserControl
{
private List<EffectParameterDefinition> mParameters;
[Browsable(false)]
public List<EffectParameterDefinition> Parameters
{
get { return mParameters; }
set
{
mParameters = value;
UpdateList();
}
}
private List<HlslSemantic> mSemantics;
[Browsable(false)]
public List<HlslSemantic> Semantics
{
get { return mSemantics; }
set
{
mSemantics = value;
SetSemantics();
}
}
private bool mSemanticEnabled = true;
[Browsable(true), DefaultValue(true)]
public bool SemanticEnabled
{
get { return mSemanticEnabled; }
set
{
mSemanticEnabled = value;
if (!SemanticEnabled)
{
semanticLabel.Visible = false;
semanticBox.Visible = false;
semanticNumberBox.Visible = false;
// resize
int height = semanticBox.Height;
paramEditPanel.Height -= height;
paramEditPanel.Top += height;
newParamButton.Top += height;
deleteParamButton.Top += height;
parameterListBox.Height += height;
}
}
}
private bool mStorageClassEnabled = true;
[Browsable(true), DefaultValue(true)]
public bool StorageClassEnabled
{
get { return mStorageClassEnabled; }
set
{
mStorageClassEnabled = value;
updateStorageClass();
}
}
private void updateStorageClass()
{
if (!StorageClassEnabled)
{
storageClassLabel.Visible = false;
storageClassBox.Visible = false;
// resize
int height = semanticBox.Height;
paramEditPanel.Height -= height;
paramEditPanel.Top += height;
newParamButton.Top += height;
deleteParamButton.Top += height;
parameterListBox.Height += height;
semanticLabel.Top -= height;
semanticBox.Top -= height;
semanticNumberBox.Top -= height;
}
else
{
storageClassBox.Items.Clear();
string[] storageClassNames = Enum.GetNames(typeof(StorageClass));
storageClassBox.Items.AddRange(storageClassNames);
storageClassBox.SelectedText = "None";
}
}
bool LoadingNewParam = false; // used to stop params from raising change events while switching
public event EventHandler ParametersChanged;
public ComponentParameterList()
{
mParameters = new List<EffectParameterDefinition>();
InitializeComponent();
parameterListBox.DataSource = mParameters;
// Initialize type values
string[] typeNames = Enum.GetNames(typeof(HlslType));
for (int i = 0; i < typeNames.Length; i++)
{
paramTypeBox.Items.Add(typeNames[i]);
}
paramTypeBox.SelectedText = "Float";
updateStorageClass();
}
private void SetSemantics()
{
semanticBox.Items.Clear();
if (mSemantics != null)
{
foreach (HlslSemantic semantic in mSemantics)
{
semanticBox.Items.Add(semantic);
}
}
}
private void DoParametersChanged()
{
if (ParametersChanged != null)
{
ParametersChanged(this, new EventArgs());
}
}
private void paramEdited(object sender, EventArgs e)
{
if (!LoadingNewParam &&
paramNameBox.Text != "" && paramTypeBox.SelectedItem != null)
{
EditParameter(parameterListBox.SelectedIndex);
DoParametersChanged();
}
}
#region XML Docs
/// <summary>
/// Edits the parameter in the list with the selected index
/// </summary>
#endregion
private void EditParameter(int index)
{
// updates the parameter in the list
EffectParameterDefinition param = (EffectParameterDefinition)mParameters[index];
param.Name = paramNameBox.Text;
param.Type.Type = (HlslType)Enum.Parse(typeof(HlslType), (string)paramTypeBox.SelectedItem);
if (param.Type.Type == HlslType.Texture || (string)paramTypeSizeBox.SelectedItem == "Scalar")
{
param.Type.IsVector = false;
param.Type.IsArray = false;
param.Type.IsMatrix = false;
}
else if ((string)paramTypeSizeBox.SelectedItem == "Vector")
{
param.Type.IsVector = true;
param.Type.IsArray = false;
param.Type.IsMatrix = false;
param.Type.Size = (int)paramTypeSizeA.Value;
}
else if ((string)paramTypeSizeBox.SelectedItem == "Array")
{
param.Type.IsVector = false;
param.Type.IsArray = true;
param.Type.IsMatrix = false;
param.Type.Size = (int)paramTypeSizeA.Value;
}
else if ((string)paramTypeSizeBox.SelectedItem == "Matrix")
{
param.Type.IsVector = false;
param.Type.IsArray = false;
param.Type.IsMatrix = true;
param.Type.Size = (int)paramTypeSizeA.Value;
param.Type.MatrixColumns = (int)paramTypeSizeB.Value;
}
// semantic
param.HasSemantic = mSemanticEnabled;
if (mSemanticEnabled)
{
param.Semantic = mSemantics[semanticBox.SelectedIndex];
param.Semantic.ResourceNumber = (int)semanticNumberBox.Value;
}
// storage class
param.HasStorageClass = mStorageClassEnabled;
if (mStorageClassEnabled)
{
if (storageClassBox.SelectedItem == null || storageClassBox.SelectedText == String.Empty) param.StorageClass = StorageClass.None;
else param.StorageClass = (StorageClass)Enum.Parse(typeof(StorageClass), storageClassBox.SelectedText, true);
}
mParameters[index] = param;
UpdateList();
parameterListBox.SelectedItem = param;
}
private void paramTypeBox_SelectedIndexChanged(object sender, EventArgs e)
{
HlslType type = (HlslType)Enum.Parse(typeof(HlslType), (string)paramTypeBox.SelectedItem);
if (type != HlslType.Texture)
{
paramTypeSizeBox.Visible = true;
}
else
{
paramTypeSizeBox.Visible = false;
paramTypeSizeA.Visible = false;
paramTypeSizeB.Visible = false;
paramSizeDividerLabel.Visible = false;
}
paramEdited(sender, e);
}
private void setSizeBoxVisibilities()
{
if ((string)paramTypeSizeBox.SelectedItem == "Scalar")
{
paramTypeSizeA.Visible = false;
paramTypeSizeB.Visible = false;
paramSizeDividerLabel.Visible = false;
}
else if ((string)paramTypeSizeBox.SelectedItem == "Vector")
{
paramTypeSizeA.Visible = true;
paramTypeSizeA.Minimum = 1;
paramTypeSizeA.Maximum = 4;
paramTypeSizeB.Visible = false;
paramSizeDividerLabel.Visible = false;
}
else if ((string)paramTypeSizeBox.SelectedItem == "Array")
{
paramTypeSizeA.Visible = true;
paramTypeSizeA.Minimum = 1;
paramTypeSizeA.Maximum = 2048;
paramTypeSizeB.Visible = false;
paramSizeDividerLabel.Visible = false;
}
else if ((string)paramTypeSizeBox.SelectedItem == "Matrix")
{
paramTypeSizeA.Visible = true;
paramTypeSizeA.Minimum = 1;
paramTypeSizeA.Maximum = 4;
paramTypeSizeB.Visible = true;
paramTypeSizeB.Minimum = 1;
paramTypeSizeB.Maximum = 4;
paramSizeDividerLabel.Visible = true;
}
}
private void paramTypeSizeBox_SelectedIndexChanged(object sender, EventArgs e)
{
setSizeBoxVisibilities();
paramEdited(sender, e);
}
private void parameterListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (parameterListBox.SelectedIndex >= 0) SelectParameter(parameterListBox.SelectedIndex);
}
private void deleteParamButton_Click(object sender, EventArgs e)
{
RemoveParameter(parameterListBox.SelectedIndex);
}
private void UpdateList()
{
int selectIndex = parameterListBox.SelectedIndex;
int nameSelectStart = paramNameBox.SelectionStart;
int nameSelectLength = paramNameBox.SelectionLength;
if (selectIndex >= 0 && parameterListBox.Items.Count > 0)
{
EffectParameterDefinition param = mParameters[parameterListBox.SelectedIndex];
mParameters.Sort();
selectIndex = mParameters.IndexOf(param);
}
parameterListBox.DataSource = null;
parameterListBox.DataSource = mParameters;
if (selectIndex >= 0 && parameterListBox.Items.Count > 0)
{
parameterListBox.SelectedIndex = selectIndex;
paramNameBox.SelectionStart = nameSelectStart;
paramNameBox.SelectionLength = nameSelectLength;
}
}
private void newParamButton_Click(object sender, EventArgs e)
{
AddParameter(new EffectParameterDefinition(
"NewParameter", new HlslTypeDefinition(HlslType.Float)));
}
public void RemoveParameter(int index)
{
mParameters.RemoveAt(index);
parameterListBox.DataSource = null;
parameterListBox.DataSource = mParameters;
UpdateList();
if (index >= mParameters.Count)
{
index--;
}
if (index >= 0) parameterListBox.SelectedIndex = index;
else
{
deleteParamButton.Enabled = false;
paramEditPanel.Enabled = false;
}
DoParametersChanged();
}
public void AddParameter(EffectParameterDefinition param)
{
mParameters.Add(param);
mParameters.Sort();
UpdateList();
parameterListBox.SelectedItem = param;
DoParametersChanged();
}
public void SelectParameter(int index)
{
LoadingNewParam = true;
deleteParamButton.Enabled = true;
paramEditPanel.Enabled = true;
EditParameter((EffectParameterDefinition)mParameters[index]);
LoadingNewParam = false;
}
public void EditParameter(EffectParameterDefinition param)
{
// populate the editing panel
paramNameBox.Text = param.Name;
paramTypeBox.SelectedItem = param.Type.Type.ToString();
if (param.Name != HlslType.Texture.ToString())
{
if (param.Type.IsVector)
{
paramTypeSizeBox.SelectedItem = "Vector";
paramTypeSizeA.Value = param.Type.Size;
}
else if (param.Type.IsArray)
{
paramTypeSizeBox.SelectedItem = "Array";
paramTypeSizeA.Value = param.Type.Size;
}
else if (param.Type.IsMatrix)
{
paramTypeSizeBox.SelectedItem = "Matrix";
paramTypeSizeA.Value = param.Type.Size;
paramTypeSizeB.Value = param.Type.MatrixColumns;
}
else
{
paramTypeSizeBox.SelectedItem = "Scalar";
}
}
bool semanticChanged = false;
if (mSemanticEnabled)
{
if (param.Semantic.Name == null || param.Semantic.Name == String.Empty)
{
param.Semantic = mSemantics[0];
param.Semantic.ResourceNumber = 0;
semanticChanged = true;
}
// Find the index to select
int index = -1;
if (semanticBox.Items.Contains(param.Semantic))
{
index = semanticBox.Items.IndexOf(param.Semantic);
}
else
{
for (int i = 0; i < semanticBox.Items.Count; i++)
{
if (param.Semantic.Name.Equals(((HlslSemantic)semanticBox.Items[i]).Name))
{
index = i;
}
}
}
if (index == -1) index = 0;
semanticBox.SelectedIndex = index;
}
if (mStorageClassEnabled)
{
storageClassBox.Text = (param.StorageClass == StorageClass.None) ?
String.Empty : param.StorageClass.ToString();
}
if (semanticChanged) EditParameter(parameterListBox.SelectedIndex);
}
private void storageClassBox_SelectedIndexChanged(object sender, EventArgs e)
{
paramEdited(sender, e);
}
private void semanticBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (SemanticEnabled)
{
semanticNumberBox.Visible = mSemantics[semanticBox.SelectedIndex].MultipleResourcesSupported;
paramEdited(sender, e);
}
}
private void semanticNumberBox_ValueChanged(object sender, EventArgs e)
{
paramEdited(sender, e);
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class JoinLogEncoder
{
public const ushort BLOCK_LENGTH = 36;
public const ushort TEMPLATE_ID = 40;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private JoinLogEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public JoinLogEncoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public JoinLogEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public JoinLogEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int LogPositionEncodingOffset()
{
return 0;
}
public static int LogPositionEncodingLength()
{
return 8;
}
public static long LogPositionNullValue()
{
return -9223372036854775808L;
}
public static long LogPositionMinValue()
{
return -9223372036854775807L;
}
public static long LogPositionMaxValue()
{
return 9223372036854775807L;
}
public JoinLogEncoder LogPosition(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int MaxLogPositionEncodingOffset()
{
return 8;
}
public static int MaxLogPositionEncodingLength()
{
return 8;
}
public static long MaxLogPositionNullValue()
{
return -9223372036854775808L;
}
public static long MaxLogPositionMinValue()
{
return -9223372036854775807L;
}
public static long MaxLogPositionMaxValue()
{
return 9223372036854775807L;
}
public JoinLogEncoder MaxLogPosition(long value)
{
_buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int MemberIdEncodingOffset()
{
return 16;
}
public static int MemberIdEncodingLength()
{
return 4;
}
public static int MemberIdNullValue()
{
return -2147483648;
}
public static int MemberIdMinValue()
{
return -2147483647;
}
public static int MemberIdMaxValue()
{
return 2147483647;
}
public JoinLogEncoder MemberId(int value)
{
_buffer.PutInt(_offset + 16, value, ByteOrder.LittleEndian);
return this;
}
public static int LogSessionIdEncodingOffset()
{
return 20;
}
public static int LogSessionIdEncodingLength()
{
return 4;
}
public static int LogSessionIdNullValue()
{
return -2147483648;
}
public static int LogSessionIdMinValue()
{
return -2147483647;
}
public static int LogSessionIdMaxValue()
{
return 2147483647;
}
public JoinLogEncoder LogSessionId(int value)
{
_buffer.PutInt(_offset + 20, value, ByteOrder.LittleEndian);
return this;
}
public static int LogStreamIdEncodingOffset()
{
return 24;
}
public static int LogStreamIdEncodingLength()
{
return 4;
}
public static int LogStreamIdNullValue()
{
return -2147483648;
}
public static int LogStreamIdMinValue()
{
return -2147483647;
}
public static int LogStreamIdMaxValue()
{
return 2147483647;
}
public JoinLogEncoder LogStreamId(int value)
{
_buffer.PutInt(_offset + 24, value, ByteOrder.LittleEndian);
return this;
}
public static int IsStartupEncodingOffset()
{
return 28;
}
public static int IsStartupEncodingLength()
{
return 4;
}
public JoinLogEncoder IsStartup(BooleanType value)
{
_buffer.PutInt(_offset + 28, (int)value, ByteOrder.LittleEndian);
return this;
}
public static int RoleEncodingOffset()
{
return 32;
}
public static int RoleEncodingLength()
{
return 4;
}
public static int RoleNullValue()
{
return -2147483648;
}
public static int RoleMinValue()
{
return -2147483647;
}
public static int RoleMaxValue()
{
return 2147483647;
}
public JoinLogEncoder Role(int value)
{
_buffer.PutInt(_offset + 32, value, ByteOrder.LittleEndian);
return this;
}
public static int LogChannelId()
{
return 8;
}
public static string LogChannelCharacterEncoding()
{
return "US-ASCII";
}
public static string LogChannelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int LogChannelHeaderLength()
{
return 4;
}
public JoinLogEncoder PutLogChannel(IDirectBuffer src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public JoinLogEncoder PutLogChannel(byte[] src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public JoinLogEncoder LogChannel(string value)
{
int length = value.Length;
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutStringWithoutLengthAscii(limit + headerLength, value);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
JoinLogDecoder writer = new JoinLogDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure.Management.RemoteApp.Model;
namespace Microsoft.Azure.Management.RemoteApp.Model
{
/// <summary>
/// The collection details.
/// </summary>
public partial class CollectionProperties
{
private ActiveDirectoryConfig _adInfo;
/// <summary>
/// Optional. The domain join details for this collection.
/// </summary>
public ActiveDirectoryConfig AdInfo
{
get { return this._adInfo; }
set { this._adInfo = value; }
}
private string _customRdpProperty;
/// <summary>
/// Optional. Optional customer defined RDP properties of the
/// collection.
/// </summary>
public string CustomRdpProperty
{
get { return this._customRdpProperty; }
set { this._customRdpProperty = value; }
}
private string _description;
/// <summary>
/// Optional. The description of the collection.
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
private IList<string> _dnsServers;
/// <summary>
/// Optional. List of the DNS Servers.
/// </summary>
public IList<string> DnsServers
{
get { return this._dnsServers; }
set { this._dnsServers = value; }
}
private string _lastErrorCode;
/// <summary>
/// Optional. The last operation error code on this collection.
/// </summary>
public string LastErrorCode
{
get { return this._lastErrorCode; }
set { this._lastErrorCode = value; }
}
private DateTime _lastModifiedTimeUtc;
/// <summary>
/// Optional. UTC Date time of the last modification of this collection.
/// </summary>
public DateTime LastModifiedTimeUtc
{
get { return this._lastModifiedTimeUtc; }
set { this._lastModifiedTimeUtc = value; }
}
private string _location;
/// <summary>
/// Optional. The region where the collection is deployed.
/// </summary>
public string Location
{
get { return this._location; }
set { this._location = value; }
}
private int _maxSessions;
/// <summary>
/// Optional. The maximum number of concurrent users allowed for this
/// collection.
/// </summary>
public int MaxSessions
{
get { return this._maxSessions; }
set { this._maxSessions = value; }
}
private CollectionMode _mode;
/// <summary>
/// Optional. The collection mode.
/// </summary>
public CollectionMode Mode
{
get { return this._mode; }
set { this._mode = value; }
}
private string _name;
/// <summary>
/// Required. The collection name.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private OfficeType _officeType;
/// <summary>
/// Optional. If the template image for this collection includes Office
/// this will specify the type.
/// </summary>
public OfficeType OfficeType
{
get { return this._officeType; }
set { this._officeType = value; }
}
private string _planName;
/// <summary>
/// Required. The plan name associated with this collection.
/// </summary>
public string PlanName
{
get { return this._planName; }
set { this._planName = value; }
}
private ProvisioningState _provisioningState;
/// <summary>
/// Required. The collection provisioning state.
/// </summary>
public ProvisioningState ProvisioningState
{
get { return this._provisioningState; }
set { this._provisioningState = value; }
}
private bool _readyForPublishing;
/// <summary>
/// Optional. A flag denoting if this collection is ready for
/// publishing operations.
/// </summary>
public bool ReadyForPublishing
{
get { return this._readyForPublishing; }
set { this._readyForPublishing = value; }
}
private int _sessionWarningThreshold;
/// <summary>
/// Optional. The end-user session limit warning threshold. Reaching
/// or crossing this threshold will cause a capacity warning message
/// to be shown in the management portal.
/// </summary>
public int SessionWarningThreshold
{
get { return this._sessionWarningThreshold; }
set { this._sessionWarningThreshold = value; }
}
private string _status;
/// <summary>
/// Optional. The collection status.
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
private string _subnetName;
/// <summary>
/// Optional. The subnet name of the customer created Azure VNet.
/// </summary>
public string SubnetName
{
get { return this._subnetName; }
set { this._subnetName = value; }
}
private string _templateImageName;
/// <summary>
/// Optional. The name of the gold image associated with this
/// collection.
/// </summary>
public string TemplateImageName
{
get { return this._templateImageName; }
set { this._templateImageName = value; }
}
private bool _trialOnly;
/// <summary>
/// Optional. Trial-only collections can be used only during the trial
/// period of your subscription. When the trial expires or you
/// activate your subscription, these collections will be permanently
/// disabled.
/// </summary>
public bool TrialOnly
{
get { return this._trialOnly; }
set { this._trialOnly = value; }
}
private CollectionType _type;
/// <summary>
/// Optional. The collection type.
/// </summary>
public CollectionType Type
{
get { return this._type; }
set { this._type = value; }
}
private string _vNetName;
/// <summary>
/// Optional. The VNet name associated with this collection.
/// </summary>
public string VNetName
{
get { return this._vNetName; }
set { this._vNetName = value; }
}
/// <summary>
/// Initializes a new instance of the CollectionProperties class.
/// </summary>
public CollectionProperties()
{
this.DnsServers = new LazyList<string>();
}
/// <summary>
/// Initializes a new instance of the CollectionProperties class with
/// required arguments.
/// </summary>
public CollectionProperties(ProvisioningState provisioningState, string name, string planName)
: this()
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (planName == null)
{
throw new ArgumentNullException("planName");
}
this.ProvisioningState = provisioningState;
this.Name = name;
this.PlanName = planName;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using lro = Google.LongRunning;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.LifeSciences.V2Beta
{
/// <summary>Settings for <see cref="WorkflowsServiceV2BetaClient"/> instances.</summary>
public sealed partial class WorkflowsServiceV2BetaSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="WorkflowsServiceV2BetaSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="WorkflowsServiceV2BetaSettings"/>.</returns>
public static WorkflowsServiceV2BetaSettings GetDefault() => new WorkflowsServiceV2BetaSettings();
/// <summary>
/// Constructs a new <see cref="WorkflowsServiceV2BetaSettings"/> object with default settings.
/// </summary>
public WorkflowsServiceV2BetaSettings()
{
}
private WorkflowsServiceV2BetaSettings(WorkflowsServiceV2BetaSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
RunPipelineSettings = existing.RunPipelineSettings;
RunPipelineOperationsSettings = existing.RunPipelineOperationsSettings.Clone();
OnCopy(existing);
}
partial void OnCopy(WorkflowsServiceV2BetaSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>WorkflowsServiceV2BetaClient.RunPipeline</c> and <c>WorkflowsServiceV2BetaClient.RunPipelineAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings RunPipelineSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// Long Running Operation settings for calls to <c>WorkflowsServiceV2BetaClient.RunPipeline</c> and
/// <c>WorkflowsServiceV2BetaClient.RunPipelineAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings RunPipelineOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="WorkflowsServiceV2BetaSettings"/> object.</returns>
public WorkflowsServiceV2BetaSettings Clone() => new WorkflowsServiceV2BetaSettings(this);
}
/// <summary>
/// Builder class for <see cref="WorkflowsServiceV2BetaClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
public sealed partial class WorkflowsServiceV2BetaClientBuilder : gaxgrpc::ClientBuilderBase<WorkflowsServiceV2BetaClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public WorkflowsServiceV2BetaSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public WorkflowsServiceV2BetaClientBuilder()
{
UseJwtAccessWithScopes = WorkflowsServiceV2BetaClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref WorkflowsServiceV2BetaClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<WorkflowsServiceV2BetaClient> task);
/// <summary>Builds the resulting client.</summary>
public override WorkflowsServiceV2BetaClient Build()
{
WorkflowsServiceV2BetaClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<WorkflowsServiceV2BetaClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<WorkflowsServiceV2BetaClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private WorkflowsServiceV2BetaClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return WorkflowsServiceV2BetaClient.Create(callInvoker, Settings);
}
private async stt::Task<WorkflowsServiceV2BetaClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return WorkflowsServiceV2BetaClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => WorkflowsServiceV2BetaClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => WorkflowsServiceV2BetaClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => WorkflowsServiceV2BetaClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>WorkflowsServiceV2Beta client wrapper, for convenient use.</summary>
/// <remarks>
/// A service for running workflows, such as pipelines consisting of Docker
/// containers.
/// </remarks>
public abstract partial class WorkflowsServiceV2BetaClient
{
/// <summary>
/// The default endpoint for the WorkflowsServiceV2Beta service, which is a host of
/// "lifesciences.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "lifesciences.googleapis.com:443";
/// <summary>The default WorkflowsServiceV2Beta scopes.</summary>
/// <remarks>
/// The default WorkflowsServiceV2Beta scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="WorkflowsServiceV2BetaClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="WorkflowsServiceV2BetaClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="WorkflowsServiceV2BetaClient"/>.</returns>
public static stt::Task<WorkflowsServiceV2BetaClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new WorkflowsServiceV2BetaClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="WorkflowsServiceV2BetaClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="WorkflowsServiceV2BetaClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="WorkflowsServiceV2BetaClient"/>.</returns>
public static WorkflowsServiceV2BetaClient Create() => new WorkflowsServiceV2BetaClientBuilder().Build();
/// <summary>
/// Creates a <see cref="WorkflowsServiceV2BetaClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="WorkflowsServiceV2BetaSettings"/>.</param>
/// <returns>The created <see cref="WorkflowsServiceV2BetaClient"/>.</returns>
internal static WorkflowsServiceV2BetaClient Create(grpccore::CallInvoker callInvoker, WorkflowsServiceV2BetaSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
WorkflowsServiceV2Beta.WorkflowsServiceV2BetaClient grpcClient = new WorkflowsServiceV2Beta.WorkflowsServiceV2BetaClient(callInvoker);
return new WorkflowsServiceV2BetaClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC WorkflowsServiceV2Beta client</summary>
public virtual WorkflowsServiceV2Beta.WorkflowsServiceV2BetaClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Runs a pipeline. The returned Operation's [metadata]
/// [google.longrunning.Operation.metadata] field will contain a
/// [google.cloud.lifesciences.v2beta.Metadata][google.cloud.lifesciences.v2beta.Metadata] object describing the status
/// of the pipeline execution. The
/// [response][google.longrunning.Operation.response] field will contain a
/// [google.cloud.lifesciences.v2beta.RunPipelineResponse][google.cloud.lifesciences.v2beta.RunPipelineResponse] object if the
/// pipeline completes successfully.
///
/// **Note:** Before you can use this method, the *Life Sciences Service Agent*
/// must have access to your project. This is done automatically when the
/// Cloud Life Sciences API is first enabled, but if you delete this permission
/// you must disable and re-enable the API to grant the Life Sciences
/// Service Agent the required permissions.
/// Authorization requires the following [Google
/// IAM](https://cloud.google.com/iam/) permission:
///
/// * `lifesciences.workflows.run`
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<RunPipelineResponse, Metadata> RunPipeline(RunPipelineRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Runs a pipeline. The returned Operation's [metadata]
/// [google.longrunning.Operation.metadata] field will contain a
/// [google.cloud.lifesciences.v2beta.Metadata][google.cloud.lifesciences.v2beta.Metadata] object describing the status
/// of the pipeline execution. The
/// [response][google.longrunning.Operation.response] field will contain a
/// [google.cloud.lifesciences.v2beta.RunPipelineResponse][google.cloud.lifesciences.v2beta.RunPipelineResponse] object if the
/// pipeline completes successfully.
///
/// **Note:** Before you can use this method, the *Life Sciences Service Agent*
/// must have access to your project. This is done automatically when the
/// Cloud Life Sciences API is first enabled, but if you delete this permission
/// you must disable and re-enable the API to grant the Life Sciences
/// Service Agent the required permissions.
/// Authorization requires the following [Google
/// IAM](https://cloud.google.com/iam/) permission:
///
/// * `lifesciences.workflows.run`
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<RunPipelineResponse, Metadata>> RunPipelineAsync(RunPipelineRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Runs a pipeline. The returned Operation's [metadata]
/// [google.longrunning.Operation.metadata] field will contain a
/// [google.cloud.lifesciences.v2beta.Metadata][google.cloud.lifesciences.v2beta.Metadata] object describing the status
/// of the pipeline execution. The
/// [response][google.longrunning.Operation.response] field will contain a
/// [google.cloud.lifesciences.v2beta.RunPipelineResponse][google.cloud.lifesciences.v2beta.RunPipelineResponse] object if the
/// pipeline completes successfully.
///
/// **Note:** Before you can use this method, the *Life Sciences Service Agent*
/// must have access to your project. This is done automatically when the
/// Cloud Life Sciences API is first enabled, but if you delete this permission
/// you must disable and re-enable the API to grant the Life Sciences
/// Service Agent the required permissions.
/// Authorization requires the following [Google
/// IAM](https://cloud.google.com/iam/) permission:
///
/// * `lifesciences.workflows.run`
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<RunPipelineResponse, Metadata>> RunPipelineAsync(RunPipelineRequest request, st::CancellationToken cancellationToken) =>
RunPipelineAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>RunPipeline</c>.</summary>
public virtual lro::OperationsClient RunPipelineOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>RunPipeline</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<RunPipelineResponse, Metadata> PollOnceRunPipeline(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<RunPipelineResponse, Metadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), RunPipelineOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of
/// <c>RunPipeline</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<RunPipelineResponse, Metadata>> PollOnceRunPipelineAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<RunPipelineResponse, Metadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), RunPipelineOperationsClient, callSettings);
}
/// <summary>WorkflowsServiceV2Beta client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// A service for running workflows, such as pipelines consisting of Docker
/// containers.
/// </remarks>
public sealed partial class WorkflowsServiceV2BetaClientImpl : WorkflowsServiceV2BetaClient
{
private readonly gaxgrpc::ApiCall<RunPipelineRequest, lro::Operation> _callRunPipeline;
/// <summary>
/// Constructs a client wrapper for the WorkflowsServiceV2Beta service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="WorkflowsServiceV2BetaSettings"/> used within this client.
/// </param>
public WorkflowsServiceV2BetaClientImpl(WorkflowsServiceV2Beta.WorkflowsServiceV2BetaClient grpcClient, WorkflowsServiceV2BetaSettings settings)
{
GrpcClient = grpcClient;
WorkflowsServiceV2BetaSettings effectiveSettings = settings ?? WorkflowsServiceV2BetaSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
RunPipelineOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.RunPipelineOperationsSettings);
_callRunPipeline = clientHelper.BuildApiCall<RunPipelineRequest, lro::Operation>(grpcClient.RunPipelineAsync, grpcClient.RunPipeline, effectiveSettings.RunPipelineSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callRunPipeline);
Modify_RunPipelineApiCall(ref _callRunPipeline);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_RunPipelineApiCall(ref gaxgrpc::ApiCall<RunPipelineRequest, lro::Operation> call);
partial void OnConstruction(WorkflowsServiceV2Beta.WorkflowsServiceV2BetaClient grpcClient, WorkflowsServiceV2BetaSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC WorkflowsServiceV2Beta client</summary>
public override WorkflowsServiceV2Beta.WorkflowsServiceV2BetaClient GrpcClient { get; }
partial void Modify_RunPipelineRequest(ref RunPipelineRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>The long-running operations client for <c>RunPipeline</c>.</summary>
public override lro::OperationsClient RunPipelineOperationsClient { get; }
/// <summary>
/// Runs a pipeline. The returned Operation's [metadata]
/// [google.longrunning.Operation.metadata] field will contain a
/// [google.cloud.lifesciences.v2beta.Metadata][google.cloud.lifesciences.v2beta.Metadata] object describing the status
/// of the pipeline execution. The
/// [response][google.longrunning.Operation.response] field will contain a
/// [google.cloud.lifesciences.v2beta.RunPipelineResponse][google.cloud.lifesciences.v2beta.RunPipelineResponse] object if the
/// pipeline completes successfully.
///
/// **Note:** Before you can use this method, the *Life Sciences Service Agent*
/// must have access to your project. This is done automatically when the
/// Cloud Life Sciences API is first enabled, but if you delete this permission
/// you must disable and re-enable the API to grant the Life Sciences
/// Service Agent the required permissions.
/// Authorization requires the following [Google
/// IAM](https://cloud.google.com/iam/) permission:
///
/// * `lifesciences.workflows.run`
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override lro::Operation<RunPipelineResponse, Metadata> RunPipeline(RunPipelineRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_RunPipelineRequest(ref request, ref callSettings);
return new lro::Operation<RunPipelineResponse, Metadata>(_callRunPipeline.Sync(request, callSettings), RunPipelineOperationsClient);
}
/// <summary>
/// Runs a pipeline. The returned Operation's [metadata]
/// [google.longrunning.Operation.metadata] field will contain a
/// [google.cloud.lifesciences.v2beta.Metadata][google.cloud.lifesciences.v2beta.Metadata] object describing the status
/// of the pipeline execution. The
/// [response][google.longrunning.Operation.response] field will contain a
/// [google.cloud.lifesciences.v2beta.RunPipelineResponse][google.cloud.lifesciences.v2beta.RunPipelineResponse] object if the
/// pipeline completes successfully.
///
/// **Note:** Before you can use this method, the *Life Sciences Service Agent*
/// must have access to your project. This is done automatically when the
/// Cloud Life Sciences API is first enabled, but if you delete this permission
/// you must disable and re-enable the API to grant the Life Sciences
/// Service Agent the required permissions.
/// Authorization requires the following [Google
/// IAM](https://cloud.google.com/iam/) permission:
///
/// * `lifesciences.workflows.run`
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override async stt::Task<lro::Operation<RunPipelineResponse, Metadata>> RunPipelineAsync(RunPipelineRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_RunPipelineRequest(ref request, ref callSettings);
return new lro::Operation<RunPipelineResponse, Metadata>(await _callRunPipeline.Async(request, callSettings).ConfigureAwait(false), RunPipelineOperationsClient);
}
}
public static partial class WorkflowsServiceV2Beta
{
public partial class WorkflowsServiceV2BetaClient
{
/// <summary>
/// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as
/// this client.
/// </summary>
/// <returns>A new Operations client for the same target as this client.</returns>
public virtual lro::Operations.OperationsClient CreateOperationsClient() =>
new lro::Operations.OperationsClient(CallInvoker);
}
}
}
| |
using System;
using System.Configuration;
using NUnit.Framework;
using System.Threading.Tasks;
using NHttp;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Collections;
using Sharpify.Models;
using System.Collections.Specialized;
namespace Sharpify.Tests.Integration
{
/// <summary>
/// Test the interaction with the actual, running service at :shop.myshopify.com.
///
/// These tests are obviously pretty naiive, and considering that
/// we can make few guarantees about the state of the store, may
/// succeed or fail quite differently depending on conditions.
/// </summary>
[TestFixture]
[Ignore]
public class LiveAPIServiceIntegrationTest
{
ShopifyAuthorizationState AuthorizationState {
get;
set;
}
HttpServer Server {
get;
set;
}
String TestStoreName;
ShopifyAPIContext ShopifyClient;
public LiveAPIServiceIntegrationTest ()
{
TestStoreName = ConfigurationManager.AppSettings ["Shopify.TestStoreName"];
}
public Task<string> ListenForIncomingShopTokenFromRedirect (int port)
{
var tcs = new TaskCompletionSource<string> ();
Server = new HttpServer ();
Server.EndPoint.Port = port;
Server.EndPoint.Address = IPAddress.Any;
Server.RequestReceived += (s, e) =>
{
using (var writer = new StreamWriter(e.Response.OutputStream)) {
writer.Write ("Nom, delicious shop access code! Test suite will now continue.");
}
// when we get our first request, have the TCS become ready
tcs.SetResult (e.Request.Params ["code"]);
// server.Dispose();
};
Server.Start ();
return tcs.Task;
}
[TestFixtureSetUp]
public void BeforeFixture ()
{
try {
// because it's so expensive on requests, get our authorization key once for the entire integration test suite
// this Task will become ready once Shopify redirects our browser back to us with the test shop's consent (in the form of the access token)
var redirectReplyPromise = ListenForIncomingShopTokenFromRedirect (5409);
Console.WriteLine ("Attempting to authorize against store " + TestStoreName);
var sa = new Sharpify.ShopifyAPIAuthorizer (TestStoreName, ConfigurationManager.AppSettings ["Shopify.TestAppKey"], ConfigurationManager.AppSettings ["Shopify.TestAppSecret"]);
var authUrl = sa.GetAuthorizationURL (new string[] { "write_content", "write_themes", "write_products", "write_customers", "write_script_tags", "write_orders" }, ConfigurationManager.AppSettings ["Shopify.TestHttpServerUri"]);
Console.WriteLine (authUrl);
// pop a web browser with the authorization UI:
Process.Start (authUrl);
Console.WriteLine ("Waiting for Shopify to answer...");
redirectReplyPromise.Wait ();
var shopCode = redirectReplyPromise.Result;
Assert.NotNull (shopCode);
Console.WriteLine ("Got code: " + shopCode);
var authTask = sa.AuthorizeClient (shopCode);
authTask.Wait ();
// acquire our authorization token for actual API requests
AuthorizationState = authTask.Result;
ShopifyClient = new ShopifyAPIContext (AuthorizationState, new JsonDataTranslator ());
} catch (Exception e) {
using (var fd = new StreamWriter("sharpify_test_before_fixture_error.txt")) {
fd.Write (e.ToString ());
}
throw new Exception ("Rethrowing exception emitted during BeforeFixture()", e);
}
}
[TestFixtureTearDown]
public void AfterFixture ()
{
Server.Dispose ();
}
[Test]
public void ShouldAuthorizeAgainstANewShop ()
{
Assert.AreEqual (TestStoreName, AuthorizationState.ShopName);
Assert.NotNull (AuthorizationState.AccessToken);
}
[Test]
public void ShouldFetchAllProducts ()
{
var productsTask = ShopifyClient.Get ("/admin/products");
productsTask.Wait();
dynamic products = productsTask.Result;
// validate that we're actually getting a list back, even though we can't check
// deeper because we don't strictly know the content of the test store
Assert.AreEqual (typeof(Newtonsoft.Json.Linq.JArray), products.products.GetType ());
Assert.Greater(products.products.Count, 2);
// informative for the log:
foreach (var product in products.products) {
Console.WriteLine ("GOT PRODUCT: " + product.title);
}
}
[Test]
public void ShouldFetchAllArticles() {
var articlesTask = ShopifyClient.Get("/admin/articles.json");
articlesTask.Wait();
}
[Test]
public void ShouldThrowErrorWhenFetchingNonexistentResource ()
{
var getTask = ShopifyClient.Get ("/admin/products/doesnotexist");
var notFound = false;
try {
getTask.Wait ();
} catch (AggregateException ae) {
ae.Handle((e) => {
if(e is NotFoundException) {
notFound = true;
return true;
}
return false;
});
}
Assert.IsTrue(notFound);
}
[Test]
public void ShouldCreateAndFetchBackAProduct ()
{
var postTask = ShopifyClient.Post ("/admin/products", new {
product = new {
title = "Rearden Metal",
body_html = "Resistant to corrosion and evasion of reality",
product_type = "metal"
}
});
postTask.Wait();
dynamic postResult = postTask.Result;
String newId = postResult.product.id;
Assert.NotNull (newId);
// and fetch it back
var getTask = ShopifyClient.Get (String.Format("/admin/products/{0}", newId));
getTask.Wait ();
Assert.NotNull(getTask.Result);
dynamic getResult = getTask.Result;
Assert.AreEqual("Rearden Metal", (string)getResult.product.title);
// and with the typesafe api:
var getTypeTask = ShopifyClient.GetResource<Product>().Find(Int32.Parse(newId));
getTypeTask.Wait();
Assert.AreEqual("Rearden Metal", getTypeTask.Result.Title);
}
[Test]
public void ShouldThrowErrorWhenPostingInvalidResource ()
{
var postTask = ShopifyClient.Post ("/admin/products", new {
product = new {
title = "Invalid"
}
});
var gotError = false;
try {
postTask.Wait ();
} catch (AggregateException ae) {
ae.Handle ((e) => {
if(e is InvalidContentException) {
gotError = true;
return true;
}
return false;
});
}
Assert.IsTrue(gotError);
}
[Test]
public void ShopifyShouldReturnInlinedSubResourceAsSeparate()
{
// try to get either /orders/:id/line_items
// or /orders/:id/fulfillments
// or /orders/:id/fulfillments/:id/line_items
// this is to confirm if inlines are guaranteed fetchable as subresources intead.
// NO THEY ARE NOT
//var getTask = ShopifyClient.Get("/admin/orders/147593684/line_items.json", null);
var query = new NameValueCollection();
query.Add("page", "2");
var getTask = ShopifyClient.Get("/admin/products", query);
getTask.Wait();
Console.WriteLine("done");
}
[Test]
public void ShouldHandleBeingAskedForPageByWhere() {
var query = new NameValueCollection();
query.Add("page", "2");
var getTask = ShopifyClient.GetResource<Product>().Where("page", "2").AsList();
getTask.Wait();
Assert.NotNull(getTask.Result);
}
[Test]
public void ShouldFetchAllOrders() {
var answer = ShopifyClient.GetResource<Order>().AsList();
answer.Wait();
Console.WriteLine("dsafdasf");
}
[Test]
public void ShouldFetchAllTopLevelResources()
{
// all it will really do it flush out some obvious crashes lurking
// in fetching and translating the toplevel resources.
// still, a handy thing to have to validate the behaviour of Sharpify
// against whatever your current store contents are, and thus
// worth keeping around in this harness even if it horribly breaks
// testing methodology.
var productsCount = ShopifyClient.GetResource<Product>().Count();
productsCount.Wait();
ShopifyClient.GetResource<Asset>().AsList().Wait();
ShopifyClient.GetResource<ApplicationCharge>().AsList().Wait();
ShopifyClient.GetResource<Article>().AsList().Wait();
ShopifyClient.GetResource<Blog>().AsList().Wait();
ShopifyClient.GetResource<Checkout>().AsList().Wait();
ShopifyClient.GetResource<Collect>().AsList().Wait();
ShopifyClient.GetResource<CustomCollection>().AsList().Wait();
ShopifyClient.GetResource<Comment>().AsList().Wait();
ShopifyClient.GetResource<Country>().AsList().Wait();
ShopifyClient.GetResource<Customer>().AsList().Wait();
ShopifyClient.GetResource<CustomerGroup>().AsList().Wait();
ShopifyClient.GetResource<Event>().AsList().Wait();
ShopifyClient.GetResource<Order>().AsList().Wait();
ShopifyClient.GetResource<Page>().AsList().Wait();
ShopifyClient.GetResource<Product>().AsList().Wait();
ShopifyClient.GetResource<ProductSearchEngine>().AsList().Wait();
ShopifyClient.GetResource<RecurringApplicationCharge>().AsList().Wait();
ShopifyClient.GetResource<Redirect>().AsList().Wait();
ShopifyClient.GetResource<ScriptTag>().AsList().Wait();
ShopifyClient.GetResource<SmartCollection>().AsList().Wait();
ShopifyClient.GetResource<Theme>().AsList().Wait();
ShopifyClient.GetResource<Webhook>().AsList().Wait();
}
}
}
| |
namespace AngleSharp.Core.Tests.Html
{
using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using NUnit.Framework;
using System;
/// <summary>
/// Tests generated according to the W3C-Test.org page:
/// http://www.w3c-test.org/html/semantics/forms/constraints/form-validation-validity-tooLong.html
/// </summary>
[TestFixture]
public class ValidityTooLongTests
{
static IDocument Html(String code)
{
return code.ToHtmlDocument();
}
[Test]
public void TestToolongInputText1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "");
element.Value = "abc";
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputText2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "";
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputText3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputText4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputText5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputText6()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputText7()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "AAA";
element.IsDirty = true;
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputText8()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputText9()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual("text", element.Type);
Assert.AreEqual(true, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputSearch1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "");
element.Value = "abc";
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputSearch2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "";
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputSearch3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputSearch4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputSearch5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputSearch6()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputSearch7()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "AAA";
element.IsDirty = true;
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputSearch8()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputSearch9()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual("search", element.Type);
Assert.AreEqual(true, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputTel1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "");
element.Value = "abc";
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputTel2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "";
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputTel3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputTel4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputTel5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputTel6()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputTel7()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "AAA";
element.IsDirty = true;
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputTel8()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputTel9()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(true, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputUrl1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "");
element.Value = "abc";
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputUrl2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "";
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputUrl3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputUrl4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputUrl5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputUrl6()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputUrl7()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "AAA";
element.IsDirty = true;
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputUrl8()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputUrl9()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual("url", element.Type);
Assert.AreEqual(true, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputEmail1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "");
element.Value = "abc";
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputEmail2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "";
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputEmail3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputEmail4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputEmail5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputEmail6()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputEmail7()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "AAA";
element.IsDirty = true;
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputEmail8()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputEmail9()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual("email", element.Type);
Assert.AreEqual(true, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputPassword1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "");
element.Value = "abc";
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputPassword2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "";
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputPassword3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputPassword4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputPassword5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputPassword6()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputPassword7()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "AAA";
element.IsDirty = true;
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputPassword8()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongInputPassword9()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual("password", element.Type);
Assert.AreEqual(true, element.Validity.IsTooLong);
}
[Test]
public void TestToolongTextarea1()
{
var document = Html("");
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "");
element.Value = "abc";
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongTextarea2()
{
var document = Html("");
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "";
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongTextarea3()
{
var document = Html("");
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongTextarea4()
{
var document = Html("");
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongTextarea5()
{
var document = Html("");
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongTextarea6()
{
var document = Html("");
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abc";
element.IsDirty = true;
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongTextarea7()
{
var document = Html("");
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "\r\n";
element.IsDirty = true;
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongTextarea8()
{
var document = Html("");
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcd";
element.IsDirty = true;
Assert.AreEqual(false, element.Validity.IsTooLong);
}
[Test]
public void TestToolongTextarea9()
{
var document = Html("");
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
element.IsDirty = true;
Assert.AreEqual(true, element.Validity.IsTooLong);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace BookFast.Proxy
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.Rest;
using Models;
/// <summary>
/// </summary>
public partial interface IBookFastAPI : IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Subscription credentials which uniquely identify client
/// subscription.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// List accommodations by facility
/// </summary>
/// <param name='facilityId'>
/// Facility ID
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<AccommodationRepresentation>>> ListAccommodationsWithHttpMessagesAsync(Guid facilityId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create new accommodation
/// </summary>
/// <param name='facilityId'>
/// Facility ID
/// </param>
/// <param name='accommodationData'>
/// Accommodation details
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<AccommodationRepresentation>> CreateAccommodationWithHttpMessagesAsync(Guid facilityId, AccommodationData accommodationData = default(AccommodationData), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Find accommodation by ID
/// </summary>
/// <param name='id'>
/// Accommodation ID
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<AccommodationRepresentation>> FindAccommodationWithHttpMessagesAsync(Guid id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update accommodation
/// </summary>
/// <param name='id'>
/// Accommodation ID
/// </param>
/// <param name='accommodationData'>
/// Accommodation details
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<AccommodationRepresentation>> UpdateAccommodationWithHttpMessagesAsync(Guid id, AccommodationData accommodationData = default(AccommodationData), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete accommodation
/// </summary>
/// <param name='id'>
/// Accommodation ID
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeleteAccommodationWithHttpMessagesAsync(Guid id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List bookings by customer
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<BookingRepresentation>>> ListBookingsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Find booking by ID
/// </summary>
/// <param name='id'>
/// Booking ID
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<BookingRepresentation>> FindBookingWithHttpMessagesAsync(Guid id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Cancel booking
/// </summary>
/// <param name='id'>
/// Booking ID
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeleteBookingWithHttpMessagesAsync(Guid id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Book an accommodation
/// </summary>
/// <param name='accommodationId'>
/// Accommodation ID
/// </param>
/// <param name='bookingData'>
/// Booking details
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<BookingRepresentation>> CreateBookingWithHttpMessagesAsync(Guid accommodationId, BookingData bookingData = default(BookingData), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List facilities by owner
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<FacilityRepresentation>>> ListFacilitiesWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create new facility
/// </summary>
/// <param name='facilityData'>
/// Facility details
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<FacilityRepresentation>> CreateFacilityWithHttpMessagesAsync(FacilityData facilityData = default(FacilityData), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Find facility by ID
/// </summary>
/// <param name='id'>
/// Facility ID
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<FacilityRepresentation>> FindFacilityWithHttpMessagesAsync(Guid id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update facility
/// </summary>
/// <param name='id'>
/// Facility ID
/// </param>
/// <param name='facilityData'>
/// Facility details
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<FacilityRepresentation>> UpdateFacilityWithHttpMessagesAsync(Guid id, FacilityData facilityData = default(FacilityData), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete facility
/// </summary>
/// <param name='id'>
/// Facility ID
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeleteFacilityWithHttpMessagesAsync(Guid id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a write access token for a new facility image
/// </summary>
/// <param name='id'>
/// Facility ID
/// </param>
/// <param name='originalFileName'>
/// Image file name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<FileAccessTokenRepresentation>> GetFacilityImageUploadTokenWithHttpMessagesAsync(Guid id, string originalFileName = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a write access token for a new accommodation image
/// </summary>
/// <param name='id'>
/// Accommodation ID
/// </param>
/// <param name='originalFileName'>
/// Image file name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<FileAccessTokenRepresentation>> GetAccommodationImageUploadTokenWithHttpMessagesAsync(Guid id, string originalFileName = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Search for accommodations
/// </summary>
/// <param name='searchText'>
/// Search terms
/// </param>
/// <param name='page'>
/// Page number
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<SearchResult>>> SearchWithHttpMessagesAsync(string searchText = default(string), int? page = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// 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.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Roslyn.Utilities;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.CodeAnalysis.CommandLine;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// This class defines all of the common stuff that is shared between the Vbc and Csc tasks.
/// This class is not instantiatable as a Task just by itself.
/// </summary>
public abstract class ManagedCompiler : ToolTask
{
private CancellationTokenSource _sharedCompileCts;
internal readonly PropertyDictionary _store = new PropertyDictionary();
public ManagedCompiler()
{
TaskResources = ErrorString.ResourceManager;
}
#region Properties
// Please keep these alphabetized.
public string[] AdditionalLibPaths
{
set { _store[nameof(AdditionalLibPaths)] = value; }
get { return (string[])_store[nameof(AdditionalLibPaths)]; }
}
public string[] AddModules
{
set { _store[nameof(AddModules)] = value; }
get { return (string[])_store[nameof(AddModules)]; }
}
public ITaskItem[] AdditionalFiles
{
set { _store[nameof(AdditionalFiles)] = value; }
get { return (ITaskItem[])_store[nameof(AdditionalFiles)]; }
}
public ITaskItem[] EmbeddedFiles
{
set { _store[nameof(EmbeddedFiles)] = value; }
get { return (ITaskItem[])_store[nameof(EmbeddedFiles)]; }
}
public ITaskItem[] Analyzers
{
set { _store[nameof(Analyzers)] = value; }
get { return (ITaskItem[])_store[nameof(Analyzers)]; }
}
// We do not support BugReport because it always requires user interaction,
// which will cause a hang.
public string ChecksumAlgorithm
{
set { _store[nameof(ChecksumAlgorithm)] = value; }
get { return (string)_store[nameof(ChecksumAlgorithm)]; }
}
public string CodeAnalysisRuleSet
{
set { _store[nameof(CodeAnalysisRuleSet)] = value; }
get { return (string)_store[nameof(CodeAnalysisRuleSet)]; }
}
public int CodePage
{
set { _store[nameof(CodePage)] = value; }
get { return _store.GetOrDefault(nameof(CodePage), 0); }
}
[Output]
public ITaskItem[] CommandLineArgs
{
set { _store[nameof(CommandLineArgs)] = value; }
get { return (ITaskItem[])_store[nameof(CommandLineArgs)]; }
}
public string DebugType
{
set { _store[nameof(DebugType)] = value; }
get { return (string)_store[nameof(DebugType)]; }
}
public string SourceLink
{
set { _store[nameof(SourceLink)] = value; }
get { return (string)_store[nameof(SourceLink)]; }
}
public string DefineConstants
{
set { _store[nameof(DefineConstants)] = value; }
get { return (string)_store[nameof(DefineConstants)]; }
}
public bool DelaySign
{
set { _store[nameof(DelaySign)] = value; }
get { return _store.GetOrDefault(nameof(DelaySign), false); }
}
public bool Deterministic
{
set { _store[nameof(Deterministic)] = value; }
get { return _store.GetOrDefault(nameof(Deterministic), false); }
}
public bool PublicSign
{
set { _store[nameof(PublicSign)] = value; }
get { return _store.GetOrDefault(nameof(PublicSign), false); }
}
public bool EmitDebugInformation
{
set { _store[nameof(EmitDebugInformation)] = value; }
get { return _store.GetOrDefault(nameof(EmitDebugInformation), false); }
}
public string ErrorLog
{
set { _store[nameof(ErrorLog)] = value; }
get { return (string)_store[nameof(ErrorLog)]; }
}
public string Features
{
set { _store[nameof(Features)] = value; }
get { return (string)_store[nameof(Features)]; }
}
public int FileAlignment
{
set { _store[nameof(FileAlignment)] = value; }
get { return _store.GetOrDefault(nameof(FileAlignment), 0); }
}
public bool HighEntropyVA
{
set { _store[nameof(HighEntropyVA)] = value; }
get { return _store.GetOrDefault(nameof(HighEntropyVA), false); }
}
/// <summary>
/// Specifies the list of instrumentation kinds to be used during compilation.
/// </summary>
public string Instrument
{
set { _store[nameof(Instrument)] = value; }
get { return (string)_store[nameof(Instrument)]; }
}
public string KeyContainer
{
set { _store[nameof(KeyContainer)] = value; }
get { return (string)_store[nameof(KeyContainer)]; }
}
public string KeyFile
{
set { _store[nameof(KeyFile)] = value; }
get { return (string)_store[nameof(KeyFile)]; }
}
public ITaskItem[] LinkResources
{
set { _store[nameof(LinkResources)] = value; }
get { return (ITaskItem[])_store[nameof(LinkResources)]; }
}
public string MainEntryPoint
{
set { _store[nameof(MainEntryPoint)] = value; }
get { return (string)_store[nameof(MainEntryPoint)]; }
}
public bool NoConfig
{
set { _store[nameof(NoConfig)] = value; }
get { return _store.GetOrDefault(nameof(NoConfig), false); }
}
public bool NoLogo
{
set { _store[nameof(NoLogo)] = value; }
get { return _store.GetOrDefault(nameof(NoLogo), false); }
}
public bool NoWin32Manifest
{
set { _store[nameof(NoWin32Manifest)] = value; }
get { return _store.GetOrDefault(nameof(NoWin32Manifest), false); }
}
public bool Optimize
{
set { _store[nameof(Optimize)] = value; }
get { return _store.GetOrDefault(nameof(Optimize), false); }
}
[Output]
public ITaskItem OutputAssembly
{
set { _store[nameof(OutputAssembly)] = value; }
get { return (ITaskItem)_store[nameof(OutputAssembly)]; }
}
public string Platform
{
set { _store[nameof(Platform)] = value; }
get { return (string)_store[nameof(Platform)]; }
}
public bool Prefer32Bit
{
set { _store[nameof(Prefer32Bit)] = value; }
get { return _store.GetOrDefault(nameof(Prefer32Bit), false); }
}
public bool ProvideCommandLineArgs
{
set { _store[nameof(ProvideCommandLineArgs)] = value; }
get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); }
}
public ITaskItem[] References
{
set { _store[nameof(References)] = value; }
get { return (ITaskItem[])_store[nameof(References)]; }
}
public bool ReportAnalyzer
{
set { _store[nameof(ReportAnalyzer)] = value; }
get { return _store.GetOrDefault(nameof(ReportAnalyzer), false); }
}
public ITaskItem[] Resources
{
set { _store[nameof(Resources)] = value; }
get { return (ITaskItem[])_store[nameof(Resources)]; }
}
public string RuntimeMetadataVersion
{
set { _store[nameof(RuntimeMetadataVersion)] = value; }
get { return (string)_store[nameof(RuntimeMetadataVersion)]; }
}
public ITaskItem[] ResponseFiles
{
set { _store[nameof(ResponseFiles)] = value; }
get { return (ITaskItem[])_store[nameof(ResponseFiles)]; }
}
public bool SkipCompilerExecution
{
set { _store[nameof(SkipCompilerExecution)] = value; }
get { return _store.GetOrDefault(nameof(SkipCompilerExecution), false); }
}
public ITaskItem[] Sources
{
set
{
if (UsedCommandLineTool)
{
NormalizePaths(value);
}
_store[nameof(Sources)] = value;
}
get { return (ITaskItem[])_store[nameof(Sources)]; }
}
public string SubsystemVersion
{
set { _store[nameof(SubsystemVersion)] = value; }
get { return (string)_store[nameof(SubsystemVersion)]; }
}
public string TargetType
{
set { _store[nameof(TargetType)] = CultureInfo.InvariantCulture.TextInfo.ToLower(value); }
get { return (string)_store[nameof(TargetType)]; }
}
public bool TreatWarningsAsErrors
{
set { _store[nameof(TreatWarningsAsErrors)] = value; }
get { return _store.GetOrDefault(nameof(TreatWarningsAsErrors), false); }
}
public bool Utf8Output
{
set { _store[nameof(Utf8Output)] = value; }
get { return _store.GetOrDefault(nameof(Utf8Output), false); }
}
public string Win32Icon
{
set { _store[nameof(Win32Icon)] = value; }
get { return (string)_store[nameof(Win32Icon)]; }
}
public string Win32Manifest
{
set { _store[nameof(Win32Manifest)] = value; }
get { return (string)_store[nameof(Win32Manifest)]; }
}
public string Win32Resource
{
set { _store[nameof(Win32Resource)] = value; }
get { return (string)_store[nameof(Win32Resource)]; }
}
public string PathMap
{
set { _store[nameof(PathMap)] = value; }
get { return (string)_store[nameof(PathMap)]; }
}
/// <summary>
/// If this property is true then the task will take every C# or VB
/// compilation which is queued by MSBuild and send it to the
/// VBCSCompiler server instance, starting a new instance if necessary.
/// If false, we will use the values from ToolPath/Exe.
/// </summary>
public bool UseSharedCompilation
{
set { _store[nameof(UseSharedCompilation)] = value; }
get { return _store.GetOrDefault(nameof(UseSharedCompilation), false); }
}
// Map explicit platform of "AnyCPU" or the default platform (null or ""), since it is commonly understood in the
// managed build process to be equivalent to "AnyCPU", to platform "AnyCPU32BitPreferred" if the Prefer32Bit
// property is set.
internal string PlatformWith32BitPreference
{
get
{
string platform = Platform;
if ((string.IsNullOrEmpty(platform) || platform.Equals("anycpu", StringComparison.OrdinalIgnoreCase)) && Prefer32Bit)
{
platform = "anycpu32bitpreferred";
}
return platform;
}
}
/// <summary>
/// Overridable property specifying the encoding of the captured task standard output stream
/// </summary>
protected override Encoding StandardOutputEncoding
{
get
{
return (Utf8Output) ? Encoding.UTF8 : base.StandardOutputEncoding;
}
}
#endregion
internal abstract RequestLanguage Language { get; }
protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
{
if (ProvideCommandLineArgs)
{
CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands)
.Select(arg => new TaskItem(arg)).ToArray();
}
if (SkipCompilerExecution)
{
return 0;
}
if (!UseSharedCompilation ||
!string.IsNullOrEmpty(ToolPath) ||
!Utilities.IsCompilerServerSupported)
{
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
using (_sharedCompileCts = new CancellationTokenSource())
{
try
{
CompilerServerLogger.Log($"CommandLine = '{commandLineCommands}'");
CompilerServerLogger.Log($"BuildResponseFile = '{responseFileCommands}'");
// Try to get the location of the user-provided build client and server,
// which should be located next to the build task. If not, fall back to
// "pathToTool", which is the compiler in the MSBuild default bin directory.
var clientDir = TryGetClientDir() ?? Path.GetDirectoryName(pathToTool);
pathToTool = Path.Combine(clientDir, ToolExe);
// Note: we can't change the "tool path" printed to the console when we run
// the Csc/Vbc task since MSBuild logs it for us before we get here. Instead,
// we'll just print our own message that contains the real client location
Log.LogMessage(ErrorString.UsingSharedCompilation, clientDir);
var buildPaths = new BuildPaths(
clientDir: clientDir,
// MSBuild doesn't need the .NET SDK directory
sdkDir: null,
workingDir: CurrentDirectoryToUse());
var responseTask = DesktopBuildClient.RunServerCompilation(
Language,
GetArguments(commandLineCommands, responseFileCommands).ToList(),
buildPaths,
keepAlive: null,
libEnvVariable: LibDirectoryToUse(),
cancellationToken: _sharedCompileCts.Token);
responseTask.Wait(_sharedCompileCts.Token);
var response = responseTask.Result;
if (response != null)
{
ExitCode = HandleResponse(response, pathToTool, responseFileCommands, commandLineCommands);
}
else
{
Log.LogMessage(ErrorString.SharedCompilationFallback, pathToTool);
ExitCode = base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
}
catch (OperationCanceledException)
{
ExitCode = 0;
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("Compiler_UnexpectedException");
LogErrorOutput(e.ToString());
ExitCode = -1;
}
}
return ExitCode;
}
/// <summary>
/// Try to get the directory this assembly is in. Returns null if assembly
/// was in the GAC or DLL location can not be retrieved.
/// </summary>
private static string TryGetClientDir()
{
var buildTask = typeof(ManagedCompiler).GetTypeInfo().Assembly;
var inGac = (bool?)typeof(Assembly)
.GetTypeInfo()
.GetDeclaredProperty("GlobalAssemblyCache")
?.GetMethod.Invoke(buildTask, parameters: null);
if (inGac != false)
return null;
var codeBase = (string)typeof(Assembly)
.GetTypeInfo()
.GetDeclaredProperty("CodeBase")
?.GetMethod.Invoke(buildTask, parameters: null);
if (codeBase == null) return null;
var uri = new Uri(codeBase);
string assemblyPath;
if (uri.IsFile)
{
assemblyPath = uri.LocalPath;
}
else
{
var callingAssembly = (Assembly)typeof(Assembly)
.GetTypeInfo()
.GetDeclaredMethod("GetCallingAssembly")
?.Invoke(null, null);
var location = (string)typeof(Assembly)
.GetTypeInfo()
.GetDeclaredProperty("Location")
?.GetMethod.Invoke(callingAssembly, parameters: null);
if (location == null) return null;
assemblyPath = location;
}
return Path.GetDirectoryName(assemblyPath);
}
/// <summary>
/// Cancel the in-process build task.
/// </summary>
public override void Cancel()
{
base.Cancel();
_sharedCompileCts?.Cancel();
}
/// <summary>
/// Get the current directory that the compiler should run in.
/// </summary>
private string CurrentDirectoryToUse()
{
// ToolTask has a method for this. But it may return null. Use the process directory
// if ToolTask didn't override. MSBuild uses the process directory.
string workingDirectory = GetWorkingDirectory();
if (string.IsNullOrEmpty(workingDirectory))
workingDirectory = Directory.GetCurrentDirectory();
return workingDirectory;
}
/// <summary>
/// Get the "LIB" environment variable, or NULL if none.
/// </summary>
private string LibDirectoryToUse()
{
// First check the real environment.
string libDirectory = Environment.GetEnvironmentVariable("LIB");
// Now go through additional environment variables.
string[] additionalVariables = EnvironmentVariables;
if (additionalVariables != null)
{
foreach (string var in EnvironmentVariables)
{
if (var.StartsWith("LIB=", StringComparison.OrdinalIgnoreCase))
{
libDirectory = var.Substring(4);
}
}
}
return libDirectory;
}
/// <summary>
/// The return code of the compilation. Strangely, this isn't overridable from ToolTask, so we need
/// to create our own.
/// </summary>
[Output]
public new int ExitCode { get; private set; }
/// <summary>
/// Handle a response from the server, reporting messages and returning
/// the appropriate exit code.
/// </summary>
private int HandleResponse(BuildResponse response, string pathToTool, string responseFileCommands, string commandLineCommands)
{
switch (response.Type)
{
case BuildResponse.ResponseType.MismatchedVersion:
LogErrorOutput(CommandLineParser.MismatchedVersionErrorText);
return -1;
case BuildResponse.ResponseType.Completed:
var completedResponse = (CompletedBuildResponse)response;
LogMessages(completedResponse.Output, StandardOutputImportanceToUse);
if (LogStandardErrorAsError)
{
LogErrorOutput(completedResponse.ErrorOutput);
}
else
{
LogMessages(completedResponse.ErrorOutput, StandardErrorImportanceToUse);
}
return completedResponse.ReturnCode;
case BuildResponse.ResponseType.Rejected:
case BuildResponse.ResponseType.AnalyzerInconsistency:
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
default:
throw new InvalidOperationException("Encountered unknown response type");
}
}
private void LogErrorOutput(string output)
{
string[] lines = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string trimmedMessage = line.Trim();
if (trimmedMessage != "")
{
Log.LogError(trimmedMessage);
}
}
}
/// <summary>
/// Log each of the messages in the given output with the given importance.
/// We assume each line is a message to log.
/// </summary>
/// <remarks>
/// Should be "private protected" visibility once it is introduced into C#.
/// </remarks>
internal abstract void LogMessages(string output, MessageImportance messageImportance);
public string GenerateResponseFileContents()
{
return GenerateResponseFileCommands();
}
/// <summary>
/// Get the command line arguments to pass to the compiler.
/// </summary>
private string[] GetArguments(string commandLineCommands, string responseFileCommands)
{
var commandLineArguments =
CommandLineParser.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true);
var responseFileArguments =
CommandLineParser.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true);
return commandLineArguments.Concat(responseFileArguments).ToArray();
}
/// <summary>
/// Returns the command line switch used by the tool executable to specify the response file
/// Will only be called if the task returned a non empty string from GetResponseFileCommands
/// Called after ValidateParameters, SkipTaskExecution and GetResponseFileCommands
/// </summary>
protected override string GenerateResponseFileCommands()
{
CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
AddResponseFileCommands(commandLineBuilder);
return commandLineBuilder.ToString();
}
protected override string GenerateCommandLineCommands()
{
CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
AddCommandLineCommands(commandLineBuilder);
return commandLineBuilder.ToString();
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and
/// must go directly onto the command line.
/// </summary>
protected internal virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendWhenTrue("/noconfig", _store, nameof(NoConfig));
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
/// </summary>
protected internal virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
// If outputAssembly is not specified, then an "/out: <name>" option won't be added to
// overwrite the one resulting from the OutputAssembly member of the CompilerParameters class.
// In that case, we should set the outputAssembly member based on the first source file.
if (
(OutputAssembly == null) &&
(Sources != null) &&
(Sources.Length > 0) &&
(ResponseFiles == null) // The response file may already have a /out: switch in it, so don't try to be smart here.
)
{
try
{
OutputAssembly = new TaskItem(Path.GetFileNameWithoutExtension(Sources[0].ItemSpec));
}
catch (ArgumentException e)
{
throw new ArgumentException(e.Message, "Sources");
}
if (string.Compare(TargetType, "library", StringComparison.OrdinalIgnoreCase) == 0)
{
OutputAssembly.ItemSpec += ".dll";
}
else if (string.Compare(TargetType, "module", StringComparison.OrdinalIgnoreCase) == 0)
{
OutputAssembly.ItemSpec += ".netmodule";
}
else
{
OutputAssembly.ItemSpec += ".exe";
}
}
commandLine.AppendSwitchIfNotNull("/addmodule:", AddModules, ",");
commandLine.AppendSwitchWithInteger("/codepage:", _store, nameof(CodePage));
ConfigureDebugProperties();
// The "DebugType" parameter should be processed after the "EmitDebugInformation" parameter
// because it's more specific. Order matters on the command-line, and the last one wins.
// /debug+ is just a shorthand for /debug:full. And /debug- is just a shorthand for /debug:none.
commandLine.AppendPlusOrMinusSwitch("/debug", _store, nameof(EmitDebugInformation));
commandLine.AppendSwitchIfNotNull("/debug:", DebugType);
commandLine.AppendPlusOrMinusSwitch("/delaysign", _store, nameof(DelaySign));
commandLine.AppendSwitchWithInteger("/filealign:", _store, nameof(FileAlignment));
commandLine.AppendSwitchIfNotNull("/keycontainer:", KeyContainer);
commandLine.AppendSwitchIfNotNull("/keyfile:", KeyFile);
// If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
commandLine.AppendSwitchIfNotNull("/linkresource:", LinkResources, new string[] { "LogicalName", "Access" });
commandLine.AppendWhenTrue("/nologo", _store, nameof(NoLogo));
commandLine.AppendWhenTrue("/nowin32manifest", _store, nameof(NoWin32Manifest));
commandLine.AppendPlusOrMinusSwitch("/optimize", _store, nameof(Optimize));
commandLine.AppendSwitchIfNotNull("/pathmap:", PathMap);
commandLine.AppendSwitchIfNotNull("/out:", OutputAssembly);
commandLine.AppendSwitchIfNotNull("/ruleset:", CodeAnalysisRuleSet);
commandLine.AppendSwitchIfNotNull("/errorlog:", ErrorLog);
commandLine.AppendSwitchIfNotNull("/subsystemversion:", SubsystemVersion);
commandLine.AppendWhenTrue("/reportanalyzer", _store, nameof(ReportAnalyzer));
// If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
commandLine.AppendSwitchIfNotNull("/resource:", Resources, new string[] { "LogicalName", "Access" });
commandLine.AppendSwitchIfNotNull("/target:", TargetType);
commandLine.AppendPlusOrMinusSwitch("/warnaserror", _store, nameof(TreatWarningsAsErrors));
commandLine.AppendWhenTrue("/utf8output", _store, nameof(Utf8Output));
commandLine.AppendSwitchIfNotNull("/win32icon:", Win32Icon);
commandLine.AppendSwitchIfNotNull("/win32manifest:", Win32Manifest);
AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(commandLine);
AddAnalyzersToCommandLine(commandLine, Analyzers);
AddAdditionalFilesToCommandLine(commandLine);
// Append the sources.
commandLine.AppendFileNamesIfNotNull(Sources, " ");
}
internal void AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(CommandLineBuilderExtension commandLine)
{
commandLine.AppendPlusOrMinusSwitch("/deterministic", _store, nameof(Deterministic));
commandLine.AppendPlusOrMinusSwitch("/publicsign", _store, nameof(PublicSign));
commandLine.AppendSwitchIfNotNull("/runtimemetadataversion:", RuntimeMetadataVersion);
commandLine.AppendSwitchIfNotNull("/checksumalgorithm:", ChecksumAlgorithm);
commandLine.AppendSwitchWithSplitting("/instrument:", Instrument, ",", ';', ',');
commandLine.AppendSwitchIfNotNull("/sourcelink:", SourceLink);
AddFeatures(commandLine, Features);
AddEmbeddedFilesToCommandLine(commandLine);
}
/// <summary>
/// Adds a "/features:" switch to the command line for each provided feature.
/// </summary>
internal static void AddFeatures(CommandLineBuilderExtension commandLine, string features)
{
if (string.IsNullOrEmpty(features))
{
return;
}
foreach (var feature in CompilerOptionParseUtilities.ParseFeatureFromMSBuild(features))
{
commandLine.AppendSwitchIfNotNull("/features:", feature.Trim());
}
}
/// <summary>
/// Adds a "/analyzer:" switch to the command line for each provided analyzer.
/// </summary>
internal static void AddAnalyzersToCommandLine(CommandLineBuilderExtension commandLine, ITaskItem[] analyzers)
{
// If there were no analyzers passed in, don't add any /analyzer: switches
// on the command-line.
if (analyzers == null)
{
return;
}
foreach (ITaskItem analyzer in analyzers)
{
commandLine.AppendSwitchIfNotNull("/analyzer:", analyzer.ItemSpec);
}
}
/// <summary>
/// Adds a "/additionalfile:" switch to the command line for each additional file.
/// </summary>
private void AddAdditionalFilesToCommandLine(CommandLineBuilderExtension commandLine)
{
if (AdditionalFiles != null)
{
foreach (ITaskItem additionalFile in AdditionalFiles)
{
commandLine.AppendSwitchIfNotNull("/additionalfile:", additionalFile.ItemSpec);
}
}
}
/// <summary>
/// Adds a "/embed:" switch to the command line for each pdb embedded file.
/// </summary>
private void AddEmbeddedFilesToCommandLine(CommandLineBuilderExtension commandLine)
{
if (EmbeddedFiles != null)
{
foreach (ITaskItem embeddedFile in EmbeddedFiles)
{
commandLine.AppendSwitchIfNotNull("/embed:", embeddedFile.ItemSpec);
}
}
}
/// <summary>
/// Configure the debug switches which will be placed on the compiler command-line.
/// The matrix of debug type and symbol inputs and the desired results is as follows:
///
/// Debug Symbols DebugType Desired Results
/// True Full /debug+ /debug:full
/// True PdbOnly /debug+ /debug:PdbOnly
/// True None /debug-
/// True Blank /debug+
/// False Full /debug- /debug:full
/// False PdbOnly /debug- /debug:PdbOnly
/// False None /debug-
/// False Blank /debug-
/// Blank Full /debug:full
/// Blank PdbOnly /debug:PdbOnly
/// Blank None /debug-
/// Debug: Blank Blank /debug+ //Microsoft.common.targets will set this
/// Release: Blank Blank "Nothing for either switch"
///
/// The logic is as follows:
/// If debugtype is none set debugtype to empty and debugSymbols to false
/// If debugType is blank use the debugsymbols "as is"
/// If debug type is set, use its value and the debugsymbols value "as is"
/// </summary>
private void ConfigureDebugProperties()
{
// If debug type is set we need to take some action depending on the value. If debugtype is not set
// We don't need to modify the EmitDebugInformation switch as its value will be used as is.
if (_store[nameof(DebugType)] != null)
{
// If debugtype is none then only show debug- else use the debug type and the debugsymbols as is.
if (string.Compare((string)_store[nameof(DebugType)], "none", StringComparison.OrdinalIgnoreCase) == 0)
{
_store[nameof(DebugType)] = null;
_store[nameof(EmitDebugInformation)] = false;
}
}
}
/// <summary>
/// Validate parameters, log errors and warnings and return true if
/// Execute should proceed.
/// </summary>
protected override bool ValidateParameters()
{
return ListHasNoDuplicateItems(Resources, nameof(Resources), "LogicalName", Log) && ListHasNoDuplicateItems(Sources, nameof(Sources), Log);
}
/// <summary>
/// Returns true if the provided item list contains duplicate items, false otherwise.
/// </summary>
internal static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, TaskLoggingHelper log)
{
return ListHasNoDuplicateItems(itemList, parameterName, null, log);
}
/// <summary>
/// Returns true if the provided item list contains duplicate items, false otherwise.
/// </summary>
/// <param name="itemList"></param>
/// <param name="disambiguatingMetadataName">Optional name of metadata that may legitimately disambiguate items. May be null.</param>
/// <param name="parameterName"></param>
/// <param name="log"></param>
private static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, string disambiguatingMetadataName, TaskLoggingHelper log)
{
if (itemList == null || itemList.Length == 0)
{
return true;
}
var alreadySeen = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (ITaskItem item in itemList)
{
string key;
string disambiguatingMetadataValue = null;
if (disambiguatingMetadataName != null)
{
disambiguatingMetadataValue = item.GetMetadata(disambiguatingMetadataName);
}
if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue))
{
key = item.ItemSpec;
}
else
{
key = item.ItemSpec + ":" + disambiguatingMetadataValue;
}
if (alreadySeen.ContainsKey(key))
{
if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue))
{
log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupported", item.ItemSpec, parameterName);
}
else
{
log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupportedWithMetadata", item.ItemSpec, parameterName, disambiguatingMetadataValue, disambiguatingMetadataName);
}
return false;
}
else
{
alreadySeen[key] = string.Empty;
}
}
return true;
}
/// <summary>
/// Allows tool to handle the return code.
/// This method will only be called with non-zero exitCode.
/// </summary>
protected override bool HandleTaskExecutionErrors()
{
// For managed compilers, the compiler should emit the appropriate
// error messages before returning a non-zero exit code, so we don't
// normally need to emit any additional messages now.
//
// If somehow the compiler DID return a non-zero exit code and didn't log an error, we'd like to log that exit code.
// We can only do this for the command line compiler: if the inproc compiler was used,
// we can't tell what if anything it logged as it logs directly to Visual Studio's output window.
//
if (!Log.HasLoggedErrors && UsedCommandLineTool)
{
// This will log a message "MSB3093: The command exited with code {0}."
base.HandleTaskExecutionErrors();
}
return false;
}
/// <summary>
/// Takes a list of files and returns the normalized locations of these files
/// </summary>
private void NormalizePaths(ITaskItem[] taskItems)
{
foreach (var item in taskItems)
{
item.ItemSpec = Utilities.GetFullPathNoThrow(item.ItemSpec);
}
}
/// <summary>
/// Whether the command line compiler was invoked, instead
/// of the host object compiler.
/// </summary>
protected bool UsedCommandLineTool
{
get;
set;
}
private bool _hostCompilerSupportsAllParameters;
protected bool HostCompilerSupportsAllParameters
{
get { return _hostCompilerSupportsAllParameters; }
set { _hostCompilerSupportsAllParameters = value; }
}
/// <summary>
/// Checks the bool result from calling one of the methods on the host compiler object to
/// set one of the parameters. If it returned false, that means the host object doesn't
/// support a particular parameter or variation on a parameter. So we log a comment,
/// and set our state so we know not to call the host object to do the actual compilation.
/// </summary>
/// <owner>RGoel</owner>
protected void CheckHostObjectSupport
(
string parameterName,
bool resultFromHostObjectSetOperation
)
{
if (!resultFromHostObjectSetOperation)
{
Log.LogMessageFromResources(MessageImportance.Normal, "General_ParameterUnsupportedOnHostCompiler", parameterName);
_hostCompilerSupportsAllParameters = false;
}
}
internal void InitializeHostObjectSupportForNewSwitches(ITaskHost hostObject, ref string param)
{
var compilerOptionsHostObject = hostObject as ICompilerOptionsHostObject;
if (compilerOptionsHostObject != null)
{
var commandLineBuilder = new CommandLineBuilderExtension();
AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(commandLineBuilder);
param = "CompilerOptions";
CheckHostObjectSupport(param, compilerOptionsHostObject.SetCompilerOptions(commandLineBuilder.ToString()));
}
}
/// <summary>
/// Checks to see whether all of the passed-in references exist on disk before we launch the compiler.
/// </summary>
/// <owner>RGoel</owner>
protected bool CheckAllReferencesExistOnDisk()
{
if (null == References)
{
// No references
return true;
}
bool success = true;
foreach (ITaskItem reference in References)
{
if (!File.Exists(reference.ItemSpec))
{
success = false;
Log.LogErrorWithCodeFromResources("General_ReferenceDoesNotExist", reference.ItemSpec);
}
}
return success;
}
/// <summary>
/// The IDE and command line compilers unfortunately differ in how win32
/// manifests are specified. In particular, the command line compiler offers a
/// "/nowin32manifest" switch, while the IDE compiler does not offer analogous
/// functionality. If this switch is omitted from the command line and no win32
/// manifest is specified, the compiler will include a default win32 manifest
/// named "default.win32manifest" found in the same directory as the compiler
/// executable. Again, the IDE compiler does not offer analogous support.
///
/// We'd like to imitate the command line compiler's behavior in the IDE, but
/// it isn't aware of the default file, so we must compute the path to it if
/// noDefaultWin32Manifest is false and no win32Manifest was provided by the
/// project.
///
/// This method will only be called during the initialization of the host object,
/// which is only used during IDE builds.
/// </summary>
/// <returns>the path to the win32 manifest to provide to the host object</returns>
internal string GetWin32ManifestSwitch
(
bool noDefaultWin32Manifest,
string win32Manifest
)
{
if (!noDefaultWin32Manifest)
{
if (string.IsNullOrEmpty(win32Manifest) && string.IsNullOrEmpty(Win32Resource))
{
// We only want to consider the default.win32manifest if this is an executable
if (!string.Equals(TargetType, "library", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(TargetType, "module", StringComparison.OrdinalIgnoreCase))
{
// We need to compute the path to the default win32 manifest
string pathToDefaultManifest = ToolLocationHelper.GetPathToDotNetFrameworkFile
(
"default.win32manifest",
// We are choosing to pass Version46 instead of VersionLatest. TargetDotNetFrameworkVersion
// is an enum, and VersionLatest is not some sentinel value but rather a constant that is
// equal to the highest version defined in the enum. Enum values, being constants, are baked
// into consuming assembly, so specifying VersionLatest means not the latest version wherever
// this code is running, but rather the latest version of the framework according to the
// reference assembly with which this assembly was built. As of this writing, we are building
// our bits on machines with Visual Studio 2015 that know about 4.6.1, so specifying
// VersionLatest would bake in the enum value for 4.6.1. But we need to run on machines with
// MSBuild that only know about Version46 (and no higher), so VersionLatest will fail there.
// Explicitly passing Version46 prevents this problem.
TargetDotNetFrameworkVersion.Version46
);
if (null == pathToDefaultManifest)
{
// This is rather unlikely, and the inproc compiler seems to log an error anyway.
// So just a message is fine.
Log.LogMessageFromResources
(
"General_ExpectedFileMissing",
"default.win32manifest"
);
}
return pathToDefaultManifest;
}
}
}
return win32Manifest;
}
}
}
| |
using UnityEngine;
using System;
using Cinemachine.Utility;
namespace Cinemachine
{
/// <summary>Defines a group of target objects, each with a radius and a weight.
/// The weight is used when calculating the average position of the target group.
/// Higher-weighted members of the group will count more.
/// The bounding box is calculated by taking the member positions, weight,
/// and radii into account.
/// </summary>
[DocumentationSorting(19, DocumentationSortingAttribute.Level.UserRef)]
[AddComponentMenu("Cinemachine/CinemachineTargetGroup")]
[SaveDuringPlay]
[ExecuteInEditMode]
public class CinemachineTargetGroup : MonoBehaviour
{
/// <summary>Holds the information that represents a member of the group</summary>
[DocumentationSorting(19.1f, DocumentationSortingAttribute.Level.UserRef)]
[Serializable] public struct Target
{
/// <summary>The target objects. This object's position and orientation will contribute to the
/// group's average position and orientation, in accordance with its weight</summary>
[Tooltip("The target objects. This object's position and orientation will contribute to the group's average position and orientation, in accordance with its weight")]
public Transform target;
/// <summary>How much weight to give the target when averaging. Cannot be negative</summary>
[Tooltip("How much weight to give the target when averaging. Cannot be negative")]
public float weight;
/// <summary>The radius of the target, used for calculating the bounding box. Cannot be negative</summary>
[Tooltip("The radius of the target, used for calculating the bounding box. Cannot be negative")]
public float radius;
}
/// <summary>How the group's position is calculated</summary>
[DocumentationSorting(19.2f, DocumentationSortingAttribute.Level.UserRef)]
public enum PositionMode
{
///<summary>Group position will be the center of the group's axis-aligned bounding box</summary>
GroupCenter,
/// <summary>Group position will be the weighted average of the positions of the members</summary>
GroupAverage
}
/// <summary>How the group's position is calculated</summary>
[Tooltip("How the group's position is calculated. Select GroupCenter for the center of the bounding box, and GroupAverage for a weighted average of the positions of the members.")]
public PositionMode m_PositionMode = PositionMode.GroupCenter;
/// <summary>How the group's orientation is calculated</summary>
[DocumentationSorting(19.3f, DocumentationSortingAttribute.Level.UserRef)]
public enum RotationMode
{
/// <summary>Manually set in the group's transform</summary>
Manual,
/// <summary>Weighted average of the orientation of its members.</summary>
GroupAverage
}
/// <summary>How the group's orientation is calculated</summary>
[Tooltip("How the group's rotation is calculated. Select Manual to use the value in the group's transform, and GroupAverage for a weighted average of the orientations of the members.")]
public RotationMode m_RotationMode = RotationMode.Manual;
/// <summary>This enum defines the options available for the update method.</summary>
public enum UpdateMethod
{
/// <summary>Updated in normal MonoBehaviour Update.</summary>
Update,
/// <summary>Updated in sync with the Physics module, in FixedUpdate</summary>
FixedUpdate,
/// <summary>Updated in MonoBehaviour LateUpdate.</summary>
LateUpdate
};
/// <summary>When to update the group's transform based on the position of the group members</summary>
[Tooltip("When to update the group's transform based on the position of the group members")]
public UpdateMethod m_UpdateMethod = UpdateMethod.LateUpdate;
/// <summary>The target objects, together with their weights and radii, that will
/// contribute to the group's average position, orientation, and size</summary>
[NoSaveDuringPlay]
[Tooltip("The target objects, together with their weights and radii, that will contribute to the group's average position, orientation, and size.")]
public Target[] m_Targets = new Target[0];
/// Cache of the last valid radius
private float m_lastRadius = 0;
/// <summary>The axis-aligned bounding box of the group, computed using the
/// targets positions and radii</summary>
public Bounds BoundingBox
{
get
{
float averageWeight;
Vector3 center = CalculateAveragePosition(out averageWeight);
bool gotOne = false;
Bounds b = new Bounds(center, new Vector3(m_lastRadius*2, m_lastRadius*2, m_lastRadius*2));
if (averageWeight > UnityVectorExtensions.Epsilon)
{
for (int i = 0; i < m_Targets.Length; ++i)
{
if (m_Targets[i].target != null)
{
float w = m_Targets[i].weight;
if (w < averageWeight - UnityVectorExtensions.Epsilon)
w = w / averageWeight;
else
w = 1;
float d = m_Targets[i].radius * 2 * w;
Vector3 p = Vector3.Lerp(center, m_Targets[i].target.position, w);
Bounds b2 = new Bounds(p, new Vector3(d, d, d));
if (!gotOne)
b = b2;
else
b.Encapsulate(b2);
gotOne = true;
}
}
}
Vector3 r = b.extents;
m_lastRadius = Mathf.Max(r.x, Mathf.Max(r.y, r.z));
return b;
}
}
/// <summary>Return true if there are no members with weight > 0</summary>
public bool IsEmpty
{
get
{
for (int i = 0; i < m_Targets.Length; ++i)
if (m_Targets[i].target != null && m_Targets[i].weight > UnityVectorExtensions.Epsilon)
return false;
return true;
}
}
/// <summary>The axis-aligned bounding box of the group, in a specific reference frame</summary>
/// <param name="mView">The frame of reference in which to compute the bounding box</param>
/// <returns>The axis-aligned bounding box of the group, in the desired frame of reference</returns>
public Bounds GetViewSpaceBoundingBox(Matrix4x4 mView)
{
Matrix4x4 inverseView = mView.inverse;
float averageWeight;
Vector3 center = inverseView.MultiplyPoint3x4(CalculateAveragePosition(out averageWeight));
bool gotOne = false;
Bounds b = new Bounds(center, new Vector3(m_lastRadius*2, m_lastRadius*2, m_lastRadius*2));
if (averageWeight > UnityVectorExtensions.Epsilon)
{
for (int i = 0; i < m_Targets.Length; ++i)
{
if (m_Targets[i].target != null)
{
float w = m_Targets[i].weight;
if (w < averageWeight - UnityVectorExtensions.Epsilon)
w = w / averageWeight;
else
w = 1;
float d = m_Targets[i].radius * 2;
Vector4 p = inverseView.MultiplyPoint3x4(m_Targets[i].target.position);
p = Vector3.Lerp(center, p, w);
Bounds b2 = new Bounds(p, new Vector3(d, d, d));
if (!gotOne)
b = b2;
else
b.Encapsulate(b2);
gotOne = true;
}
}
}
Vector3 r = b.extents;
m_lastRadius = Mathf.Max(r.x, Mathf.Max(r.y, r.z));
return b;
}
Vector3 CalculateAveragePosition(out float averageWeight)
{
Vector3 pos = Vector3.zero;
float weight = 0;
int numTargets = 0;
for (int i = 0; i < m_Targets.Length; ++i)
{
if (m_Targets[i].target != null && m_Targets[i].weight > UnityVectorExtensions.Epsilon)
{
++numTargets;
weight += m_Targets[i].weight;
pos += m_Targets[i].target.position * m_Targets[i].weight;
}
}
if (weight > UnityVectorExtensions.Epsilon)
pos /= weight;
if (numTargets == 0)
{
averageWeight = 0;
return transform.position;
}
averageWeight = weight / numTargets;
return pos;
}
Quaternion CalculateAverageOrientation()
{
Quaternion r = Quaternion.identity;
for (int i = 0; i < m_Targets.Length; ++i)
{
if (m_Targets[i].target != null)
{
float w = m_Targets[i].weight;
Quaternion q = m_Targets[i].target.rotation;
// This is probably bogus
r = new Quaternion(r.x + q.x * w, r.y + q.y * w, r.z + q.z * w, r.w + q.w * w);
}
}
return r.Normalized();
}
private void OnValidate()
{
for (int i = 0; i < m_Targets.Length; ++i)
{
if (m_Targets[i].weight < 0)
m_Targets[i].weight = 0;
if (m_Targets[i].radius < 0)
m_Targets[i].radius = 0;
}
}
void FixedUpdate()
{
if (m_UpdateMethod == UpdateMethod.FixedUpdate)
UpdateTransform();
}
void Update()
{
if (!Application.isPlaying || m_UpdateMethod == UpdateMethod.Update)
UpdateTransform();
}
void LateUpdate()
{
if (m_UpdateMethod == UpdateMethod.LateUpdate)
UpdateTransform();
}
void UpdateTransform()
{
if (IsEmpty)
return;
switch (m_PositionMode)
{
case PositionMode.GroupCenter:
transform.position = BoundingBox.center;
break;
case PositionMode.GroupAverage:
float averageWeight;
transform.position = CalculateAveragePosition(out averageWeight);
break;
}
switch (m_RotationMode)
{
case RotationMode.Manual:
break;
case RotationMode.GroupAverage:
transform.rotation = CalculateAverageOrientation();
break;
}
}
}
}
| |
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.Helpers;
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>
///
/// </summary>
[History("Jes1111", "2003/03/04", "Cache flushing now handled by inherited page")]
public partial class ArticlesEdit : AddEditItemPage
{
/// <summary>
/// Html Text editor for the control
/// </summary>
protected IHtmlEditor DesktopText;
/// <summary>
/// Html Text editor for the control abstract
/// </summary>
protected IHtmlEditor AbstractText;
/// <summary>
/// The Page_Load event on this Page is used to obtain the ModuleID
/// and ItemID of the Article to edit.
/// It then uses the Rainbow.ArticlesDB() data component
/// to populate the page's edit controls with the Article 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)
{
// Add the setting
HtmlEditorDataType editor = new HtmlEditorDataType();
editor.Value = moduleSettings["Editor"].ToString();
DesktopText =
editor.GetEditor(PlaceHolderHTMLEditor, ModuleID, bool.Parse(moduleSettings["ShowUpload"].ToString()),
portalSettings);
DesktopText.Width = new Unit(moduleSettings["Width"].ToString());
DesktopText.Height = new Unit(moduleSettings["Height"].ToString());
HtmlEditorDataType abstractEditor = new HtmlEditorDataType();
if (moduleSettings["ARTICLES_RICHABSTRACT"] != null &&
bool.Parse(moduleSettings["ARTICLES_RICHABSTRACT"].ToString()))
{
abstractEditor.Value = moduleSettings["Editor"].ToString();
AbstractText =
abstractEditor.GetEditor(PlaceHolderAbstractHTMLEditor, ModuleID,
bool.Parse(moduleSettings["ShowUpload"].ToString()), portalSettings);
}
else
{
abstractEditor.Value = "Plain Text";
AbstractText =
abstractEditor.GetEditor(PlaceHolderAbstractHTMLEditor, ModuleID,
bool.Parse(moduleSettings["ShowUpload"].ToString()), portalSettings);
}
AbstractText.Width = new Unit(moduleSettings["Width"].ToString());
AbstractText.Height = new Unit("130px");
// Construct the page
// Added css Styles by Mario Endara <[email protected]> (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 the page is being requested the first time, determine if an
// Article itemID value is specified, and if so populate page
// contents with the Article details
if (Page.IsPostBack == false)
{
if (ItemID != 0)
{
// Obtain a single row of Article information
ArticlesDB Articles = new ArticlesDB();
SqlDataReader dr = Articles.GetSingleArticle(ItemID, WorkFlowVersion.Staging);
try
{
// Load first row into Datareader
if (dr.Read())
{
StartField.Text = ((DateTime) dr["StartDate"]).ToShortDateString();
ExpireField.Text = ((DateTime) dr["ExpireDate"]).ToShortDateString();
TitleField.Text = (string) dr["Title"].ToString();
SubtitleField.Text = (string) dr["Subtitle"].ToString();
AbstractText.Text = (string) dr["Abstract"].ToString();
DesktopText.Text = Server.HtmlDecode(dr["Description"].ToString());
CreatedBy.Text = (string) dr["CreatedByUser"].ToString();
CreatedDate.Text = ((DateTime) dr["CreatedDate"]).ToString();
// 15/7/2004 added localization by Mario Endara [email protected]
if (CreatedBy.Text == "unknown")
{
CreatedBy.Text = General.GetString("UNKNOWN", "unknown");
}
}
}
finally
{
dr.Close();
}
}
else
{
//New article - set defaults
StartField.Text = DateTime.Now.ToShortDateString();
ExpireField.Text =
DateTime.Now.AddDays(int.Parse(moduleSettings["DefaultVisibleDays"].ToString())).
ToShortDateString();
CreatedBy.Text = PortalSettings.CurrentUser.Identity.Email;
CreatedDate.Text = DateTime.Now.ToString();
}
}
}
/// <summary>
/// Set the module guids with free access to this page
/// </summary>
protected override ArrayList AllowedModules
{
get
{
ArrayList al = new ArrayList();
al.Add("87303CF7-76D0-49B1-A7E7-A5C8E26415BA"); //Articles
al.Add("5B7B52D3-837C-4942-A85C-AAF4B5CC098F"); //ArticlesInline
return al;
}
}
/// <summary>
/// Is used to either create or update an Article.
/// It uses the Rainbow.ArticlesDB()
/// data component to encapsulate all data functionality.
/// </summary>
protected override void OnUpdate(EventArgs e)
{
base.OnUpdate(e);
// Only Update if Input Data is Valid
if (Page.IsValid == true)
{
ArticlesDB Articles = new ArticlesDB();
if (AbstractText.Text == string.Empty)
{
AbstractText.Text = ((HTMLText) DesktopText.Text).GetAbstractText(500);
}
if (ItemID == 0)
{
Articles.AddArticle(ModuleID, PortalSettings.CurrentUser.Identity.Email,
((HTMLText) TitleField.Text).InnerText,
((HTMLText) SubtitleField.Text).InnerText, AbstractText.Text,
Server.HtmlEncode(DesktopText.Text), DateTime.Parse(StartField.Text),
DateTime.Parse(ExpireField.Text), true, string.Empty);
}
else
{
Articles.UpdateArticle(ModuleID, ItemID, PortalSettings.CurrentUser.Identity.Email,
((HTMLText) TitleField.Text).InnerText,
((HTMLText) SubtitleField.Text).InnerText, AbstractText.Text,
Server.HtmlEncode(DesktopText.Text), DateTime.Parse(StartField.Text),
DateTime.Parse(ExpireField.Text), true, string.Empty);
}
RedirectBackToReferringPage();
}
}
/// <summary>
/// The DeleteBtn_Click event handler on this Page is used to delete an
/// a Article. It uses the Rainbow.ArticlesDB()
/// data component to encapsulate all data functionality.
/// </summary>
/// <param name="e"></param>
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)
{
ArticlesDB Articles = new ArticlesDB();
Articles.DeleteArticle(ItemID);
}
RedirectBackToReferringPage();
}
#region Web Form Designer generated code
/// <summary>
/// On Init
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
this.Load += new EventHandler(this.Page_Load);
//Controls must be created here
updateButton = new LinkButton();
cancelButton = new LinkButton();
deleteButton = new LinkButton();
updateButton.Click += new EventHandler(updateButton_Click);
deleteButton.Click += new EventHandler(deleteButton_Click);
InitializeComponent();
base.OnInit(e);
}
void deleteButton_Click(object sender, EventArgs e)
{
OnDelete(e);
}
void updateButton_Click(object sender, EventArgs e)
{
OnUpdate(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace MysteryRiddles.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.BinaryAuthorization.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedSystemPolicyV1ClientTest
{
[xunit::FactAttribute]
public void GetSystemPolicyRequestObject()
{
moq::Mock<SystemPolicyV1.SystemPolicyV1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1.SystemPolicyV1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SystemPolicyV1Client client = new SystemPolicyV1ClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetSystemPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSystemPolicyRequestObjectAsync()
{
moq::Mock<SystemPolicyV1.SystemPolicyV1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1.SystemPolicyV1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SystemPolicyV1Client client = new SystemPolicyV1ClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetSystemPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetSystemPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSystemPolicy()
{
moq::Mock<SystemPolicyV1.SystemPolicyV1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1.SystemPolicyV1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SystemPolicyV1Client client = new SystemPolicyV1ClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetSystemPolicy(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSystemPolicyAsync()
{
moq::Mock<SystemPolicyV1.SystemPolicyV1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1.SystemPolicyV1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SystemPolicyV1Client client = new SystemPolicyV1ClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetSystemPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetSystemPolicyAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSystemPolicyResourceNames()
{
moq::Mock<SystemPolicyV1.SystemPolicyV1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1.SystemPolicyV1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SystemPolicyV1Client client = new SystemPolicyV1ClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetSystemPolicy(request.PolicyName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSystemPolicyResourceNamesAsync()
{
moq::Mock<SystemPolicyV1.SystemPolicyV1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1.SystemPolicyV1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SystemPolicyV1Client client = new SystemPolicyV1ClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetSystemPolicyAsync(request.PolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetSystemPolicyAsync(request.PolicyName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
#region License
/*
Copyright (c) 2010-2014 Danko Kozar
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 License
using System;
using eDriven.Core.Events;
using eDriven.Core.Managers;
using UnityEngine;
using Event=eDriven.Core.Events.Event;
using MulticastDelegate=eDriven.Core.Events.MulticastDelegate;
namespace eDriven.Core.Util
{
/// <summary>
/// Timer class
/// </summary>
/// <remarks>Coded by Danko Kozar</remarks>
public class Timer : EventDispatcher
{
#if DEBUG
public new static bool DebugMode;
#endif
#region Events
// ReSharper disable InconsistentNaming
public const string START = "start";
public const string PAUSE = "pause";
public const string STOP = "stop";
public const string RESET = "reset";
public const string TICK = "tick";
public const string COMPLETE = "complete";
// ReSharper restore InconsistentNaming
private MulticastDelegate _startHandler;
/// <summary>
/// The handler which fires when the timer is started
/// </summary>
public MulticastDelegate StartHandler
{
get
{
if (null == _startHandler)
_startHandler = new MulticastDelegate(this, START);
return _startHandler;
}
set
{
_startHandler = value;
}
}
private MulticastDelegate _stopHandler;
/// <summary>
/// The handler which fires when the timer is stopped
/// </summary>
public MulticastDelegate StopHandler
{
get
{
if (null == _stopHandler)
_stopHandler = new MulticastDelegate(this, STOP);
return _stopHandler;
}
set
{
_stopHandler = value;
}
}
private MulticastDelegate _resetHandler;
/// <summary>
/// The handler which fires when the timer has been reset
/// </summary>
public MulticastDelegate ResetHandler
{
get
{
if (null == _resetHandler)
_resetHandler = new MulticastDelegate(this, RESET);
return _resetHandler;
}
set
{
_resetHandler = value;
}
}
private MulticastDelegate _tickHandler;
/// <summary>
/// The handler which fires on each timer tick
/// </summary>
public MulticastDelegate Tick
{
get
{
if (null == _tickHandler)
_tickHandler = new MulticastDelegate(this, TICK);
return _tickHandler;
}
set
{
_tickHandler = value;
}
}
private MulticastDelegate _completeHandler;
/// <summary>
/// The handler which fires when the timer is complete (on the last tick)
/// </summary>
public MulticastDelegate Complete
{
get
{
if (null == _completeHandler)
_completeHandler = new MulticastDelegate(this, COMPLETE);
return _completeHandler;
}
set
{
_completeHandler = value;
}
}
#endregion
#region Properties
/// <summary>
/// Should the timer tick on start, or after the first delay
/// </summary>
public bool TickOnStart;
private float _delay = 1f;
/// <summary>
/// Delay time in seconds
/// (seconds because Unity deals with seconds rather than milliseconds)
/// </summary>
public float Delay
{
get
{
return _delay;
}
set
{
if (value != _delay)
{
if (_delay <= 0)
throw new TimerException(TimerException.DelayError);
_delay = value;
// if messing with delay, we should reset the timer!!! :)
// if not, strange effects happen (in calculating tick in the OnUpdate method, line "if (_time > _delay * _count) // step ")
Reset();
}
}
}
private float _repeatCount;
/// <summary>
/// Tick in seconds
/// </summary>
public float RepeatCount
{
get
{
return _repeatCount;
}
set
{
if (value != _repeatCount)
{
if (_repeatCount < 0)
throw new TimerException(TimerException.DelayError);
_repeatCount = value;
}
CheckRepeatCount();
}
}
private DateTime _lastTickTime;
/// <summary>
/// The time the timer had the last tick
/// </summary>
public DateTime LastTickTime
{
get
{
return _lastTickTime;
}
}
/// <summary>
/// The flag indicating if the timer is running
/// </summary>
public bool IsRunning { get; private set; }
#endregion
#region Members
private float _time;
private int _count;
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public Timer()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="delay"></param>
public Timer(float delay) : this()
{
_delay = delay;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="delay"></param>
/// <param name="repeatCount"></param>
public Timer(float delay, int repeatCount) : this(delay)
{
_repeatCount = repeatCount;
}
#endregion
#region IDisposable
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public override void Dispose()
{
base.Dispose();
SystemManager.Instance.UpdateSignal.Disconnect(UpdateSlot);
}
#endregion
#region Methods
/// <summary>
/// Starts the timer
/// </summary>
public void Start()
{
Start(false);
}
/// <summary>
/// Starts the timer
/// </summary>
/// <param name="reset">Should the time be reset</param>
public void Start(bool reset)
{
if (!IsRunning)
SystemManager.Instance.UpdateSignal.Connect(UpdateSlot); //, 0, false); // Subscribe to update signal
IsRunning = true;
if (reset)
Reset();
// dispatch start event
if (HasEventListener(START))
DispatchEvent(new Event(START));
// if tick on start, dispatch tick event
if (TickOnStart && !_paused)
DoTick();
_paused = false;
}
private bool _paused;
/// <summary>
/// Stops the timer
/// </summary>
public void Pause()
{
// Unsubscribe from update signal
SystemManager.Instance.UpdateSignal.Disconnect(UpdateSlot);
IsRunning = false;
_paused = true;
// dispatch stop event
if (HasEventListener(PAUSE))
DispatchEvent(new Event(PAUSE));
}
/// <summary>
/// Stops the timer
/// </summary>
public void Stop()
{
// Unsubscribe from update signal
SystemManager.Instance.UpdateSignal.Disconnect(UpdateSlot);
IsRunning = false;
Reset();
// dispatch stop event
if (HasEventListener(STOP))
DispatchEvent(new Event(STOP));
}
/// <summary>
/// Resets time and the tick count
/// </summary>
public void Reset()
{
//Active = false;
/**
* Unsubscribe from SystemManager Update
* */
_time = 0;
_count = 0;
if (HasEventListener(RESET))
DispatchEvent(new Event(RESET));
}
/// <summary>
/// Resets time, but not the tick count
/// </summary>
public void Defer()
{
_time = 0;
}
#endregion
#region Private methods
private void DoTick()
{
_lastTickTime = DateTime.Now;
if (HasEventListener(TICK))
DispatchEvent(new Event(TICK));
}
private void CheckRepeatCount()
{
if (_repeatCount > 0 && _count >= _repeatCount){
Stop();
if (HasEventListener(COMPLETE))
DispatchEvent(new Event(COMPLETE));
}
}
#endregion
#region Implementation of ISlot
/// <summary>
/// The slot which is being executed on each update
/// </summary>
/// <param name="parameters"></param>
public void UpdateSlot(params object[] parameters)
{
_time += Time.deltaTime;
// the logic: maintain delay * count greater than time
if (_time > _delay * (_count + 1)) // step
{
_count++;
#if DEBUG
if (DebugMode)
Debug.Log("Timer tick.");
#endif
DoTick();
CheckRepeatCount();
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Collections;
namespace l2pvp
{
public partial class BotView : Form
{
public List<uint> newplayers;
public List<uint> deletedplayer;
public List<uint> players;
public object listlock;
public GameServer gs;
public BotView(GameServer _gs)
{
gs = _gs;
newplayers = new List<uint>();
deletedplayer = new List<uint>();
players = new List<uint>();
listlock = new Object();
InitializeComponent();
}
public delegate void addClient(UserControl cv);
public void d_addClient(UserControl cv)
{
if (InvokeRequired)
{
Invoke(new addClient(f_addClient), new object[] { cv });
}
else
f_addClient(cv);
}
public void d_removeClient(UserControl cv)
{
if (InvokeRequired)
{
Invoke(new addClient(f_removeClient), new object[] { cv });
}
else
f_removeClient(cv);
}
protected void f_addClient(UserControl cv)
{
panel.SuspendLayout();
panel.Controls.Add(cv);
panel.ResumeLayout();
}
protected void f_removeClient(UserControl cv)
{
panel.SuspendLayout();
panel.Controls.Remove(cv);
panel.ResumeLayout();
panel.Update();
}
private void timer1_Tick(object sender, EventArgs e)
{
lock (listlock)
{
foreach (uint i in newplayers)
{
if (!players.Contains(i))
players.Add(i);
}
foreach (uint i in deletedplayer)
{
if (players.Contains(i))
players.Remove(i);
}
newplayers.Clear();
deletedplayer.Clear();
}
foreach (Client c in gs.clist)
{
if (c.pinfo != null)
{
c.cv.lb_name.Text = c.pinfo.Name;
if (c == gs.leader)
c.cv.lb_name.ForeColor = Color.Red;
else
c.cv.lb_name.ForeColor = Color.Black;
c.cv.lb_HPMAX.Text = c.pinfo.Max_HP.ToString();
c.cv.lb_HP.Text = c.pinfo.Cur_HP.ToString();
c.cv.lb_CPMAX.Text = c.pinfo.Max_CP.ToString();
c.cv.lb_CP.Text = c.pinfo.Cur_CP.ToString();
}
}
if (gs.target != null)
{
lb_targetname.Text = gs.target.Name;
targethp.Text = gs.target.Cur_HP.ToString();
targetmaxhp.Text = gs.target.Max_HP.ToString();
}
else
{
lb_targetname.Text = "None";
targethp.Text = "0";
targetmaxhp.Text = "0";
}
}
private void checkBox22_CheckedChanged(object sender, EventArgs e)
{
if (checkBox22.Checked)
{
//unchecking it
gs.distanceupdates = false;
}
else
gs.distanceupdates = true;
}
private void timer2_Tick(object sender, EventArgs e)
{
listView1.SuspendLayout();
listView1.Items.Clear();
foreach (uint i in players)
{
if (gs.allplayerinfo.ContainsKey(i))
{
CharInfo cinfo = gs.allplayerinfo[i];
string distance = Convert.ToString(Convert.ToUInt32(cinfo.distance));
ListViewItem item = new ListViewItem(distance);
item.Tag = cinfo;
item.SubItems.Add(cinfo.Name);
if (gs.clanlist.ContainsKey(cinfo.ClanID))
item.SubItems.Add(gs.clanlist[cinfo.ClanID].name);
else
item.SubItems.Add(String.Empty);
item.SubItems.Add(cinfo.ID.ToString());
if (gs.enemylist.ContainsKey(cinfo.ID) || gs.attacklist.ContainsKey(cinfo.ID))
item.Checked = true;
listView1.Items.Add(item);
}
}
foreach (Clans cl in gs.clanlist.Values)
{
if (!checkedListBox1.Items.Contains(cl))
{
checkedListBox1.Items.Add(cl);
}
}
// listView1.Sort();
listView1.ResumeLayout();
listView1.Update();
}
private void button1_Click(object sender, EventArgs e)
{
gs.battack = true;
if (gs.targetselection.ThreadState != ThreadState.Running && gs.targetselection.ThreadState != ThreadState.WaitSleepJoin)
gs.targetselection.Start();
}
private void button2_Click(object sender, EventArgs e)
{
gs.battack = false;
}
//private void checkBox23_CheckedChanged(object sender, EventArgs e)
//{
// if (checkBox23.Checked)
// gs.autofollow = true;
// else
// gs.autofollow = false;
//}
private void BotView_Load(object sender, EventArgs e)
{
gs.ghphp = Convert.ToUInt32(textBox13.Text);
gs.cpelixir = Convert.ToUInt32(textBox14.Text);
gs.hpelixir = Convert.ToUInt32(textBox12.Text);
}
private void textBox13_TextChanged(object sender, EventArgs e)
{
gs.ghphp = Convert.ToUInt32(textBox13.Text);
}
private void textBox14_TextChanged(object sender, EventArgs e)
{
gs.cpelixir = Convert.ToUInt32(textBox14.Text);
}
private void textBox12_TextChanged(object sender, EventArgs e)
{
gs.hpelixir = Convert.ToUInt32(textBox12.Text);
}
private void BotView_FormClosed(object sender, FormClosedEventArgs e)
{
Environment.Exit(0);
}
private void button3_Click(object sender, EventArgs e)
{
string fname = textBox15.Text;
StreamWriter writefile = new StreamWriter(new FileStream(fname, FileMode.Create), Encoding.UTF8);
//file format
/*number of enemy clans
* [name of clans - 1 per line]
* name 1
* [on buff line]
* [after buff line]
* name 2
* ...
*
*/
writefile.WriteLine("{0}", gs.enemyclans.Count);
foreach (Clans c in gs.enemyclans.Values)
{
writefile.WriteLine("{0}", c.name);
}
writefile.Flush();
writefile.Close();
}
private void button4_Click(object sender, EventArgs e)
{
string fname = textBox15.Text;
StreamReader readfile;
try
{
readfile = new StreamReader(new FileStream(fname, FileMode.Open), Encoding.UTF8);
if (readfile == null)
return;
}
catch
{
MessageBox.Show("Couldn't find file");
return;
}
string line;
line = readfile.ReadLine();
uint clancount = Convert.ToUInt32(line);
for (int i = 0; i < clancount; i++)
{
line = readfile.ReadLine();
gs.enemynames.Add(line);
}
foreach (string s in gs.enemynames)
{
if (s == "Purgatory")
continue;
foreach (Clans c in gs.clanlist.Values)
{
if (s == c.name)
{
if (!gs.enemyclans.ContainsKey(c.id))
{
gs.enemyclans.Add(c.id, c);
int index = checkedListBox1.Items.IndexOf(c);
if (index != -1)
{
checkedListBox1.SetItemChecked(index, true);
}
int allplayercount = gs.allplayerinfo.Count;
foreach (uint j in gs.allplayerinfo.Keys)
{
if (gs.allplayerinfo[j].ClanID == c.id)
{
//enemy player!
if (!gs.enemylist.ContainsKey(gs.allplayerinfo[j].ID)
&& !gs.attacklist.ContainsKey(gs.allplayerinfo[j].ID))
gs.enemylist.Add(gs.allplayerinfo[j].ID, gs.allplayerinfo[j]);
}
}
}
break;
}
}
}
}
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.CurrentValue == CheckState.Unchecked)
{
Clans c = (Clans)checkedListBox1.Items[e.Index];
string clanname = c.name;
if (clanname == "Purgatory")
{
MessageBox.Show("Purgatory is your friend!");
e.NewValue = CheckState.Unchecked;
return;
}
int clancount = gs.clanlist.Count;
if (!gs.enemyclans.ContainsKey(c.id))
{
gs.enemyclans.Add(c.id, c);
int allplayercount = gs.allplayerinfo.Count;
foreach (CharInfo j in gs.allplayerinfo.Values)
{
if (j.ClanID == c.id)
{
//enemy player!
if (!gs.enemylist.ContainsKey(j.ID))
{
gs.enemylist.Add(j.ID, j);
}
}
}
}
}
else if (e.CurrentValue == CheckState.Checked)
{
Clans c = (Clans)checkedListBox1.Items[e.Index];
foreach (CharInfo j in gs.allplayerinfo.Values)
{
if (j.ClanID == c.id)
{
//enemy player not //fix
if (gs.enemylist.ContainsKey(j.ID))
gs.enemylist.Remove(j.ID);
if (gs.attacklist.ContainsKey(j.ID))
gs.attacklist.Remove(j.ID);
}
}
gs.enemyclans.Remove(c.id);
}
}
private void listView1_ItemCheck(object sender, ItemCheckEventArgs e)
{
listView1.SuspendLayout();
uint objectid = Convert.ToUInt32(listView1.Items[e.Index].SubItems[3].Text);
if (e.CurrentValue == CheckState.Unchecked)
{
if (gs.allplayerinfo.ContainsKey(objectid) && !gs.enemylist.ContainsKey(objectid)
&& !gs.attacklist.ContainsKey(objectid))
{
//in the list
//check if this is a purg member
//if (gs.allplayerinfo[objectid].ClanID == gs.PurgId)
//{
// MessageBox.Show("Purgatory is your friend!");
// e.NewValue = CheckState.Unchecked;
//}
//else if (gs.allplayerinfo[objectid].ClanID == gs.LPid)
//{
// MessageBox.Show("Is your friend!");
// e.NewValue = CheckState.Unchecked;
//}
//else if (gs.allplayerinfo[objectid].ClanID == gs.MimrId)
//{
// MessageBox.Show("Is your friend!");
// e.NewValue = CheckState.Unchecked;
//}
//else
{
gs.enemylist.Add(objectid, gs.allplayerinfo[objectid]);
e.NewValue = CheckState.Checked;
}
}
}
if (e.CurrentValue == CheckState.Checked)
{
if (gs.enemylist.ContainsKey(objectid))
{
gs.enemylist.Remove(objectid);
}
else if (gs.attacklist.ContainsKey(objectid))
{
gs.attacklist.Remove(objectid);
}
e.NewValue = CheckState.Unchecked;
}
listView1.ResumeLayout();
}
private void textBox11_TextChanged(object sender, EventArgs e)
{
try
{
gs.AttackDistance = Convert.ToInt32(textBox11.Text);
}
catch
{
gs.AttackDistance = 1200;
}
}
private void cb_CPpots_CheckedChanged(object sender, EventArgs e)
{
if (cb_CPpots.Checked)
{
gs.cppots = true;
}
else
{
gs.cppots = false;
}
}
private void cb_HPpots_CheckedChanged(object sender, EventArgs e)
{
if (cb_HPpots.Checked)
{
gs.ghppots = true;
}
else
gs.ghppots = false;
}
private void cb_Elixirs_CheckedChanged(object sender, EventArgs e)
{
if (cb_Elixirs.Checked)
{
gs.elixir = true;
}
else
gs.elixir = false;
}
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
ListViewItemComparer sorter = new ListViewItemComparer(e.Column);
if (e.Column == 0)
sorter.Numeric = true;
if (listView1.Sorting == SortOrder.Ascending || listView1.Sorting == SortOrder.None)
listView1.Sorting = SortOrder.Descending;
else
listView1.Sorting = SortOrder.Ascending;
listView1.ListViewItemSorter = sorter;
listView1.Sort();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
gs.flagfight = true;
}
else
gs.flagfight = false;
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked)
{
gs.kill2waywar = true;
}
else
gs.kill2waywar = false;
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked)
{
DialogResult res = MessageBox.Show("Are you sure you want to bsoe like a pussy?",
"Confirm pussiness", MessageBoxButtons.YesNo);
if (res == DialogResult.Yes)
{
gs.usebsoe = true;
}
else
{
checkBox3.Checked = false;
gs.usebsoe = false;
}
}
else
gs.usebsoe = false;
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
if (checkBox4.Checked)
{
gs.qhp = true;
}
else
gs.qhp = false;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
gs.qhphp = Convert.ToUInt32(textBox1.Text);
}
private void checkBox33_CheckedChanged(object sender, EventArgs e)
{
if (checkBox33.Checked)
{
gs.AssistLeader = true;
}
else
{
gs.AssistLeader = false;
}
}
private void textBox10_TextChanged(object sender, EventArgs e)
{
gs.Targetter = textBox10.Text;
foreach (CharInfo c in gs.allplayerinfo.Values)
{
if (c.Name == gs.Targetter)
{
gs.TargetterID = c.ID;
break;
}
}
}
private void fbuffs_Click(object sender, EventArgs e)
{
foreach (Client c in gs.clist)
{
if (c != null)
{
c.fightbuff_mre.Set();
}
}
}
private void button5_Click(object sender, EventArgs e)
{
foreach (Client c in gs.clist)
{
if (c != null)
c.item_mre.Set();
}
}
private void button6_Click(object sender, EventArgs e)
{
gs.global = tbglobal.Text;
foreach (Client c in gs.clist)
{
try
{
if (c != null)
c.saveConfiguration();
}
catch
{
}
}
}
private void button7_Click(object sender, EventArgs e)
{
gs.global = tbglobal.Text;
foreach (Client c in gs.clist)
{
try
{
if (c != null)
c.loadClientConfiguration();
}
catch
{
}
}
}
private void checkBox5_CheckedChanged(object sender, EventArgs e)
{
if (checkBox5.Checked)
{
gs.buffs = true;
}
else
gs.buffs = false;
}
private void cb_percent_CheckedChanged(object sender, EventArgs e)
{
if (cb_percent.Checked)
{
gs.bPercentRecover = true;
}
else
{
gs.bPercentRecover = false;
}
}
private void tb_Recover_TextChanged(object sender, EventArgs e)
{
try
{
gs.PercentRecover = Convert.ToDouble(tb_Recover.Text);
}
catch
{
gs.PercentRecover = 80;
}
}
//private void checkBox5_CheckedChanged(object sender, EventArgs e)
//{
// if (checkBox5.Checked)
// gs.autotalk = true;
// else
// {
// gs.autotalk = false;
// }
//}
//private void textBox2_TextChanged(object sender, EventArgs e)
//{
// gs.talkdelay = Convert.ToInt32(textBox2.Text);
//}
}
public class ListViewItemComparer : IComparer
{
private int column;
private bool numeric = false;
public int Column
{
get { return column; }
set { column = value; }
}
public bool Numeric
{
get { return numeric; }
set { numeric = value; }
}
public ListViewItemComparer(int columnIndex)
{
Column = columnIndex;
}
public int Compare(object x, object y)
{
ListViewItem listX = (ListViewItem)x;
ListViewItem listY = (ListViewItem)y;
if (Numeric)
{
// Convert column text to numbers before comparing.
// If the conversion fails, just use the value 0.
decimal listXVal, listYVal;
try
{
listXVal = Decimal.Parse(listX.SubItems[Column].Text);
}
catch
{
listXVal = 0;
}
try
{
listYVal = Decimal.Parse(listY.SubItems[Column].Text);
}
catch
{
listYVal = 0;
}
return Decimal.Compare(listXVal, listYVal);
}
else
{
// Keep the column text in its native string format
// and perform an alphabetic comparison.
string listXText = listX.SubItems[Column].Text;
string listYText = listY.SubItems[Column].Text;
return String.Compare(listXText, listYText);
}
}
}
}
| |
using FluentFTP.Helpers;
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
#if ASYNC
using System.Threading.Tasks;
#endif
namespace FluentFTP.Proxy {
/// <summary> A FTP client with a HTTP 1.1 proxy implementation. </summary>
public class FtpClientHttp11Proxy : FtpClientProxy {
/// <summary> A FTP client with a HTTP 1.1 proxy implementation </summary>
/// <param name="proxy">Proxy information</param>
public FtpClientHttp11Proxy(ProxyInfo proxy)
: base(proxy) {
ConnectionType = "HTTP 1.1 Proxy";
}
/// <summary> Redefine the first dialog: HTTP Frame for the HTTP 1.1 Proxy </summary>
protected override void Handshake() {
var proxyConnectionReply = GetReply();
if (!proxyConnectionReply.Success) {
throw new FtpException("Can't connect " + Host + " via proxy " + Proxy.Host + ".\nMessage : " +
proxyConnectionReply.ErrorMessage);
}
// TO TEST: if we are able to detect the actual FTP server software from this reply
HandshakeReply = proxyConnectionReply;
}
/// <summary>
/// Creates a new instance of this class. Useful in FTP proxy classes.
/// </summary>
protected override FtpClient Create() {
return new FtpClientHttp11Proxy(Proxy);
}
/// <summary>
/// Connects to the server using an existing <see cref="FtpSocketStream"/>
/// </summary>
/// <param name="stream">The existing socket stream</param>
protected override void Connect(FtpSocketStream stream) {
Connect(stream, Host, Port, FtpIpVersion.ANY);
}
#if ASYNC
/// <summary>
/// Connects to the server using an existing <see cref="FtpSocketStream"/>
/// </summary>
/// <param name="stream">The existing socket stream</param>
protected override Task ConnectAsync(FtpSocketStream stream, CancellationToken token) {
return ConnectAsync(stream, Host, Port, FtpIpVersion.ANY, token);
}
#endif
/// <summary>
/// Connects to the server using an existing <see cref="FtpSocketStream"/>
/// </summary>
/// <param name="stream">The existing socket stream</param>
/// <param name="host">Host name</param>
/// <param name="port">Port number</param>
/// <param name="ipVersions">IP version to use</param>
protected override void Connect(FtpSocketStream stream, string host, int port, FtpIpVersion ipVersions) {
base.Connect(stream);
var writer = new StreamWriter(stream);
writer.WriteLine("CONNECT {0}:{1} HTTP/1.1", host, port);
writer.WriteLine("Host: {0}:{1}", host, port);
if (Proxy.Credentials != null) {
var credentialsHash = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Proxy.Credentials.UserName + ":" + Proxy.Credentials.Password));
writer.WriteLine("Proxy-Authorization: Basic " + credentialsHash);
}
writer.WriteLine("User-Agent: custom-ftp-client");
writer.WriteLine();
writer.Flush();
ProxyHandshake(stream);
}
#if ASYNC
/// <summary>
/// Connects to the server using an existing <see cref="FtpSocketStream"/>
/// </summary>
/// <param name="stream">The existing socket stream</param>
/// <param name="host">Host name</param>
/// <param name="port">Port number</param>
/// <param name="ipVersions">IP version to use</param>
/// <param name="token">IP version to use</param>
protected override async Task ConnectAsync(FtpSocketStream stream, string host, int port, FtpIpVersion ipVersions, CancellationToken token) {
await base.ConnectAsync(stream, token);
var writer = new StreamWriter(stream);
await writer.WriteLineAsync(string.Format("CONNECT {0}:{1} HTTP/1.1", host, port));
await writer.WriteLineAsync(string.Format("Host: {0}:{1}", host, port));
if (Proxy.Credentials != null) {
var credentialsHash = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Proxy.Credentials.UserName + ":" + Proxy.Credentials.Password));
await writer.WriteLineAsync("Proxy-Authorization: Basic " + credentialsHash);
}
await writer.WriteLineAsync("User-Agent: custom-ftp-client");
await writer.WriteLineAsync();
await writer.FlushAsync();
await ProxyHandshakeAsync(stream, token);
}
#endif
private void ProxyHandshake(FtpSocketStream stream) {
var proxyConnectionReply = GetProxyReply(stream);
if (!proxyConnectionReply.Success) {
throw new FtpException("Can't connect " + Host + " via proxy " + Proxy.Host + ".\nMessage : " + proxyConnectionReply.ErrorMessage);
}
}
#if ASYNC
private async Task ProxyHandshakeAsync(FtpSocketStream stream, CancellationToken token = default(CancellationToken)) {
var proxyConnectionReply = await GetProxyReplyAsync(stream, token);
if (!proxyConnectionReply.Success) {
throw new FtpException("Can't connect " + Host + " via proxy " + Proxy.Host + ".\nMessage : " + proxyConnectionReply.ErrorMessage);
}
}
#endif
private FtpReply GetProxyReply(FtpSocketStream stream) {
var reply = new FtpReply();
string buf;
#if !CORE14
lock (Lock) {
#endif
if (!IsConnected) {
throw new InvalidOperationException("No connection to the server has been established.");
}
stream.ReadTimeout = ReadTimeout;
while ((buf = stream.ReadLine(Encoding)) != null) {
Match m;
LogLine(FtpTraceLevel.Info, buf);
if ((m = Regex.Match(buf, @"^HTTP/.*\s(?<code>[0-9]{3}) (?<message>.*)$")).Success) {
reply.Code = m.Groups["code"].Value;
reply.Message = m.Groups["message"].Value;
break;
}
reply.InfoMessages += buf + "\n";
}
// fixes #84 (missing bytes when downloading/uploading files through proxy)
while ((buf = stream.ReadLine(Encoding)) != null) {
LogLine(FtpTraceLevel.Info, buf);
if (Strings.IsNullOrWhiteSpace(buf)) {
break;
}
reply.InfoMessages += buf + "\n";
}
#if !CORE14
}
#endif
return reply;
}
#if ASYNC
private async Task<FtpReply> GetProxyReplyAsync(FtpSocketStream stream, CancellationToken token = default(CancellationToken)) {
var reply = new FtpReply();
string buf;
if (!IsConnected) {
throw new InvalidOperationException("No connection to the server has been established.");
}
stream.ReadTimeout = ReadTimeout;
while ((buf = await stream.ReadLineAsync(Encoding, token)) != null) {
Match m;
LogLine(FtpTraceLevel.Info, buf);
if ((m = Regex.Match(buf, @"^HTTP/.*\s(?<code>[0-9]{3}) (?<message>.*)$")).Success) {
reply.Code = m.Groups["code"].Value;
reply.Message = m.Groups["message"].Value;
break;
}
reply.InfoMessages += buf + "\n";
}
// fixes #84 (missing bytes when downloading/uploading files through proxy)
while ((buf = await stream.ReadLineAsync(Encoding, token)) != null) {
LogLine(FtpTraceLevel.Info, buf);
if (Strings.IsNullOrWhiteSpace(buf)) {
break;
}
reply.InfoMessages += buf + "\n";
}
return reply;
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: The CLR implementation of Variant.
**
**
===========================================================*/
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System
{
internal struct Variant
{
// Do Not change the order of these fields.
// They are mapped to the native VariantData * data structure.
private object? _objref;
private long _data;
private int _flags;
// The following bits have been taken up as follows
// bits 0-15 - Type code
// bit 16 - Array
// bits 19-23 - Enums
// bits 24-31 - Optional VT code (for roundtrip VT preservation)
// What are the consequences of making this an enum?
///////////////////////////////////////////////////////////////////////
// If you update this, update the corresponding stuff in OAVariantLib.cs,
// COMOAVariant.cpp (2 tables, forwards and reverse), and perhaps OleVariant.h
///////////////////////////////////////////////////////////////////////
internal const int CV_EMPTY = 0x0;
internal const int CV_VOID = 0x1;
internal const int CV_BOOLEAN = 0x2;
internal const int CV_CHAR = 0x3;
internal const int CV_I1 = 0x4;
internal const int CV_U1 = 0x5;
internal const int CV_I2 = 0x6;
internal const int CV_U2 = 0x7;
internal const int CV_I4 = 0x8;
internal const int CV_U4 = 0x9;
internal const int CV_I8 = 0xa;
internal const int CV_U8 = 0xb;
internal const int CV_R4 = 0xc;
internal const int CV_R8 = 0xd;
internal const int CV_STRING = 0xe;
internal const int CV_PTR = 0xf;
internal const int CV_DATETIME = 0x10;
internal const int CV_TIMESPAN = 0x11;
internal const int CV_OBJECT = 0x12;
internal const int CV_DECIMAL = 0x13;
internal const int CV_ENUM = 0x15;
internal const int CV_MISSING = 0x16;
internal const int CV_NULL = 0x17;
internal const int CV_LAST = 0x18;
internal const int TypeCodeBitMask = 0xffff;
internal const int VTBitMask = unchecked((int)0xff000000);
internal const int VTBitShift = 24;
internal const int ArrayBitMask = 0x10000;
// Enum enum and Mask
internal const int EnumI1 = 0x100000;
internal const int EnumU1 = 0x200000;
internal const int EnumI2 = 0x300000;
internal const int EnumU2 = 0x400000;
internal const int EnumI4 = 0x500000;
internal const int EnumU4 = 0x600000;
internal const int EnumI8 = 0x700000;
internal const int EnumU8 = 0x800000;
internal const int EnumMask = 0xF00000;
internal static readonly Type[] ClassTypes = {
typeof(System.Empty),
typeof(void),
typeof(bool),
typeof(char),
typeof(sbyte),
typeof(byte),
typeof(short),
typeof(ushort),
typeof(int),
typeof(uint),
typeof(long),
typeof(ulong),
typeof(float),
typeof(double),
typeof(string),
typeof(void), // ptr for the moment
typeof(DateTime),
typeof(TimeSpan),
typeof(object),
typeof(decimal),
typeof(object), // Treat enum as Object
typeof(System.Reflection.Missing),
typeof(System.DBNull),
};
internal static readonly Variant Empty = new Variant();
internal static readonly Variant Missing = new Variant(Variant.CV_MISSING, Type.Missing, 0);
internal static readonly Variant DBNull = new Variant(Variant.CV_NULL, System.DBNull.Value, 0);
//
// Native Methods
//
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern void SetFieldsObject(object val);
//
// Constructors
//
internal Variant(int flags, object or, long data)
{
_flags = flags;
_objref = or;
_data = data;
}
public Variant(bool val)
{
_objref = null;
_flags = CV_BOOLEAN;
_data = (val) ? bool.True : bool.False;
}
public Variant(sbyte val)
{
_objref = null;
_flags = CV_I1;
_data = val;
}
public Variant(byte val)
{
_objref = null;
_flags = CV_U1;
_data = val;
}
public Variant(short val)
{
_objref = null;
_flags = CV_I2;
_data = val;
}
public Variant(ushort val)
{
_objref = null;
_flags = CV_U2;
_data = val;
}
public Variant(char val)
{
_objref = null;
_flags = CV_CHAR;
_data = val;
}
public Variant(int val)
{
_objref = null;
_flags = CV_I4;
_data = val;
}
public Variant(uint val)
{
_objref = null;
_flags = CV_U4;
_data = val;
}
public Variant(long val)
{
_objref = null;
_flags = CV_I8;
_data = val;
}
public Variant(ulong val)
{
_objref = null;
_flags = CV_U8;
_data = (long)val;
}
public Variant(float val)
{
_objref = null;
_flags = CV_R4;
_data = (uint)BitConverter.SingleToInt32Bits(val);
}
public Variant(double val)
{
_objref = null;
_flags = CV_R8;
_data = BitConverter.DoubleToInt64Bits(val);
}
public Variant(DateTime val)
{
_objref = null;
_flags = CV_DATETIME;
_data = val.Ticks;
}
public Variant(decimal val)
{
_objref = (object)val;
_flags = CV_DECIMAL;
_data = 0;
}
public Variant(object? obj)
{
_data = 0;
VarEnum vt = VarEnum.VT_EMPTY;
if (obj is DateTime)
{
_objref = null;
_flags = CV_DATETIME;
_data = ((DateTime)obj).Ticks;
return;
}
if (obj is string)
{
_flags = CV_STRING;
_objref = obj;
return;
}
if (obj == null)
{
this = Empty;
return;
}
if (obj == System.DBNull.Value)
{
this = DBNull;
return;
}
if (obj == Type.Missing)
{
this = Missing;
return;
}
if (obj is Array)
{
_flags = CV_OBJECT | ArrayBitMask;
_objref = obj;
return;
}
// Compiler appeasement
_flags = CV_EMPTY;
_objref = null;
// Check to see if the object passed in is a wrapper object.
if (obj is UnknownWrapper)
{
vt = VarEnum.VT_UNKNOWN;
obj = ((UnknownWrapper)obj).WrappedObject;
}
else if (obj is DispatchWrapper)
{
vt = VarEnum.VT_DISPATCH;
obj = ((DispatchWrapper)obj).WrappedObject;
}
else if (obj is ErrorWrapper)
{
vt = VarEnum.VT_ERROR;
obj = (object)(((ErrorWrapper)obj).ErrorCode);
Debug.Assert(obj != null, "obj != null");
}
else if (obj is CurrencyWrapper)
{
vt = VarEnum.VT_CY;
obj = (object)(((CurrencyWrapper)obj).WrappedObject);
Debug.Assert(obj != null, "obj != null");
}
else if (obj is BStrWrapper)
{
vt = VarEnum.VT_BSTR;
obj = (object?)(((BStrWrapper)obj).WrappedObject);
}
if (obj != null)
{
SetFieldsObject(obj);
}
// If the object passed in is one of the wrappers then set the VARIANT type.
if (vt != VarEnum.VT_EMPTY)
_flags |= ((int)vt << VTBitShift);
}
// This is a family-only accessor for the CVType.
// This is never to be exposed externally.
internal int CVType => _flags & TypeCodeBitMask;
public object? ToObject()
{
switch (CVType)
{
case CV_EMPTY:
return null;
case CV_BOOLEAN:
return (object)((int)_data != 0);
case CV_I1:
return (object)((sbyte)_data);
case CV_U1:
return (object)((byte)_data);
case CV_CHAR:
return (object)((char)_data);
case CV_I2:
return (object)((short)_data);
case CV_U2:
return (object)((ushort)_data);
case CV_I4:
return (object)((int)_data);
case CV_U4:
return (object)((uint)_data);
case CV_I8:
return (object)((long)_data);
case CV_U8:
return (object)((ulong)_data);
case CV_R4:
return (object)(BitConverter.Int32BitsToSingle((int)_data));
case CV_R8:
return (object)(BitConverter.Int64BitsToDouble(_data));
case CV_DATETIME:
return new DateTime(_data);
case CV_TIMESPAN:
return new TimeSpan(_data);
case CV_ENUM:
return BoxEnum();
case CV_MISSING:
return Type.Missing;
case CV_NULL:
return System.DBNull.Value;
case CV_DECIMAL:
case CV_STRING:
case CV_OBJECT:
default:
return _objref;
}
}
// This routine will return an boxed enum.
[MethodImpl(MethodImplOptions.InternalCall)]
private extern object BoxEnum();
// Helper code for marshaling managed objects to VARIANT's (we use
// managed variants as an intermediate type.
internal static void MarshalHelperConvertObjectToVariant(object o, ref Variant v)
{
if (o == null)
{
v = Empty;
}
else if (o is IConvertible ic)
{
IFormatProvider provider = CultureInfo.InvariantCulture;
v = ic.GetTypeCode() switch
{
TypeCode.Empty => Empty,
TypeCode.Object => new Variant((object)o),
TypeCode.DBNull => DBNull,
TypeCode.Boolean => new Variant(ic.ToBoolean(provider)),
TypeCode.Char => new Variant(ic.ToChar(provider)),
TypeCode.SByte => new Variant(ic.ToSByte(provider)),
TypeCode.Byte => new Variant(ic.ToByte(provider)),
TypeCode.Int16 => new Variant(ic.ToInt16(provider)),
TypeCode.UInt16 => new Variant(ic.ToUInt16(provider)),
TypeCode.Int32 => new Variant(ic.ToInt32(provider)),
TypeCode.UInt32 => new Variant(ic.ToUInt32(provider)),
TypeCode.Int64 => new Variant(ic.ToInt64(provider)),
TypeCode.UInt64 => new Variant(ic.ToUInt64(provider)),
TypeCode.Single => new Variant(ic.ToSingle(provider)),
TypeCode.Double => new Variant(ic.ToDouble(provider)),
TypeCode.Decimal => new Variant(ic.ToDecimal(provider)),
TypeCode.DateTime => new Variant(ic.ToDateTime(provider)),
TypeCode.String => new Variant(ic.ToString(provider)),
_ => throw new NotSupportedException(SR.Format(SR.NotSupported_UnknownTypeCode, ic.GetTypeCode())),
};
}
else
{
// This path should eventually go away. But until
// the work is done to have all of our wrapper types implement
// IConvertible, this is a cheapo way to get the work done.
v = new Variant(o);
}
}
// Helper code for marshaling VARIANTS to managed objects (we use
// managed variants as an intermediate type.
internal static object? MarshalHelperConvertVariantToObject(ref Variant v)
{
return v.ToObject();
}
// Helper code: on the back propagation path where a VT_BYREF VARIANT*
// is marshaled to a "ref Object", we use this helper to force the
// updated object back to the original type.
internal static void MarshalHelperCastVariant(object pValue, int vt, ref Variant v)
{
if (!(pValue is IConvertible iv))
{
switch (vt)
{
case 9: /*VT_DISPATCH*/
v = new Variant(new DispatchWrapper(pValue));
break;
case 12: /*VT_VARIANT*/
v = new Variant(pValue);
break;
case 13: /*VT_UNKNOWN*/
v = new Variant(new UnknownWrapper(pValue));
break;
case 36: /*VT_RECORD*/
v = new Variant(pValue);
break;
case 8: /*VT_BSTR*/
if (pValue == null)
{
v = new Variant(null);
v._flags = CV_STRING;
}
else
{
throw new InvalidCastException(SR.InvalidCast_CannotCoerceByRefVariant);
}
break;
default:
throw new InvalidCastException(SR.InvalidCast_CannotCoerceByRefVariant);
}
}
else
{
IFormatProvider provider = CultureInfo.InvariantCulture;
v = vt switch
{
0 => /*VT_EMPTY*/ Empty,
1 => /*VT_NULL*/ DBNull,
2 => /*VT_I2*/ new Variant(iv.ToInt16(provider)),
3 => /*VT_I4*/ new Variant(iv.ToInt32(provider)),
4 => /*VT_R4*/ new Variant(iv.ToSingle(provider)),
5 => /*VT_R8*/ new Variant(iv.ToDouble(provider)),
6 => /*VT_CY*/ new Variant(new CurrencyWrapper(iv.ToDecimal(provider))),
7 => /*VT_DATE*/ new Variant(iv.ToDateTime(provider)),
8 => /*VT_BSTR*/ new Variant(iv.ToString(provider)),
9 => /*VT_DISPATCH*/ new Variant(new DispatchWrapper((object)iv)),
10 => /*VT_ERROR*/ new Variant(new ErrorWrapper(iv.ToInt32(provider))),
11 => /*VT_BOOL*/ new Variant(iv.ToBoolean(provider)),
12 => /*VT_VARIANT*/ new Variant((object)iv),
13 => /*VT_UNKNOWN*/ new Variant(new UnknownWrapper((object)iv)),
14 => /*VT_DECIMAL*/ new Variant(iv.ToDecimal(provider)),
// 15 => : /*unused*/ NOT SUPPORTED
16 => /*VT_I1*/ new Variant(iv.ToSByte(provider)),
17 => /*VT_UI1*/ new Variant(iv.ToByte(provider)),
18 => /*VT_UI2*/ new Variant(iv.ToUInt16(provider)),
19 => /*VT_UI4*/ new Variant(iv.ToUInt32(provider)),
20 => /*VT_I8*/ new Variant(iv.ToInt64(provider)),
21 => /*VT_UI8*/ new Variant(iv.ToUInt64(provider)),
22 => /*VT_INT*/ new Variant(iv.ToInt32(provider)),
23 => /*VT_UINT*/ new Variant(iv.ToUInt32(provider)),
_ => throw new InvalidCastException(SR.InvalidCast_CannotCoerceByRefVariant),
};
}
}
}
}
| |
/*
* 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 System.Text;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using CSJ2K;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Agent.TextureSender
{
public delegate void J2KDecodeDelegate(UUID assetID);
public class J2KDecoderModule : IRegionModule, IJ2KDecoder
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>Temporarily holds deserialized layer data information in memory</summary>
private readonly ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]> m_decodedCache = new ExpiringCache<UUID,OpenJPEG.J2KLayerInfo[]>();
/// <summary>List of client methods to notify of results of decode</summary>
private readonly Dictionary<UUID, List<DecodedCallback>> m_notifyList = new Dictionary<UUID, List<DecodedCallback>>();
/// <summary>Cache that will store decoded JPEG2000 layer boundary data</summary>
private IImprovedAssetCache m_cache;
/// <summary>Reference to a scene (doesn't matter which one as long as it can load the cache module)</summary>
private Scene m_scene;
#region IRegionModule
public string Name { get { return "J2KDecoderModule"; } }
public bool IsSharedModule { get { return true; } }
public J2KDecoderModule()
{
}
public void Initialise(Scene scene, IConfigSource source)
{
if (m_scene == null)
m_scene = scene;
scene.RegisterModuleInterface<IJ2KDecoder>(this);
}
public void PostInitialise()
{
m_cache = m_scene.RequestModuleInterface<IImprovedAssetCache>();
}
public void Close()
{
}
#endregion IRegionModule
#region IJ2KDecoder
public void BeginDecode(UUID assetID, byte[] j2kData, DecodedCallback callback)
{
OpenJPEG.J2KLayerInfo[] result;
// If it's cached, return the cached results
if (m_decodedCache.TryGetValue(assetID, out result))
{
callback(assetID, result);
}
else
{
// Not cached, we need to decode it.
// Add to notify list and start decoding.
// Next request for this asset while it's decoding will only be added to the notify list
// once this is decoded, requests will be served from the cache and all clients in the notifylist will be updated
bool decode = false;
lock (m_notifyList)
{
if (m_notifyList.ContainsKey(assetID))
{
m_notifyList[assetID].Add(callback);
}
else
{
List<DecodedCallback> notifylist = new List<DecodedCallback>();
notifylist.Add(callback);
m_notifyList.Add(assetID, notifylist);
decode = true;
}
}
// Do Decode!
if (decode)
DoJ2KDecode(assetID, j2kData);
}
}
/// <summary>
/// Provides a synchronous decode so that caller can be assured that this executes before the next line
/// </summary>
/// <param name="assetID"></param>
/// <param name="j2kData"></param>
public void Decode(UUID assetID, byte[] j2kData)
{
DoJ2KDecode(assetID, j2kData);
}
#endregion IJ2KDecoder
/// <summary>
/// Decode Jpeg2000 Asset Data
/// </summary>
/// <param name="assetID">UUID of Asset</param>
/// <param name="j2kData">JPEG2000 data</param>
private void DoJ2KDecode(UUID assetID, byte[] j2kData)
{
// int DecodeTime = 0;
// DecodeTime = Environment.TickCount;
OpenJPEG.J2KLayerInfo[] layers;
if (!TryLoadCacheForAsset(assetID, out layers))
{
try
{
List<int> layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(new MemoryStream(j2kData));
if (layerStarts != null && layerStarts.Count > 0)
{
layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count];
for (int i = 0; i < layerStarts.Count; i++)
{
OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo();
if (i == 0)
layer.Start = 0;
else
layer.Start = layerStarts[i];
if (i == layerStarts.Count - 1)
layer.End = j2kData.Length;
else
layer.End = layerStarts[i + 1] - 1;
layers[i] = layer;
}
}
}
catch (Exception ex)
{
m_log.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " + ex.Message);
}
if (layers == null || layers.Length == 0)
{
m_log.Warn("[J2KDecoderModule]: Failed to decode layer data for texture " + assetID + ", guessing sane defaults");
// Layer decoding completely failed. Guess at sane defaults for the layer boundaries
layers = CreateDefaultLayers(j2kData.Length);
}
// Cache Decoded layers
SaveFileCacheForAsset(assetID, layers);
}
// Notify Interested Parties
lock (m_notifyList)
{
if (m_notifyList.ContainsKey(assetID))
{
foreach (DecodedCallback d in m_notifyList[assetID])
{
if (d != null)
d.DynamicInvoke(assetID, layers);
}
m_notifyList.Remove(assetID);
}
}
}
private OpenJPEG.J2KLayerInfo[] CreateDefaultLayers(int j2kLength)
{
OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[5];
for (int i = 0; i < layers.Length; i++)
layers[i] = new OpenJPEG.J2KLayerInfo();
// These default layer sizes are based on a small sampling of real-world texture data
// with extra padding thrown in for good measure. This is a worst case fallback plan
// and may not gracefully handle all real world data
layers[0].Start = 0;
layers[1].Start = (int)((float)j2kLength * 0.02f);
layers[2].Start = (int)((float)j2kLength * 0.05f);
layers[3].Start = (int)((float)j2kLength * 0.20f);
layers[4].Start = (int)((float)j2kLength * 0.50f);
layers[0].End = layers[1].Start - 1;
layers[1].End = layers[2].Start - 1;
layers[2].End = layers[3].Start - 1;
layers[3].End = layers[4].Start - 1;
layers[4].End = j2kLength;
return layers;
}
private void SaveFileCacheForAsset(UUID AssetId, OpenJPEG.J2KLayerInfo[] Layers)
{
m_decodedCache.AddOrUpdate(AssetId, Layers, TimeSpan.FromMinutes(10));
if (m_cache != null)
{
string assetID = "j2kCache_" + AssetId.ToString();
AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, (sbyte)AssetType.Notecard);
layerDecodeAsset.Local = true;
layerDecodeAsset.Temporary = true;
#region Serialize Layer Data
StringBuilder stringResult = new StringBuilder();
string strEnd = "\n";
for (int i = 0; i < Layers.Length; i++)
{
if (i == Layers.Length - 1)
strEnd = String.Empty;
stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd);
}
layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString());
#endregion Serialize Layer Data
m_cache.Cache(layerDecodeAsset);
}
}
bool TryLoadCacheForAsset(UUID AssetId, out OpenJPEG.J2KLayerInfo[] Layers)
{
if (m_decodedCache.TryGetValue(AssetId, out Layers))
{
return true;
}
else if (m_cache != null)
{
string assetName = "j2kCache_" + AssetId.ToString();
AssetBase layerDecodeAsset = m_cache.Get(assetName);
if (layerDecodeAsset != null)
{
#region Deserialize Layer Data
string readResult = Util.UTF8.GetString(layerDecodeAsset.Data);
string[] lines = readResult.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
if (lines.Length == 0)
{
m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (empty) " + assetName);
m_cache.Expire(assetName);
return false;
}
Layers = new OpenJPEG.J2KLayerInfo[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
string[] elements = lines[i].Split('|');
if (elements.Length == 3)
{
int element1, element2;
try
{
element1 = Convert.ToInt32(elements[0]);
element2 = Convert.ToInt32(elements[1]);
}
catch (FormatException)
{
m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (format) " + assetName);
m_cache.Expire(assetName);
return false;
}
Layers[i] = new OpenJPEG.J2KLayerInfo();
Layers[i].Start = element1;
Layers[i].End = element2;
}
else
{
m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (layout) " + assetName);
m_cache.Expire(assetName);
return false;
}
}
#endregion Deserialize Layer Data
return true;
}
}
return false;
}
}
}
| |
using System;
using Lucene.Net.Documents;
namespace Lucene.Net.Codecs.Perfield
{
using Lucene.Net.Randomized.Generators;
using NUnit.Framework;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
/*using MockSepPostingsFormat = Lucene.Net.Codecs.mocksep.MockSepPostingsFormat;
using Pulsing41PostingsFormat = Lucene.Net.Codecs.pulsing.Pulsing41PostingsFormat;
using SimpleTextPostingsFormat = Lucene.Net.Codecs.simpletext.SimpleTextPostingsFormat;*/
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig;
using LogDocMergePolicy = Lucene.Net.Index.LogDocMergePolicy;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using Term = Lucene.Net.Index.Term;
using TermQuery = Lucene.Net.Search.TermQuery;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
using TopDocs = Lucene.Net.Search.TopDocs;
//TODO: would be better in this test to pull termsenums and instanceof or something?
// this way we can verify PFPF is doing the right thing.
// for now we do termqueries.
[TestFixture]
public class TestPerFieldPostingsFormat2 : LuceneTestCase
{
private IndexWriter NewWriter(Directory dir, IndexWriterConfig conf)
{
LogDocMergePolicy logByteSizeMergePolicy = new LogDocMergePolicy();
logByteSizeMergePolicy.NoCFSRatio = 0.0; // make sure we use plain
// files
conf.SetMergePolicy(logByteSizeMergePolicy);
IndexWriter writer = new IndexWriter(dir, conf);
return writer;
}
private void AddDocs(IndexWriter writer, int numDocs)
{
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
doc.Add(NewTextField("content", "aaa", Field.Store.NO));
writer.AddDocument(doc);
}
}
private void AddDocs2(IndexWriter writer, int numDocs)
{
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
doc.Add(NewTextField("content", "bbb", Field.Store.NO));
writer.AddDocument(doc);
}
}
private void AddDocs3(IndexWriter writer, int numDocs)
{
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
doc.Add(NewTextField("content", "ccc", Field.Store.NO));
doc.Add(NewStringField("id", "" + i, Field.Store.YES));
writer.AddDocument(doc);
}
}
/*
* Test that heterogeneous index segments are merge successfully
*/
/*public virtual void TestMergeUnusedPerFieldCodec()
{
Directory dir = NewDirectory();
IndexWriterConfig iwconf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(IndexWriterConfig.OpenMode_e.CREATE).SetCodec(new MockCodec());
IndexWriter writer = NewWriter(dir, iwconf);
AddDocs(writer, 10);
writer.Commit();
AddDocs3(writer, 10);
writer.Commit();
AddDocs2(writer, 10);
writer.Commit();
Assert.AreEqual(30, writer.MaxDoc());
TestUtil.CheckIndex(dir);
writer.ForceMerge(1);
Assert.AreEqual(30, writer.MaxDoc());
writer.Dispose();
dir.Dispose();
}*/
/*
* Test that heterogeneous index segments are merged sucessfully
*/
// TODO: not sure this test is that great, we should probably peek inside PerFieldPostingsFormat or something?!
/*public virtual void TestChangeCodecAndMerge()
{
Directory dir = NewDirectory();
if (VERBOSE)
{
Console.WriteLine("TEST: make new index");
}
IndexWriterConfig iwconf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(IndexWriterConfig.OpenMode_e.CREATE).SetCodec(new MockCodec());
iwconf.SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);
//((LogMergePolicy) iwconf.getMergePolicy()).setMergeFactor(10);
IndexWriter writer = NewWriter(dir, iwconf);
AddDocs(writer, 10);
writer.Commit();
AssertQuery(new Term("content", "aaa"), dir, 10);
if (VERBOSE)
{
Console.WriteLine("TEST: addDocs3");
}
AddDocs3(writer, 10);
writer.Commit();
writer.Dispose();
AssertQuery(new Term("content", "ccc"), dir, 10);
AssertQuery(new Term("content", "aaa"), dir, 10);
Codec codec = iwconf.Codec;
iwconf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(IndexWriterConfig.OpenMode_e.APPEND).SetCodec(codec);
//((LogMergePolicy) iwconf.getMergePolicy()).setNoCFSRatio(0.0);
//((LogMergePolicy) iwconf.getMergePolicy()).setMergeFactor(10);
iwconf.SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);
iwconf.SetCodec(new MockCodec2()); // uses standard for field content
writer = NewWriter(dir, iwconf);
// swap in new codec for currently written segments
if (VERBOSE)
{
Console.WriteLine("TEST: add docs w/ Standard codec for content field");
}
AddDocs2(writer, 10);
writer.Commit();
codec = iwconf.Codec;
Assert.AreEqual(30, writer.MaxDoc());
AssertQuery(new Term("content", "bbb"), dir, 10);
AssertQuery(new Term("content", "ccc"), dir, 10); ////
AssertQuery(new Term("content", "aaa"), dir, 10);
if (VERBOSE)
{
Console.WriteLine("TEST: add more docs w/ new codec");
}
AddDocs2(writer, 10);
writer.Commit();
AssertQuery(new Term("content", "ccc"), dir, 10);
AssertQuery(new Term("content", "bbb"), dir, 20);
AssertQuery(new Term("content", "aaa"), dir, 10);
Assert.AreEqual(40, writer.MaxDoc());
if (VERBOSE)
{
Console.WriteLine("TEST: now optimize");
}
writer.ForceMerge(1);
Assert.AreEqual(40, writer.MaxDoc());
writer.Dispose();
AssertQuery(new Term("content", "ccc"), dir, 10);
AssertQuery(new Term("content", "bbb"), dir, 20);
AssertQuery(new Term("content", "aaa"), dir, 10);
dir.Dispose();
}*/
public virtual void AssertQuery(Term t, Directory dir, int num)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: assertQuery " + t);
}
IndexReader reader = DirectoryReader.Open(dir, 1);
IndexSearcher searcher = NewSearcher(reader);
TopDocs search = searcher.Search(new TermQuery(t), num + 10);
Assert.AreEqual(num, search.TotalHits);
reader.Dispose();
}
/*public class MockCodec : Lucene46Codec
{
internal readonly PostingsFormat Lucene40 = new Lucene41PostingsFormat();
internal readonly PostingsFormat SimpleText = new SimpleTextPostingsFormat();
internal readonly PostingsFormat MockSep = new MockSepPostingsFormat();
public override PostingsFormat GetPostingsFormatForField(string field)
{
if (field.Equals("id"))
{
return SimpleText;
}
else if (field.Equals("content"))
{
return MockSep;
}
else
{
return Lucene40;
}
}
}*/
/*public class MockCodec2 : Lucene46Codec
{
internal readonly PostingsFormat Lucene40 = new Lucene41PostingsFormat();
internal readonly PostingsFormat SimpleText = new SimpleTextPostingsFormat();
public override PostingsFormat GetPostingsFormatForField(string field)
{
if (field.Equals("id"))
{
return SimpleText;
}
else
{
return Lucene40;
}
}
}*/
/*
* Test per field codec support - adding fields with random codecs
*/
[Test]
public virtual void TestStressPerFieldCodec()
{
Directory dir = NewDirectory(Random());
const int docsPerRound = 97;
int numRounds = AtLeast(1);
for (int i = 0; i < numRounds; i++)
{
int num = TestUtil.NextInt(Random(), 30, 60);
IndexWriterConfig config = NewIndexWriterConfig(Random(), TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
config.SetOpenMode(IndexWriterConfig.OpenMode_e.CREATE_OR_APPEND);
IndexWriter writer = NewWriter(dir, config);
for (int j = 0; j < docsPerRound; j++)
{
Document doc = new Document();
for (int k = 0; k < num; k++)
{
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.Tokenized = Random().NextBoolean();
customType.OmitNorms = Random().NextBoolean();
Field field = NewField("" + k, TestUtil.RandomRealisticUnicodeString(Random(), 128), customType);
doc.Add(field);
}
writer.AddDocument(doc);
}
if (Random().NextBoolean())
{
writer.ForceMerge(1);
}
writer.Commit();
Assert.AreEqual((i + 1) * docsPerRound, writer.MaxDoc);
writer.Dispose();
}
dir.Dispose();
}
/*public virtual void TestSameCodecDifferentInstance()
{
Codec codec = new Lucene46CodecAnonymousInnerClassHelper(this);
DoTestMixedPostings(codec);
}*/
/*private class Lucene46CodecAnonymousInnerClassHelper : Lucene46Codec
{
private readonly TestPerFieldPostingsFormat2 OuterInstance;
public Lucene46CodecAnonymousInnerClassHelper(TestPerFieldPostingsFormat2 outerInstance)
{
this.OuterInstance = outerInstance;
}
public override PostingsFormat GetPostingsFormatForField(string field)
{
if ("id".Equals(field))
{
return new Pulsing41PostingsFormat(1);
}
else if ("date".Equals(field))
{
return new Pulsing41PostingsFormat(1);
}
else
{
return base.GetPostingsFormatForField(field);
}
}
}*/
/*public virtual void TestSameCodecDifferentParams()
{
Codec codec = new Lucene46CodecAnonymousInnerClassHelper2(this);
DoTestMixedPostings(codec);
}*/
/*private class Lucene46CodecAnonymousInnerClassHelper2 : Lucene46Codec
{
private readonly TestPerFieldPostingsFormat2 OuterInstance;
public Lucene46CodecAnonymousInnerClassHelper2(TestPerFieldPostingsFormat2 outerInstance)
{
this.OuterInstance = outerInstance;
}
public override PostingsFormat GetPostingsFormatForField(string field)
{
if ("id".Equals(field))
{
return new Pulsing41PostingsFormat(1);
}
else if ("date".Equals(field))
{
return new Pulsing41PostingsFormat(2);
}
else
{
return base.GetPostingsFormatForField(field);
}
}
}*/
[Test]
private void TestMixedPostings(Codec codec)
{
Directory dir = NewDirectory();
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
iwc.SetCodec(codec);
RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwc);
Document doc = new Document();
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
// turn on vectors for the checkindex cross-check
ft.StoreTermVectors = true;
ft.StoreTermVectorOffsets = true;
ft.StoreTermVectorPositions = true;
Field idField = new Field("id", "", ft);
Field dateField = new Field("date", "", ft);
doc.Add(idField);
doc.Add(dateField);
for (int i = 0; i < 100; i++)
{
idField.StringValue = Convert.ToString(Random().Next(50));
dateField.StringValue = Convert.ToString(Random().Next(100));
iw.AddDocument(doc);
}
iw.Dispose();
dir.Dispose(); // checkindex
}
}
}
| |
// 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.AcceptanceTestsAzureBodyDuration
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestDurationTestService : ServiceClient<AutoRestDurationTestService>, IAutoRestDurationTestService, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IDurationOperations.
/// </summary>
public virtual IDurationOperations Duration { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestDurationTestService(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestDurationTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestDurationTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestDurationTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Duration = new DurationOperations(this);
this.BaseUri = new Uri("https://localhost");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Signum.Utilities.Reflection;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Reflection;
using System.Collections.Concurrent;
using System.Collections;
using Signum.Utilities.ExpressionTrees;
namespace Signum.Utilities
{
public static class Csv
{
// Default changed since Excel exports not to UTF8 and https://stackoverflow.com/questions/49215791/vs-code-c-sharp-system-notsupportedexception-no-data-is-available-for-encodin
public static Encoding DefaultEncoding => Encoding.UTF8;
public static CultureInfo? DefaultCulture = null;
public static string ToCsvFile<T>(this IEnumerable<T> collection, string fileName, Encoding? encoding = null, CultureInfo? culture = null, bool writeHeaders = true, bool autoFlush = false, bool append = false,
Func<CsvMemberInfo<T>, CultureInfo, Func<object?, string?>>? toStringFactory = null)
{
using (FileStream fs = append ? new FileStream(fileName, FileMode.Append, FileAccess.Write) : File.Create(fileName))
ToCsv<T>(collection, fs, encoding, culture, writeHeaders, autoFlush, toStringFactory);
return fileName;
}
public static byte[] ToCsvBytes<T>(this IEnumerable<T> collection, Encoding? encoding = null, CultureInfo? culture = null, bool writeHeaders = true, bool autoFlush = false,
Func<CsvMemberInfo<T>, CultureInfo, Func<object?, string?>>? toStringFactory = null)
{
using (MemoryStream ms = new MemoryStream())
{
collection.ToCsv(ms, encoding, culture, writeHeaders, autoFlush, toStringFactory);
return ms.ToArray();
}
}
public static void ToCsv<T>(this IEnumerable<T> collection, Stream stream, Encoding? encoding = null, CultureInfo? culture = null, bool writeHeaders = true, bool autoFlush = false,
Func<CsvMemberInfo<T>, CultureInfo, Func<object?, string?>>? toStringFactory = null)
{
var defEncoding = encoding ?? DefaultEncoding;
var defCulture = culture ?? DefaultCulture ?? CultureInfo.CurrentCulture;
string separator = defCulture.TextInfo.ListSeparator;
if (typeof(IList).IsAssignableFrom(typeof(T)))
{
using (StreamWriter sw = new StreamWriter(stream, defEncoding) { AutoFlush = autoFlush })
{
foreach (IList? row in collection)
{
for (int i = 0; i < row!.Count; i++)
{
var obj = row![i];
var str = EncodeCsv(ConvertToString(obj, null, defCulture), defCulture);
sw.Write(str);
if (i < row!.Count - 1)
sw.Write(separator);
else
sw.WriteLine();
}
}
}
}
else
{
var members = CsvMemberCache<T>.Members;
var toString = members.Select(c => GetToString(defCulture, c, toStringFactory)).ToList();
using (StreamWriter sw = new StreamWriter(stream, defEncoding) { AutoFlush = autoFlush })
{
if (writeHeaders)
sw.WriteLine(members.ToString(m => HandleSpaces(m.MemberInfo.Name), separator));
foreach (var item in collection)
{
for (int i = 0; i < members.Count; i++)
{
var member = members[i];
var toStr = toString[i];
if (!member.IsCollection)
{
if (i != 0)
sw.Write(separator);
var obj = member.MemberEntry.Getter!(item);
var str = EncodeCsv(toStr(obj), defCulture);
sw.Write(str);
}
else
{
var list = (IList?)member.MemberEntry.Getter!(item);
for (int j = 0; j < list!.Count; j++)
{
if (!(i == 0 && j == 0))
sw.Write(separator);
var str = EncodeCsv(toStr(list[j]), defCulture);
sw.Write(str);
}
}
}
sw.WriteLine();
}
}
}
}
static string? EncodeCsv(string? p, CultureInfo culture)
{
if (p == null)
return null;
string separator = culture.TextInfo.ListSeparator;
if (p.Contains(separator) || p.Contains("\"") || p.Contains("\r") || p.Contains("\n"))
{
return "\"" + p.Replace("\"", "\"\"") + "\"";
}
return p;
}
private static Func<object?, string?> GetToString<T>(CultureInfo culture, CsvMemberInfo<T> column, Func<CsvMemberInfo<T>, CultureInfo, Func<object?, string?>>? toStringFactory)
{
if (toStringFactory != null)
{
var result = toStringFactory(column, culture);
if (result != null)
return result;
}
return obj => ConvertToString(obj, column.Format, culture);
}
static string ConvertToString(object? obj, string? format, CultureInfo culture)
{
if (obj == null)
return "";
if (obj is IFormattable f)
return f.ToString(format, culture);
else
return obj!.ToString()!;
}
static string HandleSpaces(string p)
{
return p.Replace("__", "^").Replace("_", " ").Replace("^", "_");
}
public static List<T> ReadFile<T>(string fileName, Encoding? encoding = null, CultureInfo? culture = null, int skipLines = 1, CsvReadOptions<T>? options = null) where T : class, new()
{
encoding = encoding ?? DefaultEncoding;
culture = culture ?? DefaultCulture ?? CultureInfo.CurrentCulture;
using (FileStream fs = File.OpenRead(fileName))
return ReadStream<T>(fs, encoding, culture, skipLines, options).ToList();
}
public static List<T> ReadBytes<T>(byte[] data, Encoding? encoding = null, CultureInfo? culture = null, int skipLines = 1, CsvReadOptions<T>? options = null) where T : class, new()
{
using (MemoryStream ms = new MemoryStream(data))
return ReadStream<T>(ms, encoding, culture, skipLines, options).ToList();
}
public static IEnumerable<T> ReadStream<T>(Stream stream, Encoding? encoding = null, CultureInfo? culture = null, int skipLines = 1, CsvReadOptions<T>? options = null) where T : class, new()
{
encoding = encoding ?? DefaultEncoding;
var defCulture = culture ?? DefaultCulture ?? CultureInfo.CurrentCulture;
var defOptions = options ?? new CsvReadOptions<T>();
var members = CsvMemberCache<T>.Members;
var parsers = members.Select(m => GetParser(defCulture, m, defOptions.ParserFactory)).ToList();
Regex regex = GetRegex(defCulture, defOptions.RegexTimeout);
if (defOptions.AsumeSingleLine)
{
using (StreamReader sr = new StreamReader(stream, encoding))
{
for (int i = 0; i < skipLines; i++)
sr.ReadLine();
var line = skipLines;
while(true)
{
string? csvLine = sr.ReadLine();
if (csvLine == null)
yield break;
Match? m = null;
T? t = null;
try
{
m = regex.Match(csvLine);
if (m.Length > 0)
{
t = ReadObject<T>(m, members, parsers);
}
}
catch(Exception e)
{
e.Data["row"] = line;
if (defOptions.SkipError == null || !defOptions.SkipError(e, m))
throw new ParseCsvException(e);
}
if (t != null)
yield return t;
}
}
}
else
{
using (StreamReader sr = new StreamReader(stream, encoding))
{
string str = sr.ReadToEnd();
var matches = regex.Matches(str).Cast<Match>();
if (skipLines > 0)
matches = matches.Skip(skipLines);
int line = skipLines;
foreach (var m in matches)
{
if (m.Length > 0)
{
T? t = null;
try
{
t = ReadObject<T>(m, members, parsers);
}
catch (Exception e)
{
e.Data["row"] = line;
if (defOptions.SkipError == null || !defOptions.SkipError(e, m))
throw new ParseCsvException(e);
}
if (t != null)
yield return t;
}
line++;
}
}
}
}
public static T ReadLine<T>(string csvLine, CultureInfo? culture = null, CsvReadOptions<T>? options = null)
where T : class, new()
{
var defOptions = options ?? new CsvReadOptions<T>();
var defCulture = culture ?? DefaultCulture ?? CultureInfo.CurrentCulture;
Regex regex = GetRegex(defCulture, defOptions.RegexTimeout);
Match m = regex.Match(csvLine);
var members = CsvMemberCache<T>.Members;
return ReadObject<T>(m,
members,
members.Select(c => GetParser(defCulture, c, defOptions.ParserFactory)).ToList());
}
private static Func<string, object?> GetParser<T>(CultureInfo culture, CsvMemberInfo<T> column, Func<CsvMemberInfo<T>, CultureInfo, Func<string, object?>?>? parserFactory)
{
if (parserFactory != null)
{
var result = parserFactory(column, culture);
if (result != null)
return result;
}
var type = column.IsCollection ? column.MemberInfo.ReturningType().ElementType()! : column.MemberInfo.ReturningType();
return str => ConvertTo(str, type, culture, column.Format);
}
static T ReadObject<T>(Match m, List<CsvMemberInfo<T>> members, List<Func<string, object?>> parsers) where T : new()
{
var vals = m.Groups["val"].Captures;
if (vals.Count < members.Count)
throw new FormatException("Only {0} columns found (instead of {1}) in line: {2}".FormatWith(vals.Count, members.Count, m.Value));
T t = new T();
for (int i = 0; i < members.Count; i++)
{
var member = members[i];
var parser = parsers[i];
string? str = null;
try
{
if (!member.IsCollection)
{
str = DecodeCsv(vals[i].Value);
object? val = parser(str);
member.MemberEntry.Setter!(t, val);
}
else
{
var list = (IList)Activator.CreateInstance(member.MemberInfo.ReturningType())!;
for (int j = i; j < vals.Count; j++)
{
str = DecodeCsv(vals[j].Value);
object? val = parser(str);
list.Add(val);
}
member.MemberEntry.Setter!(t, list);
}
}
catch (Exception e)
{
e.Data["value"] = str;
e.Data["member"] = members[i].MemberInfo.Name;
throw;
}
}
return t;
}
static ConcurrentDictionary<char, Regex> regexCache = new ConcurrentDictionary<char, Regex>();
const string BaseRegex = @"^((?<val>'(?:[^']+|'')*'|[^;\r\n]*))?((?!($|\r\n));(?<val>'(?:[^']+|'')*'|[^;\r\n]*))*($|\r\n)";
static Regex GetRegex(CultureInfo culture, TimeSpan timeout)
{
char separator = culture.TextInfo.ListSeparator.SingleEx();
return regexCache.GetOrAdd(separator, s =>
new Regex(BaseRegex.Replace('\'', '"').Replace(';', s), RegexOptions.Multiline | RegexOptions.ExplicitCapture, timeout));
}
static class CsvMemberCache<T>
{
static CsvMemberCache()
{
var memberEntries = MemberEntryFactory.GenerateList<T>(MemberOptions.Fields | MemberOptions.Properties | MemberOptions.Typed | MemberOptions.Setters | MemberOptions.Getter);
Members = memberEntries.Select((me, i) =>
{
var type = me.MemberInfo.ReturningType();
var isCollection = typeof(IList).IsAssignableFrom(type);
if (isCollection)
{
if (type.IsArray)
throw new InvalidOperationException($"{me.MemberInfo.Name} is an array, use a List<T> instead");
if (i != memberEntries.Count - 1)
throw new InvalidOperationException($"{me.MemberInfo.Name} is of {type} but is not the last member");
}
return new CsvMemberInfo<T>(i, me, me.MemberInfo.GetCustomAttribute<FormatAttribute>()?.Format, isCollection);
}).ToList();
}
public static List<CsvMemberInfo<T>> Members;
}
static string DecodeCsv(string s)
{
if (s.StartsWith("\"") && s.EndsWith("\""))
{
string str = s.Substring(1, s.Length - 2).Replace("\"\"", "\"");
return Regex.Replace(str, "(?<!\r)\n", "\r\n");
}
return s;
}
static object? ConvertTo(string s, Type type, CultureInfo culture, string? format)
{
Type? baseType = Nullable.GetUnderlyingType(type);
if (baseType != null)
{
if (!s.HasText())
return null;
type = baseType;
}
if (type.IsEnum)
return Enum.Parse(type, s);
if (type == typeof(DateTime))
if (format == null)
return DateTime.Parse(s, culture);
else
return DateTime.ParseExact(s, format, culture);
if (type == typeof(Guid))
return Guid.Parse(s);
return Convert.ChangeType(s, type, culture);
}
}
public class CsvReadOptions<T> where T: class
{
public Func<CsvMemberInfo<T>, CultureInfo, Func<string, object?>?>? ParserFactory;
public bool AsumeSingleLine = false;
public Func<Exception, Match?, bool>? SkipError;
public TimeSpan RegexTimeout = Regex.InfiniteMatchTimeout;
}
public class CsvMemberInfo<T>
{
public readonly int Index;
public readonly MemberEntry<T> MemberEntry;
public readonly string? Format;
public readonly bool IsCollection;
public MemberInfo MemberInfo
{
get { return this.MemberEntry.MemberInfo; }
}
internal CsvMemberInfo(int index, MemberEntry<T> memberEntry, string? format, bool isCollection)
{
this.Index = index;
this.MemberEntry = memberEntry;
this.Format = format;
this.IsCollection = isCollection;
}
}
[Serializable]
public class ParseCsvException : Exception
{
public int? Row { get; set; }
public string Member { get; set; }
public string Value { get; set; }
public ParseCsvException(Exception inner) : base(inner.Message, inner)
{
this.Row = (int?)inner.Data["row"];
this.Value = (string)inner.Data["value"]!;
this.Member = (string)inner.Data["member"]!;
}
public override string Message
{
get
{
return $"(Row: {this.Row}, Member: {this.Member}, Value: '{this.Value}') {base.Message})";
}
}
}
}
| |
namespace Gu.SerializationAsserts.Tests
{
using System.Collections;
using System.Collections.Generic;
using Gu.SerializationAsserts.Tests.Dtos;
using NUnit.Framework;
public class FieldsComparerTests
{
[Test]
public void EqualDummies()
{
var d1 = new Dummy { Value = 1 };
var d2 = new Dummy { Value = 1 };
var comparer = FieldComparer<Dummy>.Default;
Assert.IsTrue(comparer.Equals(d1, d1));
Assert.IsTrue(comparer.Equals(d1, d2));
Assert.IsTrue(comparer.Equals(d2, d1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(d1, d1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(d1, d2));
Assert.AreEqual(0, ((IComparer)comparer).Compare(d2, d1));
}
[Test]
public void NotEqualDummies()
{
var d1 = new Dummy { Value = 1 };
var d2 = new Dummy { Value = 2 };
var comparer = FieldComparer<Dummy>.Default;
Assert.IsFalse(comparer.Equals(d1, d2));
Assert.IsFalse(comparer.Equals(d2, d1));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(d1, d2));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(d2, d1));
}
[Test]
public void EqualNestedNoLevels()
{
var l1 = new Level { Value = 2 };
var l2 = new Level { Value = 2 };
var comparer = FieldComparer<Level>.Default;
Assert.IsTrue(comparer.Equals(l1, l1));
Assert.IsTrue(comparer.Equals(l1, l2));
Assert.IsTrue(comparer.Equals(l2, l1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l1, l1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void NotEqualNestedNoLevels()
{
var l1 = new Level { Value = 1 };
var l2 = new Level { Value = 2 };
var comparer = FieldComparer<Level>.Default;
Assert.IsFalse(comparer.Equals(l1, l2));
Assert.IsFalse(comparer.Equals(l2, l1));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void EqualNestedOneLevel1()
{
var l1 = new Level { Value = 2 };
var l2 = new Level { Value = 2 };
var comparer = FieldComparer<Level>.Default;
Assert.IsTrue(comparer.Equals(l1, l1));
Assert.IsTrue(comparer.Equals(l1, l2));
Assert.IsTrue(comparer.Equals(l2, l1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l1, l1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void EqualNestedOneLevel2()
{
var l1 = new Level { Value = 1, Next = new Level { Value = 2 } };
var l2 = new Level { Value = 1, Next = new Level { Value = 2 } };
var comparer = FieldComparer<Level>.Default;
Assert.IsTrue(comparer.Equals(l1, l1));
Assert.IsTrue(comparer.Equals(l1, l2));
Assert.IsTrue(comparer.Equals(l2, l1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l1, l1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void NotEqualNestedOneLevel1()
{
var l1 = new Level { Value = 1, Next = new Level() };
var l2 = new Level { Value = 2, Next = new Level() };
var comparer = FieldComparer<Level>.Default;
Assert.IsFalse(comparer.Equals(l1, l2));
Assert.IsFalse(comparer.Equals(l2, l1));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void NotEqualNestedOneLevel2()
{
var l1 = new Level { Value = 2, Next = null };
var l2 = new Level { Value = 2, Next = new Level() };
var comparer = FieldComparer<Level>.Default;
Assert.IsFalse(comparer.Equals(l1, l2));
Assert.IsFalse(comparer.Equals(l2, l1));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void NotEqualNestedOneLevel3()
{
var l1 = new Level { Value = 1, Next = new Level { Value = 2 } };
var l2 = new Level { Value = 1, Next = new Level { Value = 3 } };
var comparer = FieldComparer<Level>.Default;
Assert.IsFalse(comparer.Equals(l1, l2));
Assert.IsFalse(comparer.Equals(l2, l1));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void EqualIEnumerablesOfDummies()
{
var l1 = new[] { new Dummy { Value = 1 }, new Dummy { Value = 2 } };
var l2 = new[] { new Dummy { Value = 1 }, new Dummy { Value = 2 } };
var comparer = FieldComparer<IEnumerable<Dummy>>.Default;
Assert.IsTrue(comparer.Equals(l1, l1));
Assert.IsTrue(comparer.Equals(l1, l2));
Assert.IsTrue(comparer.Equals(l2, l1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l1, l1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void EqualIEnumerablesOfInts()
{
var l1 = new[] { 1, 2 };
var l2 = new[] { 1, 2 };
var comparer = FieldComparer<IEnumerable<int>>.Default;
Assert.IsTrue(comparer.Equals(l1, l1));
Assert.IsTrue(comparer.Equals(l1, l2));
Assert.IsTrue(comparer.Equals(l2, l1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l1, l1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(0, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void NotEqualIEnumerablesOfDummies()
{
var l1 = new[] { new Dummy { Value = 1 }, new Dummy { Value = 2 } };
var l2 = new[] { new Dummy { Value = 1 }, new Dummy { Value = 5 } };
var comparer = FieldComparer<IEnumerable<Dummy>>.Default;
Assert.IsFalse(comparer.Equals(l1, l2));
Assert.IsFalse(comparer.Equals(l2, l1));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void NotEqualIEnumerablesOfDummiesTwoDiffs()
{
var l1 = new[] { new Dummy { Value = 1 }, new Dummy { Value = 2 } };
var l2 = new[] { new Dummy { Value = 2 }, new Dummy { Value = 5 } };
var comparer = FieldComparer<IEnumerable<Dummy>>.Default;
Assert.IsFalse(comparer.Equals(l1, l2));
Assert.IsFalse(comparer.Equals(l2, l1));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void NotEqualIEnumerablesOfInts()
{
var l1 = new[] { 1, 2 };
var l2 = new[] { 1, 5 };
var comparer = FieldComparer<IEnumerable<int>>.Default;
Assert.IsFalse(comparer.Equals(l1, l2));
Assert.IsFalse(comparer.Equals(l2, l1));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void NotEqualIEnumerablesOfIntsLength()
{
var l1 = new[] { 1, 2 };
var l2 = new[] { 1, 2, 3 };
var comparer = FieldComparer<IEnumerable<int>>.Default;
Assert.IsFalse(comparer.Equals(l1, l2));
Assert.IsFalse(comparer.Equals(l2, l1));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l1, l2));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(l2, l1));
}
[Test]
public void EqualParentChildren()
{
var p1 = new Parent { new Child(1), new Child(2) };
var p2 = new Parent { new Child(1), new Child(2) };
var comparer = FieldComparer<Parent>.Default;
Assert.IsTrue(comparer.Equals(p1, p1));
Assert.IsTrue(comparer.Equals(p1, p2));
Assert.IsTrue(comparer.Equals(p2, p1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(p1, p1));
Assert.AreEqual(0, ((IComparer)comparer).Compare(p1, p2));
Assert.AreEqual(0, ((IComparer)comparer).Compare(p2, p1));
}
[Test]
public void NotEqualParentChildren()
{
var p1 = new Parent { new Child(1), new Child(2) };
var p2 = new Parent { new Child(1), new Child(5) };
var comparer = FieldComparer<Parent>.Default;
Assert.IsFalse(comparer.Equals(p1, p2));
Assert.IsFalse(comparer.Equals(p2, p1));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(p1, p2));
Assert.AreEqual(-1, ((IComparer)comparer).Compare(p2, p1));
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
/**
* INSTRUCTIONS
*
* - Only modify properties in the USER SETTINGS region.
* - All content is loaded from external files (pc_AboutEntry_YourProduct. Use the templates!
*/
/**
* Used to pop up the window on import.
*/
public class pg_AboutWindowSetup : AssetPostprocessor
{
#region Initialization
static void OnPostprocessAllAssets (
string[] importedAssets,
string[] deletedAssets,
string[] movedAssets,
string[] movedFromAssetPaths)
{
string[] entries = System.Array.FindAll(importedAssets, name => name.Contains("pc_AboutEntry") && !name.EndsWith(".meta"));
foreach(string str in entries)
if( pg_AboutWindow.Init(str, false) )
break;
}
// [MenuItem("Edit/Preferences/Clear About Version: " + AboutWindow.PRODUCT_IDENTIFIER)]
// public static void MenuClearVersionPref()
// {
// EditorPrefs.DeleteKey(AboutWindow.PRODUCT_IDENTIFIER);
// }
#endregion
}
public class pg_AboutWindow : EditorWindow
{
/**
* Modify these constants to customize about screen.
*/
#region User Settings
/* Path to the root folder */
const string ABOUT_ROOT = "Assets/ProCore/ProGrids/About";
/**
* Changelog.txt file should follow this format:
*
* | -- Product Name 2.1.0 -
* |
* | # Features
* | - All kinds of awesome stuff
* | - New flux capacitor design achieves time travel at lower velocities.
* | - Dark matter reactor recalibrated.
* |
* | # Bug Fixes
* | - No longer explodes when spacebar is pressed.
* | - Fix rolling issue in Rickmeter.
* |
* | # Changes
* | - Changed Blue to Red.
* | - Enter key now causes explosions.
*
* This path is relative to the PRODUCT_ROOT path.
*
* Note that your changelog may contain multiple entries. Only the top-most
* entry will be displayed.
*/
/**
* Advertisement thumb constructor is:
* new AdvertisementThumb( PathToAdImage : string, URLToPurchase : string, ProductDescription : string )
* Provide as many or few (or none) as desired.
*
* Notes - The http:// part is required. Partial URLs do not work on Mac.
*/
[SerializeField]
public static AdvertisementThumb[] advertisements = new AdvertisementThumb[] {
new AdvertisementThumb( ABOUT_ROOT + "/Images/ProBuilder_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/probuilder/", "Build and Texture Geometry In-Editor"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/ProGrids_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/progrids/", "True Grids and Grid-Snapping"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/ProGroups_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/progroups/", "Hide, Freeze, Group, & Organize"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/Prototype_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/prototype/", "Design and Build With Zero Lag"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickBrush_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickbrush/", "Quickly Add Detail Geometry"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickDecals_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickdecals/", "Add Dirt, Splatters, Posters, etc"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickEdit_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickedit/", "Edit Imported Meshes!"),
};
#endregion
/* Recommend you do not modify these. */
#region Private Fields (automatically populated)
private string AboutEntryPath = "";
private string ProductName = "";
// private string ProductIdentifer = "";
private string ProductVersion = "";
private string ChangelogPath = "";
private string BannerPath = ABOUT_ROOT + "/Images/Banner.png";
const int AD_HEIGHT = 96;
/**
* Struct containing data for use in Advertisement shelf.
*/
[System.Serializable]
public struct AdvertisementThumb
{
public Texture2D image;
public string url;
public string about;
public GUIContent guiContent;
public AdvertisementThumb(string imagePath, string url, string about)
{
guiContent = new GUIContent("", about);
this.image = (Texture2D) AssetDatabase.LoadAssetAtPath(imagePath, typeof(Texture2D));
guiContent.image = this.image;
this.url = url;
this.about = about;
}
}
Texture2D banner;
// populated by first entry in changelog
string changelog = "";
#endregion
#region Init
// [MenuItem("Tools/Test Search About Window", false, 0)]
// public static void MenuInit()
// {
// // this could be slow in large projects?
// string[] allFiles = System.IO.Directory.GetFiles("Assets/", "*.*", System.IO.SearchOption.AllDirectories);
// string[] entries = System.Array.FindAll(allFiles, name => name.Contains("pc_AboutEntry"));
// if(entries.Length > 0)
// AboutWindow.Init(entries[0], true);
// }
/**
* Return true if Init took place, false if not.
*/
public static bool Init (string aboutEntryPath, bool fromMenu)
{
string identifier, version;
if( !GetField(aboutEntryPath, "version: ", out version) || !GetField(aboutEntryPath, "identifier: ", out identifier))
return false;
if(fromMenu || EditorPrefs.GetString(identifier) != version)
{
string tname;
pg_AboutWindow win;
if(!GetField(aboutEntryPath, "name: ", out tname) || !tname.Contains("ProGrids"))
return false;
win = (pg_AboutWindow)EditorWindow.GetWindow(typeof(pg_AboutWindow), true, tname, true);
win.SetAboutEntryPath(aboutEntryPath);
win.ShowUtility();
EditorPrefs.SetString(identifier, version);
return true;
}
else
{
return false;
}
}
public void OnEnable()
{
banner = (Texture2D)AssetDatabase.LoadAssetAtPath(BannerPath, typeof(Texture2D));
// With Unity 4 (on PC) if you have different values for minSize and maxSize,
// they do not apply restrictions to window size.
this.minSize = new Vector2(banner.width + 12, banner.height * 7);
this.maxSize = new Vector2(banner.width + 12, banner.height * 7);
}
public void SetAboutEntryPath(string path)
{
AboutEntryPath = path;
PopulateDataFields(AboutEntryPath);
}
#endregion
#region GUI
Color LinkColor = new Color(0f, .682f, .937f, 1f);
GUIStyle boldTextStyle,
headerTextStyle,
linkTextStyle;
GUIStyle advertisementStyle;
Vector2 scroll = Vector2.zero, adScroll = Vector2.zero;
// int mm = 32;
void OnGUI()
{
headerTextStyle = headerTextStyle ?? new GUIStyle( EditorStyles.boldLabel );//GUI.skin.label);
headerTextStyle.fontSize = 16;
linkTextStyle = linkTextStyle ?? new GUIStyle( GUI.skin.label );//GUI.skin.label);
linkTextStyle.normal.textColor = LinkColor;
linkTextStyle.alignment = TextAnchor.MiddleLeft;
boldTextStyle = boldTextStyle ?? new GUIStyle( GUI.skin.label );//GUI.skin.label);
boldTextStyle.fontStyle = FontStyle.Bold;
boldTextStyle.alignment = TextAnchor.MiddleLeft;
// #if UNITY_4
// richTextLabel.richText = true;
// #endif
advertisementStyle = advertisementStyle ?? new GUIStyle(GUI.skin.button);
advertisementStyle.normal.background = null;
if(banner != null)
GUILayout.Label(banner);
// mm = EditorGUI.IntField(new Rect(Screen.width - 200, 100, 200, 18), "W: ", mm);
{
GUILayout.Label("Thank you for purchasing " + ProductName + ". Your support allows us to keep developing this and future tools for everyone.", EditorStyles.wordWrappedLabel);
GUILayout.Space(2);
GUILayout.Label("Read these quick \"ProTips\" before starting:", headerTextStyle);
GUILayout.BeginHorizontal();
GUILayout.Label("1) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16));
GUILayout.Label("Register", boldTextStyle, GUILayout.MinWidth(58), GUILayout.MaxWidth(58));
GUILayout.Label("for instant email updates, send your invoice # to", GUILayout.MinWidth(284), GUILayout.MaxWidth(284));
if( GUILayout.Button("[email protected]", linkTextStyle, GUILayout.MinWidth(142), GUILayout.MaxWidth(142)) )
Application.OpenURL("mailto:[email protected]?subject=Sign me up for the Beta!");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("2) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16));
GUILayout.Label("Report bugs", boldTextStyle, GUILayout.MinWidth(82), GUILayout.MaxWidth(82));
GUILayout.Label("to the ProCore Forum at", GUILayout.MinWidth(144), GUILayout.MaxWidth(144));
if( GUILayout.Button("www.procore3d.com/forum", linkTextStyle, GUILayout.MinWidth(162), GUILayout.MaxWidth(162)) )
Application.OpenURL("http://www.procore3d.com/forum");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("3) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16));
GUILayout.Label("Customize!", boldTextStyle, GUILayout.MinWidth(74), GUILayout.MaxWidth(74));
GUILayout.Label("Click on \"Edit > Preferences\" then \"" + ProductName + "\"", GUILayout.MinWidth(276), GUILayout.MaxWidth(276));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("4) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16));
GUILayout.Label("Documentation", boldTextStyle, GUILayout.MinWidth(102), GUILayout.MaxWidth(102));
GUILayout.Label("Tutorials, & more info:", GUILayout.MinWidth(132), GUILayout.MaxWidth(132));
if( GUILayout.Button("www.procore3d.com/" + ProductName.ToLower(), linkTextStyle, GUILayout.MinWidth(190), GUILayout.MaxWidth(190)) )
Application.OpenURL("http://www.procore3d.com/" + ProductName.ToLower());
GUILayout.EndHorizontal();
GUILayout.Space(4);
GUILayout.BeginHorizontal(GUILayout.MaxWidth(50));
GUILayout.Label("Links:", boldTextStyle);
linkTextStyle.fontStyle = FontStyle.Italic;
linkTextStyle.alignment = TextAnchor.MiddleCenter;
if( GUILayout.Button("procore3d.com", linkTextStyle))
Application.OpenURL("http://www.procore3d.com");
if( GUILayout.Button("facebook", linkTextStyle))
Application.OpenURL("http://www.facebook.com/probuilder3d");
if( GUILayout.Button("twitter", linkTextStyle))
Application.OpenURL("http://www.twitter.com/probuilder3d");
linkTextStyle.fontStyle = FontStyle.Normal;
GUILayout.EndHorizontal();
GUILayout.Space(4);
}
HorizontalLine();
// always bold the first line (cause it's the version info stuff)
scroll = EditorGUILayout.BeginScrollView(scroll);
GUILayout.Label(ProductName + " | version: " + ProductVersion, EditorStyles.boldLabel);
GUILayout.Label("\n" + changelog);
EditorGUILayout.EndScrollView();
HorizontalLine();
GUILayout.Label("More ProCore Products", EditorStyles.boldLabel);
int pad = advertisements.Length * AD_HEIGHT > Screen.width ? 22 : 6;
adScroll = EditorGUILayout.BeginScrollView(adScroll, false, false, GUILayout.MinHeight(AD_HEIGHT + pad), GUILayout.MaxHeight(AD_HEIGHT + pad));
GUILayout.BeginHorizontal();
foreach(AdvertisementThumb ad in advertisements)
{
if(ad.url.ToLower().Contains(ProductName.ToLower()))
continue;
if(GUILayout.Button(ad.guiContent, advertisementStyle,
GUILayout.MinWidth(AD_HEIGHT), GUILayout.MaxWidth(AD_HEIGHT),
GUILayout.MinHeight(AD_HEIGHT), GUILayout.MaxHeight(AD_HEIGHT)))
{
Application.OpenURL(ad.url);
}
}
GUILayout.EndHorizontal();
EditorGUILayout.EndScrollView();
/* shill other products */
}
/**
* Draw a horizontal line across the screen and update the guilayout.
*/
void HorizontalLine()
{
Rect r = GUILayoutUtility.GetLastRect();
Color og = GUI.backgroundColor;
GUI.backgroundColor = Color.black;
GUI.Box(new Rect(0f, r.y + r.height + 2, Screen.width, 2f), "");
GUI.backgroundColor = og;
GUILayout.Space(6);
}
#endregion
#region Data Parsing
/* rich text ain't wuurkin' in unity 3.5 */
const string RemoveBraketsRegex = "(\\<.*?\\>)";
/**
* Open VersionInfo and Changelog and pull out text to populate vars for OnGUI to display.
*/
void PopulateDataFields(string entryPath)
{
/* Get data from VersionInfo.txt */
TextAsset versionInfo = (TextAsset)AssetDatabase.LoadAssetAtPath( entryPath, typeof(TextAsset));
ProductName = "";
// ProductIdentifer = "";
ProductVersion = "";
ChangelogPath = "";
if(versionInfo != null)
{
string[] txt = versionInfo.text.Split('\n');
foreach(string cheese in txt)
{
if(cheese.StartsWith("name:"))
ProductName = cheese.Replace("name: ", "").Trim();
else
if(cheese.StartsWith("version:"))
ProductVersion = cheese.Replace("version: ", "").Trim();
else
if(cheese.StartsWith("changelog:"))
ChangelogPath = cheese.Replace("changelog: ", "").Trim();
}
}
// notes = notes.Trim();
/* Get first entry in changelog.txt */
TextAsset changelogText = (TextAsset)AssetDatabase.LoadAssetAtPath( ChangelogPath, typeof(TextAsset));
if(changelogText)
{
string[] split = changelogText.text.Split( new string[] {"--"}, System.StringSplitOptions.RemoveEmptyEntries );
StringBuilder sb = new StringBuilder();
string[] newLineSplit = split[0].Trim().Split('\n');
for(int i = 2; i < newLineSplit.Length; i++)
sb.AppendLine(newLineSplit[i]);
changelog = sb.ToString();
}
}
private static bool GetField(string path, string field, out string value)
{
TextAsset entry = (TextAsset)AssetDatabase.LoadAssetAtPath(path, typeof(TextAsset));
value = "";
if(!entry) return false;
foreach(string str in entry.text.Split('\n'))
{
if(str.Contains(field))
{
value = str.Replace(field, "").Trim();
return true;
}
}
return false;
}
#endregion
}
| |
// Copyright 2020, 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.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FirebaseAdmin.Tests;
using FirebaseAdmin.Util;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Json;
using Newtonsoft.Json.Linq;
using Xunit;
namespace FirebaseAdmin.Auth.Multitenancy.Tests
{
public class TenantManagerTest
{
public static readonly IEnumerable<object[]> TestConfigs = new List<object[]>()
{
new object[] { TestConfig.Default },
new object[] { TestConfig.WithEmulator },
};
private const string TenantResponse = @"{
""name"": ""projects/project1/tenants/tenant1"",
""displayName"": ""Test Tenant"",
""allowPasswordSignup"": true,
""enableEmailLinkSignin"": true
}";
private const string TenantNotFoundResponse = @"{
""error"": {
""message"": ""TENANT_NOT_FOUND""
}
}";
private const string UnknownErrorResponse = @"{
""error"": {
""message"": ""UNKNOWN""
}
}";
private static readonly IList<string> ListTenantsResponses = new List<string>()
{
$@"{{
""nextPageToken"": ""token"",
""tenants"": [
{TenantResponse},
{TenantResponse},
{TenantResponse}
]
}}",
$@"{{
""tenants"": [
{TenantResponse},
{TenantResponse}
]
}}",
};
public static IEnumerable<object[]> InvalidStrings()
{
var strings = new List<string>() { null, string.Empty };
return TestConfigs.SelectMany(
config => strings, (config, str) => config.Append(str).ToArray());
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task GetTenant(TestConfig config)
{
var handler = new MockMessageHandler()
{
Response = TenantResponse,
};
var auth = config.CreateFirebaseAuth(handler);
var provider = await auth.TenantManager.GetTenantAsync("tenant1");
AssertTenant(provider);
Assert.Equal(1, handler.Requests.Count);
var request = handler.Requests[0];
Assert.Equal(HttpMethod.Get, request.Method);
config.AssertRequest("tenants/tenant1", request);
}
[Theory]
[MemberData(nameof(InvalidStrings))]
public async Task GetTenantNoId(TestConfig config, string tenantId)
{
var auth = config.CreateFirebaseAuth();
var exception = await Assert.ThrowsAsync<ArgumentException>(
() => auth.TenantManager.GetTenantAsync(tenantId));
Assert.Equal("Tenant ID cannot be null or empty.", exception.Message);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task GetTenantNotFoundError(TestConfig config)
{
var handler = new MockMessageHandler()
{
StatusCode = HttpStatusCode.NotFound,
Response = TenantNotFoundResponse,
};
var auth = config.CreateFirebaseAuth(handler);
var exception = await Assert.ThrowsAsync<FirebaseAuthException>(
() => auth.TenantManager.GetTenantAsync("tenant1"));
Assert.Equal(ErrorCode.NotFound, exception.ErrorCode);
Assert.Equal(AuthErrorCode.TenantNotFound, exception.AuthErrorCode);
Assert.Equal(
"No tenant found for the given identifier (TENANT_NOT_FOUND).",
exception.Message);
Assert.NotNull(exception.HttpResponse);
Assert.Null(exception.InnerException);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task CreateTenant(TestConfig config)
{
var handler = new MockMessageHandler()
{
Response = TenantResponse,
};
var auth = config.CreateFirebaseAuth(handler);
var args = new TenantArgs()
{
DisplayName = "Test Tenant",
PasswordSignUpAllowed = true,
EmailLinkSignInEnabled = true,
};
var provider = await auth.TenantManager.CreateTenantAsync(args);
AssertTenant(provider);
Assert.Equal(1, handler.Requests.Count);
var request = handler.Requests[0];
Assert.Equal(HttpMethod.Post, request.Method);
config.AssertRequest("tenants", request);
var body = NewtonsoftJsonSerializer.Instance.Deserialize<JObject>(
handler.LastRequestBody);
Assert.Equal(3, body.Count);
Assert.Equal("Test Tenant", body["displayName"]);
Assert.True((bool)body["allowPasswordSignup"]);
Assert.True((bool)body["enableEmailLinkSignin"]);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task CreateTenantMinimal(TestConfig config)
{
var handler = new MockMessageHandler()
{
Response = TenantResponse,
};
var auth = config.CreateFirebaseAuth(handler);
var provider = await auth.TenantManager.CreateTenantAsync(new TenantArgs());
AssertTenant(provider);
Assert.Equal(1, handler.Requests.Count);
var request = handler.Requests[0];
Assert.Equal(HttpMethod.Post, request.Method);
config.AssertRequest("tenants", request);
var body = NewtonsoftJsonSerializer.Instance.Deserialize<JObject>(
handler.LastRequestBody);
Assert.Empty(body);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task CreateTenantNullArgs(TestConfig config)
{
var auth = config.CreateFirebaseAuth();
await Assert.ThrowsAsync<ArgumentNullException>(
() => auth.TenantManager.CreateTenantAsync(null));
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task CreateTenantError(TestConfig config)
{
var handler = new MockMessageHandler()
{
StatusCode = HttpStatusCode.InternalServerError,
Response = UnknownErrorResponse,
};
var auth = config.CreateFirebaseAuth(handler);
var exception = await Assert.ThrowsAsync<FirebaseAuthException>(
() => auth.TenantManager.CreateTenantAsync(new TenantArgs()));
Assert.Equal(ErrorCode.Internal, exception.ErrorCode);
Assert.Null(exception.AuthErrorCode);
Assert.StartsWith(
"Unexpected HTTP response with status: 500 (InternalServerError)",
exception.Message);
Assert.NotNull(exception.HttpResponse);
Assert.Null(exception.InnerException);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task UpdateTenant(TestConfig config)
{
var handler = new MockMessageHandler()
{
Response = TenantResponse,
};
var auth = config.CreateFirebaseAuth(handler);
var args = new TenantArgs()
{
DisplayName = "Test Tenant",
PasswordSignUpAllowed = true,
EmailLinkSignInEnabled = true,
};
var provider = await auth.TenantManager.UpdateTenantAsync("tenant1", args);
AssertTenant(provider);
Assert.Equal(1, handler.Requests.Count);
var request = handler.Requests[0];
Assert.Equal(HttpUtils.Patch, request.Method);
var mask = "allowPasswordSignup,displayName,enableEmailLinkSignin";
config.AssertRequest($"tenants/tenant1?updateMask={mask}", request);
var body = NewtonsoftJsonSerializer.Instance.Deserialize<JObject>(
handler.LastRequestBody);
Assert.Equal(3, body.Count);
Assert.Equal("Test Tenant", body["displayName"]);
Assert.True((bool)body["allowPasswordSignup"]);
Assert.True((bool)body["enableEmailLinkSignin"]);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task UpdateTenantMinimal(TestConfig config)
{
var handler = new MockMessageHandler()
{
Response = TenantResponse,
};
var auth = config.CreateFirebaseAuth(handler);
var args = new TenantArgs()
{
DisplayName = "Test Tenant",
};
var provider = await auth.TenantManager.UpdateTenantAsync("tenant1", args);
AssertTenant(provider);
Assert.Equal(1, handler.Requests.Count);
var request = handler.Requests[0];
Assert.Equal(HttpUtils.Patch, request.Method);
config.AssertRequest("tenants/tenant1?updateMask=displayName", request);
var body = NewtonsoftJsonSerializer.Instance.Deserialize<JObject>(
handler.LastRequestBody);
Assert.Single(body);
Assert.Equal("Test Tenant", body["displayName"]);
}
[Theory]
[MemberData(nameof(InvalidStrings))]
public async Task UpdateTenantNoId(TestConfig config, string tenantId)
{
var auth = config.CreateFirebaseAuth();
var args = new TenantArgs()
{
DisplayName = "Test Tenant",
};
var exception = await Assert.ThrowsAsync<ArgumentException>(
() => auth.TenantManager.UpdateTenantAsync(tenantId, args));
Assert.Equal("Tenant ID cannot be null or empty.", exception.Message);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task UpdateTenantNullArgs(TestConfig config)
{
var auth = config.CreateFirebaseAuth();
await Assert.ThrowsAsync<ArgumentNullException>(
() => auth.TenantManager.UpdateTenantAsync("tenant1", null));
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task UpdateTenantEmptyArgs(TestConfig config)
{
var auth = config.CreateFirebaseAuth();
await Assert.ThrowsAsync<ArgumentException>(
() => auth.TenantManager.UpdateTenantAsync("tenant1", new TenantArgs()));
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task UpdateTenantError(TestConfig config)
{
var handler = new MockMessageHandler()
{
StatusCode = HttpStatusCode.NotFound,
Response = TenantNotFoundResponse,
};
var auth = config.CreateFirebaseAuth(handler);
var args = new TenantArgs()
{
DisplayName = "Test Tenant",
};
var exception = await Assert.ThrowsAsync<FirebaseAuthException>(
() => auth.TenantManager.UpdateTenantAsync("tenant1", args));
Assert.Equal(ErrorCode.NotFound, exception.ErrorCode);
Assert.Equal(AuthErrorCode.TenantNotFound, exception.AuthErrorCode);
Assert.Equal(
"No tenant found for the given identifier (TENANT_NOT_FOUND).",
exception.Message);
Assert.NotNull(exception.HttpResponse);
Assert.Null(exception.InnerException);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task DeleteTenant(TestConfig config)
{
var handler = new MockMessageHandler()
{
Response = TenantResponse,
};
var auth = config.CreateFirebaseAuth(handler);
await auth.TenantManager.DeleteTenantAsync("tenant1");
Assert.Equal(1, handler.Requests.Count);
var request = handler.Requests[0];
Assert.Equal(HttpMethod.Delete, request.Method);
config.AssertRequest("tenants/tenant1", request);
}
[Theory]
[MemberData(nameof(InvalidStrings))]
public async Task DeleteTenantNoId(TestConfig config, string tenantId)
{
var auth = config.CreateFirebaseAuth();
var exception = await Assert.ThrowsAsync<ArgumentException>(
() => auth.TenantManager.DeleteTenantAsync(tenantId));
Assert.Equal("Tenant ID cannot be null or empty.", exception.Message);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task DeleteTenantNotFoundError(TestConfig config)
{
var handler = new MockMessageHandler()
{
StatusCode = HttpStatusCode.NotFound,
Response = TenantNotFoundResponse,
};
var auth = config.CreateFirebaseAuth(handler);
var exception = await Assert.ThrowsAsync<FirebaseAuthException>(
() => auth.TenantManager.DeleteTenantAsync("tenant1"));
Assert.Equal(ErrorCode.NotFound, exception.ErrorCode);
Assert.Equal(AuthErrorCode.TenantNotFound, exception.AuthErrorCode);
Assert.Equal(
"No tenant found for the given identifier (TENANT_NOT_FOUND).",
exception.Message);
Assert.NotNull(exception.HttpResponse);
Assert.Null(exception.InnerException);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task ListTenants(TestConfig config)
{
var handler = new MockMessageHandler()
{
Response = ListTenantsResponses,
};
var auth = config.CreateFirebaseAuth(handler);
var tenants = new List<Tenant>();
var pagedEnumerable = auth.TenantManager.ListTenantsAsync(null);
var enumerator = pagedEnumerable.GetAsyncEnumerator();
while (await enumerator.MoveNextAsync())
{
tenants.Add(enumerator.Current);
}
Assert.Equal(5, tenants.Count);
Assert.All(tenants, AssertTenant);
Assert.Equal(2, handler.Requests.Count);
config.AssertRequest("tenants?pageSize=100", handler.Requests[0]);
config.AssertRequest("tenants?pageSize=100&pageToken=token", handler.Requests[1]);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public void ListTenantsForEach(TestConfig config)
{
var handler = new MockMessageHandler()
{
Response = ListTenantsResponses,
};
var auth = config.CreateFirebaseAuth(handler);
var tenants = new List<Tenant>();
var pagedEnumerable = auth.TenantManager.ListTenantsAsync(null);
foreach (var tenant in pagedEnumerable.ToEnumerable())
{
tenants.Add(tenant);
}
Assert.Equal(5, tenants.Count);
Assert.All(tenants, AssertTenant);
Assert.Equal(2, handler.Requests.Count);
config.AssertRequest("tenants?pageSize=100", handler.Requests[0]);
config.AssertRequest("tenants?pageSize=100&pageToken=token", handler.Requests[1]);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task ListTenantsByPages(TestConfig config)
{
var handler = new MockMessageHandler()
{
Response = ListTenantsResponses,
};
var auth = config.CreateFirebaseAuth(handler);
var tenants = new List<Tenant>();
// Read page 1.
var pagedEnumerable = auth.TenantManager.ListTenantsAsync(null);
var tenantsPage = await pagedEnumerable.ReadPageAsync(3);
Assert.Equal(3, tenantsPage.Count());
Assert.Equal("token", tenantsPage.NextPageToken);
Assert.Single(handler.Requests);
config.AssertRequest("tenants?pageSize=3", handler.Requests[0]);
tenants.AddRange(tenantsPage);
// Read page 2.
pagedEnumerable = auth.TenantManager.ListTenantsAsync(new ListTenantsOptions()
{
PageToken = tenantsPage.NextPageToken,
});
tenantsPage = await pagedEnumerable.ReadPageAsync(3);
Assert.Equal(2, tenantsPage.Count());
Assert.Null(tenantsPage.NextPageToken);
Assert.Equal(2, handler.Requests.Count);
config.AssertRequest("tenants?pageSize=3&pageToken=token", handler.Requests[1]);
tenants.AddRange(tenantsPage);
Assert.Equal(5, tenants.Count);
Assert.All(tenants, AssertTenant);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task ListTenantsAsRawResponses(TestConfig config)
{
var handler = new MockMessageHandler()
{
Response = ListTenantsResponses,
};
var auth = config.CreateFirebaseAuth(handler);
var tenants = new List<Tenant>();
var tokens = new List<string>();
var pagedEnumerable = auth.TenantManager.ListTenantsAsync(null);
var responses = pagedEnumerable.AsRawResponses().GetAsyncEnumerator();
while (await responses.MoveNextAsync())
{
tenants.AddRange(responses.Current.Tenants);
tokens.Add(responses.Current.NextPageToken);
Assert.Equal(tokens.Count, handler.Requests.Count);
}
Assert.Equal(new List<string>() { "token", null }, tokens);
Assert.Equal(5, tenants.Count);
Assert.All(tenants, AssertTenant);
Assert.Equal(2, handler.Requests.Count);
config.AssertRequest("tenants?pageSize=100", handler.Requests[0]);
config.AssertRequest("tenants?pageSize=100&pageToken=token", handler.Requests[1]);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public void ListTenantsOptions(TestConfig config)
{
var handler = new MockMessageHandler()
{
Response = ListTenantsResponses,
};
var auth = config.CreateFirebaseAuth(handler);
var tenants = new List<Tenant>();
var customOptions = new ListTenantsOptions()
{
PageSize = 3,
PageToken = "custom-token",
};
var pagedEnumerable = auth.TenantManager.ListTenantsAsync(customOptions);
foreach (var tenant in pagedEnumerable.ToEnumerable())
{
tenants.Add(tenant);
}
Assert.Equal(5, tenants.Count);
Assert.All(tenants, AssertTenant);
Assert.Equal(2, handler.Requests.Count);
config.AssertRequest("tenants?pageSize=3&pageToken=custom-token", handler.Requests[0]);
config.AssertRequest("tenants?pageSize=3&pageToken=token", handler.Requests[1]);
}
[Theory]
[ClassData(typeof(TenantManagerTest.InvalidListOptions))]
public void ListInvalidOptions(TestConfig config, ListTenantsOptions options, string expected)
{
var handler = new MockMessageHandler()
{
Response = ListTenantsResponses,
};
var auth = config.CreateFirebaseAuth(handler);
var exception = Assert.Throws<ArgumentException>(
() => auth.TenantManager.ListTenantsAsync(options));
Assert.Equal(expected, exception.Message);
Assert.Empty(handler.Requests);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task ListReadPageSizeTooLarge(TestConfig config)
{
var handler = new MockMessageHandler()
{
Response = ListTenantsResponses,
};
var auth = config.CreateFirebaseAuth(handler);
var pagedEnumerable = auth.TenantManager.ListTenantsAsync(null);
await Assert.ThrowsAsync<ArgumentException>(
async () => await pagedEnumerable.ReadPageAsync(101));
Assert.Empty(handler.Requests);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public void AuthForTenant(TestConfig config)
{
var auth = config.CreateFirebaseAuth();
var tenantAwareAuth = auth.TenantManager.AuthForTenant("tenant1");
Assert.Equal("tenant1", tenantAwareAuth.TenantId);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public void AuthForTenantCaching(TestConfig config)
{
var auth = config.CreateFirebaseAuth();
var tenantAwareAuth1 = auth.TenantManager.AuthForTenant("tenant1");
var tenantAwareAuth2 = auth.TenantManager.AuthForTenant("tenant1");
var tenantAwareAuth3 = auth.TenantManager.AuthForTenant("tenant2");
Assert.Same(tenantAwareAuth1, tenantAwareAuth2);
Assert.NotSame(tenantAwareAuth1, tenantAwareAuth3);
}
[Theory]
[MemberData(nameof(InvalidStrings))]
public void AuthForTenantNoTenantId(TestConfig config, string tenantId)
{
var auth = config.CreateFirebaseAuth();
var exception = Assert.Throws<ArgumentException>(
() => auth.TenantManager.AuthForTenant(tenantId));
Assert.Equal("Tenant ID cannot be null or empty.", exception.Message);
}
[Theory]
[MemberData(nameof(TestConfigs))]
public async Task UseAfterDelete(TestConfig config)
{
var auth = config.CreateFirebaseAuth();
var tenantManager = auth.TenantManager;
(auth as IFirebaseService).Delete();
await Assert.ThrowsAsync<ObjectDisposedException>(
() => tenantManager.GetTenantAsync("tenant1"));
Assert.Throws<ObjectDisposedException>(
() => tenantManager.AuthForTenant("tenant1"));
}
private static void AssertTenant(Tenant tenant)
{
Assert.Equal("tenant1", tenant.TenantId);
Assert.Equal("Test Tenant", tenant.DisplayName);
Assert.True(tenant.PasswordSignUpAllowed);
Assert.True(tenant.EmailLinkSignInEnabled);
}
public class TestConfig
{
private static readonly string IdToolkitUrl = $"identitytoolkit.googleapis.com/v2/projects/project1";
private static readonly string ClientVersion =
$"DotNet/Admin/{FirebaseApp.GetSdkVersion()}";
private static readonly GoogleCredential MockCredential =
GoogleCredential.FromAccessToken("test-token");
private TestConfig(string emulatorHost = null)
{
this.EmulatorHost = emulatorHost;
}
public static TestConfig Default => new TestConfig();
public static TestConfig WithEmulator => new TestConfig("localhost:9090");
internal string EmulatorHost { get; }
internal FirebaseAuth CreateFirebaseAuth(HttpMessageHandler handler = null)
{
var tenantManager = new TenantManager(new TenantManager.Args
{
Credential = MockCredential,
ProjectId = "project1",
ClientFactory = new MockHttpClientFactory(handler ?? new MockMessageHandler()),
RetryOptions = RetryOptions.NoBackOff,
EmulatorHost = this.EmulatorHost,
});
var args = FirebaseAuth.Args.CreateDefault();
args.TenantManager = new Lazy<TenantManager>(tenantManager);
return new FirebaseAuth(args);
}
internal void AssertRequest(
string expectedSuffix, MockMessageHandler.IncomingRequest request)
{
if (this.EmulatorHost != null)
{
var expectedUrl = $"http://{this.EmulatorHost}/{IdToolkitUrl}/{expectedSuffix}";
Assert.Equal(expectedUrl, request.Url.ToString());
Assert.Equal("Bearer owner", request.Headers.Authorization.ToString());
}
else
{
var expectedUrl = $"https://{IdToolkitUrl}/{expectedSuffix}";
Assert.Equal(expectedUrl, request.Url.ToString());
Assert.Equal("Bearer test-token", request.Headers.Authorization.ToString());
}
Assert.Contains(ClientVersion, request.Headers.GetValues("X-Client-Version"));
}
}
public class InvalidListOptions : IEnumerable<object[]>
{
// {
// 1st element: InvalidInput,
// 2nd element: ExpectedError,
// }
private static readonly List<object[]> TestCases = new List<object[]>
{
new object[]
{
new ListTenantsOptions()
{
PageSize = 101,
},
"Page size must not exceed 100.",
},
new object[]
{
new ListTenantsOptions()
{
PageSize = 0,
},
"Page size must be positive.",
},
new object[]
{
new ListTenantsOptions()
{
PageSize = -1,
},
"Page size must be positive.",
},
new object[]
{
new ListTenantsOptions()
{
PageToken = string.Empty,
},
"Page token must not be empty.",
},
};
public IEnumerator<object[]> GetEnumerator()
{
return TestConfigs
.SelectMany(config => TestCases, (config, testCase) => config.Concat(testCase).ToArray())
.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System.IO;
[System.Serializable]
public class MegaPCVert
{
public int[] indices;
public Vector3[] points;
}
public enum MegaInterpMethod
{
None,
Linear,
Bez,
}
public enum MegaBlendAnimMode
{
Replace,
Additive,
}
[AddComponentMenu("Modifiers/Point Cache")]
public class MegaPointCache : MegaModifier
{
public float time = 0.0f;
public bool animated = false;
public float speed = 1.0f;
public float maxtime = 1.0f;
public MegaRepeatMode LoopMode = MegaRepeatMode.PingPong;
public MegaInterpMethod interpMethod = MegaInterpMethod.Linear;
public MegaPCVert[] Verts;
public float weight = 1.0f;
public bool framedelay = true;
public MegaBlendAnimMode blendMode = MegaBlendAnimMode.Additive; // local space
int numPoints; // Number of points per sample
float startFrame; // Corresponds to the UI value of the same name.
float sampleRate; // Corresponds to the UI value of the same name.
int numSamples; // Defines how many samples are stored in the file.
float t;
float alpha = 0.0f;
float dalpha = 0.0f;
int sindex;
int sindex1;
public bool showmapping = false;
public float mappingSize = 0.001f;
public int mapStart = 0;
public int mapEnd = 0;
public bool havemapping = false;
public float scl = 1.0f;
public bool flipyz = false;
public bool negx = false;
public bool negz = false;
public float adjustscl = 1.0f;
public Vector3 adjustoff = Vector3.zero;
public override string ModName() { return "Point Cache"; }
public override string GetHelpURL() { return "?page_id=1335"; }
void LinearAbs(MegaModifiers mc, int start, int end)
{
for ( int i = start; i < end; i++ )
{
Vector3 p = Verts[i].points[sindex];
Vector3 p1 = Verts[i].points[sindex1];
p.x = p.x + ((p1.x - p.x) * dalpha);
p.y = p.y + ((p1.y - p.y) * dalpha);
p.z = p.z + ((p1.z - p.z) * dalpha);
for ( int v = 0; v < Verts[i].indices.Length; v++ )
sverts[Verts[i].indices[v]] = p;
}
}
void LinearAbsWeighted(MegaModifiers mc, int start, int end)
{
for ( int i = start; i < end; i++ )
{
Vector3 p = Verts[i].points[sindex];
Vector3 p1 = Verts[i].points[sindex1];
p.x = p.x + ((p1.x - p.x) * dalpha);
p.y = p.y + ((p1.y - p.y) * dalpha);
p.z = p.z + ((p1.z - p.z) * dalpha);
float w = mc.selection[Verts[i].indices[0]]; //[wc];
p1 = verts[Verts[i].indices[0]];
p = p1 + ((p - p1) * w);
for ( int v = 0; v < Verts[i].indices.Length; v++ )
sverts[Verts[i].indices[v]] = p;
}
}
void LinearRel(MegaModifiers mc, int start, int end)
{
for ( int i = start; i < end; i++ )
{
int ix = Verts[i].indices[0];
Vector3 basep = mc.verts[ix];
Vector3 p = Verts[i].points[sindex];
Vector3 p1 = Verts[i].points[sindex1];
p.x += (((p1.x - p.x) * dalpha) - basep.x); // * weight; //mc.verts[ix].x;
p.y += (((p1.y - p.y) * dalpha) - basep.y); // * weight; //mc.verts[ix].y;
p.z += (((p1.z - p.z) * dalpha) - basep.z); // * weight; //mc.verts[ix].z;
p1 = verts[Verts[i].indices[0]];
p.x = p1.x + (p.x * weight);
p.y = p1.y + (p.y * weight);
p.z = p1.z + (p.z * weight);
for ( int v = 0; v < Verts[i].indices.Length; v++ )
{
int idx = Verts[i].indices[v];
sverts[idx] = p;
}
}
}
void LinearRelWeighted(MegaModifiers mc, int start, int end)
{
for ( int i = start; i < end; i++ )
{
int ix = Verts[i].indices[0];
Vector3 basep = verts[ix];
Vector3 p = Verts[i].points[sindex];
Vector3 p1 = Verts[i].points[sindex1];
p.x += (((p1.x - p.x) * dalpha) - basep.x); // * weight; //mc.verts[ix].x;
p.y += (((p1.y - p.y) * dalpha) - basep.y); // * weight; //mc.verts[ix].y;
p.z += (((p1.z - p.z) * dalpha) - basep.z); // * weight; //mc.verts[ix].z;
float w = mc.selection[Verts[i].indices[0]] * weight; //[wc];
p1 = verts[Verts[i].indices[0]];
p.x = p1.x + (p.x * w);
p.y = p1.y + (p.y * w);
p.z = p1.z + (p.z * w);
for ( int v = 0; v < Verts[i].indices.Length; v++ )
{
int idx = Verts[i].indices[v];
sverts[idx] = p;
}
}
}
void NoInterpAbs(MegaModifiers mc, int start, int end)
{
for ( int i = start; i < end; i++ )
{
Vector3 p = Verts[i].points[sindex];
for ( int v = 0; v < Verts[i].indices.Length; v++ )
sverts[Verts[i].indices[v]] = p;
}
}
void NoInterpAbsWeighted(MegaModifiers mc, int start, int end)
{
for ( int i = start; i < end; i++ )
{
Vector3 p = Verts[i].points[sindex];
float w = mc.selection[Verts[i].indices[0]] * weight; //[wc];
Vector3 p1 = verts[Verts[i].indices[0]];
p = p1 + ((p - p1) * w);
for ( int v = 0; v < Verts[i].indices.Length; v++ )
sverts[Verts[i].indices[v]] = p;
}
}
void NoInterpRel(MegaModifiers mc, int start, int end)
{
for ( int i = start; i < end; i++ )
{
int ix = Verts[i].indices[0];
Vector3 p = Verts[i].points[sindex] - verts[ix];
Vector3 p1 = verts[Verts[i].indices[0]];
p.x = p1.x + (p.x * weight);
p.y = p1.y + (p.y * weight);
p.z = p1.z + (p.z * weight);
for ( int v = 0; v < Verts[i].indices.Length; v++ )
{
int idx = Verts[i].indices[v];
sverts[idx] = p;
}
}
}
void NoInterpRelWeighted(MegaModifiers mc, int start, int end)
{
for ( int i = start; i < end; i++ )
{
int ix = Verts[i].indices[0];
Vector3 p = Verts[i].points[sindex] - verts[ix];
float w = mc.selection[Verts[i].indices[0]] * weight; //[wc];
Vector3 p1 = verts[Verts[i].indices[0]];
p = p1 + ((p - p1) * w);
for ( int v = 0; v < Verts[i].indices.Length; v++ )
{
int idx = Verts[i].indices[v];
sverts[idx] = p;
}
}
}
bool skipframe = true;
// TODO: Option to lerp or even bez, depends on how many samples
public override void Modify(MegaModifiers mc)
{
if ( Verts != null )
{
switch ( interpMethod )
{
case MegaInterpMethod.Linear:
switch ( blendMode )
{
case MegaBlendAnimMode.Additive: LinearRel(mc, 0, Verts.Length); break;
case MegaBlendAnimMode.Replace: LinearAbs(mc, 0, Verts.Length); break;
}
break;
case MegaInterpMethod.Bez:
switch ( blendMode )
{
case MegaBlendAnimMode.Additive: LinearRel(mc, 0, Verts.Length); break;
case MegaBlendAnimMode.Replace: LinearAbs(mc, 0, Verts.Length); break;
}
break;
case MegaInterpMethod.None:
switch ( blendMode )
{
case MegaBlendAnimMode.Additive: NoInterpRel(mc, 0, Verts.Length); break;
case MegaBlendAnimMode.Replace: NoInterpAbs(mc, 0, Verts.Length); break;
}
break;
}
}
else
{
for ( int i = 0; i < verts.Length; i++ )
sverts[i] = verts[i];
}
}
public void ModifyInstance(MegaModifiers mc, float itime)
{
if ( Verts != null )
{
switch ( LoopMode )
{
case MegaRepeatMode.Loop: t = Mathf.Repeat(itime, maxtime); break;
case MegaRepeatMode.PingPong: t = Mathf.PingPong(itime, maxtime); break;
case MegaRepeatMode.Clamp: t = Mathf.Clamp(itime, 0.0f, maxtime); break;
}
alpha = t / maxtime;
float val = (float)(Verts[0].points.Length - 1) * alpha;
sindex = (int)val;
dalpha = val - sindex;
if ( sindex == Verts[0].points.Length - 1 )
{
sindex1 = sindex;
dalpha = 0.0f;
}
else
sindex1 = sindex + 1;
switch ( interpMethod )
{
case MegaInterpMethod.Linear:
switch ( blendMode )
{
case MegaBlendAnimMode.Additive: LinearRel(mc, 0, Verts.Length); break;
case MegaBlendAnimMode.Replace: LinearAbs(mc, 0, Verts.Length); break;
}
break;
case MegaInterpMethod.Bez:
switch ( blendMode )
{
case MegaBlendAnimMode.Additive: LinearRel(mc, 0, Verts.Length); break;
case MegaBlendAnimMode.Replace: LinearAbs(mc, 0, Verts.Length); break;
}
break;
case MegaInterpMethod.None:
switch ( blendMode )
{
case MegaBlendAnimMode.Additive: NoInterpRel(mc, 0, Verts.Length); break;
case MegaBlendAnimMode.Replace: NoInterpAbs(mc, 0, Verts.Length); break;
}
break;
}
}
else
{
for ( int i = 0; i < verts.Length; i++ )
sverts[i] = verts[i];
}
}
public void SetAnim(float _t)
{
time = _t;
t = _t;
skipframe = true;
}
public override bool ModLateUpdate(MegaModContext mc)
{
if ( !Prepare(mc) )
return false;
if ( animated ) //&& !lateanimupdate )
{
if ( framedelay && skipframe )
skipframe = false;
else
time += Time.deltaTime * speed;
}
switch ( LoopMode )
{
case MegaRepeatMode.Loop: t = Mathf.Repeat(time, maxtime); break;
case MegaRepeatMode.PingPong: t = Mathf.PingPong(time, maxtime); break;
case MegaRepeatMode.Clamp: t = Mathf.Clamp(time, 0.0f, maxtime); break;
}
alpha = t / maxtime;
float val = (float)(Verts[0].points.Length - 1) * alpha;
sindex = (int)val;
dalpha = val - sindex;
if ( sindex == Verts[0].points.Length - 1 )
{
sindex1 = sindex;
dalpha = 0.0f;
}
else
sindex1 = sindex + 1;
return true;
}
public override bool Prepare(MegaModContext mc)
{
if ( Verts != null && Verts.Length > 0 && Verts[0].indices != null && Verts[0].indices.Length > 0 )
return true;
return false;
}
public override void DoWork(MegaModifiers mc, int index, int start, int end, int cores)
{
ModifyCompressedMT(mc, index, cores);
}
public void ModifyCompressedMT(MegaModifiers mc, int tindex, int cores)
{
if ( Verts != null )
{
int step = Verts.Length / cores;
int startvert = (tindex * step);
int endvert = startvert + step;
if ( tindex == cores - 1 )
endvert = Verts.Length;
switch ( interpMethod )
{
case MegaInterpMethod.Linear:
switch ( blendMode )
{
case MegaBlendAnimMode.Additive: LinearRel(mc, startvert, endvert); break;
case MegaBlendAnimMode.Replace: LinearAbs(mc, startvert, endvert); break;
}
break;
case MegaInterpMethod.Bez:
switch ( blendMode )
{
case MegaBlendAnimMode.Additive: LinearRel(mc, startvert, endvert); break;
case MegaBlendAnimMode.Replace: LinearAbs(mc, startvert, endvert); break;
}
break;
case MegaInterpMethod.None:
switch ( blendMode )
{
case MegaBlendAnimMode.Additive: NoInterpRel(mc, startvert, endvert); break;
case MegaBlendAnimMode.Replace: NoInterpAbs(mc, startvert, endvert); break;
}
break;
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using 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>
/// BgpServiceCommunitiesOperations operations.
/// </summary>
internal partial class BgpServiceCommunitiesOperations : IServiceOperations<NetworkClient>, IBgpServiceCommunitiesOperations
{
/// <summary>
/// Initializes a new instance of the BgpServiceCommunitiesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BgpServiceCommunitiesOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Gets all the available bgp service communities.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <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<IPage<BgpServiceCommunity>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/bgpServiceCommunities").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<BgpServiceCommunity>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<BgpServiceCommunity>>(_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>
/// Gets all the available bgp service communities.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <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<IPage<BgpServiceCommunity>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<BgpServiceCommunity>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<BgpServiceCommunity>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using TermPositions = Lucene.Net.Index.TermPositions;
namespace Lucene.Net.Search
{
sealed class SloppyPhraseScorer:PhraseScorer
{
private int slop;
private PhrasePositions[] repeats;
private PhrasePositions[] tmpPos; // for flipping repeating pps.
private bool checkedRepeats;
internal SloppyPhraseScorer(Weight weight, TermPositions[] tps, int[] offsets, Similarity similarity, int slop, byte[] norms):base(weight, tps, offsets, similarity, norms)
{
this.slop = slop;
}
/// <summary> Score a candidate doc for all slop-valid position-combinations (matches)
/// encountered while traversing/hopping the PhrasePositions.
/// <br/> The score contribution of a match depends on the distance:
/// <br/> - highest score for distance=0 (exact match).
/// <br/> - score gets lower as distance gets higher.
/// <br/>Example: for query "a b"~2, a document "x a b a y" can be scored twice:
/// once for "a b" (distance=0), and once for "b a" (distance=2).
/// <br/>Possibly not all valid combinations are encountered, because for efficiency
/// we always propagate the least PhrasePosition. This allows to base on
/// PriorityQueue and move forward faster.
/// As result, for example, document "a b c b a"
/// would score differently for queries "a b c"~4 and "c b a"~4, although
/// they really are equivalent.
/// Similarly, for doc "a b c b a f g", query "c b"~2
/// would get same score as "g f"~2, although "c b"~2 could be matched twice.
/// We may want to fix this in the future (currently not, for performance reasons).
/// </summary>
protected internal override float PhraseFreq()
{
int end = InitPhrasePositions();
float freq = 0.0f;
bool done = (end < 0);
while (!done)
{
PhrasePositions pp = (PhrasePositions) pq.Pop();
int start = pp.position;
int next = ((PhrasePositions) pq.Top()).position;
bool tpsDiffer = true;
for (int pos = start; pos <= next || !tpsDiffer; pos = pp.position)
{
if (pos <= next && tpsDiffer)
start = pos; // advance pp to min window
if (!pp.NextPosition())
{
done = true; // ran out of a term -- done
break;
}
PhrasePositions pp2 = null;
tpsDiffer = !pp.repeats || (pp2 = TermPositionsDiffer(pp)) == null;
if (pp2 != null && pp2 != pp)
{
pp = Flip(pp, pp2); // flip pp to pp2
}
}
int matchLength = end - start;
if (matchLength <= slop)
freq += GetSimilarity().SloppyFreq(matchLength); // score match
if (pp.position > end)
end = pp.position;
pq.Put(pp); // restore pq
}
return freq;
}
// flip pp2 and pp in the queue: pop until finding pp2, insert back all but pp2, insert pp back.
// assumes: pp!=pp2, pp2 in pq, pp not in pq.
// called only when there are repeating pps.
private PhrasePositions Flip(PhrasePositions pp, PhrasePositions pp2)
{
int n = 0;
PhrasePositions pp3;
//pop until finding pp2
while ((pp3 = (PhrasePositions) pq.Pop()) != pp2)
{
tmpPos[n++] = pp3;
}
//insert back all but pp2
for (n--; n >= 0; n--)
{
pq.Insert(tmpPos[n]);
}
//insert pp back
pq.Put(pp);
return pp2;
}
/// <summary> Init PhrasePositions in place.
/// There is a one time initialization for this scorer:
/// <br/>- Put in repeats[] each pp that has another pp with same position in the doc.
/// <br/>- Also mark each such pp by pp.repeats = true.
/// <br/>Later can consult with repeats[] in termPositionsDiffer(pp), making that check efficient.
/// In particular, this allows to score queries with no repetitions with no overhead due to this computation.
/// <br/>- Example 1 - query with no repetitions: "ho my"~2
/// <br/>- Example 2 - query with repetitions: "ho my my"~2
/// <br/>- Example 3 - query with repetitions: "my ho my"~2
/// <br/>Init per doc w/repeats in query, includes propagating some repeating pp's to avoid false phrase detection.
/// </summary>
/// <returns> end (max position), or -1 if any term ran out (i.e. done)
/// </returns>
/// <throws> IOException </throws>
private int InitPhrasePositions()
{
int end = 0;
// no repeats at all (most common case is also the simplest one)
if (checkedRepeats && repeats == null)
{
// build queue from list
pq.Clear();
for (PhrasePositions pp = first; pp != null; pp = pp.next)
{
pp.FirstPosition();
if (pp.position > end)
end = pp.position;
pq.Put(pp); // build pq from list
}
return end;
}
// position the pp's
for (PhrasePositions pp = first; pp != null; pp = pp.next)
pp.FirstPosition();
// one time initializatin for this scorer
if (!checkedRepeats)
{
checkedRepeats = true;
// check for repeats
System.Collections.Hashtable m = null;
for (PhrasePositions pp = first; pp != null; pp = pp.next)
{
int tpPos = pp.position + pp.offset;
for (PhrasePositions pp2 = pp.next; pp2 != null; pp2 = pp2.next)
{
int tpPos2 = pp2.position + pp2.offset;
if (tpPos2 == tpPos)
{
if (m == null)
{
m = new System.Collections.Hashtable();
}
pp.repeats = true;
pp2.repeats = true;
m[pp] = null;
m[pp2] = null;
}
}
}
if (m != null)
{
repeats = (PhrasePositions[])(new System.Collections.ArrayList(m.Keys).ToArray(typeof(PhrasePositions)));
}
}
// with repeats must advance some repeating pp's so they all start with differing tp's
if (repeats != null)
{
for (int i = 0; i < repeats.Length; i++)
{
PhrasePositions pp = repeats[i];
PhrasePositions pp2;
while ((pp2 = TermPositionsDiffer(pp)) != null)
{
if (!pp2.NextPosition())
// out of pps that do not differ, advance the pp with higher offset
return - 1; // ran out of a term -- done
}
}
}
// build queue from list
pq.Clear();
for (PhrasePositions pp = first; pp != null; pp = pp.next)
{
if (pp.position > end)
end = pp.position;
pq.Put(pp); // build pq from list
}
if (repeats != null)
{
tmpPos = new PhrasePositions[pq.Size()];
}
return end;
}
/// <summary> We disallow two pp's to have the same TermPosition, thereby verifying multiple occurrences
/// in the query of the same word would go elsewhere in the matched doc.
/// </summary>
/// <returns> null if differ (i.e. valid) otherwise return the higher offset PhrasePositions
/// out of the first two PPs found to not differ.
/// </returns>
private PhrasePositions TermPositionsDiffer(PhrasePositions pp)
{
// efficiency note: a more efficient implementation could keep a map between repeating
// pp's, so that if pp1a, pp1b, pp1c are repeats term1, and pp2a, pp2b are repeats
// of term2, pp2a would only be checked against pp2b but not against pp1a, pp1b, pp1c.
// However this would complicate code, for a rather rare case, so choice is to compromise here.
int tpPos = pp.position + pp.offset;
for (int i = 0; i < repeats.Length; i++)
{
PhrasePositions pp2 = repeats[i];
if (pp2 == pp)
continue;
int tpPos2 = pp2.position + pp2.offset;
if (tpPos2 == tpPos)
return pp.offset > pp2.offset?pp:pp2; // do not differ: return the one with higher offset.
}
return null;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public struct SelectContext {
public enum States {
ACTIVE_UNIT,
MOVE,
ATTACK,
};
public delegate void SelectAction(USquareGridSquare us);
public SelectContext.States State { get { return this.state; } }
public SelectContext.SelectAction Action { get { return this.action; } }
public SquareGridArea move_area;
public bool input_enabled;
public USquareGridSquare prev_square;
private SelectContext.States state;
private SelectContext.SelectAction action;
private USquareGridSelector selector;
public SelectContext(PrefabCache prefab_cache,
SelectContext.States state,
SelectContext.SelectAction action) {
this.selector = new USquareGridSelector(prefab_cache);
this.move_area = null;
this.prev_square = null;
this.input_enabled = true;
this.state = state;
this.action = action;
}
public void Transition(SelectContext.States state, SelectContext.SelectAction action) {
this.state = state;
this.action = action;
if ((this.move_area != null) && (SelectContext.States.MOVE != state)) {
/* TODO: probably pass selector the prev move_area to cleanup */
this.selector.HighlightMoveableSquares(null);
this.move_area = null;
}
}
public void SelectActiveUnit(USquareGridSquare us) {
this.selector.SelectActiveUnit(us);
}
public void HighlightMoveableArea(SquareGridArea area) {
if (this.move_area != null) {
/* TODO: clean up old area? */
}
this.move_area = area;
this.selector.HighlightMoveableSquares(
from s in area.GetEnumerable() select (USquareGridSquare)s);
}
public void SelectMoveTarget(USquareGridSquare us) {
this.selector.SelectMoveTarget(us);
this.prev_square = us;
}
};
public class UGame : MonoBehaviour {
/* For inspector */
public int NUM_ROWS = 8;
public int NUM_COLS = 10;
public GameObject UNIT_SIZE_CUBE;
public GameObject TERRAIN;
private UMouseGrid mgrid;
private UUIManager ui_mgr;
private PrefabCache prefab_cache;
private USquareGridGame game;
private SelectContext select_context;
// Use this for initialization
void Start () {
GameObject g;
this.prefab_cache = new PrefabCache();
g = (GameObject)GameObject.Find ("level_globals");
this.ui_mgr = (UUIManager)g.GetComponent("UUIManager");
/* iterating through transform doesn't work well with linq */
var terrain = new HashSet<GameObject>();
this.GetAllChildrenWithColliders(terrain, this.TERRAIN);
this.game = new USquareGridGame(this.prefab_cache, this.NUM_ROWS, this.NUM_COLS,
this.UNIT_SIZE_CUBE.renderer.bounds.size.x,
terrain);
this.mgrid = new UMouseGrid(this.game.UGrid, terrain);
this.select_context = new SelectContext(this.prefab_cache,
SelectContext.States.ACTIVE_UNIT,
this.SelectActiveUnit);
}
void GetAllChildrenWithColliders(HashSet<GameObject> terrain, GameObject o) {
foreach (Transform t in o.transform) {
if (t.gameObject.collider != null) {
terrain.Add(t.gameObject);
} else {
this.GetAllChildrenWithColliders(terrain, t.gameObject);
}
}
}
// Update is called once per frame
void Update () {
USquareGridSquare us;
if (this.select_context.input_enabled) {
if (Input.GetMouseButtonDown(UKeyBinds.LEFT_CLICK)) {
us = this.mgrid.FindSquare(Input.mousePosition);
this.select_context.Action(us);
} else if (Input.GetMouseButtonDown(UKeyBinds.RIGHT_CLICK)) {
this.RightSelectedSquare(this.mgrid.FindSquare(Input.mousePosition));
}
}
}
private void UISquareSelected(USquareGridSquare us) {
this.ui_mgr.SelectedSquare(us);
this.ui_mgr.SelectedUnit ((USquareGridUnit)us.GetUnit ());
}
private void SelectActiveUnit(USquareGridSquare us) {
USquareGridUnit unit;
if (us == null) {
return;
}
this.UISquareSelected(us);
unit = (USquareGridUnit)us.GetUnit();
if ((unit != null) && (this.game.UActiveUnit == unit)) {
this.ui_mgr.unit_action_panel.SetActive (true);
this.ui_mgr.SelectedActiveUnit(unit);
}
this.select_context.SelectActiveUnit(us);
}
private IEnumerator MoveUnit(USquareGridUnit unit, USquareGridSquare us) {
/* FIXME: since our distances are so small, doesn't matter but we can cache this result earlier */
var moveable = unit.GetMoveableArea(this.game.Grid);
moveable.ResetForSearch();
foreach (var tmp in moveable.GetPath(us)) {
//Debug.Log (tmp);
this.game.MoveUnit(unit, tmp);
yield return new WaitForSeconds(0.5f);
}
Debug.Log ("---move animation done---");
this.ui_mgr.unit_action_move.button.interactable = false;
this.ui_mgr.unit_action_move.text.text = "Move";
this.select_context.Transition (SelectContext.States.ACTIVE_UNIT, this.SelectActiveUnit);
/**
* move cursor to unit's new position
* TODO: since we're wiping the moveable in transition,
* we have to do the select after. need to do something more elegant
*/
this.SelectActiveUnit(us);
this.select_context.input_enabled = true;
}
private void SelectMoveTarget(USquareGridSquare us) {
if (us == null) {
return;
}
this.UISquareSelected(us);
if (this.select_context.move_area == null) {
Debug.Log ("arrrrrgh");
return;
}
if (!this.select_context.move_area.Squares.Contains(us)) {
return;
}
if (this.select_context.prev_square == us) {
/* disable input while waiting for move animation and cleanup */
this.select_context.input_enabled = false;
this.StartCoroutine(this.MoveUnit(this.game.UActiveUnit, us));
} else {
this.select_context.SelectMoveTarget(us);
}
}
public void RightSelectedSquare(USquareGridSquare us) {
}
public void UIMoveButton() {
if (!this.select_context.input_enabled) {
return;
}
if (this.select_context.State == SelectContext.States.MOVE) {
this.ui_mgr.unit_action_move.text.text = "Move";
this.select_context.Transition(SelectContext.States.ACTIVE_UNIT, this.SelectActiveUnit);
} else if (this.select_context.State == SelectContext.States.ACTIVE_UNIT) {
this.ui_mgr.unit_action_move.text.text = "Cancel";
this.select_context.HighlightMoveableArea(
this.game.ActiveUnit.GetMoveableArea(this.game.Grid));
this.select_context.Transition (SelectContext.States.MOVE, this.SelectMoveTarget);
}
}
public void UIEndTurnButton() {
if (!this.select_context.input_enabled) {
return;
}
this.select_context.Transition (SelectContext.States.ACTIVE_UNIT, this.SelectActiveUnit);
/* clean up should happen here */
this.game.ActiveUnitTurnEnded ();
/* after this, active unit is updated */
this.select_context.SelectActiveUnit((USquareGridSquare)this.game.ActiveUnit.Square);
this.ui_mgr.SelectedActiveUnit(this.game.UActiveUnit);
this.ui_mgr.SelectedUnit (this.game.UActiveUnit);
this.ui_mgr.unit_action_panel.SetActive (true);
this.ui_mgr.unit_action_move.button.interactable = true;
this.ui_mgr.unit_action_move.text.text = "Move";
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.IO;
using Google.Protobuf.TestProtos;
using Google.Protobuf.Buffers;
using NUnit.Framework;
using System.Text;
namespace Google.Protobuf
{
public class CodedOutputStreamTest
{
/// <summary>
/// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and
/// checks that the result matches the given bytes
/// </summary>
private static void AssertWriteVarint(byte[] data, ulong value)
{
// Only do 32-bit write if the value fits in 32 bits.
if ((value >> 32) == 0)
{
// CodedOutputStream
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput);
output.WriteRawVarint32((uint) value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
// IBufferWriter
var bufferWriter = new TestArrayBufferWriter<byte>();
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteUInt32((uint) value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
// Also try computing size.
Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value));
}
{
// CodedOutputStream
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput);
output.WriteRawVarint64(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
// IBufferWriter
var bufferWriter = new TestArrayBufferWriter<byte>();
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteUInt64(value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
// Also try computing size.
Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value));
}
// Try different buffer sizes.
for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
{
// Only do 32-bit write if the value fits in 32 bits.
if ((value >> 32) == 0)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output =
new CodedOutputStream(rawOutput, bufferSize);
output.WriteRawVarint32((uint) value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
var bufferWriter = new TestArrayBufferWriter<byte>();
bufferWriter.MaxGrowBy = bufferSize;
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteUInt32((uint) value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
}
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput, bufferSize);
output.WriteRawVarint64(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
var bufferWriter = new TestArrayBufferWriter<byte>();
bufferWriter.MaxGrowBy = bufferSize;
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteUInt64(value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
}
}
}
/// <summary>
/// Tests WriteRawVarint32() and WriteRawVarint64()
/// </summary>
[Test]
public void WriteVarint()
{
AssertWriteVarint(new byte[] {0x00}, 0);
AssertWriteVarint(new byte[] {0x01}, 1);
AssertWriteVarint(new byte[] {0x7f}, 127);
// 14882
AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7));
// 2961488830
AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b},
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x0bL << 28));
// 64-bit
// 7256456126
AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b},
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x1bL << 28));
// 41256202580718336
AssertWriteVarint(
new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49},
(0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
(0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49));
// 11964378330978735131
AssertWriteVarint(
new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01},
unchecked((ulong)
((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
(0x3bL << 28) | (0x56L << 35) | (0x00L << 42) |
(0x05L << 49) | (0x26L << 56) | (0x01L << 63))));
}
/// <summary>
/// Parses the given bytes using WriteRawLittleEndian32() and checks
/// that the result matches the given value.
/// </summary>
private static void AssertWriteLittleEndian32(byte[] data, uint value)
{
{
var rawOutput = new MemoryStream();
var output = new CodedOutputStream(rawOutput);
output.WriteRawLittleEndian32(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
var bufferWriter = new TestArrayBufferWriter<byte>();
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteFixed32(value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
}
// Try different buffer sizes.
for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
{
var rawOutput = new MemoryStream();
var output = new CodedOutputStream(rawOutput, bufferSize);
output.WriteRawLittleEndian32(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
var bufferWriter = new TestArrayBufferWriter<byte>();
bufferWriter.MaxGrowBy = bufferSize;
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteFixed32(value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
}
}
/// <summary>
/// Parses the given bytes using WriteRawLittleEndian64() and checks
/// that the result matches the given value.
/// </summary>
private static void AssertWriteLittleEndian64(byte[] data, ulong value)
{
{
var rawOutput = new MemoryStream();
var output = new CodedOutputStream(rawOutput);
output.WriteRawLittleEndian64(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
var bufferWriter = new TestArrayBufferWriter<byte>();
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteFixed64(value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
}
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
{
var rawOutput = new MemoryStream();
var output = new CodedOutputStream(rawOutput, blockSize);
output.WriteRawLittleEndian64(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
var bufferWriter = new TestArrayBufferWriter<byte>();
bufferWriter.MaxGrowBy = blockSize;
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteFixed64(value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
}
}
/// <summary>
/// Tests writeRawLittleEndian32() and writeRawLittleEndian64().
/// </summary>
[Test]
public void WriteLittleEndian()
{
AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678);
AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0);
AssertWriteLittleEndian64(
new byte[] {0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12},
0x123456789abcdef0L);
AssertWriteLittleEndian64(
new byte[] {0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a},
0x9abcdef012345678UL);
}
[Test]
public void WriteWholeMessage_VaryingBlockSizes()
{
TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
byte[] rawBytes = message.ToByteArray();
// Try different block sizes.
for (int blockSize = 1; blockSize < 256; blockSize *= 2)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput, blockSize);
message.WriteTo(output);
output.Flush();
Assert.AreEqual(rawBytes, rawOutput.ToArray());
var bufferWriter = new TestArrayBufferWriter<byte>();
bufferWriter.MaxGrowBy = blockSize;
message.WriteTo(bufferWriter);
Assert.AreEqual(rawBytes, bufferWriter.WrittenSpan.ToArray());
}
}
[Test]
public void WriteContext_WritesWithFlushes()
{
TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
MemoryStream expectedOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(expectedOutput);
output.WriteMessage(message);
output.Flush();
byte[] expectedBytes1 = expectedOutput.ToArray();
output.WriteMessage(message);
output.Flush();
byte[] expectedBytes2 = expectedOutput.ToArray();
var bufferWriter = new TestArrayBufferWriter<byte>();
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteMessage(message);
ctx.Flush();
Assert.AreEqual(expectedBytes1, bufferWriter.WrittenSpan.ToArray());
ctx.WriteMessage(message);
ctx.Flush();
Assert.AreEqual(expectedBytes2, bufferWriter.WrittenSpan.ToArray());
}
[Test]
public void EncodeZigZag32()
{
Assert.AreEqual(0u, WritingPrimitives.EncodeZigZag32(0));
Assert.AreEqual(1u, WritingPrimitives.EncodeZigZag32(-1));
Assert.AreEqual(2u, WritingPrimitives.EncodeZigZag32(1));
Assert.AreEqual(3u, WritingPrimitives.EncodeZigZag32(-2));
Assert.AreEqual(0x7FFFFFFEu, WritingPrimitives.EncodeZigZag32(0x3FFFFFFF));
Assert.AreEqual(0x7FFFFFFFu, WritingPrimitives.EncodeZigZag32(unchecked((int) 0xC0000000)));
Assert.AreEqual(0xFFFFFFFEu, WritingPrimitives.EncodeZigZag32(0x7FFFFFFF));
Assert.AreEqual(0xFFFFFFFFu, WritingPrimitives.EncodeZigZag32(unchecked((int) 0x80000000)));
}
[Test]
public void EncodeZigZag64()
{
Assert.AreEqual(0u, WritingPrimitives.EncodeZigZag64(0));
Assert.AreEqual(1u, WritingPrimitives.EncodeZigZag64(-1));
Assert.AreEqual(2u, WritingPrimitives.EncodeZigZag64(1));
Assert.AreEqual(3u, WritingPrimitives.EncodeZigZag64(-2));
Assert.AreEqual(0x000000007FFFFFFEuL,
WritingPrimitives.EncodeZigZag64(unchecked((long) 0x000000003FFFFFFFUL)));
Assert.AreEqual(0x000000007FFFFFFFuL,
WritingPrimitives.EncodeZigZag64(unchecked((long) 0xFFFFFFFFC0000000UL)));
Assert.AreEqual(0x00000000FFFFFFFEuL,
WritingPrimitives.EncodeZigZag64(unchecked((long) 0x000000007FFFFFFFUL)));
Assert.AreEqual(0x00000000FFFFFFFFuL,
WritingPrimitives.EncodeZigZag64(unchecked((long) 0xFFFFFFFF80000000UL)));
Assert.AreEqual(0xFFFFFFFFFFFFFFFEL,
WritingPrimitives.EncodeZigZag64(unchecked((long) 0x7FFFFFFFFFFFFFFFUL)));
Assert.AreEqual(0xFFFFFFFFFFFFFFFFL,
WritingPrimitives.EncodeZigZag64(unchecked((long) 0x8000000000000000UL)));
}
[Test]
public void RoundTripZigZag32()
{
// Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
// were chosen semi-randomly via keyboard bashing.
Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(0)));
Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(1)));
Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(-1)));
Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(14927)));
Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(-3612)));
}
[Test]
public void RoundTripZigZag64()
{
Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(0)));
Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(1)));
Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-1)));
Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(14927)));
Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-3612)));
Assert.AreEqual(856912304801416L,
ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(856912304801416L)));
Assert.AreEqual(-75123905439571256L,
ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-75123905439571256L)));
}
[Test]
public void TestNegativeEnumNoTag()
{
Assert.AreEqual(10, CodedOutputStream.ComputeInt32Size(-2));
Assert.AreEqual(10, CodedOutputStream.ComputeEnumSize((int) SampleEnum.NegativeValue));
byte[] bytes = new byte[10];
CodedOutputStream output = new CodedOutputStream(bytes);
output.WriteEnum((int) SampleEnum.NegativeValue);
Assert.AreEqual(0, output.SpaceLeft);
Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes));
}
[Test]
public void TestCodedInputOutputPosition()
{
byte[] content = new byte[110];
for (int i = 0; i < content.Length; i++)
content[i] = (byte)i;
byte[] child = new byte[120];
{
MemoryStream ms = new MemoryStream(child);
CodedOutputStream cout = new CodedOutputStream(ms, 20);
// Field 11: numeric value: 500
cout.WriteTag(11, WireFormat.WireType.Varint);
Assert.AreEqual(1, cout.Position);
cout.WriteInt32(500);
Assert.AreEqual(3, cout.Position);
//Field 12: length delimited 120 bytes
cout.WriteTag(12, WireFormat.WireType.LengthDelimited);
Assert.AreEqual(4, cout.Position);
cout.WriteBytes(ByteString.CopyFrom(content));
Assert.AreEqual(115, cout.Position);
// Field 13: fixed numeric value: 501
cout.WriteTag(13, WireFormat.WireType.Fixed32);
Assert.AreEqual(116, cout.Position);
cout.WriteSFixed32(501);
Assert.AreEqual(120, cout.Position);
cout.Flush();
}
byte[] bytes = new byte[130];
{
CodedOutputStream cout = new CodedOutputStream(bytes);
// Field 1: numeric value: 500
cout.WriteTag(1, WireFormat.WireType.Varint);
Assert.AreEqual(1, cout.Position);
cout.WriteInt32(500);
Assert.AreEqual(3, cout.Position);
//Field 2: length delimited 120 bytes
cout.WriteTag(2, WireFormat.WireType.LengthDelimited);
Assert.AreEqual(4, cout.Position);
cout.WriteBytes(ByteString.CopyFrom(child));
Assert.AreEqual(125, cout.Position);
// Field 3: fixed numeric value: 500
cout.WriteTag(3, WireFormat.WireType.Fixed32);
Assert.AreEqual(126, cout.Position);
cout.WriteSFixed32(501);
Assert.AreEqual(130, cout.Position);
cout.Flush();
}
// Now test Input stream:
{
CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0, false);
Assert.AreEqual(0, cin.Position);
// Field 1:
uint tag = cin.ReadTag();
Assert.AreEqual(1, tag >> 3);
Assert.AreEqual(1, cin.Position);
Assert.AreEqual(500, cin.ReadInt32());
Assert.AreEqual(3, cin.Position);
//Field 2:
tag = cin.ReadTag();
Assert.AreEqual(2, tag >> 3);
Assert.AreEqual(4, cin.Position);
int childlen = cin.ReadLength();
Assert.AreEqual(120, childlen);
Assert.AreEqual(5, cin.Position);
int oldlimit = cin.PushLimit((int)childlen);
Assert.AreEqual(5, cin.Position);
// Now we are reading child message
{
// Field 11: numeric value: 500
tag = cin.ReadTag();
Assert.AreEqual(11, tag >> 3);
Assert.AreEqual(6, cin.Position);
Assert.AreEqual(500, cin.ReadInt32());
Assert.AreEqual(8, cin.Position);
//Field 12: length delimited 120 bytes
tag = cin.ReadTag();
Assert.AreEqual(12, tag >> 3);
Assert.AreEqual(9, cin.Position);
ByteString bstr = cin.ReadBytes();
Assert.AreEqual(110, bstr.Length);
Assert.AreEqual((byte) 109, bstr[109]);
Assert.AreEqual(120, cin.Position);
// Field 13: fixed numeric value: 501
tag = cin.ReadTag();
Assert.AreEqual(13, tag >> 3);
// ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit
Assert.AreEqual(121, cin.Position);
Assert.AreEqual(501, cin.ReadSFixed32());
Assert.AreEqual(125, cin.Position);
Assert.IsTrue(cin.IsAtEnd);
}
cin.PopLimit(oldlimit);
Assert.AreEqual(125, cin.Position);
// Field 3: fixed numeric value: 501
tag = cin.ReadTag();
Assert.AreEqual(3, tag >> 3);
Assert.AreEqual(126, cin.Position);
Assert.AreEqual(501, cin.ReadSFixed32());
Assert.AreEqual(130, cin.Position);
Assert.IsTrue(cin.IsAtEnd);
}
}
[Test]
public void Dispose_DisposesUnderlyingStream()
{
var memoryStream = new MemoryStream();
Assert.IsTrue(memoryStream.CanWrite);
using (var cos = new CodedOutputStream(memoryStream))
{
cos.WriteRawBytes(new byte[] {0});
Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
}
Assert.AreEqual(1, memoryStream.ToArray().Length); // Flushed data from CodedOutputStream to MemoryStream
Assert.IsFalse(memoryStream.CanWrite); // Disposed
}
[Test]
public void Dispose_WithLeaveOpen()
{
var memoryStream = new MemoryStream();
Assert.IsTrue(memoryStream.CanWrite);
using (var cos = new CodedOutputStream(memoryStream, true))
{
cos.WriteRawBytes(new byte[] {0});
Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
}
Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream
Assert.IsTrue(memoryStream.CanWrite); // We left the stream open
}
[Test]
public void Dispose_FromByteArray()
{
var stream = new CodedOutputStream(new byte[10]);
stream.Dispose();
}
[Test]
public void WriteString_AsciiSmall_MaxUtf8SizeExceedsBuffer()
{
var buffer = new byte[5];
var output = new CodedOutputStream(buffer);
output.WriteString("ABC");
output.Flush();
// Verify written content
var input = new CodedInputStream(buffer);
Assert.AreEqual("ABC", input.ReadString());
}
[Test]
public void WriteStringsOfDifferentSizes_Ascii()
{
for (int i = 1; i <= 1024; i++)
{
var buffer = new byte[4096];
var output = new CodedOutputStream(buffer);
var sb = new StringBuilder();
for (int j = 0; j < i; j++)
{
sb.Append((j % 10).ToString()); // incrementing numbers, repeating
}
var s = sb.ToString();
output.WriteString(s);
output.Flush();
// Verify written content
var input = new CodedInputStream(buffer);
Assert.AreEqual(s, input.ReadString());
}
}
[Test]
public void WriteStringsOfDifferentSizes_Unicode()
{
for (int i = 1; i <= 1024; i++)
{
var buffer = new byte[4096];
var output = new CodedOutputStream(buffer);
var sb = new StringBuilder();
for (int j = 0; j < i; j++)
{
char c = (char)((j % 10) + 10112);
sb.Append(c.ToString()); // incrementing unicode numbers, repeating
}
var s = sb.ToString();
output.WriteString(s);
output.Flush();
// Verify written content
var input = new CodedInputStream(buffer);
Assert.AreEqual(s, input.ReadString());
}
}
}
}
| |
/*
* This sample is released as public domain. It 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.
*
* 2007-08-01:
* Initial release.
*
*/
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
namespace Inbox2.Framework.Interop.WebBrowser
{
public enum GW : uint
{
HWNDFIRST = 0,
HWNDLAST = 1,
HWNDNEXT = 2,
HWNDPREV = 3,
OWNER = 4,
CHILD = 5,
ENABLEDPOPUP = 6,
}
public class ICON
{
public const UInt32 SMALL = 0;
public const UInt32 BIG = 1;
public const UInt32 SMALL2 = 2; // XP+
}
public enum MB : uint
{
SimpleBeep = 0xFFFFFFFF,
IconAsterisk = 0x00000040,
IconWarning = 0x00000030,
IconError = 0x00000010,
IconQuestion = 0x00000020,
OK = 0x00000000
}
[ Flags ]
public enum RDW : uint
{
INVALIDATE = 0x0001,
INTERNALPAINT = 0x0002,
ERASE = 0x0004,
VALIDATE = 0x0008,
NOINTERNALPAINT = 0x0010,
NOERASE = 0x0020,
NOCHILDREN = 0x0040,
ALLCHILDREN = 0x0080,
UPDATENOW = 0x0100,
ERASENOW = 0x0200,
FRAME = 0x0400,
NOFRAME = 0x0800,
}
public class SW
{
public const int HIDE = 0;
public const int SHOWNORMAL = 1;
public const int NORMAL = 1;
public const int SHOWMINIMIZED = 2;
public const int SHOWMAXIMIZED = 3;
public const int MAXIMIZE = 3;
public const int SHOWNOACTIVATE = 4;
public const int SHOW = 5;
public const int MINIMIZE = 6;
public const int SHOWMINNOACTIVE = 7;
public const int SHOWNA = 8;
public const int RESTORE = 9;
public const int SHOWDEFAULT = 10;
public const int FORCEMINIMIZE = 11;
public const int MAX = 11;
}
public class TB
{
public const uint GETBUTTON = WM.USER + 23 ;
public const uint BUTTONCOUNT = WM.USER + 24 ;
public const uint CUSTOMIZE = WM.USER + 27 ;
public const uint GETBUTTONTEXTA = WM.USER + 45 ;
public const uint GETBUTTONTEXTW = WM.USER + 75 ;
}
public class TBSTATE
{
public const uint CHECKED = 0x01 ;
public const uint PRESSED = 0x02 ;
public const uint ENABLED = 0x04 ;
public const uint HIDDEN = 0x08 ;
public const uint INDETERMINATE = 0x10 ;
public const uint WRAP = 0x20 ;
public const uint ELLIPSES = 0x40 ;
public const uint MARKED = 0x80 ;
}
public class WM
{
public const uint CLOSE = 0x0010;
public const uint GETICON = 0x007F;
public const uint KEYDOWN = 0x0100;
public const uint COMMAND = 0x0111;
public const uint USER = 0x0400; // 0x0400 - 0x7FFF
public const uint APP = 0x8000; // 0x8000 - 0xBFFF
}
public class GCL
{
public const int MENUNAME = - 8;
public const int HBRBACKGROUND = -10;
public const int HCURSOR = -12;
public const int HICON = -14;
public const int HMODULE = -16;
public const int CBWNDEXTRA = -18;
public const int CBCLSEXTRA = -20;
public const int WNDPROC = -24;
public const int STYLE = -26;
public const int ATOM = -32;
public const int HICONSM = -34;
// GetClassLongPtr ( 64-bit )
private const int GCW_ATOM = -32;
private const int GCL_CBCLSEXTRA = -20;
private const int GCL_CBWNDEXTRA = -18;
private const int GCLP_MENUNAME = - 8;
private const int GCLP_HBRBACKGROUND = -10;
private const int GCLP_HCURSOR = -12;
private const int GCLP_HICON = -14;
private const int GCLP_HMODULE = -16;
private const int GCLP_WNDPROC = -24;
private const int GCLP_HICONSM = -34;
private const int GCL_STYLE = -26;
}
public class INPUT
{
public const int MOUSE = 0;
public const int KEYBOARD = 1;
public const int HARDWARE = 2;
}
public class MOUSEEVENTF
{
public const int MOVE = 0x0001 ; /* mouse move */
public const int LEFTDOWN = 0x0002 ; /* left button down */
public const int LEFTUP = 0x0004 ; /* left button up */
public const int RIGHTDOWN = 0x0008 ; /* right button down */
public const int RIGHTUP = 0x0010 ; /* right button up */
public const int MIDDLEDOWN = 0x0020 ; /* middle button down */
public const int MIDDLEUP = 0x0040 ; /* middle button up */
public const int XDOWN = 0x0080 ; /* x button down */
public const int XUP = 0x0100 ; /* x button down */
public const int WHEEL = 0x0800 ; /* wheel button rolled */
public const int VIRTUALDESK = 0x4000 ; /* map to entire virtual desktop */
public const int ABSOLUTE = 0x8000 ; /* absolute move */
}
[ StructLayout( LayoutKind.Sequential ) ]
public struct POINT
{
public Int32 X;
public Int32 Y;
}
[ StructLayout( LayoutKind.Sequential ) ]
public struct RECT
{
public Int32 Left;
public Int32 Top;
public Int32 Right;
public Int32 Bottom;
}
[ StructLayout( LayoutKind.Sequential ) ]
public struct TBBUTTON
{
public Int32 iBitmap;
public Int32 idCommand;
public byte fsState;
public byte fsStyle;
// [ MarshalAs( UnmanagedType.ByValArray, SizeConst=2 ) ]
// public byte[] bReserved;
public byte bReserved1;
public byte bReserved2;
public UInt32 dwData;
public IntPtr iString;
};
[ StructLayout( LayoutKind.Sequential ) ]
public struct WINDOWPLACEMENT
{
public int Length;
public int Flags;
public int ShowCmd;
public POINT MinPosition;
public POINT MaxPosition;
public RECT NormalPosition;
}
[ StructLayout( LayoutKind.Sequential ) ]
public struct MOUSEINPUT
{
public int dx;
public int dy;
public int mouseData;
public int dwFlags;
public int time;
public IntPtr dwExtraInfo;
}
[ StructLayout( LayoutKind.Sequential ) ]
public struct KEYBDINPUT
{
public short wVk;
public short wScan;
public int dwFlags;
public int time;
public IntPtr dwExtraInfo;
}
[ StructLayout( LayoutKind.Sequential ) ]
public struct HARDWAREINPUT
{
public int uMsg;
public short wParamL;
public short wParamH;
}
[ StructLayout( LayoutKind.Explicit ) ]
public struct Input
{
[ FieldOffset( 0 ) ] public int type;
[ FieldOffset( 4 ) ] public MOUSEINPUT mi;
[ FieldOffset( 4 ) ] public KEYBDINPUT ki;
[ FieldOffset( 4 ) ] public HARDWAREINPUT hi;
}
public class User32
{
private User32() {}
// public const UInt32 WM_USER = 0x0400;
// public const UInt32 WM_KEYDOWN = 0x0100;
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(
IntPtr hWnd,
UInt32 msg,
IntPtr wParam,
IntPtr lParam );
[DllImport("user32.dll")]
public static extern UInt32 SendMessage(
IntPtr hWnd,
UInt32 msg,
UInt32 wParam,
UInt32 lParam );
[ DllImport( "User32.dll" ) ]
public static extern bool PostMessage
(
IntPtr hWnd,
UInt32 Msg,
IntPtr wParam,
IntPtr lParam
);
[ DllImport( "User32.dll" ) ]
public static extern bool PostMessage
(
IntPtr hWnd,
UInt32 Msg,
UInt32 wParam,
UInt32 lParam
);
[ DllImport( "User32.dll" ) ]
public static extern bool MessageBeep
(
MB BeepType
);
[DllImport( "user32.dll" )]
public static extern bool SetWindowPos( IntPtr hWnd, IntPtr hWndInsertAfter, int X,
int Y, int cx, int cy, uint uFlags );
[DllImport( "user32.dll" )]
public static extern IntPtr SetActiveWindow( IntPtr hWnd );
[DllImport("user32.dll")]
public static extern bool ShowWindow
(
IntPtr hWnd,
int nCmdShow
);
[ DllImport( "User32.dll" ) ]
public static extern bool SetForegroundWindow
(
IntPtr hWnd
);
[ DllImport( "User32.dll" ) ]
public static extern IntPtr GetDesktopWindow
(
);
[ DllImport( "User32.dll" ) ]
public static extern IntPtr GetTaskmanWindow
(
);
[ DllImport( "user32.dll", CharSet = CharSet.Unicode ) ]
public static extern IntPtr FindWindowEx(
IntPtr hwndParent,
IntPtr hwndChildAfter,
string lpszClass,
string lpszWindow);
[ DllImport( "User32.dll" ) ]
public static extern IntPtr GetWindow
(
HandleRef hWnd,
GW uCmd
);
[ DllImport( "User32.dll" ) ]
public static extern Int32 GetWindowTextLength
(
HandleRef hWnd
);
[ DllImport( "User32.dll", SetLastError = true, CharSet = CharSet.Auto ) ]
public static extern Int32 GetWindowText
(
HandleRef hWnd,
StringBuilder lpString,
Int32 nMaxCount
);
[DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr GetCapture();
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern Int32 GetClassName
(
HandleRef hWnd,
out StringBuilder lpClassName,
Int32 nMaxCount
);
// [ DllImport( "user32.dll", EntryPoint = "GetClassLongPtrW" ) ]
[ DllImport( "user32.dll" ) ]
public static extern UInt32 GetClassLong
(
HandleRef hWnd,
int nIndex
);
[DllImport("user32.dll")]
public static extern uint SetClassLong
(
HandleRef hWnd,
int nIndex,
uint dwNewLong
);
[ DllImport( "User32.dll", CharSet=CharSet.Auto ) ]
public static extern UInt32 GetWindowThreadProcessId
(
IntPtr hWnd,
// [ MarshalAs( UnmanagedType.
out UInt32 lpdwProcessId
);
[DllImport("User32.dll", SetLastError = true)]
public static extern bool RedrawWindow
(
HandleRef hWnd,
// [In] ref RECT lprcUpdate,
IntPtr lprcUpdate,
IntPtr hrgnUpdate,
uint flags
);
public static bool RedrawWindow(HandleRef hWnd)
{
return RedrawWindow( hWnd, IntPtr.Zero, IntPtr.Zero,
( uint ) ( RDW.ERASE | RDW.INVALIDATE | RDW.UPDATENOW ) );
}
[DllImport("user32.dll", SetLastError = true)]
public static extern bool PrintWindow
(
IntPtr hwnd,
IntPtr hdcBlt,
uint nFlags
);
[DllImport("User32.dll", SetLastError = true)]
public static extern UInt32 SendInput
(
UInt32 nInputs,
Input[] pInputs,
Int32 cbSize
);
[DllImport("User32.dll", SetLastError = true)]
public static extern bool GetWindowPlacement
(
IntPtr hWnd,
ref WINDOWPLACEMENT lpwndpl
);
[DllImport("User32.dll", SetLastError = true)]
public static extern IntPtr WindowFromPoint(
POINT point
);
[DllImport("User32.dll", SetLastError = true)]
public static extern IntPtr ChildWindowFromPoint(
POINT point
);
[DllImport("User32.dll", SetLastError=true)]
public static extern IntPtr GetParent
(
HandleRef hWnd
);
[DllImport("User32.dll", SetLastError = true)]
private static extern IntPtr GetParent
(
IntPtr hWnd
);
[DllImport("User32.dll", SetLastError = true)]
public static extern bool ScreenToClient
(
HandleRef hWnd,
ref POINT lpPoint
);
[DllImport("User32", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int ClientToScreen(HandleRef hWnd, [In, Out] POINT pt);
[DllImport("User32.dll", SetLastError = true)]
public static extern bool GetClientRect
(
HandleRef hWnd,
out RECT lpRect
);
[DllImport("User32.dll", SetLastError = true)]
public static extern bool PtInRect
(
ref RECT lprc,
POINT pt
);
[DllImport("User32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);
public static POINT GetCursorPos()
{
POINT p;
GetCursorPos(out p);
return p;
}
[DllImport( "user32.dll" )]
static extern bool GetUpdateRect( HandleRef hWnd, out RECT rect, bool bErase );
public static RECT GetUpdateRect( HandleRef hWnd, bool bErase )
{
RECT rect;
GetUpdateRect( hWnd, out rect, bErase );
return rect;
}
[DllImport( "user32.dll" )]
public static extern bool ValidateRect( IntPtr hWnd, ref RECT lpRect );
public static uint MAKEDWORD(ushort loWord, ushort hiWord)
{
return (uint)(loWord + (hiWord << 16));
}
public static uint MAKEDWORD(short loWord, short hiWord)
{
return (uint)(loWord + (hiWord << 16));
}
public static Point DWordToPoint(UInt32 dWord)
{
return new Point(
(int)(dWord & 0xFFFF),
(int)(dWord >> 16)
);
}
[DllImport("user32.dll")]
public static extern void mouse_event
(
UInt32 dwFlags, // motion and click options
UInt32 dx, // horizontal position or change
UInt32 dy, // vertical position or change
UInt32 dwData, // wheel movement
IntPtr dwExtraInfo // application-defined information
);
public static bool IsParentWindow(IntPtr hWnd, HandleRef parent)
{
while (hWnd != IntPtr.Zero)
{
if (hWnd == parent.Handle)
return true;
hWnd = GetParent(hWnd);
}
return false;
}
public const int WS_EX_TRANSPARENT = 0x00000020;
public const int GWL_EXSTYLE = ( -20 );
[DllImport( "user32.dll" )]
public static extern int GetWindowLong( IntPtr hwnd, int index );
[DllImport( "user32.dll" )]
public static extern int SetWindowLong( IntPtr hwnd, int index, int newStyle );
public const int WM_SETCURSOR = 0x20;
public const int WM_TIMER = 0x113;
public const int WM_MOUSEMOVE = 0x200;
public const int WM_MBUTTONDOWN = 0x0207;
public const int WM_MBUTTONUP = 0x0208;
public const int WM_MBUTTONDBLCLK = 0x0209;
public const int WM_LBUTTONDOWN = 0x0201;
public const int WM_LBUTTONUP = 0x0202;
public const int WM_LBUTTONDBLCLK = 0x0203;
public const int WM_RBUTTONDOWN = 0x0204;
public const int WM_RBUTTONUP = 0x0205;
public const int WM_RBUTTONDBLCLK = 0x0206;
public const int WM_ACTIVATE = 0x006;
public const int WM_ACTIVATEAPP = 0x01C;
public const int WM_NCACTIVATE = 0x086;
public const int WM_CLOSE = 0x010;
public const int WM_PAINT = 0x000F;
public const int WM_ERASEBKGND = 0x0014;
}
}
| |
// 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.Xml;
using System.Xml.Schema;
using System.Runtime.Serialization;
using System.Globalization;
using System.Collections;
using System.Data.Common;
namespace System.Data
{
[Serializable]
internal sealed class SimpleType : ISerializable
{
private string _baseType = null; // base type name
private SimpleType _baseSimpleType = null;
private XmlQualifiedName _xmlBaseType = null; // Qualified name of Basetype
private string _name = string.Empty;
private int _length = -1;
private int _minLength = -1;
private int _maxLength = -1;
private string _pattern = string.Empty;
private string _ns = string.Empty; // my ns
private string _maxExclusive = string.Empty;
private string _maxInclusive = string.Empty;
private string _minExclusive = string.Empty;
private string _minInclusive = string.Empty;
internal string _enumeration = string.Empty;
internal SimpleType(string baseType)
{
// anonymous simpletype
_baseType = baseType;
}
internal SimpleType(XmlSchemaSimpleType node)
{ // named simpletype
_name = node.Name;
_ns = (node.QualifiedName != null) ? node.QualifiedName.Namespace : "";
LoadTypeValues(node);
}
private SimpleType(SerializationInfo info, StreamingContext context)
{
_baseType = info.GetString("SimpleType.BaseType");
_baseSimpleType = (SimpleType)info.GetValue("SimpleType.BaseSimpleType", typeof(SimpleType));
if (info.GetBoolean("SimpleType.XmlBaseType.XmlQualifiedNameExists"))
{
string xmlQNName = info.GetString("SimpleType.XmlBaseType.Name");
string xmlQNNamespace = info.GetString("SimpleType.XmlBaseType.Namespace");
_xmlBaseType = new XmlQualifiedName(xmlQNName, xmlQNNamespace);
}
else
{
_xmlBaseType = null;
}
_name = info.GetString("SimpleType.Name");
_ns = info.GetString("SimpleType.NS");
_maxLength = info.GetInt32("SimpleType.MaxLength");
_length = info.GetInt32("SimpleType.Length");
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("SimpleType.BaseType", _baseType);
info.AddValue("SimpleType.BaseSimpleType", _baseSimpleType);
XmlQualifiedName xmlQN = (_xmlBaseType as XmlQualifiedName);
info.AddValue("SimpleType.XmlBaseType.XmlQualifiedNameExists", xmlQN != null ? true : false);
info.AddValue("SimpleType.XmlBaseType.Name", xmlQN != null ? xmlQN.Name : null);
info.AddValue("SimpleType.XmlBaseType.Namespace", xmlQN != null ? xmlQN.Namespace : null);
info.AddValue("SimpleType.Name", _name);
info.AddValue("SimpleType.NS", _ns);
info.AddValue("SimpleType.MaxLength", _maxLength);
info.AddValue("SimpleType.Length", _length);
}
internal void LoadTypeValues(XmlSchemaSimpleType node)
{
if ((node.Content is XmlSchemaSimpleTypeList) ||
(node.Content is XmlSchemaSimpleTypeUnion))
throw ExceptionBuilder.SimpleTypeNotSupported();
if (node.Content is XmlSchemaSimpleTypeRestriction)
{
XmlSchemaSimpleTypeRestriction content = (XmlSchemaSimpleTypeRestriction)node.Content;
XmlSchemaSimpleType ancestor = node.BaseXmlSchemaType as XmlSchemaSimpleType;
if ((ancestor != null) && (ancestor.QualifiedName.Namespace != Keywords.XSDNS))
{
_baseSimpleType = new SimpleType(node.BaseXmlSchemaType as XmlSchemaSimpleType);
}
// do we need to put qualified name?
// for user defined simpletype, always go with qname
if (content.BaseTypeName.Namespace == Keywords.XSDNS)
_baseType = content.BaseTypeName.Name;
else
_baseType = content.BaseTypeName.ToString();
if (_baseSimpleType != null && _baseSimpleType.Name != null && _baseSimpleType.Name.Length > 0)
{
_xmlBaseType = _baseSimpleType.XmlBaseType;// SimpleTypeQualifiedName;
}
else
{
_xmlBaseType = content.BaseTypeName;
}
if (_baseType == null || _baseType.Length == 0)
{
_baseType = content.BaseType.Name;
_xmlBaseType = null;
}
if (_baseType == "NOTATION")
_baseType = "string";
foreach (XmlSchemaFacet facet in content.Facets)
{
if (facet is XmlSchemaLengthFacet)
_length = Convert.ToInt32(facet.Value, null);
if (facet is XmlSchemaMinLengthFacet)
_minLength = Convert.ToInt32(facet.Value, null);
if (facet is XmlSchemaMaxLengthFacet)
_maxLength = Convert.ToInt32(facet.Value, null);
if (facet is XmlSchemaPatternFacet)
_pattern = facet.Value;
if (facet is XmlSchemaEnumerationFacet)
_enumeration = !string.IsNullOrEmpty(_enumeration) ? _enumeration + " " + facet.Value : facet.Value;
if (facet is XmlSchemaMinExclusiveFacet)
_minExclusive = facet.Value;
if (facet is XmlSchemaMinInclusiveFacet)
_minInclusive = facet.Value;
if (facet is XmlSchemaMaxExclusiveFacet)
_maxExclusive = facet.Value;
if (facet is XmlSchemaMaxInclusiveFacet)
_maxInclusive = facet.Value;
}
}
string tempStr = XSDSchema.GetMsdataAttribute(node, Keywords.TARGETNAMESPACE);
if (tempStr != null)
_ns = tempStr;
}
internal bool IsPlainString()
{
return (
XSDSchema.QualifiedName(_baseType) == XSDSchema.QualifiedName("string") &&
string.IsNullOrEmpty(_name) &&
_length == -1 &&
_minLength == -1 &&
_maxLength == -1 &&
string.IsNullOrEmpty(_pattern) &&
string.IsNullOrEmpty(_maxExclusive) &&
string.IsNullOrEmpty(_maxInclusive) &&
string.IsNullOrEmpty(_minExclusive) &&
string.IsNullOrEmpty(_minInclusive) &&
string.IsNullOrEmpty(_enumeration)
);
}
internal string BaseType
{
get
{
return _baseType;
}
}
internal XmlQualifiedName XmlBaseType
{
get
{
return _xmlBaseType;
}
}
internal string Name
{
get
{
return _name;
}
}
internal string Namespace
{
get
{
return _ns;
}
}
internal int Length
{
get
{
return _length;
}
}
internal int MaxLength
{
get
{
return _maxLength;
}
set
{
_maxLength = value;
}
}
internal SimpleType BaseSimpleType
{
get
{
return _baseSimpleType;
}
}
// return qualified name of this simple type
public string SimpleTypeQualifiedName
{
get
{
if (_ns.Length == 0)
return _name;
return (_ns + ":" + _name);
}
}
internal string QualifiedName(string name)
{
int iStart = name.IndexOf(':');
if (iStart == -1)
return Keywords.XSD_PREFIXCOLON + name;
else
return name;
}
/*
internal XmlNode ToNode(XmlDocument dc) {
return ToNode(dc, null, false);
}
*/
internal XmlNode ToNode(XmlDocument dc, Hashtable prefixes, bool inRemoting)
{
XmlElement typeNode = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SIMPLETYPE, Keywords.XSDNS);
if (_name != null && _name.Length != 0)
{
// this is a global type
typeNode.SetAttribute(Keywords.NAME, _name);
if (inRemoting)
{
typeNode.SetAttribute(Keywords.TARGETNAMESPACE, Keywords.MSDNS, Namespace);
}
}
XmlElement type = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_RESTRICTION, Keywords.XSDNS);
if (!inRemoting)
{
if (_baseSimpleType != null)
{
if (_baseSimpleType.Namespace != null && _baseSimpleType.Namespace.Length > 0)
{
string prefix = (prefixes != null) ? (string)prefixes[_baseSimpleType.Namespace] : null;
if (prefix != null)
{
type.SetAttribute(Keywords.BASE, (prefix + ":" + _baseSimpleType.Name));
}
else
{
type.SetAttribute(Keywords.BASE, _baseSimpleType.Name);
}
}
else
{ // amirhmy
type.SetAttribute(Keywords.BASE, _baseSimpleType.Name);
}
}
else
{
type.SetAttribute(Keywords.BASE, QualifiedName(_baseType)); // has to be xs:SomePrimitiveType
}
}
else
{
type.SetAttribute(Keywords.BASE, (_baseSimpleType != null) ? _baseSimpleType.Name : QualifiedName(_baseType));
}
XmlElement constraint;
if (_length >= 0)
{
constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_LENGTH, Keywords.XSDNS);
constraint.SetAttribute(Keywords.VALUE, _length.ToString(CultureInfo.InvariantCulture));
type.AppendChild(constraint);
}
if (_maxLength >= 0)
{
constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_MAXLENGTH, Keywords.XSDNS);
constraint.SetAttribute(Keywords.VALUE, _maxLength.ToString(CultureInfo.InvariantCulture));
type.AppendChild(constraint);
}
typeNode.AppendChild(type);
return typeNode;
}
internal static SimpleType CreateEnumeratedType(string values)
{
SimpleType enumType = new SimpleType("string");
enumType._enumeration = values;
return enumType;
}
internal static SimpleType CreateByteArrayType(string encoding)
{
SimpleType byteArrayType = new SimpleType("base64Binary");
return byteArrayType;
}
internal static SimpleType CreateLimitedStringType(int length)
{
SimpleType limitedString = new SimpleType("string");
limitedString._maxLength = length;
return limitedString;
}
internal static SimpleType CreateSimpleType(StorageType typeCode, Type type)
{
if ((typeCode == StorageType.Char) && (type == typeof(char)))
{
return new SimpleType("string") { _length = 1 };
}
return null;
}
// Assumption is otherSimpleType and current ST name and NS matches.
// if existing simpletype is being redefined with different facets, then it will return no-empty string defining the error
internal string HasConflictingDefinition(SimpleType otherSimpleType)
{
if (otherSimpleType == null)
return nameof(otherSimpleType);
if (MaxLength != otherSimpleType.MaxLength)
return ("MaxLength");
if (!string.Equals(BaseType, otherSimpleType.BaseType, StringComparison.Ordinal))
return ("BaseType");
if ((BaseSimpleType != null && otherSimpleType.BaseSimpleType != null) &&
(BaseSimpleType.HasConflictingDefinition(otherSimpleType.BaseSimpleType)).Length != 0)
return ("BaseSimpleType");
return string.Empty;
}
// only string types can have MaxLength
internal bool CanHaveMaxLength()
{
SimpleType rootType = this;
while (rootType.BaseSimpleType != null)
{
rootType = rootType.BaseSimpleType;
}
return string.Equals(rootType.BaseType, "string", StringComparison.OrdinalIgnoreCase);
}
internal void ConvertToAnnonymousSimpleType()
{
_name = null;
_ns = string.Empty;
SimpleType tmpSimpleType = this;
while (tmpSimpleType._baseSimpleType != null)
{
tmpSimpleType = tmpSimpleType._baseSimpleType;
}
_baseType = tmpSimpleType._baseType;
_baseSimpleType = tmpSimpleType._baseSimpleType;
_xmlBaseType = tmpSimpleType._xmlBaseType;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ExpectationBuilder.cs" company="NMock2">
//
// http://www.sourceforge.net/projects/NMock2
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Reflection;
using NMock2;
using NMock2.Matchers;
using NMock2.Syntax;
namespace NMocha.Internal {
public class ExpectationBuilder :
IReceiverSyntax, IMethodSyntax, IArgumentSyntax {
private readonly InvocationExpectation expectation;
private IMockObject mockObject;
public ExpectationBuilder(Cardinality cardinality) {
expectation = new InvocationExpectation(cardinality);
}
#region IArgumentSyntax Members
/// <summary>
/// Defines the arguments that are expected on the method call.
/// </summary>
/// <param name="expectedArguments">The expected arguments.</param>
/// <returns>Matcher syntax.</returns>
public IMatchSyntax With(params object[] expectedArguments) {
expectation.ArgumentsMatcher = new ArgumentsMatcher(ArgumentMatchers(expectedArguments));
return this;
}
/// <summary>
/// Defines that no arguments are expected on the method call.
/// </summary>
/// <returns>Matcher syntax.</returns>
public IMatchSyntax WithNoArguments() {
return With(new Matcher[0]);
}
/// <summary>
/// Defines that all arguments are allowed on the method call.
/// </summary>
/// <returns>Matcher syntax.</returns>
public IMatchSyntax WithAnyArguments() {
expectation.ArgumentsMatcher = new AlwaysMatcher(true, "(any arguments)");
return this;
}
public IStateSyntax When(IStatePredicate predicate) {
expectation.AddOrderingConstraint(new InStateOrderingConstraint(predicate));
return this;
}
public IStateSyntax Then(State state) {
expectation.AddSideEffect(new ChangeStateEffect(state));
return this;
}
/// <summary>
/// Defines a matching criteria.
/// </summary>
/// <param name="matcher">The matcher.</param>
/// <returns>
/// Action syntax defining the action to take.
/// </returns>
public IActionSyntax Matching(Matcher matcher) {
expectation.AddInvocationMatcher(matcher);
return this;
}
/// <summary>
/// Defines what will happen.
/// </summary>
/// <param name="actions">The actions to take.</param>
/// <returns>
/// Returns the comment syntax defined after will.
/// </returns>
public IStateSyntax Will(params IAction[] actions) {
foreach (IAction action in actions)
{
expectation.AddAction(action);
}
return this;
}
/// <summary>
/// Adds a comment for the expectation that is added to the error message if the expectation is not met.
/// </summary>
/// <param name="comment">The comment that is shown in the error message if this expectation is not met.
/// You can describe here why this expectation has to be met.</param>
public void Comment(string comment) {
expectation.AddComment(comment);
}
#endregion
#region IMethodSyntax Members
/// <summary>
/// Gets an indexer (get operation).
/// </summary>
/// <value>Get indexer syntax defining the value returned by the indexer.</value>
public IGetIndexerSyntax Get {
get {
Matcher methodMatcher = NewMethodNameMatcher(string.Empty, "get_Item");
EnsureMatchingMethodExistsOnMock(methodMatcher, "an indexed getter");
expectation.DescribeAsIndexer();
expectation.MethodMatcher = methodMatcher;
return new IndexGetterBuilder(expectation, this);
}
}
/// <summary>
/// Gets an indexer (set operation).
/// </summary>
/// <value>Set indexer syntax defining the value the indexer is set to.</value>
public ISetIndexerSyntax Set {
get {
Matcher methodMatcher = NewMethodNameMatcher(string.Empty, "set_Item");
EnsureMatchingMethodExistsOnMock(methodMatcher, "an indexed getter");
expectation.DescribeAsIndexer();
expectation.MethodMatcher = methodMatcher;
return new IndexSetterBuilder(expectation, this);
}
}
/// <summary>
/// Methods the specified method name.
/// </summary>
/// <param name="methodName">Name of the method.</param>
/// <param name="typeParams">The type params.</param>
/// <returns></returns>
public IArgumentSyntax Message(string methodName, params Type[] typeParams) {
return Message(new MethodNameMatcher(methodName), typeParams);
}
/// <summary>
/// Defines a method.
/// </summary>
/// <param name="method">The method.</param>
/// <param name="typeParams">The generic type params to match.</param>
/// <returns>
/// Argument syntax defining the arguments of the method.
/// </returns>
public IArgumentSyntax Message(MethodInfo method, params Type[] typeParams) {
return Message(new DescriptionOverride(method.Name, Is.Same(method)), typeParams);
}
/// <summary>
/// Methods the specified method matcher.
/// </summary>
/// <param name="methodMatcher">The method matcher.</param>
/// <param name="typeParams">The type params.</param>
/// <returns></returns>
public IArgumentSyntax Message(Matcher methodMatcher, params Type[] typeParams) {
if (typeParams != null && typeParams.Length > 0)
{
var typeMatchers = new List<Matcher>();
foreach (Type type in typeParams)
{
typeMatchers.Add(new DescriptionOverride(type.FullName, new SameMatcher(type)));
}
return Message(
methodMatcher, new GenericMethodTypeParametersMatcher(typeMatchers.ToArray()));
}
else
{
return Message(methodMatcher, new AlwaysMatcher(true, string.Empty));
}
}
/// <summary>
/// Defines a method.
/// </summary>
/// <param name="methodMatcher">Matcher for matching the method on an invocation.</param>
/// <param name="typeParamsMatcher">Matchers for matching type parameters.</param>
/// <returns>
/// Argument syntax defining the arguments of the method.
/// </returns>
public IArgumentSyntax Message(Matcher methodMatcher, Matcher typeParamsMatcher) {
EnsureMatchingMethodExistsOnMock(methodMatcher, "a method matching " + methodMatcher);
expectation.MethodMatcher = methodMatcher;
expectation.GenericMethodTypeMatcher = typeParamsMatcher;
return this;
}
/// <summary>
/// Gets the property.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <returns></returns>
public IMatchSyntax GetProperty(string propertyName) {
Matcher methodMatcher = NewMethodNameMatcher(propertyName, "get_" + propertyName);
EnsureMatchingMethodExistsOnMock(methodMatcher, "a getter for property " + propertyName);
expectation.MethodMatcher = methodMatcher;
expectation.ArgumentsMatcher = new DescriptionOverride(string.Empty, new ArgumentsMatcher());
return this;
}
/// <summary>
/// Sets the property.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <returns></returns>
public IValueSyntax SetProperty(string propertyName) {
Matcher methodMatcher = NewMethodNameMatcher(propertyName + " = ", "set_" + propertyName);
EnsureMatchingMethodExistsOnMock(methodMatcher, "a setter for property " + propertyName);
expectation.MethodMatcher = methodMatcher;
return new PropertyValueBuilder(this);
}
#endregion
#region IReceiverSyntax Members
/// <summary>
/// Defines the receiver.
/// </summary>
/// <param name="receiver">The dynamic mock on which the expectation or stub is applied.</param>
/// <returns>Method syntax defining the method, property or event.</returns>
public IMethodSyntax On(object receiver) {
if (receiver is IMockObject)
{
mockObject = (IMockObject) receiver;
expectation.Receiver = mockObject;
mockObject.AddExpectation(expectation);
}
else
{
throw new ArgumentException("not a mock object", "receiver");
}
return this;
}
#endregion
/// <summary>
/// Arguments the matchers.
/// </summary>
/// <param name="expectedArguments">The expected arguments.</param>
/// <returns></returns>
private static Matcher[] ArgumentMatchers(object[] expectedArguments) {
var matchers = new Matcher[expectedArguments.Length];
for (int i = 0; i < matchers.Length; i++)
{
object o = expectedArguments[i];
matchers[i] = (o is Matcher) ? (Matcher) o : new EqualMatcher(o);
}
return matchers;
}
/// <summary>
/// News the method name matcher.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="methodName">Name of the method.</param>
/// <returns></returns>
private static Matcher NewMethodNameMatcher(string description, string methodName) {
return new DescriptionOverride(description, new MethodNameMatcher(methodName));
}
/// <summary>
/// Ensures the matching method exists on mock.
/// </summary>
/// <param name="methodMatcher">The method matcher.</param>
/// <param name="methodDescription">The method description.</param>
private void EnsureMatchingMethodExistsOnMock(Matcher methodMatcher, string methodDescription) {
IList<MethodInfo> matches = mockObject.GetMethodsMatching(methodMatcher);
if (matches.Count == 0)
{
throw new ArgumentException("mock object " + mockObject.MockName + " does not have " + methodDescription);
}
foreach (MethodInfo methodInfo in matches)
{
// Note that methods on classes that are implementations of an interface
// method are considered virtual regardless of whether they are actually
// marked as virtual or not. Hence the additional call to IsFinal.
if ((methodInfo.IsVirtual || methodInfo.IsAbstract) && !methodInfo.IsFinal)
{
return;
}
}
throw new ArgumentException("mock object " + mockObject.MockName + " has " + methodDescription +
", but it is not virtual or abstract");
}
#region Nested type: IndexGetterBuilder
private class IndexGetterBuilder : IGetIndexerSyntax {
/// <summary>
/// Holds the instance to the <see cref="ExpectationBuilder"/>.
/// </summary>
private readonly ExpectationBuilder builder;
private readonly InvocationExpectation expectation;
/// <summary>
/// Initializes a new instance of the <see cref="IndexGetterBuilder"/> class.
/// </summary>
/// <param name="expectation">The expectation.</param>
/// <param name="builder">The builder.</param>
public IndexGetterBuilder(InvocationExpectation expectation, ExpectationBuilder builder) {
this.expectation = expectation;
this.builder = builder;
}
#region IGetIndexerSyntax Members
public IMatchSyntax this[params object[] expectedArguments] {
get {
expectation.ArgumentsMatcher = new IndexGetterArgumentsMatcher(ArgumentMatchers(expectedArguments));
return builder;
}
}
#endregion
}
#endregion
#region Nested type: IndexSetterBuilder
private class IndexSetterBuilder : ISetIndexerSyntax, IValueSyntax {
private readonly ExpectationBuilder builder;
private readonly InvocationExpectation expectation;
private Matcher[] matchers;
/// <summary>
/// Initializes a new instance of the <see cref="IndexSetterBuilder"/> class.
/// </summary>
/// <param name="expectation">The expectation.</param>
/// <param name="builder">The builder.</param>
public IndexSetterBuilder(InvocationExpectation expectation, ExpectationBuilder builder) {
this.expectation = expectation;
this.builder = builder;
}
#region ISetIndexerSyntax Members
public IValueSyntax this[params object[] expectedArguments] {
get {
Matcher[] indexMatchers = ArgumentMatchers(expectedArguments);
matchers = new Matcher[indexMatchers.Length + 1];
Array.Copy(indexMatchers, matchers, indexMatchers.Length);
SetValueMatcher(Is.Anything);
return this;
}
}
#endregion
#region IValueSyntax Members
public IMatchSyntax To(Matcher matcher) {
SetValueMatcher(matcher);
return builder;
}
public IMatchSyntax To(object equalValue) {
return To(Is.EqualTo(equalValue));
}
#endregion
private void SetValueMatcher(Matcher matcher) {
matchers[matchers.Length - 1] = matcher;
expectation.ArgumentsMatcher = new IndexSetterArgumentsMatcher(matchers);
}
}
#endregion
#region Nested type: PropertyValueBuilder
private class PropertyValueBuilder : IValueSyntax {
private readonly ExpectationBuilder builder;
/// <summary>
/// Initializes a new instance of the <see cref="PropertyValueBuilder"/> class.
/// </summary>
/// <param name="builder">The builder.</param>
public PropertyValueBuilder(ExpectationBuilder builder) {
this.builder = builder;
}
#region IValueSyntax Members
public IMatchSyntax To(Matcher valueMatcher) {
return builder.With(valueMatcher);
}
public IMatchSyntax To(object equalValue) {
return To(Is.EqualTo(equalValue));
}
#endregion
}
#endregion
public ISequenceSyntax InSequence(ISequence sequence) {
sequence.ConstrainAsNextInSeq(expectation);
return this;
}
}
}
| |
namespace TemporalTwist.ViewModels
{
using System;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Win32;
using Interfaces;
using Model;
using TemporalTwist.Interfaces.Factories;
using TemporalTwist.Interfaces.Services;
using TemporalTwist.Messaging;
using Views;
using Window = TemporalTwist.Views.Window;
public class MainViewModel : ViewModelBase
{
#region Constants and Fields
private readonly IConfigurationService configurationService;
private readonly IConfigurationViewModelFactory configurationViewModelFactory;
private readonly IJobViewModelFactory jobViewModelFactory;
private readonly IJobProcessorFactory jobProcessorFactory;
private readonly IShutdownService shutdownService;
private JobViewModel job;
private IJobProcessor processor;
#endregion
#region Constructors and Destructors
public MainViewModel(
IMessenger messenger,
IConfigurationService configurationService,
IConfigurationViewModelFactory configurationViewModelFactory,
IJobViewModelFactory jobViewModelFactory,
IJobProcessorFactory jobProcessorFactory,
IShutdownService shutdownService) : base(messenger)
{
this.configurationService = configurationService;
this.configurationViewModelFactory = configurationViewModelFactory;
this.jobViewModelFactory = jobViewModelFactory;
this.jobProcessorFactory = jobProcessorFactory;
this.shutdownService = shutdownService;
this.LoadConfiguration();
this.InitialiseCommands();
Application.Current.Exit += (sender, args) => this.SaveConfiguration();
}
#endregion
#region Public Properties
public ICommand AddFilesCommand { get; private set; }
public ICommand CloseCommand { get; private set; }
public ICommand ConfigureCommand { get; private set; }
public ICommand DropCommand { get; private set; }
public ICommand RemoveFilesCommand { get; private set; }
public ICommand ResetCommand { get; private set; }
public ICommand ShowConsoleCommand { get; private set; }
public ICommand StartCommand { get; private set; }
public ICommand StopCommand { get; private set; }
public JobViewModel Job
{
get
{
return this.job;
}
set
{
if (this.job == value)
{
return;
}
this.job = value;
this.RaisePropertyChanged();
}
}
#endregion
#region Properties
private bool IsStartable => this.Job.IsStartable;
#endregion
#region Public Methods
public void SaveConfiguration()
{
this.configurationService.SaveConfiguration();
}
#endregion
#region Methods
private void LoadConfiguration()
{
var configuration = this.configurationService.GetConfiguration();
if (configuration != null)
{
FormatList.Instance.AddRange(configuration.Formats);
this.job = this.jobViewModelFactory.CreateJobViewModel();
}
}
private void InitialiseCommands()
{
this.AddFilesCommand = new RelayCommand(this.AddFiles, () => this.job.IsIdle);
this.RemoveFilesCommand = new RelayCommand(
this.RemoveFiles,
() => this.Job.HasPendingItems && this.job.IsIdle);
this.StartCommand = new RelayCommand(this.StartProcessing, () => this.IsStartable);
this.StopCommand = new RelayCommand(this.StopProcessing, () => !this.job.IsIdle);
this.ResetCommand = new RelayCommand(this.ResetJob, () => this.job.IsIdle && this.job.ItemsProcessed > 0);
this.ConfigureCommand = new RelayCommand(this.ShowConfiguration, () => this.job.IsIdle);
this.ShowConsoleCommand = new RelayCommand(this.ShowConsole);
this.CloseCommand = new RelayCommand(this.OnClose);
this.DropCommand = new RelayCommand<object>(this.AddDroppedFiles, p => this.job.IsIdle);
}
private void OnClose()
{
this.SaveConfiguration();
this.shutdownService.RequestShutdown();
}
private void ShowConfiguration()
{
this.MessengerInstance.Send(new OpenWindowRequest(Window.ConfigurationEditor));
}
private void AddDroppedFiles(object data)
{
var files = data as string[];
if (files != null)
{
var validFiles = files.Where(SupportedFileTypes.IsFileSupported).ToArray();
this.job.AddItems(validFiles);
}
}
private void AddFiles()
{
var fileDialog = new OpenFileDialog
{
CheckFileExists = true,
CheckPathExists = true,
Multiselect = true,
Title = "Add Audio Files",
Filter = SupportedFileTypes.GetFileFilter()
};
if (fileDialog.ShowDialog() == false)
{
return;
}
var selectedFiles = fileDialog.FileNames;
this.job.AddItems(selectedFiles);
}
private void RemoveFiles()
{
var selectedItems = new IJobItem[this.job.SelectedJobItems.Count];
this.job.SelectedJobItems.CopyTo(selectedItems, 0);
foreach (var item in selectedItems)
{
this.job.JobItems.Remove(item);
}
this.job.SelectedJobItems.Clear();
}
private void ResetJob()
{
this.job.Reset();
}
private void ShowConsole()
{
this.MessengerInstance.Send(new OpenWindowRequest(Window.Console));
}
private void StartProcessing()
{
if (this.job == null)
{
return;
}
if (this.job.IsComplete)
{
this.job.Reset();
}
this.job.IsIdle = false;
this.processor = this.jobProcessorFactory.CreateJobProcessor(this.HandleProcessingFinished);
this.processor.RunAsync(this.job);
}
private void HandleProcessingFinished(IJob completedJob)
{
MessageBox.Show("Completed: " + (DateTime.Now - completedJob.StartTime));
this.job.IsIdle = true;
}
private void StopProcessing()
{
this.processor?.Cancel();
}
#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.
namespace System.Xml.Serialization
{
using System.Reflection;
using System.Collections;
using System.IO;
using System.Xml.Schema;
using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Security;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using Hashtable = System.Collections.IDictionary;
using XmlSchema = System.ServiceModel.Dispatcher.XmlSchemaConstants;
using XmlDeserializationEvents = System.Object;
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public abstract class XmlSerializerImplementation
{
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Reader"]/*' />
public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Writer"]/*' />
public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.ReadMethods"]/*' />
public virtual IDictionary ReadMethods { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.WriteMethods"]/*' />
public virtual IDictionary WriteMethods { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.TypedSerializers"]/*' />
public virtual IDictionary TypedSerializers { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.CanSerialize"]/*' />
public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.GetSerializer"]/*' />
public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); }
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlSerializer
{
private TempAssembly _tempAssembly;
private bool _typedSerializer;
private Type _primitiveType;
private XmlMapping _mapping;
private XmlDeserializationEvents _events = new XmlDeserializationEvents();
#if NET_NATIVE
public string DefaultNamespace = null;
private XmlSerializer innerSerializer;
private readonly Type rootType;
#endif
private static TempAssemblyCache s_cache = new TempAssemblyCache();
private static volatile XmlSerializerNamespaces s_defaultNamespaces;
private static XmlSerializerNamespaces DefaultNamespaces
{
get
{
if (s_defaultNamespaces == null)
{
XmlSerializerNamespaces nss = new XmlSerializerNamespaces();
nss.AddInternal("xsi", XmlSchema.InstanceNamespace);
nss.AddInternal("xsd", XmlSchema.Namespace);
if (s_defaultNamespaces == null)
{
s_defaultNamespaces = nss;
}
}
return s_defaultNamespaces;
}
}
private static InternalHashtable s_xmlSerializerTable = new InternalHashtable();
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer8"]/*' />
///<internalonly/>
protected XmlSerializer()
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) :
this(type, overrides, extraTypes, root, defaultNamespace, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty<Type>(), root, null, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
#if !NET_NATIVE
public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null, null)
#else
public XmlSerializer(Type type, Type[] extraTypes) : this(type)
#endif // NET_NATIVE
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty<Type>(), null, null, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(XmlTypeMapping xmlTypeMapping)
{
_tempAssembly = GenerateTempAssembly(xmlTypeMapping);
_mapping = xmlTypeMapping;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer6"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type) : this(type, (string)null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, string defaultNamespace)
{
if (type == null)
throw new ArgumentNullException("type");
#if NET_NATIVE
this.DefaultNamespace = defaultNamespace;
rootType = type;
#endif
_mapping = GetKnownMapping(type, defaultNamespace);
if (_mapping != null)
{
_primitiveType = type;
return;
}
#if !NET_NATIVE
_tempAssembly = s_cache[defaultNamespace, type];
if (_tempAssembly == null)
{
lock (s_cache)
{
_tempAssembly = s_cache[defaultNamespace, type];
if (_tempAssembly == null)
{
{
// need to reflect and generate new serialization assembly
XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace);
_mapping = importer.ImportTypeMapping(type, null, defaultNamespace);
_tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
}
}
s_cache.Add(defaultNamespace, type, _tempAssembly);
}
}
if (_mapping == null)
{
_mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
}
#else
XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly();
if (contract != null)
{
this.innerSerializer = contract.GetSerializer(type);
}
#endif
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
internal XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, object location, object evidence)
{
#if NET_NATIVE
throw new PlatformNotSupportedException();
#else
if (type == null)
throw new ArgumentNullException("type");
XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);
if (extraTypes != null)
{
for (int i = 0; i < extraTypes.Length; i++)
importer.IncludeType(extraTypes[i]);
}
_mapping = importer.ImportTypeMapping(type, root, defaultNamespace);
_tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
#endif
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping)
{
return GenerateTempAssembly(xmlMapping, null, null);
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace)
{
if (xmlMapping == null)
throw new ArgumentNullException("xmlMapping");
return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, null, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(TextWriter textWriter, object o)
{
Serialize(textWriter, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings);
Serialize(xmlWriter, o, namespaces);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(Stream stream, object o)
{
Serialize(stream, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
XmlWriter xmlWriter = XmlWriter.Create(stream, settings);
Serialize(xmlWriter, o, namespaces);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(XmlWriter xmlWriter, object o)
{
Serialize(xmlWriter, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
{
Serialize(xmlWriter, o, namespaces, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle)
{
Serialize(xmlWriter, o, namespaces, encodingStyle, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
{
try
{
if (_primitiveType != null)
{
SerializePrimitive(xmlWriter, o, namespaces);
}
#if !NET_NATIVE
else if (_tempAssembly == null || _typedSerializer)
{
XmlSerializationWriter writer = CreateWriter();
writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly);
try
{
Serialize(o, writer);
}
finally
{
writer.Dispose();
}
}
else
_tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
#else
else
{
if (this.innerSerializer == null)
{
throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
}
if (!string.IsNullOrEmpty(this.DefaultNamespace))
{
this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
}
XmlSerializationWriter writer = this.innerSerializer.CreateWriter();
writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
try
{
this.innerSerializer.Serialize(o, writer);
}
finally
{
writer.Dispose();
}
}
#endif
}
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
throw new InvalidOperationException(SR.XmlGenError, e);
}
xmlWriter.Flush();
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(Stream stream)
{
XmlReaderSettings settings = new XmlReaderSettings();
// WhitespaceHandling.Significant means that you only want events for *significant* whitespace
// resulting from elements marked with xml:space="preserve". All other whitespace
// (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not
// reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true.
settings.IgnoreWhitespace = true;
settings.DtdProcessing = (DtdProcessing)2; /* DtdProcessing.Parse */
// Normalization = true, that's the default for the readers created with XmlReader.Create().
// The XmlTextReader has as default a non-conformant mode according to the XML spec
// which skips some of the required processing for new lines, hence the need for the explicit
// Normalization = true. The mode is no-longer exposed on XmlReader.Create()
XmlReader xmlReader = XmlReader.Create(stream, settings);
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(TextReader textReader)
{
XmlReaderSettings settings = new XmlReaderSettings();
// WhitespaceHandling.Significant means that you only want events for *significant* whitespace
// resulting from elements marked with xml:space="preserve". All other whitespace
// (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not
// reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true.
settings.IgnoreWhitespace = true;
settings.DtdProcessing = (DtdProcessing)2; /* DtdProcessing.Parse */
// Normalization = true, that's the default for the readers created with XmlReader.Create().
// The XmlTextReader has as default a non-conformant mode according to the XML spec
// which skips some of the required processing for new lines, hence the need for the explicit
// Normalization = true. The mode is no-longer exposed on XmlReader.Create()
XmlReader xmlReader = XmlReader.Create(textReader, settings);
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(XmlReader xmlReader)
{
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' />
internal object Deserialize(XmlReader xmlReader, string encodingStyle)
{
return Deserialize(xmlReader, encodingStyle, _events);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize5"]/*' />
internal object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)
{
try
{
if (_primitiveType != null)
{
return DeserializePrimitive(xmlReader, events);
}
#if !NET_NATIVE
else if (_tempAssembly == null || _typedSerializer)
{
XmlSerializationReader reader = CreateReader();
reader.Init(xmlReader, events, encodingStyle, _tempAssembly);
try
{
return Deserialize(reader);
}
finally
{
reader.Dispose();
}
}
else
{
return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle);
}
#else
else
{
if (this.innerSerializer == null)
{
throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
}
if (!string.IsNullOrEmpty(this.DefaultNamespace))
{
this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
}
XmlSerializationReader reader = this.innerSerializer.CreateReader();
reader.Init(xmlReader, encodingStyle);
try
{
return this.innerSerializer.Deserialize(reader);
}
finally
{
reader.Dispose();
}
}
#endif
}
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
if (xmlReader is IXmlLineInfo)
{
IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader;
throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e);
}
else
{
throw new InvalidOperationException(SR.XmlSerializeError, e);
}
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CanDeserialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual bool CanDeserialize(XmlReader xmlReader)
{
if (_primitiveType != null)
{
TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType];
return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty);
}
#if !NET_NATIVE
else if (_tempAssembly != null)
{
return _tempAssembly.CanRead(_mapping, xmlReader);
}
else
{
return false;
}
#else
if (this.innerSerializer == null)
{
return false;
}
return this.innerSerializer.CanDeserialize(xmlReader);
#endif
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromMappings(XmlMapping[] mappings)
{
return FromMappings(mappings, (Type)null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type)
{
if (mappings == null || mappings.Length == 0) return Array.Empty<XmlSerializer>();
XmlSerializerImplementation contract = null;
TempAssembly tempAssembly = null;
{
if (XmlMapping.IsShallow(mappings))
{
return Array.Empty<XmlSerializer>();
}
else
{
if (type == null)
{
tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null, null);
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
contract = tempAssembly.Contract;
for (int i = 0; i < serializers.Length; i++)
{
serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
serializers[i].SetTempAssembly(tempAssembly, mappings[i]);
}
return serializers;
}
else
{
// Use XmlSerializer cache when the type is not null.
return GetSerializersFromCache(mappings, type);
}
}
}
}
private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type)
{
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
InternalHashtable typedMappingTable = null;
lock (s_xmlSerializerTable)
{
typedMappingTable = s_xmlSerializerTable[type] as InternalHashtable;
if (typedMappingTable == null)
{
typedMappingTable = new InternalHashtable();
s_xmlSerializerTable[type] = typedMappingTable;
}
}
lock (typedMappingTable)
{
InternalHashtable pendingKeys = new InternalHashtable();
for (int i = 0; i < mappings.Length; i++)
{
XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]);
serializers[i] = typedMappingTable[mappingKey] as XmlSerializer;
if (serializers[i] == null)
{
pendingKeys.Add(mappingKey, i);
}
}
if (pendingKeys.Count > 0)
{
XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count];
int index = 0;
foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
{
pendingMappings[index++] = mappingKey.Mapping;
}
TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null, null);
XmlSerializerImplementation contract = tempAssembly.Contract;
foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
{
index = (int)pendingKeys[mappingKey];
serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key];
serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping);
typedMappingTable[mappingKey] = serializers[index];
}
}
}
return serializers;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromTypes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromTypes(Type[] types)
{
if (types == null)
return Array.Empty<XmlSerializer>();
#if NET_NATIVE
var serializers = new XmlSerializer[types.Length];
for (int i = 0; i < types.Length; i++)
{
serializers[i] = new XmlSerializer(types[i]);
}
return serializers;
#else
XmlReflectionImporter importer = new XmlReflectionImporter();
XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length];
for (int i = 0; i < types.Length; i++)
{
mappings[i] = importer.ImportTypeMapping(types[i]);
}
return FromMappings(mappings);
#endif
}
#if NET_NATIVE
// this the global XML serializer contract introduced for multi-file
private static XmlSerializerImplementation xmlSerializerContract;
internal static XmlSerializerImplementation GetXmlSerializerContractFromGeneratedAssembly()
{
// hack to pull in SetXmlSerializerContract which is only referenced from the
// code injected by MainMethodInjector transform
// there's probably also a way to do this via [DependencyReductionRoot],
// but I can't get the compiler to find that...
if (xmlSerializerContract == null)
SetXmlSerializerContract(null);
// this method body used to be rewritten by an IL transform
// with the restructuring for multi-file, it has become a regular method
return xmlSerializerContract;
}
public static void SetXmlSerializerContract(XmlSerializerImplementation xmlSerializerImplementation)
{
xmlSerializerContract = xmlSerializerImplementation;
}
#endif
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateReader"]/*' />
///<internalonly/>
protected virtual XmlSerializationReader CreateReader() { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' />
///<internalonly/>
protected virtual object Deserialize(XmlSerializationReader reader) { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateWriter"]/*' />
///<internalonly/>
protected virtual XmlSerializationWriter CreateWriter() { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize7"]/*' />
///<internalonly/>
protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new PlatformNotSupportedException(); }
internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping)
{
_tempAssembly = tempAssembly;
_mapping = mapping;
_typedSerializer = true;
}
private static XmlTypeMapping GetKnownMapping(Type type, string ns)
{
if (ns != null && ns != string.Empty)
return null;
TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[type];
if (typeDesc == null)
return null;
ElementAccessor element = new ElementAccessor();
element.Name = typeDesc.DataType.Name;
XmlTypeMapping mapping = new XmlTypeMapping(null, element);
mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null));
return mapping;
}
private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
{
XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter();
writer.Init(xmlWriter, namespaces, null, null, null);
switch (_primitiveType.GetTypeCode())
{
case TypeCode.String:
writer.Write_string(o);
break;
case TypeCode.Int32:
writer.Write_int(o);
break;
case TypeCode.Boolean:
writer.Write_boolean(o);
break;
case TypeCode.Int16:
writer.Write_short(o);
break;
case TypeCode.Int64:
writer.Write_long(o);
break;
case TypeCode.Single:
writer.Write_float(o);
break;
case TypeCode.Double:
writer.Write_double(o);
break;
case TypeCode.Decimal:
writer.Write_decimal(o);
break;
case TypeCode.DateTime:
writer.Write_dateTime(o);
break;
case TypeCode.Char:
writer.Write_char(o);
break;
case TypeCode.Byte:
writer.Write_unsignedByte(o);
break;
case TypeCode.SByte:
writer.Write_byte(o);
break;
case TypeCode.UInt16:
writer.Write_unsignedShort(o);
break;
case TypeCode.UInt32:
writer.Write_unsignedInt(o);
break;
case TypeCode.UInt64:
writer.Write_unsignedLong(o);
break;
default:
if (_primitiveType == typeof(XmlQualifiedName))
{
writer.Write_QName(o);
}
else if (_primitiveType == typeof(byte[]))
{
writer.Write_base64Binary(o);
}
else if (_primitiveType == typeof(Guid))
{
writer.Write_guid(o);
}
else if (_primitiveType == typeof(TimeSpan))
{
writer.Write_TimeSpan(o);
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
}
break;
}
}
private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events)
{
XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader();
reader.Init(xmlReader, events, null, null);
object o;
switch (_primitiveType.GetTypeCode())
{
case TypeCode.String:
o = reader.Read_string();
break;
case TypeCode.Int32:
o = reader.Read_int();
break;
case TypeCode.Boolean:
o = reader.Read_boolean();
break;
case TypeCode.Int16:
o = reader.Read_short();
break;
case TypeCode.Int64:
o = reader.Read_long();
break;
case TypeCode.Single:
o = reader.Read_float();
break;
case TypeCode.Double:
o = reader.Read_double();
break;
case TypeCode.Decimal:
o = reader.Read_decimal();
break;
case TypeCode.DateTime:
o = reader.Read_dateTime();
break;
case TypeCode.Char:
o = reader.Read_char();
break;
case TypeCode.Byte:
o = reader.Read_unsignedByte();
break;
case TypeCode.SByte:
o = reader.Read_byte();
break;
case TypeCode.UInt16:
o = reader.Read_unsignedShort();
break;
case TypeCode.UInt32:
o = reader.Read_unsignedInt();
break;
case TypeCode.UInt64:
o = reader.Read_unsignedLong();
break;
default:
if (_primitiveType == typeof(XmlQualifiedName))
{
o = reader.Read_QName();
}
else if (_primitiveType == typeof(byte[]))
{
o = reader.Read_base64Binary();
}
else if (_primitiveType == typeof(Guid))
{
o = reader.Read_guid();
}
else if (_primitiveType == typeof(TimeSpan))
{
o = reader.Read_TimeSpan();
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
}
break;
}
return o;
}
private class XmlSerializerMappingKey
{
public XmlMapping Mapping;
public XmlSerializerMappingKey(XmlMapping mapping)
{
this.Mapping = mapping;
}
public override bool Equals(object obj)
{
XmlSerializerMappingKey other = obj as XmlSerializerMappingKey;
if (other == null)
return false;
if (this.Mapping.Key != other.Mapping.Key)
return false;
if (this.Mapping.ElementName != other.Mapping.ElementName)
return false;
if (this.Mapping.Namespace != other.Mapping.Namespace)
return false;
if (this.Mapping.IsSoap != other.Mapping.IsSoap)
return false;
return true;
}
public override int GetHashCode()
{
int hashCode = this.Mapping.IsSoap ? 0 : 1;
if (this.Mapping.Key != null)
hashCode ^= this.Mapping.Key.GetHashCode();
if (this.Mapping.ElementName != null)
hashCode ^= this.Mapping.ElementName.GetHashCode();
if (this.Mapping.Namespace != null)
hashCode ^= this.Mapping.Namespace.GetHashCode();
return hashCode;
}
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using bv.common;
using bv.common.Configuration;
using bv.common.Core;
using bv.model.BLToolkit;
using bv.model.Model.Core;
using bv.winclient.Core;
using eidss.avr.BaseComponents;
using eidss.avr.db.CacheReceiver;
using eidss.avr.db.Common;
using eidss.avr.db.DBService;
using eidss.avr.db.Interfaces;
using eidss.model.Avr.Commands;
using eidss.model.Avr.Commands.Export;
using eidss.model.Avr.Commands.Layout;
using eidss.model.Avr.Commands.Refresh;
using eidss.model.AVR.Db;
using eidss.model.Avr.Export;
using eidss.model.Resources;
using eidss.winclient.Reports;
namespace eidss.avr.MainForm
{
public sealed class AvrMainFormPresenter : RelatedObjectPresenter
{
private readonly IAvrMainFormView m_FormView;
public AvrMainFormPresenter(SharedPresenter sharedPresenter, IAvrMainFormView view)
: base(sharedPresenter, view)
{
m_FormView = view;
m_FormView.DBService = new BaseAvrDbService();
}
public override void Process(Command cmd)
{
if (cmd is QueryLayoutCloseCommand)
{
m_FormView.CloseQueryLayoutStart();
cmd.State = CommandState.Processed;
}
else if (cmd is QueryLayoutDeleteCommand)
{
var deleteCommand = (cmd as QueryLayoutDeleteCommand);
m_FormView.DeleteQueryLayoutStart(deleteCommand);
cmd.State = CommandState.Processed;
}
else if (cmd is ExecQueryCommand)
{
long queryId = m_SharedPresenter.SharedModel.SelectedQueryId;
InvalidateQuery(queryId);
ExecQuery(queryId);
cmd.State = CommandState.Processed;
}
}
public void ExportQueryLineListToExcelOrAccess(long queryId, ExportType exportType)
{
if (exportType == ExportType.Mdb)
{
if (BaseSettings.UseAvrCache)
{
ExportTo("mdb", EidssMessages.Get("msgFilterAccess", "MS Access database|*.mdb"),
s =>
{
AvrAccessExportResult result = AccessExporter.ExportAnyCPU(queryId, s);
if (!result.IsOk)
{
throw new AvrException(result.ErrorMessage + result.ExceptionString);
}
});
}
else
{
ErrorForm.ShowError(EidssMessages.Get("msgCannotExportAvrServiceNotAccessable"));
}
}
else
{
DataTable sourceTable = (queryId == m_SharedPresenter.SharedModel.SelectedQueryId)
? m_SharedPresenter.GetQueryResultCopy()
: ExecQueryInternal(queryId, ModelUserContext.CurrentLanguage, SharedPresenter.SharedModel.UseArchiveData);
DataTable destTable = QueryHelper.GetTableWithoutCopiedColumns(sourceTable);
switch (exportType)
{
case ExportType.Xls:
ExportTo("xls", EidssMessages.Get("msgFilterExcel", "Excel documents|*.xls"),
s => NpoiExcelWrapper.QueryLineListToExcel(s, destTable, exportType));
break;
case ExportType.Xlsx:
ExportTo("xlsx", EidssMessages.Get("msgFilterExcelXLSX", "Excel documents|*.xlsx"),
s => NpoiExcelWrapper.QueryLineListToExcel(s, destTable, exportType));
break;
default:
throw new AvrException(String.Format("Not supported export format {0}", exportType));
}
}
}
#region Check Avr Service
#endregion
#region Executing query
public void ExecQuery(long queryId)
{
ExecQueryForPresenter(m_SharedPresenter, queryId);
}
public static void ExecQueryForPresenter(SharedPresenter sharedPresenter, long queryId)
{
// we should clear QueryResult before executing new QUery
sharedPresenter.SetQueryResult(null);
DataTable result = ExecQueryInternal(queryId, ModelUserContext.CurrentLanguage, sharedPresenter.SharedModel.UseArchiveData);
sharedPresenter.SetQueryResult(result);
sharedPresenter.SharedModel.QueryRefreshDateTime = UpdateQueryRefreshDateTime(queryId);
}
public static DataTable ExecQueryInternal
(long queryId, string lang, bool isArchive, Func<long, string, bool, DataTable> queryExecutor = null)
{
try
{
isArchive &= ArchiveDataHelper.ShowUseArchiveDataCheckbox;
DataTable result;
if (queryId > 0)
{
if (queryExecutor == null)
{
if (BaseSettings.UseAvrCache)
{
using (var wrapper = new ServiceClientWrapper())
{
result = WinCheckAvrServiceAccessability(wrapper)
? GetAvrServiceQueryResult(wrapper, queryId, isArchive)
: new DataTable();
}
}
else
{
result = GetQueryResult(queryId, isArchive);
}
}
else
{
result = queryExecutor(queryId, lang, isArchive);
}
result.TableName = QueryProcessor.GetQueryName(queryId);
QueryProcessor.SetCopyPropertyForColumnsIfNeeded(result);
QueryProcessor.TranslateTableFields(result, queryId);
QueryProcessor.SetNullForForbiddenTableFields(result, queryId);
}
else
{
result = new DataTable();
}
QueryProcessor.RemoveNotExistingColumns(result, queryId);
return result;
}
catch (OutOfMemoryException ex)
{
Trace.WriteLine(ex);
ErrorForm.ShowMessage("msgQueryResultIsTooBig", null);
return new DataTable();
}
catch (Exception ex)
{
Trace.WriteLine(ex);
throw new AvrDbException(String.Format("Error while executing query with id '{0}'", queryId), ex);
}
}
public static DataTable GetQueryResult(long queryId, bool isArchive)
{
string queryString;
DataTable defaultData;
using (CreateExecutingQueryDialog())
{
using (DbManagerProxy manager = DbManagerFactory.Factory.Create())
{
queryString = QueryHelper.GetQueryText(manager, queryId, true);
defaultData = QueryHelper.GetInnerQueryResult(manager, queryString);
}
}
if (isArchive)
{
try
{
if (DbManagerFactory.Factory[DatabaseType.Archive] == null)
{
DbManagerFactory.SetSqlFactory(new ConnectionCredentials(null, "Archive").ConnectionString, DatabaseType.Archive);
}
using (CreateExecutingArchiveQueryDialog())
{
using (DbManagerProxy archiveManager = DbManagerFactory.Factory[DatabaseType.Archive].Create())
{
using (DbManagerProxy manager = DbManagerFactory.Factory.Create())
{
QueryHelper.DropAndCreateArchiveQuery(manager, archiveManager, queryId);
}
DataTable archiveData = QueryHelper.GetInnerQueryResult(archiveManager, queryString);
defaultData.Merge(archiveData);
}
}
}
catch (SqlException ex)
{
Trace.WriteLine(ex);
ErrorForm.ShowMessage("msgErrorExecutingArchiveQuery", null);
}
}
foreach (DataColumn column in defaultData.Columns)
{
column.AllowDBNull = true;
}
return defaultData;
}
private static WaitDialog CreateExecutingQueryDialog()
{
string message = EidssMessages.Get("msgAvrExecutingQuery");
return new WaitDialog(message, m_WaitTitle);
}
private static WaitDialog CreateExecutingArchiveQueryDialog()
{
string message = EidssMessages.Get("msgAvrExecutingArchiveQuery");
return new WaitDialog(message, m_WaitTitle);
}
internal static DataTable GetAvrServiceQueryResult(ServiceClientWrapper wrapper, long queryId, bool isArchive)
{
try
{
using (CreateAvrServiceReceiveQueryDialog())
{
var receiver = new AvrCacheReceiver(wrapper);
CachedQueryResult result = receiver.GetCachedQueryTable(queryId, ModelUserContext.CurrentLanguage, isArchive);
return result.QueryTable;
}
}
catch (Exception ex)
{
Trace.WriteLine(ex);
if (BaseSettings.ThrowExceptionOnError)
{
throw;
}
ErrorForm.ShowError(EidssMessages.Get("msgAvrServiceError"), ex);
return new DataTable();
}
}
internal static DateTime UpdateQueryRefreshDateTime(long queryId)
{
try
{
if (BaseSettings.UseAvrCache)
{
using (var wrapper = new ServiceClientWrapper())
{
return wrapper.GetQueryRefreshDateTime(queryId, ModelUserContext.CurrentLanguage);
}
}
return DateTime.Now;
}
catch (Exception ex)
{
Trace.WriteLine(ex);
return DateTime.Now;
}
}
public static void InvalidateQuery(long queryId)
{
if (BaseSettings.UseAvrCache && queryId > 0)
{
using (var wrapper = new ServiceClientWrapper())
{
if (WinCheckAvrServiceAccessability(wrapper))
{
wrapper.InvalidateQueryCache(queryId);
}
}
}
}
#endregion
}
}
| |
/*
* Copyright (C) 2012, 2013 OUYA, 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.
*/
// Unity JNI reference: http://docs.unity3d.com/Documentation/ScriptReference/AndroidJNI.html
// JNI Spec: http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/jniTOC.html
// Android Plugins: http://docs.unity3d.com/Documentation/Manual/Plugins.html#AndroidPlugins
// Unity Android Plugin Guide: http://docs.unity3d.com/Documentation/Manual/PluginsForAndroid.html
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
public static class OuyaSDK
{
public const string VERSION = "1.0.10.13";
/// <summary>
/// Cache joysticks
/// </summary>
public static string[] Joysticks = null;
/// <summary>
/// Query joysticks every N seconds
/// </summary>
private static DateTime m_timerJoysticks = DateTime.MinValue;
/// <summary>
/// Update joysticks with a timer
/// </summary>
public static void UpdateJoysticks()
{
#if !UNITY_WP8
if (m_timerJoysticks < DateTime.Now)
{
//check for new joysticks every N seconds
m_timerJoysticks = DateTime.Now + TimeSpan.FromSeconds(3);
string[] joysticks = Input.GetJoystickNames();
// look for changes
bool detectedChange = false;
if (null == Joysticks)
{
detectedChange = true;
}
else if (joysticks.Length != Joysticks.Length)
{
detectedChange = true;
}
else
{
for (int index = 0; index < joysticks.Length; ++index)
{
if (joysticks[index] != Joysticks[index])
{
detectedChange = true;
break;
}
}
}
Joysticks = joysticks;
if (detectedChange)
{
foreach (OuyaSDK.IJoystickCalibrationListener listener in OuyaSDK.getJoystickCalibrationListeners())
{
//Debug.Log("OuyaGameObject: Invoke OuyaOnJoystickCalibration");
listener.OuyaOnJoystickCalibration();
}
}
}
#endif
}
/// <summary>
/// The developer ID assigned by OuyaGameObject
/// </summary>
static private string m_developerId = string.Empty;
/// <summary>
/// Inidicates IAP has been setup and is ready for processing
/// </summary>
private static bool m_iapInitComplete = false;
/// <summary>
/// Check if the device is an OUYA
/// </summary>
/// <returns></returns>
public static bool IsOUYA()
{
if (SystemInfo.deviceModel.ToUpper().Contains("OUYA"))
{
return true;
}
return false;
}
#region Controllers
#region Key Codes
public const int KEYCODE_BUTTON_A = 96;
public const int KEYCODE_BUTTON_B = 97;
public const int KEYCODE_BUTTON_X = 99;
public const int KEYCODE_BUTTON_Y = 100;
public const int KEYCODE_BUTTON_L1 = 102;
public const int KEYCODE_BUTTON_L2 = 104;
public const int KEYCODE_BUTTON_R1 = 103;
public const int KEYCODE_BUTTON_R2 = 105;
public const int KEYCODE_BUTTON_L3 = 106;
public const int KEYCODE_BUTTON_R3 = 107;
public const int KEYCODE_BUTTON_SYSTEM = 108;
public const int AXIS_X = 0;
public const int AXIS_Y = 1;
public const int AXIS_Z = 11;
public const int AXIS_RZ = 14;
public const int KEYCODE_DPAD_UP = 19;
public const int KEYCODE_DPAD_DOWN = 20;
public const int KEYCODE_DPAD_LEFT = 21;
public const int KEYCODE_DPAD_RIGHT = 22;
public const int KEYCODE_DPAD_CENTER = 23;
//For EDITOR / PC / MAC
public const int KEYCODE_BUTTON_SELECT = -1;
public const int KEYCODE_BUTTON_START = -2;
public const int KEYCODE_BUTTON_ESCAPE = 41;
#endregion
#region OUYA controller
public const int BUTTON_O = KEYCODE_BUTTON_A;
public const int BUTTON_U = KEYCODE_BUTTON_X;
public const int BUTTON_Y = KEYCODE_BUTTON_Y;
public const int BUTTON_A = KEYCODE_BUTTON_B;
public const int BUTTON_LB = KEYCODE_BUTTON_L1;
public const int BUTTON_LT = KEYCODE_BUTTON_L2;
public const int BUTTON_RB = KEYCODE_BUTTON_R1;
public const int BUTTON_RT = KEYCODE_BUTTON_R2;
public const int BUTTON_L3 = KEYCODE_BUTTON_L3;
public const int BUTTON_R3 = KEYCODE_BUTTON_R3;
public const int BUTTON_SYSTEM = KEYCODE_BUTTON_SYSTEM;
// for EDITOR / PC / MAC
public const int BUTTON_START = KEYCODE_BUTTON_START;
public const int BUTTON_SELECT = KEYCODE_BUTTON_SELECT;
public const int BUTTON_ESCAPE = KEYCODE_BUTTON_ESCAPE;
public const int AXIS_LSTICK_X = AXIS_X;
public const int AXIS_LSTICK_Y = AXIS_Y;
public const int AXIS_RSTICK_X = AXIS_Z;
public const int AXIS_RSTICK_Y = AXIS_RZ;
public const int BUTTON_DPAD_UP = KEYCODE_DPAD_UP;
public const int BUTTON_DPAD_RIGHT = KEYCODE_DPAD_RIGHT;
public const int BUTTON_DPAD_DOWN = KEYCODE_DPAD_DOWN;
public const int BUTTON_DPAD_LEFT = KEYCODE_DPAD_LEFT;
public const int BUTTON_DPAD_CENTER = KEYCODE_DPAD_CENTER;
public enum KeyEnum
{
NONE = -1,
BUTTON_O = OuyaSDK.BUTTON_O,
BUTTON_U = OuyaSDK.BUTTON_U,
BUTTON_Y = OuyaSDK.KEYCODE_BUTTON_Y,
BUTTON_A = OuyaSDK.BUTTON_A,
BUTTON_LB = OuyaSDK.BUTTON_LB,
BUTTON_LT = OuyaSDK.KEYCODE_BUTTON_L2,
BUTTON_RB = OuyaSDK.BUTTON_RB,
BUTTON_RT = OuyaSDK.BUTTON_RT,
BUTTON_L3 = OuyaSDK.BUTTON_L3,
BUTTON_R3 = OuyaSDK.BUTTON_R3,
BUTTON_SYSTEM = OuyaSDK.BUTTON_SYSTEM,
BUTTON_START = OuyaSDK.BUTTON_START,
BUTTON_SELECT = OuyaSDK.BUTTON_SELECT,
BUTTON_ESCAPE = OuyaSDK.BUTTON_ESCAPE,
AXIS_LSTICK_X = OuyaSDK.AXIS_LSTICK_X,
AXIS_LSTICK_Y = OuyaSDK.AXIS_LSTICK_Y,
AXIS_RSTICK_X = OuyaSDK.AXIS_RSTICK_X,
AXIS_RSTICK_Y = OuyaSDK.AXIS_RSTICK_Y,
BUTTON_DPAD_UP = OuyaSDK.BUTTON_DPAD_UP,
BUTTON_DPAD_RIGHT = OuyaSDK.BUTTON_DPAD_RIGHT,
BUTTON_DPAD_DOWN = OuyaSDK.BUTTON_DPAD_DOWN,
BUTTON_DPAD_LEFT = OuyaSDK.BUTTON_DPAD_LEFT,
BUTTON_DPAD_CENTER = OuyaSDK.BUTTON_DPAD_CENTER,
BUTTON_BACK,
HARMONIX_ROCK_BAND_GUITAR_GREEN,
HARMONIX_ROCK_BAND_GUITAR_RED,
HARMONIX_ROCK_BAND_GUITAR_YELLOW,
HARMONIX_ROCK_BAND_GUITAR_BLUE,
HARMONIX_ROCK_BAND_GUITAR_ORANGE,
HARMONIX_ROCK_BAND_GUITAR_LOWER,
HARMONIX_ROCK_BAND_GUITAR_WHAMMI,
HARMONIX_ROCK_BAND_GUITAR_PICKUP,
HARMONIX_ROCK_BAND_GUITAR_STRUM,
HARMONIX_ROCK_BAND_DRUMKIT_GREEN,
HARMONIX_ROCK_BAND_DRUMKIT_RED,
HARMONIX_ROCK_BAND_DRUMKIT_YELLOW,
HARMONIX_ROCK_BAND_DRUMKIT_BLUE,
HARMONIX_ROCK_BAND_DRUMKIT_ORANGE,
HARMONIX_ROCK_BAND_DRUMKIT_A,
HARMONIX_ROCK_BAND_DRUMKIT_B,
HARMONIX_ROCK_BAND_DRUMKIT_X,
HARMONIX_ROCK_BAND_DRUMKIT_Y,
}
public enum AxisEnum
{
NONE = -1,
AXIS_LSTICK_X,
AXIS_LSTICK_Y,
AXIS_RSTICK_X,
AXIS_RSTICK_Y,
AXIS_LTRIGGER,
AXIS_RTRIGGER,
}
public enum OuyaPlayer
{
player1=1,
player2=2,
player3=3,
player4=4,
player5=5,
player6=6,
player7=7,
player8=8,
player9=9,
player10=10,
player11=11,
none=0,
}
/// <summary>
/// Array of supported controllers
/// </summary>
private static List<IOuyaController> m_supportedControllers = new List<IOuyaController>();
/// <summary>
/// Register a supported controllers
/// </summary>
static OuyaSDK()
{
// Log the ouya-unity-plugin version:
Debug.Log(string.Format("ouya-unity-plugin version: {0}", VERSION));
try
{
//Debug.Log("Accessing Assembly for IOuyaController");
Assembly assembly = Assembly.GetAssembly(typeof(IOuyaController));
//Debug.Log("Getting types");
foreach (Type type in assembly.GetTypes())
{
//Debug.Log(string.Format("Type={0}", type.Name));
if (type == typeof (IOuyaController))
{
//Debug.Log(" skip...");
}
else if (typeof (IOuyaController).IsAssignableFrom(type))
{
//Debug.Log(" Creating...");
IOuyaController controller = (IOuyaController) Activator.CreateInstance(type);
if (null != controller)
{
m_supportedControllers.Add(controller);
/*
Debug.Log(string.Format("Registered Controller: {0}", controller.GetType()));
foreach (string joystick in controller.GetSupportedJoysicks())
{
Debug.Log(string.Format(" Supports: {0}", joystick));
}
*/
}
}
}
}
catch (Exception)
{
}
}
/// <summary>
/// Check for a supported controller given the controller name
/// </summary>
/// <param name="controllerName"></param>
/// <returns></returns>
public static IOuyaController GetSupportedController(string controllerName)
{
foreach (IOuyaController controller in m_supportedControllers)
{
foreach (string name in controller.GetSupportedJoysicks())
{
if (controllerName.ToUpper().Contains(name.ToUpper()))
{
return controller;
}
}
}
return null;
}
/// <summary>
/// Check if the player has a supported controller
/// </summary>
/// <param name="player"></param>
/// <returns></returns>
public static IOuyaController GetSupportedController(OuyaSDK.OuyaPlayer player)
{
if (null == OuyaSDK.Joysticks)
{
return null;
}
int playerIndex = (int) player - 1;
if (playerIndex >= OuyaSDK.Joysticks.Length)
{
return null;
}
string joystickName = OuyaSDK.Joysticks[playerIndex];
if (null == joystickName)
{
return null;
}
return GetSupportedController(joystickName);
}
/// <summary>
/// Return the supported axises
/// </summary>
/// <param name="player"></param>
/// <returns></returns>
public static OuyaSDK.KeyEnum[] GetSupportedAxises(OuyaSDK.OuyaPlayer player)
{
IOuyaController controller = GetSupportedController(player);
if (null == controller)
{
return null;
}
return controller.GetSupportedAxises();
}
/// <summary>
/// Return the supported buttons
/// </summary>
/// <param name="player"></param>
/// <returns></returns>
public static OuyaSDK.KeyEnum[] GetSupportedButtons(OuyaSDK.OuyaPlayer player)
{
IOuyaController controller = GetSupportedController(player);
if (null == controller)
{
return null;
}
return controller.GetSupportedButtons();
}
/// <summary>
/// Check if the controller axis is available
/// </summary>
/// <param name="keyCode"></param>
/// <param name="player"></param>
/// <returns></returns>
public static bool HasAxis(OuyaSDK.KeyEnum keyCode, OuyaSDK.OuyaPlayer player)
{
IOuyaController controller = GetSupportedController(player);
if (null == controller)
{
return false;
}
return controller.HasAxis(keyCode);
}
/// <summary>
/// Check if the controller button is available
/// </summary>
/// <param name="keyCode"></param>
/// <param name="player"></param>
/// <returns></returns>
public static bool HasButton(OuyaSDK.KeyEnum keyCode, OuyaSDK.OuyaPlayer player)
{
IOuyaController controller = GetSupportedController(player);
if (null == controller)
{
return false;
}
return controller.HasButton(keyCode);
}
/// <summary>
/// Check if the axis should be inverted after accessing the Unity API
/// </summary>
/// <param name="keyCode"></param>
/// <param name="player"></param>
/// <returns></returns>
public static bool GetAxisInverted(OuyaSDK.KeyEnum keyCode, OuyaSDK.OuyaPlayer player)
{
IOuyaController controller = GetSupportedController(player);
if (null == controller)
{
return false;
}
return controller.GetAxisInverted(keyCode);
}
/// <summary>
/// Get the AxisName to be used with the Unity API
/// </summary>
/// <param name="keyCode"></param>
/// <param name="player"></param>
/// <returns></returns>
public static string GetUnityAxisName(OuyaSDK.KeyEnum keyCode, OuyaSDK.OuyaPlayer player)
{
IOuyaController controller = GetSupportedController(player);
if (null == controller)
{
return string.Empty;
}
return controller.GetUnityAxisName(keyCode, player);
}
/// <summary>
/// Get the KeyCode to be used with the Unity API
/// </summary>
/// <param name="keyCode"></param>
/// <param name="player"></param>
/// <returns></returns>
public static KeyCode GetUnityKeyCode(OuyaSDK.KeyEnum keyCode, OuyaSDK.OuyaPlayer player)
{
IOuyaController controller = GetSupportedController(player);
if (null == controller)
{
return (KeyCode)(-1);
}
return controller.GetUnityKeyCode(keyCode, player);
}
#endregion
#endregion
/// <summary>
/// Initialized by OuyaGameObject
/// </summary>
/// <param name="developerId"></param>
public static void initialize(string developerId)
{
m_developerId = developerId;
OuyaSDK.OuyaJava.JavaSetDeveloperId();
OuyaSDK.OuyaJava.JavaUnityInitialized();
}
/// <summary>
/// Access the developer id
/// </summary>
/// <returns></returns>
public static string getDeveloperId()
{
return m_developerId;
}
public static bool isIAPInitComplete()
{
return m_iapInitComplete;
}
public static void setIAPInitComplete()
{
m_iapInitComplete = true;
}
#region Mirror Java API
public class GenericListener<T>
{
public delegate void SuccessDelegate(T data);
public SuccessDelegate onSuccess = null;
public delegate void FailureDelegate(int errorCode, String errorMessage);
public FailureDelegate onFailure = null;
}
public class CancelIgnoringIapResponseListener<T> : GenericListener<T>
{
}
public static void fetchGamerInfo()
{
OuyaSDK.OuyaJava.JavaFetchGamerInfo();
}
public static void showCursor(bool flag)
{
OuyaSDK.OuyaJava.JavaShowCursor(flag);
}
public static void enableUnityInput(bool enabled)
{
OuyaSDK.OuyaJava.JavaEnableUnityInput(enabled);
}
public static void putGameData(string key, string val)
{
OuyaSDK.OuyaJava.JavaPutGameData(key, val);
}
public static string getGameData(string key)
{
return OuyaSDK.OuyaJava.JavaGetGameData(key);
}
public static void requestProductList(List<Purchasable> purchasables)
{
foreach (Purchasable purchasable in purchasables)
{
//Debug.Log(string.Format("Unity Adding: {0}", purchasable.getProductId()));
OuyaSDK.OuyaJava.JavaAddGetProduct(purchasable);
}
OuyaSDK.OuyaJava.JavaGetProductsAsync();
}
public static void requestPurchase(Purchasable purchasable)
{
OuyaSDK.OuyaJava.JavaRequestPurchaseAsync(purchasable);
}
public static void requestReceiptList()
{
OuyaSDK.OuyaJava.JavaGetReceiptsAsync();
}
public class InputButtonListener<T> : GenericListener<T>
{
}
public class InputAxisListener<T> : GenericListener<T>
{
}
public class DeviceListener<T> : GenericListener<T>
{
}
#endregion
#region Data containers
[Serializable]
public class GamerInfo
{
public string uuid = string.Empty;
public string username = string.Empty;
}
[Serializable]
public class Purchasable
{
public string productId = string.Empty;
}
[Serializable]
public class Product
{
public string currencyCode = string.Empty;
public string description = string.Empty;
public string identifier = string.Empty;
public float localPrice = 0f;
public string name = string.Empty;
public float originalPrice = 0f;
public float percentOff = 0f;
public int priceInCents = 0;
public int productVersionToBundle = 0;
}
[Serializable]
public class Receipt
{
public string currency = string.Empty;
public string gamer = string.Empty;
public DateTime generatedDate = DateTime.MinValue;
public string identifier = string.Empty;
public float localPrice = 0f;
public int priceInCents = 0;
public DateTime purchaseDate = DateTime.MinValue;
public string uuid = string.Empty;
}
#endregion
#region Joystick Callibration Listeners
public interface IJoystickCalibrationListener
{
void OuyaOnJoystickCalibration();
}
private static List<IJoystickCalibrationListener> m_joystickCalibrationListeners = new List<IJoystickCalibrationListener>();
public static List<IJoystickCalibrationListener> getJoystickCalibrationListeners()
{
return m_joystickCalibrationListeners;
}
public static void registerJoystickCalibrationListener(IJoystickCalibrationListener listener)
{
if (!m_joystickCalibrationListeners.Contains(listener))
{
m_joystickCalibrationListeners.Add(listener);
}
}
public static void unregisterJoystickCalibrationListener(IJoystickCalibrationListener listener)
{
if (m_joystickCalibrationListeners.Contains(listener))
{
m_joystickCalibrationListeners.Remove(listener);
}
}
#endregion
#region Menu Button Up Listeners
public interface IMenuButtonUpListener
{
void OuyaMenuButtonUp();
}
private static List<IMenuButtonUpListener> m_menuButtonUpListeners = new List<IMenuButtonUpListener>();
public static List<IMenuButtonUpListener> getMenuButtonUpListeners()
{
return m_menuButtonUpListeners;
}
public static void registerMenuButtonUpListener(IMenuButtonUpListener listener)
{
if (!m_menuButtonUpListeners.Contains(listener))
{
m_menuButtonUpListeners.Add(listener);
}
}
public static void unregisterMenuButtonUpListener(IMenuButtonUpListener listener)
{
if (m_menuButtonUpListeners.Contains(listener))
{
m_menuButtonUpListeners.Remove(listener);
}
}
#endregion
#region Menu Appearing Listeners
public interface IMenuAppearingListener
{
void OuyaMenuAppearing();
}
private static List<IMenuAppearingListener> m_menuAppearingListeners = new List<IMenuAppearingListener>();
public static List<IMenuAppearingListener> getMenuAppearingListeners()
{
return m_menuAppearingListeners;
}
public static void registerMenuAppearingListener(IMenuAppearingListener listener)
{
if (!m_menuAppearingListeners.Contains(listener))
{
m_menuAppearingListeners.Add(listener);
}
}
public static void unregisterMenuAppearingListener(IMenuAppearingListener listener)
{
if (m_menuAppearingListeners.Contains(listener))
{
m_menuAppearingListeners.Remove(listener);
}
}
#endregion
#region Pause Listeners
public interface IPauseListener
{
void OuyaOnPause();
}
private static List<IPauseListener> m_pauseListeners = new List<IPauseListener>();
public static List<IPauseListener> getPauseListeners()
{
return m_pauseListeners;
}
public static void registerPauseListener(IPauseListener listener)
{
if (!m_pauseListeners.Contains(listener))
{
m_pauseListeners.Add(listener);
}
}
public static void unregisterPauseListener(IPauseListener listener)
{
if (m_pauseListeners.Contains(listener))
{
m_pauseListeners.Remove(listener);
}
}
#endregion
#region Resume Listeners
public interface IResumeListener
{
void OuyaOnResume();
}
private static List<IResumeListener> m_resumeListeners = new List<IResumeListener>();
public static List<IResumeListener> getResumeListeners()
{
return m_resumeListeners;
}
public static void registerResumeListener(IResumeListener listener)
{
if (!m_resumeListeners.Contains(listener))
{
m_resumeListeners.Add(listener);
}
}
public static void unregisterResumeListener(IResumeListener listener)
{
if (m_resumeListeners.Contains(listener))
{
m_resumeListeners.Remove(listener);
}
}
#endregion
#region Fetch Gamer UUID Listener
public interface IFetchGamerInfoListener
{
void OuyaFetchGamerInfoOnSuccess(string uuid, string username);
void OuyaFetchGamerInfoOnFailure(int errorCode, string errorMessage);
void OuyaFetchGamerInfoOnCancel();
}
private static List<IFetchGamerInfoListener> m_FetchGamerInfoListeners = new List<IFetchGamerInfoListener>();
public static List<IFetchGamerInfoListener> getFetchGamerInfoListeners()
{
return m_FetchGamerInfoListeners;
}
public static void registerFetchGamerInfoListener(IFetchGamerInfoListener listener)
{
if (!m_FetchGamerInfoListeners.Contains(listener))
{
m_FetchGamerInfoListeners.Add(listener);
}
}
public static void unregisterFetchGamerInfoListener(IFetchGamerInfoListener listener)
{
if (m_FetchGamerInfoListeners.Contains(listener))
{
m_FetchGamerInfoListeners.Remove(listener);
}
}
#endregion
#region Get GetProducts Listeners
public interface IGetProductsListener
{
void OuyaGetProductsOnSuccess(List<OuyaSDK.Product> products);
void OuyaGetProductsOnFailure(int errorCode, string errorMessage);
void OuyaGetProductsOnCancel();
}
private static List<IGetProductsListener> m_getProductsListeners = new List<IGetProductsListener>();
public static List<IGetProductsListener> getGetProductsListeners()
{
return m_getProductsListeners;
}
public static void registerGetProductsListener(IGetProductsListener listener)
{
if (!m_getProductsListeners.Contains(listener))
{
m_getProductsListeners.Add(listener);
}
}
public static void unregisterGetProductsListener(IGetProductsListener listener)
{
if (m_getProductsListeners.Contains(listener))
{
m_getProductsListeners.Remove(listener);
}
}
#endregion
#region Purchase Listener
public interface IPurchaseListener
{
void OuyaPurchaseOnSuccess(OuyaSDK.Product product);
void OuyaPurchaseOnFailure(int errorCode, string errorMessage);
void OuyaPurchaseOnCancel();
}
private static List<IPurchaseListener> m_purchaseListeners = new List<IPurchaseListener>();
public static List<IPurchaseListener> getPurchaseListeners()
{
return m_purchaseListeners;
}
public static void registerPurchaseListener(IPurchaseListener listener)
{
if (!m_purchaseListeners.Contains(listener))
{
m_purchaseListeners.Add(listener);
}
}
public static void unregisterPurchaseListener(IPurchaseListener listener)
{
if (m_purchaseListeners.Contains(listener))
{
m_purchaseListeners.Remove(listener);
}
}
#endregion
#region Get GetReceipts Listeners
public interface IGetReceiptsListener
{
void OuyaGetReceiptsOnSuccess(List<Receipt> receipts);
void OuyaGetReceiptsOnFailure(int errorCode, string errorMessage);
void OuyaGetReceiptsOnCancel();
}
private static List<IGetReceiptsListener> m_getReceiptsListeners = new List<IGetReceiptsListener>();
public static List<IGetReceiptsListener> getGetReceiptsListeners()
{
return m_getReceiptsListeners;
}
public static void registerGetReceiptsListener(IGetReceiptsListener listener)
{
if (!m_getReceiptsListeners.Contains(listener))
{
m_getReceiptsListeners.Add(listener);
}
}
public static void unregisterGetReceiptsListener(IGetReceiptsListener listener)
{
if (m_getReceiptsListeners.Contains(listener))
{
m_getReceiptsListeners.Remove(listener);
}
}
#endregion
#region Java Interface
public class OuyaJava
{
private const string JAVA_CLASS = "tv.ouya.sdk.OuyaUnityPlugin";
public static void JavaInit()
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// attach our thread to the java vm; obviously the main thread is already attached but this is good practice..
AndroidJNI.AttachCurrentThread();
// first we try to find our main activity..
IntPtr cls_Activity = AndroidJNI.FindClass("com/unity3d/player/UnityPlayer");
IntPtr fid_Activity = AndroidJNI.GetStaticFieldID(cls_Activity, "currentActivity", "Landroid/app/Activity;");
IntPtr obj_Activity = AndroidJNI.GetStaticObjectField(cls_Activity, fid_Activity);
Debug.Log("obj_Activity = " + obj_Activity);
// create a JavaClass object...
IntPtr cls_JavaClass = AndroidJNI.FindClass("tv/ouya/sdk/OuyaUnityPlugin");
IntPtr mid_JavaClass = AndroidJNI.GetMethodID(cls_JavaClass, "<init>", "(Landroid/app/Activity;)V");
IntPtr obj_JavaClass = AndroidJNI.NewObject(cls_JavaClass, mid_JavaClass, new jvalue[] { new jvalue() { l = obj_Activity } });
Debug.Log("JavaClass object = " + obj_JavaClass);
#endif
}
public static void JavaSetDeveloperId()
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
Debug.Log("JavaSetDeveloperId");
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic<String>("setDeveloperId", new object[] { m_developerId + "\0" });
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaSetDeveloperId exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
public static void JavaUnityInitialized()
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
Debug.Log("JavaUnityInitialized");
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic("unityInitialized");
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaUnityInitialized exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
public static void JavaSetResolution(string resolutionId)
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
Debug.Log("JavaSetResolution");
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic("setResolution", resolutionId);
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaSetResolution exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
public static void JavaShowCursor(bool flag)
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
//Debug.Log("JavaShowCursor");
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic("showCursor", new object[] { flag.ToString() });
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaShowCursor exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
public static void JavaEnableUnityInput(bool enabled)
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
//Debug.Log("JavaEnableUnityInput");
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic("enableUnityInput", new object[] { enabled.ToString() });
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaEnableUnityInput exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
public static void JavaPutGameData(string key, string val)
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
Debug.Log("JavaPutGameData");
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic("putGameData", new object[] { key + "\0", val + "\0" });
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaPutGameData exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
public static string JavaGetGameData(string key)
{
string result = string.Empty;
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
Debug.Log("JavaGetGameData");
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
result = ajc.CallStatic<String>("getGameData", new object[] { key + "\0" });
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaGetGameData exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
return result;
}
public static void JavaFetchGamerInfo()
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
Debug.Log(string.Format("{0} OuyaSDK.JavaFetchGamerInfo", DateTime.Now));
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic("fetchGamerInfo");
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaFetchGamerInfo exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
public static void JavaAddGetProduct(Purchasable purchasable)
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
Debug.Log(string.Format("{0} OuyaSDK.JavaAddGetProduct", DateTime.Now));
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic("addGetProduct", purchasable.productId);
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaAddGetProduct exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
public static void JavaDebugGetProductList()
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
Debug.Log(string.Format("{0} OuyaSDK.JavaDebugGetProductList", DateTime.Now));
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic("debugGetProductList");
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaDebugGetProductList exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
public static void JavaClearGetProductList()
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
Debug.Log(string.Format("{0} OuyaSDK.JavaClearGetProductList", DateTime.Now));
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic("clearGetProductList");
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaClearGetProductList exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
public static void JavaGetProductsAsync()
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
Debug.Log("OuyaSDK.JavaGetProductsAsync");
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic("getProductsAsync");
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaGetProductsAsync exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
public static void JavaRequestPurchaseAsync(Purchasable purchasable)
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
Debug.Log(string.Format("JavaRequestPurchaseAsync purchasable: {0}", purchasable.productId));
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic<String>("requestPurchaseAsync", new object[] { purchasable.productId + "\0" });
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaRequestPurchaseAsync exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
public static void JavaGetReceiptsAsync()
{
#if UNITY_ANDROID && !UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN && !UNITY_STANDALONE_LINUX
// again, make sure the thread is attached..
AndroidJNI.AttachCurrentThread();
AndroidJNI.PushLocalFrame(0);
try
{
Debug.Log("OuyaSDK.JavaGetReceiptsAsync");
using (AndroidJavaClass ajc = new AndroidJavaClass(JAVA_CLASS))
{
ajc.CallStatic("getReceiptsAsync");
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("OuyaSDK.JavaGetReceiptsAsync exception={0}", ex));
}
finally
{
AndroidJNI.PopLocalFrame(IntPtr.Zero);
}
#endif
}
}
#endregion
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.CloudFormation.Model;
using Amazon.CloudFormation.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.CloudFormation
{
/// <summary>
/// Implementation for accessing CloudFormation
///
/// AWS CloudFormation
/// <para>
/// AWS CloudFormation enables you to create and manage AWS infrastructure deployments
/// predictably and repeatedly. AWS CloudFormation helps you leverage AWS products such
/// as Amazon EC2, EBS, Amazon SNS, ELB, and Auto Scaling to build highly-reliable, highly
/// scalable, cost effective applications without worrying about creating and configuring
/// the underlying AWS infrastructure.
/// </para>
///
/// <para>
/// With AWS CloudFormation, you declare all of your resources and dependencies in a template
/// file. The template defines a collection of resources as a single unit called a stack.
/// AWS CloudFormation creates and deletes all member resources of the stack together
/// and manages all dependencies between the resources for you.
/// </para>
///
/// <para>
/// For more information about this product, go to the <a href="http://aws.amazon.com/cloudformation/">CloudFormation
/// Product Page</a>.
/// </para>
///
/// <para>
/// Amazon CloudFormation makes use of other AWS products. If you need additional technical
/// information about a specific AWS product, you can find the product's technical documentation
/// at <a href="http://aws.amazon.com/documentation/">http://aws.amazon.com/documentation/</a>.
/// </para>
/// </summary>
public partial class AmazonCloudFormationClient : AmazonServiceClient, IAmazonCloudFormation
{
#region Constructors
/// <summary>
/// Constructs AmazonCloudFormationClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonCloudFormationClient(AWSCredentials credentials)
: this(credentials, new AmazonCloudFormationConfig())
{
}
/// <summary>
/// Constructs AmazonCloudFormationClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudFormationClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonCloudFormationConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCloudFormationClient with AWS Credentials and an
/// AmazonCloudFormationClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonCloudFormationClient Configuration Object</param>
public AmazonCloudFormationClient(AWSCredentials credentials, AmazonCloudFormationConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCloudFormationClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonCloudFormationClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudFormationConfig())
{
}
/// <summary>
/// Constructs AmazonCloudFormationClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudFormationClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudFormationConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonCloudFormationClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCloudFormationClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonCloudFormationClient Configuration Object</param>
public AmazonCloudFormationClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCloudFormationConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCloudFormationClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonCloudFormationClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudFormationConfig())
{
}
/// <summary>
/// Constructs AmazonCloudFormationClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudFormationClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudFormationConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCloudFormationClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCloudFormationClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonCloudFormationClient Configuration Object</param>
public AmazonCloudFormationClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonCloudFormationConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Customizes the runtime pipeline.
/// </summary>
/// <param name="pipeline">Runtime pipeline for the current client.</param>
protected override void CustomizeRuntimePipeline(RuntimePipeline pipeline)
{
pipeline.AddHandlerAfter<Amazon.Runtime.Internal.Marshaller>(new Amazon.CloudFormation.Internal.ProcessRequestHandler());
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region CancelUpdateStack
internal CancelUpdateStackResponse CancelUpdateStack(CancelUpdateStackRequest request)
{
var marshaller = new CancelUpdateStackRequestMarshaller();
var unmarshaller = CancelUpdateStackResponseUnmarshaller.Instance;
return Invoke<CancelUpdateStackRequest,CancelUpdateStackResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CancelUpdateStack operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CancelUpdateStack operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CancelUpdateStackResponse> CancelUpdateStackAsync(CancelUpdateStackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CancelUpdateStackRequestMarshaller();
var unmarshaller = CancelUpdateStackResponseUnmarshaller.Instance;
return InvokeAsync<CancelUpdateStackRequest,CancelUpdateStackResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region CreateStack
internal CreateStackResponse CreateStack(CreateStackRequest request)
{
var marshaller = new CreateStackRequestMarshaller();
var unmarshaller = CreateStackResponseUnmarshaller.Instance;
return Invoke<CreateStackRequest,CreateStackResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateStack operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateStack operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateStackResponse> CreateStackAsync(CreateStackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateStackRequestMarshaller();
var unmarshaller = CreateStackResponseUnmarshaller.Instance;
return InvokeAsync<CreateStackRequest,CreateStackResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DeleteStack
internal DeleteStackResponse DeleteStack(DeleteStackRequest request)
{
var marshaller = new DeleteStackRequestMarshaller();
var unmarshaller = DeleteStackResponseUnmarshaller.Instance;
return Invoke<DeleteStackRequest,DeleteStackResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteStack operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteStack operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DeleteStackResponse> DeleteStackAsync(DeleteStackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DeleteStackRequestMarshaller();
var unmarshaller = DeleteStackResponseUnmarshaller.Instance;
return InvokeAsync<DeleteStackRequest,DeleteStackResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeStackEvents
internal DescribeStackEventsResponse DescribeStackEvents(DescribeStackEventsRequest request)
{
var marshaller = new DescribeStackEventsRequestMarshaller();
var unmarshaller = DescribeStackEventsResponseUnmarshaller.Instance;
return Invoke<DescribeStackEventsRequest,DescribeStackEventsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeStackEvents operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeStackEvents operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeStackEventsResponse> DescribeStackEventsAsync(DescribeStackEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeStackEventsRequestMarshaller();
var unmarshaller = DescribeStackEventsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeStackEventsRequest,DescribeStackEventsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeStackResource
internal DescribeStackResourceResponse DescribeStackResource(DescribeStackResourceRequest request)
{
var marshaller = new DescribeStackResourceRequestMarshaller();
var unmarshaller = DescribeStackResourceResponseUnmarshaller.Instance;
return Invoke<DescribeStackResourceRequest,DescribeStackResourceResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeStackResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeStackResource operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeStackResourceResponse> DescribeStackResourceAsync(DescribeStackResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeStackResourceRequestMarshaller();
var unmarshaller = DescribeStackResourceResponseUnmarshaller.Instance;
return InvokeAsync<DescribeStackResourceRequest,DescribeStackResourceResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeStackResources
internal DescribeStackResourcesResponse DescribeStackResources(DescribeStackResourcesRequest request)
{
var marshaller = new DescribeStackResourcesRequestMarshaller();
var unmarshaller = DescribeStackResourcesResponseUnmarshaller.Instance;
return Invoke<DescribeStackResourcesRequest,DescribeStackResourcesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeStackResources operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeStackResources operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeStackResourcesResponse> DescribeStackResourcesAsync(DescribeStackResourcesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeStackResourcesRequestMarshaller();
var unmarshaller = DescribeStackResourcesResponseUnmarshaller.Instance;
return InvokeAsync<DescribeStackResourcesRequest,DescribeStackResourcesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeStacks
internal DescribeStacksResponse DescribeStacks()
{
return DescribeStacks(new DescribeStacksRequest());
}
internal DescribeStacksResponse DescribeStacks(DescribeStacksRequest request)
{
var marshaller = new DescribeStacksRequestMarshaller();
var unmarshaller = DescribeStacksResponseUnmarshaller.Instance;
return Invoke<DescribeStacksRequest,DescribeStacksResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Returns the description for the specified stack; if no stack name was specified, then
/// it returns the description for all the stacks created.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeStacks service method, as returned by CloudFormation.</returns>
public Task<DescribeStacksResponse> DescribeStacksAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return DescribeStacksAsync(new DescribeStacksRequest(), cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeStacks operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeStacks operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeStacksResponse> DescribeStacksAsync(DescribeStacksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeStacksRequestMarshaller();
var unmarshaller = DescribeStacksResponseUnmarshaller.Instance;
return InvokeAsync<DescribeStacksRequest,DescribeStacksResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region EstimateTemplateCost
internal EstimateTemplateCostResponse EstimateTemplateCost(EstimateTemplateCostRequest request)
{
var marshaller = new EstimateTemplateCostRequestMarshaller();
var unmarshaller = EstimateTemplateCostResponseUnmarshaller.Instance;
return Invoke<EstimateTemplateCostRequest,EstimateTemplateCostResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the EstimateTemplateCost operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the EstimateTemplateCost operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<EstimateTemplateCostResponse> EstimateTemplateCostAsync(EstimateTemplateCostRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new EstimateTemplateCostRequestMarshaller();
var unmarshaller = EstimateTemplateCostResponseUnmarshaller.Instance;
return InvokeAsync<EstimateTemplateCostRequest,EstimateTemplateCostResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetStackPolicy
internal GetStackPolicyResponse GetStackPolicy(GetStackPolicyRequest request)
{
var marshaller = new GetStackPolicyRequestMarshaller();
var unmarshaller = GetStackPolicyResponseUnmarshaller.Instance;
return Invoke<GetStackPolicyRequest,GetStackPolicyResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetStackPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetStackPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<GetStackPolicyResponse> GetStackPolicyAsync(GetStackPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetStackPolicyRequestMarshaller();
var unmarshaller = GetStackPolicyResponseUnmarshaller.Instance;
return InvokeAsync<GetStackPolicyRequest,GetStackPolicyResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetTemplate
internal GetTemplateResponse GetTemplate(GetTemplateRequest request)
{
var marshaller = new GetTemplateRequestMarshaller();
var unmarshaller = GetTemplateResponseUnmarshaller.Instance;
return Invoke<GetTemplateRequest,GetTemplateResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetTemplate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetTemplate operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<GetTemplateResponse> GetTemplateAsync(GetTemplateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetTemplateRequestMarshaller();
var unmarshaller = GetTemplateResponseUnmarshaller.Instance;
return InvokeAsync<GetTemplateRequest,GetTemplateResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetTemplateSummary
internal GetTemplateSummaryResponse GetTemplateSummary(GetTemplateSummaryRequest request)
{
var marshaller = new GetTemplateSummaryRequestMarshaller();
var unmarshaller = GetTemplateSummaryResponseUnmarshaller.Instance;
return Invoke<GetTemplateSummaryRequest,GetTemplateSummaryResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetTemplateSummary operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetTemplateSummary operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<GetTemplateSummaryResponse> GetTemplateSummaryAsync(GetTemplateSummaryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetTemplateSummaryRequestMarshaller();
var unmarshaller = GetTemplateSummaryResponseUnmarshaller.Instance;
return InvokeAsync<GetTemplateSummaryRequest,GetTemplateSummaryResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ListStackResources
internal ListStackResourcesResponse ListStackResources(ListStackResourcesRequest request)
{
var marshaller = new ListStackResourcesRequestMarshaller();
var unmarshaller = ListStackResourcesResponseUnmarshaller.Instance;
return Invoke<ListStackResourcesRequest,ListStackResourcesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the ListStackResources operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListStackResources operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ListStackResourcesResponse> ListStackResourcesAsync(ListStackResourcesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ListStackResourcesRequestMarshaller();
var unmarshaller = ListStackResourcesResponseUnmarshaller.Instance;
return InvokeAsync<ListStackResourcesRequest,ListStackResourcesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ListStacks
internal ListStacksResponse ListStacks()
{
return ListStacks(new ListStacksRequest());
}
internal ListStacksResponse ListStacks(ListStacksRequest request)
{
var marshaller = new ListStacksRequestMarshaller();
var unmarshaller = ListStacksResponseUnmarshaller.Instance;
return Invoke<ListStacksRequest,ListStacksResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Returns the summary information for stacks whose status matches the specified StackStatusFilter.
/// Summary information for stacks that have been deleted is kept for 90 days after the
/// stack is deleted. If no StackStatusFilter is specified, summary information for all
/// stacks is returned (including existing stacks and stacks that have been deleted).
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListStacks service method, as returned by CloudFormation.</returns>
public Task<ListStacksResponse> ListStacksAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return ListStacksAsync(new ListStacksRequest(), cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the ListStacks operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListStacks operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ListStacksResponse> ListStacksAsync(ListStacksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ListStacksRequestMarshaller();
var unmarshaller = ListStacksResponseUnmarshaller.Instance;
return InvokeAsync<ListStacksRequest,ListStacksResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region SetStackPolicy
internal SetStackPolicyResponse SetStackPolicy(SetStackPolicyRequest request)
{
var marshaller = new SetStackPolicyRequestMarshaller();
var unmarshaller = SetStackPolicyResponseUnmarshaller.Instance;
return Invoke<SetStackPolicyRequest,SetStackPolicyResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the SetStackPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SetStackPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<SetStackPolicyResponse> SetStackPolicyAsync(SetStackPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new SetStackPolicyRequestMarshaller();
var unmarshaller = SetStackPolicyResponseUnmarshaller.Instance;
return InvokeAsync<SetStackPolicyRequest,SetStackPolicyResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region SignalResource
internal SignalResourceResponse SignalResource(SignalResourceRequest request)
{
var marshaller = new SignalResourceRequestMarshaller();
var unmarshaller = SignalResourceResponseUnmarshaller.Instance;
return Invoke<SignalResourceRequest,SignalResourceResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the SignalResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SignalResource operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<SignalResourceResponse> SignalResourceAsync(SignalResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new SignalResourceRequestMarshaller();
var unmarshaller = SignalResourceResponseUnmarshaller.Instance;
return InvokeAsync<SignalResourceRequest,SignalResourceResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region UpdateStack
internal UpdateStackResponse UpdateStack(UpdateStackRequest request)
{
var marshaller = new UpdateStackRequestMarshaller();
var unmarshaller = UpdateStackResponseUnmarshaller.Instance;
return Invoke<UpdateStackRequest,UpdateStackResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateStack operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateStack operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<UpdateStackResponse> UpdateStackAsync(UpdateStackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new UpdateStackRequestMarshaller();
var unmarshaller = UpdateStackResponseUnmarshaller.Instance;
return InvokeAsync<UpdateStackRequest,UpdateStackResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ValidateTemplate
internal ValidateTemplateResponse ValidateTemplate()
{
return ValidateTemplate(new ValidateTemplateRequest());
}
internal ValidateTemplateResponse ValidateTemplate(ValidateTemplateRequest request)
{
var marshaller = new ValidateTemplateRequestMarshaller();
var unmarshaller = ValidateTemplateResponseUnmarshaller.Instance;
return Invoke<ValidateTemplateRequest,ValidateTemplateResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Validates a specified template.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ValidateTemplate service method, as returned by CloudFormation.</returns>
public Task<ValidateTemplateResponse> ValidateTemplateAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return ValidateTemplateAsync(new ValidateTemplateRequest(), cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the ValidateTemplate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ValidateTemplate operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ValidateTemplateResponse> ValidateTemplateAsync(ValidateTemplateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ValidateTemplateRequestMarshaller();
var unmarshaller = ValidateTemplateResponseUnmarshaller.Instance;
return InvokeAsync<ValidateTemplateRequest,ValidateTemplateResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
}
}
| |
namespace IrDAServiceClient
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose (bool disposing)
{
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent ()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.labelState = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.buttonDisconnect = new System.Windows.Forms.Button();
this.comboBoxEncoding = new System.Windows.Forms.ComboBox();
this.label7 = new System.Windows.Forms.Label();
this.labelSendPduLength = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.textBoxReceive = new System.Windows.Forms.TextBox();
this.buttonSend = new System.Windows.Forms.Button();
this.textBoxSend = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.comboBoxWellKnowServices = new System.Windows.Forms.ComboBox();
this.comboBoxProtocolMode = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.textBoxServiceName = new System.Windows.Forms.TextBox();
this.buttonConnect = new System.Windows.Forms.Button();
this.listBoxDevices = new System.Windows.Forms.ListBox();
this.buttonDiscover = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelState
//
this.labelState.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.labelState.Location = new System.Drawing.Point(56, 232);
this.labelState.Name = "labelState";
this.labelState.Size = new System.Drawing.Size(286, 13);
this.labelState.TabIndex = 35;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(11, 232);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(35, 13);
this.label8.TabIndex = 34;
this.label8.Text = "State:";
//
// buttonDisconnect
//
this.buttonDisconnect.AutoSize = true;
this.buttonDisconnect.Location = new System.Drawing.Point(90, 200);
this.buttonDisconnect.Name = "buttonDisconnect";
this.buttonDisconnect.Size = new System.Drawing.Size(73, 23);
this.buttonDisconnect.TabIndex = 33;
this.buttonDisconnect.Text = "&Disconnect";
this.buttonDisconnect.Click += new System.EventHandler(this.buttonDisconnect_Click);
//
// comboBoxEncoding
//
this.comboBoxEncoding.FormattingEnabled = true;
this.comboBoxEncoding.Items.AddRange(new object[] {
"x-IA5",
"iso-8859-1",
"utf-8",
"ASCII"});
this.comboBoxEncoding.Location = new System.Drawing.Point(95, 166);
this.comboBoxEncoding.Name = "comboBoxEncoding";
this.comboBoxEncoding.Size = new System.Drawing.Size(91, 21);
this.comboBoxEncoding.TabIndex = 31;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(11, 169);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(79, 13);
this.label7.TabIndex = 30;
this.label7.Text = "Text &Encoding:";
//
// labelSendPduLength
//
this.labelSendPduLength.AutoSize = true;
this.labelSendPduLength.Location = new System.Drawing.Point(227, 299);
this.labelSendPduLength.Name = "labelSendPduLength";
this.labelSendPduLength.Size = new System.Drawing.Size(31, 13);
this.labelSendPduLength.TabIndex = 39;
this.labelSendPduLength.Text = "9999";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(89, 299);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(132, 13);
this.label6.TabIndex = 38;
this.label6.Text = "Maximum IrLMP send size:";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(11, 311);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(47, 13);
this.label5.TabIndex = 40;
this.label5.Text = "&Receive";
//
// textBoxReceive
//
this.textBoxReceive.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.textBoxReceive.Location = new System.Drawing.Point(11, 332);
this.textBoxReceive.Multiline = true;
this.textBoxReceive.Name = "textBoxReceive";
this.textBoxReceive.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxReceive.Size = new System.Drawing.Size(331, 101);
this.textBoxReceive.TabIndex = 41;
//
// buttonSend
//
this.buttonSend.AutoSize = true;
this.buttonSend.Location = new System.Drawing.Point(264, 257);
this.buttonSend.Name = "buttonSend";
this.buttonSend.Size = new System.Drawing.Size(78, 23);
this.buttonSend.TabIndex = 37;
this.buttonSend.Text = "&Send";
this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click);
//
// textBoxSend
//
this.textBoxSend.Location = new System.Drawing.Point(11, 259);
this.textBoxSend.Multiline = true;
this.textBoxSend.Name = "textBoxSend";
this.textBoxSend.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxSend.Size = new System.Drawing.Size(247, 36);
this.textBoxSend.TabIndex = 36;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(11, 42);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(119, 13);
this.label4.TabIndex = 22;
this.label4.Text = "&List of devices in range:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(11, 115);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(108, 13);
this.label3.TabIndex = 24;
this.label3.Text = "&Well known services:";
//
// comboBoxWellKnowServices
//
this.comboBoxWellKnowServices.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxWellKnowServices.DropDownWidth = 200;
this.comboBoxWellKnowServices.FormattingEnabled = true;
this.comboBoxWellKnowServices.Location = new System.Drawing.Point(124, 112);
this.comboBoxWellKnowServices.MaxDropDownItems = 10;
this.comboBoxWellKnowServices.Name = "comboBoxWellKnowServices";
this.comboBoxWellKnowServices.Size = new System.Drawing.Size(218, 21);
this.comboBoxWellKnowServices.TabIndex = 25;
this.comboBoxWellKnowServices.SelectedIndexChanged += new System.EventHandler(this.comboBoxWKS_SelectedIndexChanged);
//
// comboBoxProtocolMode
//
this.comboBoxProtocolMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxProtocolMode.FormattingEnabled = true;
this.comboBoxProtocolMode.Location = new System.Drawing.Point(272, 141);
this.comboBoxProtocolMode.Name = "comboBoxProtocolMode";
this.comboBoxProtocolMode.Size = new System.Drawing.Size(70, 21);
this.comboBoxProtocolMode.TabIndex = 29;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(188, 144);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(78, 13);
this.label2.TabIndex = 28;
this.label2.Text = "&Protocol mode:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(11, 144);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(77, 13);
this.label1.TabIndex = 26;
this.label1.Text = "Service &Name:";
//
// textBoxServiceName
//
this.textBoxServiceName.AcceptsTab = true;
this.textBoxServiceName.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.textBoxServiceName.Location = new System.Drawing.Point(95, 141);
this.textBoxServiceName.Name = "textBoxServiceName";
this.textBoxServiceName.Size = new System.Drawing.Size(91, 20);
this.textBoxServiceName.TabIndex = 27;
//
// buttonConnect
//
this.buttonConnect.AutoSize = true;
this.buttonConnect.Location = new System.Drawing.Point(11, 200);
this.buttonConnect.Name = "buttonConnect";
this.buttonConnect.Size = new System.Drawing.Size(73, 23);
this.buttonConnect.TabIndex = 32;
this.buttonConnect.Text = "&Connect";
this.buttonConnect.Click += new System.EventHandler(this.buttonConnect_Click);
//
// listBoxDevices
//
this.listBoxDevices.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listBoxDevices.FormattingEnabled = true;
this.listBoxDevices.Location = new System.Drawing.Point(11, 61);
this.listBoxDevices.Name = "listBoxDevices";
this.listBoxDevices.Size = new System.Drawing.Size(331, 43);
this.listBoxDevices.TabIndex = 23;
//
// buttonDiscover
//
this.buttonDiscover.AutoSize = true;
this.buttonDiscover.Location = new System.Drawing.Point(11, 13);
this.buttonDiscover.Name = "buttonDiscover";
this.buttonDiscover.Size = new System.Drawing.Size(108, 23);
this.buttonDiscover.TabIndex = 21;
this.buttonDiscover.Text = "Disco&ver devices";
this.buttonDiscover.Click += new System.EventHandler(this.buttonDiscover_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(352, 446);
this.Controls.Add(this.labelState);
this.Controls.Add(this.label8);
this.Controls.Add(this.buttonDisconnect);
this.Controls.Add(this.comboBoxEncoding);
this.Controls.Add(this.label7);
this.Controls.Add(this.labelSendPduLength);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.textBoxReceive);
this.Controls.Add(this.buttonSend);
this.Controls.Add(this.textBoxSend);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.comboBoxWellKnowServices);
this.Controls.Add(this.comboBoxProtocolMode);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBoxServiceName);
this.Controls.Add(this.buttonConnect);
this.Controls.Add(this.listBoxDevices);
this.Controls.Add(this.buttonDiscover);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "Form1";
this.Text = "IrDA Client";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label labelState;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Button buttonDisconnect;
private System.Windows.Forms.ComboBox comboBoxEncoding;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label labelSendPduLength;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox textBoxReceive;
private System.Windows.Forms.Button buttonSend;
private System.Windows.Forms.TextBox textBoxSend;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox comboBoxWellKnowServices;
private System.Windows.Forms.ComboBox comboBoxProtocolMode;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBoxServiceName;
private System.Windows.Forms.Button buttonConnect;
private System.Windows.Forms.ListBox listBoxDevices;
private System.Windows.Forms.Button buttonDiscover;
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using GongSolutions.Shell.Interop;
namespace GongSolutions.Shell
{
/// <summary>
/// Provides a drop-down list displaying the Windows Shell namespace.
/// </summary>
///
/// <remarks>
/// The <see cref="ShellComboBox"/> class displays a view of the Windows
/// Shell namespace in a drop-down list similar to that displayed in
/// a file open/save dialog.
/// </remarks>
public class ShellComboBox : Control
{
/// <summary>
/// Initializes a new instance of the <see cref="ShellComboBox"/> class.
/// </summary>
public ShellComboBox()
{
m_Combo.Dock = DockStyle.Fill;
m_Combo.DrawMode = DrawMode.OwnerDrawFixed;
m_Combo.DropDownStyle = ComboBoxStyle.DropDownList;
m_Combo.DropDownHeight = 300;
m_Combo.ItemHeight = SystemInformation.SmallIconSize.Height + 1;
m_Combo.Parent = this;
m_Combo.Click += new EventHandler(m_Combo_Click);
m_Combo.DrawItem += new DrawItemEventHandler(m_Combo_DrawItem);
m_Combo.SelectedIndexChanged += new EventHandler(m_Combo_SelectedIndexChanged);
m_Edit.Anchor = AnchorStyles.Left | AnchorStyles.Top |
AnchorStyles.Right | AnchorStyles.Bottom;
m_Edit.BorderStyle = BorderStyle.None;
m_Edit.Left = 8 + SystemInformation.SmallIconSize.Width;
m_Edit.Top = 4;
m_Edit.Width = Width - m_Edit.Left - 3 - SystemInformation.VerticalScrollBarWidth;
m_Edit.Parent = this;
m_Edit.Visible = false;
m_Edit.GotFocus += new EventHandler(m_Edit_GotFocus);
m_Edit.LostFocus += new EventHandler(m_Edit_LostFocus);
m_Edit.KeyDown += new KeyEventHandler(m_Edit_KeyDown);
m_Edit.MouseDown += new MouseEventHandler(m_Edit_MouseDown);
m_Edit.BringToFront();
m_ShellListener.DriveAdded += new ShellItemEventHandler(m_ShellListener_ItemUpdated);
m_ShellListener.DriveRemoved += new ShellItemEventHandler(m_ShellListener_ItemUpdated);
m_ShellListener.FolderCreated += new ShellItemEventHandler(m_ShellListener_ItemUpdated);
m_ShellListener.FolderDeleted += new ShellItemEventHandler(m_ShellListener_ItemUpdated);
m_ShellListener.FolderRenamed += new ShellItemChangeEventHandler(m_ShellListener_ItemRenamed);
m_ShellListener.FolderUpdated += new ShellItemEventHandler(m_ShellListener_ItemUpdated);
m_ShellListener.ItemCreated += new ShellItemEventHandler(m_ShellListener_ItemUpdated);
m_ShellListener.ItemDeleted += new ShellItemEventHandler(m_ShellListener_ItemUpdated);
m_ShellListener.ItemRenamed += new ShellItemChangeEventHandler(m_ShellListener_ItemRenamed);
m_ShellListener.ItemUpdated += new ShellItemEventHandler(m_ShellListener_ItemUpdated);
m_ShellListener.SharingChanged += new ShellItemEventHandler(m_ShellListener_ItemUpdated);
m_SelectedFolder = ShellItem.Desktop;
m_Edit.Text = GetEditString();
if (m_Computer == null)
{
m_Computer = new ShellItem(Environment.SpecialFolder.MyComputer);
}
CreateItems();
}
/// <summary>
/// Gets/sets a value indicating whether the combo box is editable.
/// </summary>
[DefaultValue(false)]
public bool Editable
{
get { return m_Editable; }
set
{
m_Edit.Visible = m_Editable = value;
}
}
/// <summary>
/// Gets/sets a value indicating whether the full file system path
/// should be displayed in the main portion of the control.
/// </summary>
[DefaultValue(false)]
public bool ShowFileSystemPath
{
get { return m_ShowFileSystemPath; }
set
{
m_ShowFileSystemPath = value;
m_Combo.Invalidate();
}
}
/// <summary>
/// Gets/sets the folder that the <see cref="ShellComboBox"/> should
/// display as the root folder.
/// </summary>
[Editor(typeof(ShellItemEditor), typeof(UITypeEditor))]
public ShellItem RootFolder
{
get { return m_RootFolder; }
set
{
m_RootFolder = value;
if (!m_RootFolder.IsParentOf(m_SelectedFolder))
{
m_SelectedFolder = m_RootFolder;
}
CreateItems();
}
}
/// <summary>
/// Gets/sets the folder currently selected in the
/// <see cref="ShellComboBox"/>.
/// </summary>
[Editor(typeof(ShellItemEditor), typeof(UITypeEditor))]
public ShellItem SelectedFolder
{
get { return m_SelectedFolder; }
set
{
if (m_SelectedFolder != value)
{
m_SelectedFolder = value;
CreateItems();
m_Edit.Text = GetEditString();
NavigateShellView();
OnChanged();
}
}
}
/// <summary>
/// Gets/sets a <see cref="ShellView"/> whose navigation should be
/// controlled by the combo box.
/// </summary>
[DefaultValue(null), Category("Behaviour")]
public ShellView ShellView
{
get { return m_ShellView; }
set
{
if (m_ShellView != null)
{
m_ShellView.Navigated -= new EventHandler(m_ShellView_Navigated);
}
m_ShellView = value;
if (m_ShellView != null)
{
m_ShellView.Navigated += new EventHandler(m_ShellView_Navigated);
m_ShellView_Navigated(m_ShellView, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the <see cref="ShellComboBox"/>'s
/// <see cref="SelectedFolder"/> property changes.
/// </summary>
public event EventHandler Changed;
/// <summary>
/// Occurs when the <see cref="ShellComboBox"/> control wants to know
/// if it should include a folder in its view.
/// </summary>
///
/// <remarks>
/// This event allows the folders displayed in the
/// <see cref="ShellComboBox"/> control to be filtered.
/// </remarks>
public event FilterItemEventHandler FilterItem;
internal bool ShouldSerializeRootFolder()
{
return m_RootFolder != ShellItem.Desktop;
}
internal bool ShouldSerializeSelectedFolder()
{
return m_SelectedFolder != ShellItem.Desktop;
}
void CreateItems()
{
if (!m_CreatingItems)
{
try
{
m_CreatingItems = true;
m_Combo.Items.Clear();
CreateItem(m_RootFolder, 0);
}
finally
{
m_CreatingItems = false;
}
}
}
void CreateItems(ShellItem folder, int indent)
{
IEnumerator<ShellItem> e = folder.GetEnumerator(
SHCONTF.FOLDERS | SHCONTF.INCLUDEHIDDEN);
while (e.MoveNext())
{
if (ShouldCreateItem(e.Current))
{
CreateItem(e.Current, indent);
}
}
}
void CreateItem(ShellItem folder, int indent)
{
int index = m_Combo.Items.Add(new ComboItem(folder, indent));
if (folder == m_SelectedFolder)
{
m_Combo.SelectedIndex = index;
}
if (ShouldCreateChildren(folder))
{
CreateItems(folder, indent + 1);
}
}
bool ShouldCreateItem(ShellItem folder)
{
FilterItemEventArgs e = new FilterItemEventArgs(folder);
ShellItem myComputer = new ShellItem(Environment.SpecialFolder.MyComputer);
e.Include = false;
if (ShellItem.Desktop.IsImmediateParentOf(folder) ||
m_Computer.IsImmediateParentOf(folder))
{
e.Include = folder.IsFileSystemAncestor;
}
else if ((folder == m_SelectedFolder) ||
folder.IsParentOf(m_SelectedFolder))
{
e.Include = true;
}
if (FilterItem != null)
{
FilterItem(this, e);
}
return e.Include;
}
bool ShouldCreateChildren(ShellItem folder)
{
return (folder == m_Computer) ||
(folder == ShellItem.Desktop) ||
folder.IsParentOf(m_SelectedFolder);
}
string GetEditString()
{
if (m_ShowFileSystemPath && m_SelectedFolder.IsFileSystem)
{
return m_SelectedFolder.FileSystemPath;
}
else
{
return m_SelectedFolder.DisplayName;
}
}
void NavigateShellView()
{
if ((m_ShellView != null) && !m_ChangingLocation)
{
try
{
m_ChangingLocation = true;
m_ShellView.Navigate(m_SelectedFolder);
}
catch (Exception)
{
SelectedFolder = m_ShellView.CurrentFolder;
}
finally
{
m_ChangingLocation = false;
}
}
}
void OnChanged()
{
if (Changed != null)
{
Changed(this, EventArgs.Empty);
}
}
void m_Combo_Click(object sender, EventArgs e)
{
OnClick(e);
}
void m_Combo_DrawItem(object sender, DrawItemEventArgs e)
{
int iconWidth = SystemInformation.SmallIconSize.Width;
int indent = ((e.State & DrawItemState.ComboBoxEdit) == 0) ?
(iconWidth / 2) : 0;
if (e.Index != -1)
{
string display;
ComboItem item = (ComboItem)m_Combo.Items[e.Index];
Color textColor = SystemColors.WindowText;
Rectangle textRect;
int textOffset;
SizeF size;
if ((e.State & DrawItemState.ComboBoxEdit) != 0)
{
// Don't draw the folder location in the edit box when
// the control is Editable as the edit control will
// take care of that.
display = m_Editable ? string.Empty : GetEditString();
}
else
{
display = item.Folder.DisplayName;
}
size = TextRenderer.MeasureText(display, m_Combo.Font);
textRect = new Rectangle(
e.Bounds.Left + iconWidth + (item.Indent * indent) + 3,
e.Bounds.Y, (int)size.Width, e.Bounds.Height);
textOffset = (int)((e.Bounds.Height - size.Height) / 2);
// If the text is being drawin in the main combo box edit area,
// draw the text 1 pixel higher - this is how it looks in Windows.
if ((e.State & DrawItemState.ComboBoxEdit) != 0)
{
textOffset -= 1;
}
if ((e.State & DrawItemState.Selected) != 0)
{
e.Graphics.FillRectangle(SystemBrushes.Highlight, textRect);
textColor = SystemColors.HighlightText;
}
else
{
e.DrawBackground();
}
if ((e.State & DrawItemState.Focus) != 0)
{
ControlPaint.DrawFocusRectangle(e.Graphics, textRect);
}
SystemImageList.DrawSmallImage(e.Graphics,
new Point(e.Bounds.Left + (item.Indent * indent),
e.Bounds.Top),
item.Folder.GetSystemImageListIndex(ShellIconType.SmallIcon,
ShellIconFlags.OverlayIndex),
(e.State & DrawItemState.Selected) != 0);
TextRenderer.DrawText(e.Graphics, display, m_Combo.Font,
new Point(textRect.Left, textRect.Top + textOffset),
textColor);
}
}
void m_Combo_SelectedIndexChanged(object sender, EventArgs e)
{
if (!m_CreatingItems)
{
SelectedFolder = ((ComboItem)m_Combo.SelectedItem).Folder;
}
}
void m_Edit_GotFocus(object sender, EventArgs e)
{
m_Edit.SelectAll();
m_SelectAll = true;
}
void m_Edit_LostFocus(object sender, EventArgs e)
{
m_SelectAll = false;
}
void m_Edit_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string path = m_Edit.Text;
if ((path == string.Empty) ||
(string.Compare(path, "Desktop", true) == 0))
{
SelectedFolder = ShellItem.Desktop;
return;
}
if (Directory.Exists(path))
{
SelectedFolder = new ShellItem(path);
return;
}
path = Path.Combine(m_SelectedFolder.FileSystemPath, path);
if (Directory.Exists(path))
{
SelectedFolder = new ShellItem(path);
return;
}
}
}
void m_Edit_MouseDown(object sender, MouseEventArgs e)
{
if (m_SelectAll)
{
m_Edit.SelectAll();
m_SelectAll = false;
}
else
{
m_Edit.SelectionStart = m_Edit.Text.Length;
}
}
void m_ShellView_Navigated(object sender, EventArgs e)
{
if (!m_ChangingLocation)
{
try
{
m_ChangingLocation = true;
SelectedFolder = m_ShellView.CurrentFolder;
OnChanged();
}
finally
{
m_ChangingLocation = false;
}
}
}
void m_ShellListener_ItemRenamed(object sender, ShellItemChangeEventArgs e)
{
CreateItems();
}
void m_ShellListener_ItemUpdated(object sender, ShellItemEventArgs e)
{
CreateItems();
}
class ComboItem
{
public ComboItem(ShellItem folder, int indent)
{
Folder = folder;
Indent = indent;
}
public ShellItem Folder;
public int Indent;
}
ComboBox m_Combo = new ComboBox();
TextBox m_Edit = new TextBox();
ShellView m_ShellView;
bool m_Editable;
ShellItem m_RootFolder = ShellItem.Desktop;
ShellItem m_SelectedFolder;
bool m_ChangingLocation;
bool m_ShowFileSystemPath;
bool m_CreatingItems;
bool m_SelectAll;
ShellNotificationListener m_ShellListener = new ShellNotificationListener();
static ShellItem m_Computer;
}
}
| |
using System;
namespace DoFactory.HeadFirst.Template.Barista
{
class BeverageTestDrive
{
static void Main(string[] args)
{
Console.WriteLine("\nMaking tea...");
var tea = new Tea();
tea.PrepareRecipe();
Console.WriteLine("\nMaking coffee...");
var coffee = new Coffee();
coffee.PrepareRecipe();
// Hooked on Template (page 292)
Console.WriteLine("\nMaking tea...");
var teaHook = new TeaWithHook();
teaHook.PrepareRecipe();
Console.WriteLine("\nMaking coffee...");
var coffeeHook = new CoffeeWithHook();
coffeeHook.PrepareRecipe();
// Wait for user
Console.ReadKey();
}
}
#region Coffee and Tea
public abstract class CaffeineBeverage
{
public void PrepareRecipe()
{
BoilWater();
Brew();
PourInCup();
AddCondiments();
}
public abstract void Brew();
public abstract void AddCondiments();
void BoilWater()
{
Console.WriteLine("Boiling water");
}
void PourInCup()
{
Console.WriteLine("Pouring into cup");
}
}
public class Coffee : CaffeineBeverage
{
public override void Brew()
{
Console.WriteLine("Dripping Coffee through filter");
}
public override void AddCondiments()
{
Console.WriteLine("Adding Sugar and Milk");
}
}
public class Tea : CaffeineBeverage
{
public override void Brew()
{
Console.WriteLine("Steeping the tea");
}
public override void AddCondiments()
{
Console.WriteLine("Adding Lemon");
}
}
#endregion
#region Coffee and Tea with Hook
public abstract class CaffeineBeverageWithHook
{
public void PrepareRecipe()
{
BoilWater();
Brew();
PourInCup();
if (CustomerWantsCondiments())
{
AddCondiments();
}
}
public abstract void Brew();
public abstract void AddCondiments();
public void BoilWater()
{
Console.WriteLine("Boiling water");
}
public void PourInCup()
{
Console.WriteLine("Pouring into cup");
}
public virtual bool CustomerWantsCondiments()
{
return true;
}
}
public class CoffeeWithHook : CaffeineBeverageWithHook
{
public override void Brew()
{
Console.WriteLine("Dripping Coffee through filter");
}
public override void AddCondiments()
{
Console.WriteLine("Adding Sugar and Milk");
}
public override bool CustomerWantsCondiments()
{
string answer = GetUserInput();
if (answer.ToLower().StartsWith("y"))
{
return true;
}
else
{
return false;
}
}
public string GetUserInput()
{
string answer = null;
Console.WriteLine("Would you like milk and sugar with your coffee (y/n)? ");
try
{
answer = Console.ReadLine();
}
catch
{
Console.WriteLine("IO error trying to read your answer");
}
if (answer == null)
{
return "no";
}
return answer;
}
}
public class TeaWithHook : CaffeineBeverageWithHook
{
public override void Brew()
{
Console.WriteLine("Steeping the tea");
}
public override void AddCondiments()
{
Console.WriteLine("Adding Lemon");
}
public override bool CustomerWantsCondiments()
{
string answer = GetUserInput();
if (answer.ToLower().StartsWith("y"))
{
return true;
}
else
{
return false;
}
}
private string GetUserInput()
{
// get the user's response
string answer = null;
Console.WriteLine("Would you like lemon with your tea (y/n)? ");
try
{
answer = Console.ReadLine();
}
catch
{
Console.WriteLine("IO error trying to read your answer");
}
if (answer == null)
{
return "no";
}
return answer;
}
}
#endregion
}
| |
using System.Collections.Generic;
using System.IO;
using System.Xml;
using UnityEditor;
using UnityEngine;
namespace LuviKunG
{
public class LocalizationSheetData
{
public Dictionary<string, Dictionary<string, string>> localizationKey;
public LocalizationSheetData()
{
localizationKey = new Dictionary<string, Dictionary<string, string>>();
}
}
public class EditorImportLocalizationCSV : EditorWindow
{
static Object sourceCSV;
static string exportPath = "";
[MenuItem("Window/LuviKunG/Export CSV Localization")]
public static void WindowOpen()
{
//EditorWindow window = GetWindowWithRect<EditorImportLocalizationCSV>(new Rect(0, 0, 200, 100), false, "Import Localization CSV", true);
//window.Show();
GetWindow<EditorImportLocalizationCSV>(false, "Import Localization CSV", true);
exportPath = Application.dataPath + "/Localization/Resources/Languages";
}
void OnGUI()
{
exportPath = EditorGUILayout.TextField("Export path", exportPath);
sourceCSV = EditorGUILayout.ObjectField("CSV", sourceCSV, typeof(TextAsset), false);
if (GUILayout.Button("Select Export Location"))
{
exportPath = EditorUtility.OpenFolderPanel("Select localization for export XML file.", Application.dataPath, "");
if (string.IsNullOrEmpty(exportPath))
{
return;
}
}
if (GUILayout.Button("Export CSV Localization"))
{
_settings = settings;
if (_settings == null)
{
Debug.LogError("Cannot find LocalizationSettings.asset");
return;
}
if (string.IsNullOrEmpty(exportPath))
{
Debug.LogError("Invalid export path.");
return;
}
if (sourceCSV == null)
{
Debug.LogError("Source are null.");
return;
}
if (exportPath == null)
{
string exportPath = EditorUtility.OpenFolderPanel("Select localization for export XML file.", Application.dataPath, "");
if (string.IsNullOrEmpty(exportPath))
{
exportPath = "";
return;
}
}
TextAsset textAssetCSV = sourceCSV as TextAsset;
//string importFilePath = EditorUtility.OpenFilePanel("Select localization CSV file.", Application.dataPath, "csv");
//if (string.IsNullOrEmpty(importFilePath))
//{
// return;
//}
string exportDirectory = exportPath;
//string exportDirectory = EditorUtility.OpenFolderPanel("Select localization for export XML file.", Application.dataPath, "");
//if (string.IsNullOrEmpty(exportDirectory))
//{
// return;
//}
string fileName = textAssetCSV.name;
//string fileName = Path.GetFileNameWithoutExtension(importFilePath);
List<List<string>> lists = ReadCSVTextAsset(textAssetCSV);
LocalizationSheetData sheetData = new LocalizationSheetData();
for (int i = 0; i < lists.Count; i++)
{
if (i == 0) //first column
{
for (int j = 0; j < lists[i].Count; j++)
{
if (j == 0) //first row
{
//nothing to do.
continue;
}
else //other row
{
sheetData.localizationKey.Add(lists[i][j], new Dictionary<string, string>());
}
}
}
else //other column
{
string key = "";
for (int j = 0; j < lists[i].Count; j++)
{
if (j == 0) //first row
{
key = lists[i][j];
}
else //other row
{
sheetData.localizationKey[lists[0][j]].Add(key, lists[i][j]);
}
}
}
}
foreach (KeyValuePair<string, Dictionary<string, string>> lang in sheetData.localizationKey)
{
string exportFilePath = exportDirectory + "/" + lang.Key + "_" + fileName + ".xml";
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace
};
using (XmlWriter xmlWriter = XmlWriter.Create(exportFilePath, settings))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("entries");
foreach (KeyValuePair<string, string> pair in lang.Value)
{
xmlWriter.WriteStartElement("entry");
xmlWriter.WriteAttributeString("name", pair.Key);
xmlWriter.WriteString(pair.Value);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
}
List<string> sheetTitle = new List<string>(_settings.sheetTitles);
if (!sheetTitle.Contains(fileName))
{
sheetTitle.Add(fileName);
}
_settings.sheetTitles = sheetTitle.ToArray();
AssetDatabase.Refresh();
}
}
private static LocalizationSettings _settings = null;
public static LocalizationSettings settings
{
get
{
if (_settings == null)
{
string settingsFile = "Languages/" + System.IO.Path.GetFileNameWithoutExtension(Language.settingsAssetPath);
_settings = (LocalizationSettings)Resources.Load(settingsFile, typeof(LocalizationSettings));
}
return _settings;
}
}
public static List<List<string>> ReadCSVTextAsset(TextAsset text, char sepChar = ',', char quoteChar = '"')
{
char[] archDelim = new char[] { '\r', '\n' };
List<List<string>> ret = new List<List<string>>();
string[] csvRows = text.text.Split(archDelim, System.StringSplitOptions.RemoveEmptyEntries);
foreach (string csvRow in csvRows)
{
bool inQuotes = false;
List<string> fields = new List<string>();
string field = "";
for (int i = 0; i < csvRow.Length; i++)
{
if (inQuotes)
{
if (i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar)
{
i++;
field += quoteChar;
}
else if (csvRow[i] == quoteChar)
{
inQuotes = false;
}
else
{
field += csvRow[i];
}
}
else
{
if (csvRow[i] == quoteChar)
{
inQuotes = true;
continue;
}
if (csvRow[i] == sepChar)
{
fields.Add(field);
field = "";
}
else
{
field += csvRow[i];
}
}
}
if (!string.IsNullOrEmpty(field))
{
fields.Add(field);
field = "";
}
ret.Add(fields);
}
return ret;
}
public static List<List<string>> ReadCSVFileMSStyle(string filePath, char sepChar = ',', char quoteChar = '"')
{
List<List<string>> ret = new List<List<string>>();
string[] csvRows = System.IO.File.ReadAllLines(filePath);
foreach (string csvRow in csvRows)
{
bool inQuotes = false;
List<string> fields = new List<string>();
string field = "";
for (int i = 0; i < csvRow.Length; i++)
{
if (inQuotes)
{
if (i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar)
{
i++;
field += quoteChar;
}
else if (csvRow[i] == quoteChar)
{
inQuotes = false;
}
else
{
field += csvRow[i];
}
}
else
{
if (csvRow[i] == quoteChar)
{
inQuotes = true;
continue;
}
if (csvRow[i] == sepChar)
{
fields.Add(field);
field = "";
}
else
{
field += csvRow[i];
}
}
}
if (!string.IsNullOrEmpty(field))
{
fields.Add(field);
field = "";
}
ret.Add(fields);
}
return ret;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IdentityModel;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.Xml;
using SysAuthorizationContext = System.IdentityModel.Policy.AuthorizationContext;
namespace System.ServiceModel.Security
{
/// <summary>
/// Custom ServiceAuthorizationManager implementation. This class substitues the WCF
/// generated IAuthorizationPolicies with
/// <see cref="System.IdentityModel.Tokens.AuthorizationPolicy"/>. These
/// policies do not participate in the EvaluationContext and hence will render an
/// empty WCF AuthorizationConext. Once this AuthorizationManager is substitued to
/// a ServiceHost, only <see cref="System.Security.Claims.ClaimsPrincipal"/>
/// will be available for Authorization decisions.
/// </summary>
class IdentityModelServiceAuthorizationManager : ServiceAuthorizationManager
{
/// <summary>
/// Authorization policy for anonymous authentication.
/// </summary>
protected static readonly ReadOnlyCollection<IAuthorizationPolicy> AnonymousAuthorizationPolicy
= new ReadOnlyCollection<IAuthorizationPolicy>(
new List<IAuthorizationPolicy>() { new AuthorizationPolicy(new ClaimsIdentity()) });
/// <summary>
/// Override of the base class method. Substitues WCF IAuthorizationPolicy with
/// <see cref="System.IdentityModel.Tokens.AuthorizationPolicy"/>.
/// </summary>
/// <param name="operationContext">Current OperationContext that contains all the IAuthorizationPolicies.</param>
/// <returns>Read-Only collection of <see cref="IAuthorizationPolicy"/> </returns>
protected override ReadOnlyCollection<IAuthorizationPolicy> GetAuthorizationPolicies(OperationContext operationContext)
{
//
// Make sure we always return at least one claims identity, if there are no auth policies
// that contain any identities, then return an anonymous identity wrapped in an authorization policy.
//
// If we do not, then Thread.CurrentPrincipal may end up being null inside service operations after the
// authorization polices are evaluated since ServiceCredentials.ConfigureServiceHost will
// turn the PrincipalPermissionMode knob to Custom.
//
ReadOnlyCollection<IAuthorizationPolicy> baseAuthorizationPolicies = base.GetAuthorizationPolicies(operationContext);
if (baseAuthorizationPolicies == null)
{
return AnonymousAuthorizationPolicy;
}
else
{
ServiceCredentials sc = GetServiceCredentials();
AuthorizationPolicy transformedPolicy = TransformAuthorizationPolicies(baseAuthorizationPolicies,
sc.IdentityConfiguration.SecurityTokenHandlers,
true);
if (transformedPolicy == null || transformedPolicy.IdentityCollection.Count == 0)
{
return AnonymousAuthorizationPolicy;
}
return (new List<IAuthorizationPolicy>() { transformedPolicy }).AsReadOnly();
}
}
internal static AuthorizationPolicy TransformAuthorizationPolicies(
ReadOnlyCollection<IAuthorizationPolicy> baseAuthorizationPolicies,
SecurityTokenHandlerCollection securityTokenHandlerCollection,
bool includeTransportTokens)
{
List<ClaimsIdentity> identities = new List<ClaimsIdentity>();
List<IAuthorizationPolicy> uncheckedAuthorizationPolicies = new List<IAuthorizationPolicy>();
//
// STEP 1: Filter out the IAuthorizationPolicy that WCF generated. These
// are generated as IDFx does not have a proper SecurityTokenHandler
// to handle these. For example, SSPI at message layer and all token
// types at the Transport layer.
//
foreach (IAuthorizationPolicy authPolicy in baseAuthorizationPolicies)
{
if ((authPolicy is SctAuthorizationPolicy) ||
(authPolicy is EndpointAuthorizationPolicy))
{
//
// We ignore the SctAuthorizationPolicy if any found as they were created
// as wrapper policies to hold the primary identity claim during a token renewal path.
// WCF would otherwise fault thinking the token issuance and renewal identities are
// different. This policy should be treated as a dummy policy and thereby should not be transformed.
//
// We ignore EndpointAuthorizationPolicy as well. This policy is used only to carry
// the endpoint Identity and there is no useful claims that this policy contributes.
//
continue;
}
AuthorizationPolicy idfxAuthPolicy = authPolicy as AuthorizationPolicy;
if (idfxAuthPolicy != null)
{
// Identities obtained from the Tokens in the message layer would
identities.AddRange(idfxAuthPolicy.IdentityCollection);
}
else
{
uncheckedAuthorizationPolicies.Add(authPolicy);
}
}
//
// STEP 2: Generate IDFx claims from the transport token
//
if (includeTransportTokens && (OperationContext.Current != null) &&
(OperationContext.Current.IncomingMessageProperties != null) &&
(OperationContext.Current.IncomingMessageProperties.Security != null) &&
(OperationContext.Current.IncomingMessageProperties.Security.TransportToken != null))
{
SecurityToken transportToken =
OperationContext.Current.IncomingMessageProperties.Security.TransportToken.SecurityToken;
ReadOnlyCollection<IAuthorizationPolicy> policyCollection =
OperationContext.Current.IncomingMessageProperties.Security.TransportToken.SecurityTokenPolicies;
bool isWcfAuthPolicy = true;
foreach (IAuthorizationPolicy policy in policyCollection)
{
//
// Iterate over each of the policies in the policyCollection to make sure
// we don't have an idfx policy, if we do we will not consider this as
// a wcf auth policy: Such a case will be hit for the SslStreamSecurityBinding over net tcp
//
if (policy is AuthorizationPolicy)
{
isWcfAuthPolicy = false;
break;
}
}
if (isWcfAuthPolicy)
{
ReadOnlyCollection<ClaimsIdentity> tranportTokenIdentities = GetTransportTokenIdentities(transportToken);
identities.AddRange(tranportTokenIdentities);
//
// NOTE: In the below code, we are trying to identify the IAuthorizationPolicy that WCF
// created for the Transport token and eliminate it. This assumes that any client Security
// Token that came in the Security header would have been validated by the SecurityTokenHandler
// and hence would have created a IDFx AuthorizationPolicy.
// For example, if X.509 Certificate was used to authenticate the client at the transport layer
// and then again at the Message security layer we depend on our TokenHandlers to have been in
// place to validate the X.509 Certificate at the message layer. This would clearly distinguish
// which policy was created for the Transport token by WCF.
//
EliminateTransportTokenPolicy(transportToken, tranportTokenIdentities, uncheckedAuthorizationPolicies);
}
}
//
// STEP 3: Process any uncheckedAuthorizationPolicies here. Convert these to IDFx
// Claims.
//
if (uncheckedAuthorizationPolicies.Count > 0)
{
identities.AddRange(ConvertToIDFxIdentities(uncheckedAuthorizationPolicies, securityTokenHandlerCollection));
}
//
// STEP 4: Create an AuthorizationPolicy with all the ClaimsIdentities.
//
AuthorizationPolicy idfxAuthorizationPolicy = null;
if (identities.Count == 0)
{
//
// No IDFx ClaimsIdentity was found. Return AnonymousIdentity.
//
idfxAuthorizationPolicy = new AuthorizationPolicy(new ClaimsIdentity());
}
else
{
idfxAuthorizationPolicy = new AuthorizationPolicy(identities.AsReadOnly());
}
return idfxAuthorizationPolicy;
}
/// <summary>
/// Creates ClaimsIdentityCollection for the given Transport SecurityToken.
/// </summary>
/// <param name="transportToken">Client SecurityToken provided at the Transport layer.</param>
/// <returns>ClaimsIdentityCollection built from the Transport SecurityToken</returns>
static ReadOnlyCollection<ClaimsIdentity> GetTransportTokenIdentities(SecurityToken transportToken)
{
if (transportToken == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("transportToken");
}
ServiceCredentials serviceCreds = GetServiceCredentials();
List<ClaimsIdentity> transportTokenIdentityCollection = new List<ClaimsIdentity>();
//////////////////////////////////////////////////////////////////////////////////////////
//
// There are 5 well-known Client Authentication types at the transport layer. Each of these will
// result either in a WindowsSecurityToken, X509SecurityToken or UserNameSecurityToken.
// All other type of credentials (like OAuth token) result other token that will be passed trough regular validation process.
//
// ClientCredential Type || Transport Token Type
// -------------------------------------------------------------------
// Basic -> UserNameSecurityToken (In Self-hosted case)
// Basic -> WindowsSecurityToken (In Web-Hosted case)
// NTLM -> WindowsSecurityToken
// Negotiate -> WindowsSecurityToken
// Windows -> WindowsSecurityToken
// Certificate -> X509SecurityToken
//
//////////////////////////////////////////////////////////////////////////////////////////
WindowsSecurityToken windowsSecurityToken = transportToken as WindowsSecurityToken;
if ( windowsSecurityToken != null )
{
WindowsIdentity claimsIdentity = new WindowsIdentity( windowsSecurityToken.WindowsIdentity.Token,
AuthenticationTypes.Windows );
AddAuthenticationMethod( claimsIdentity, AuthenticationMethods.Windows );
AddAuthenticationInstantClaim(claimsIdentity, XmlConvert.ToString(DateTime.UtcNow, DateTimeFormats.Generated));
// Just reflect on the wrapped WindowsIdentity and build the WindowsClaimsIdentity class.
transportTokenIdentityCollection.Add(claimsIdentity);
}
else
{
// WCF does not call our SecurityTokenHandlers for the Transport token. So run the token through
// the SecurityTokenHandler and generate claims for this token.
transportTokenIdentityCollection.AddRange(serviceCreds.IdentityConfiguration.SecurityTokenHandlers.ValidateToken( transportToken ));
}
return transportTokenIdentityCollection.AsReadOnly();
}
/// <summary>
/// Given a collection of IAuthorizationPolicies this method will eliminate the IAuthorizationPolicy
/// that was created for the given transport Security Token. The method modifies the given collection
/// of IAuthorizationPolicy.
/// </summary>
/// <param name="transportToken">Client's Security Token provided at the transport layer.</param>
/// <param name="tranportTokenIdentities"></param>
/// <param name="baseAuthorizationPolicies">Collection of IAuthorizationPolicies that were created by WCF.</param>
static void EliminateTransportTokenPolicy(
SecurityToken transportToken,
IEnumerable<ClaimsIdentity> tranportTokenIdentities,
List<IAuthorizationPolicy> baseAuthorizationPolicies)
{
if (transportToken == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("transportToken");
}
if (tranportTokenIdentities == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tranportTokenIdentities");
}
if (baseAuthorizationPolicies == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("baseAuthorizationPolicy");
}
if (baseAuthorizationPolicies.Count == 0)
{
// This should never happen in our current configuration. IDFx token handlers do not validate
// client tokens present at the transport level. So we should atleast have one IAuthorizationPolicy
// that WCF generated for the transport token.
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("baseAuthorizationPolicy", SR.GetString(SR.ID0020));
}
//
// We will process one IAuthorizationPolicy at a time. Transport token will have been authenticated
// by WCF and would have created a IAuthorizationPolicy for the same. If the transport token is a X.509
// SecurityToken and 'mapToWindows' was set to true then the IAuthorizationPolicy that was created
// by WCF will have two Claimsets, a X509ClaimSet and a WindowsClaimSet. We need to prune out this case
// and ignore both these Claimsets as we have made a call to the token handler to authenticate this
// token above. If we create a AuthorizationContext using all the IAuthorizationPolicies then all
// the claimsets are merged and it becomes hard to identify this case.
//
IAuthorizationPolicy policyToEliminate = null;
foreach (IAuthorizationPolicy authPolicy in baseAuthorizationPolicies)
{
if (DoesPolicyMatchTransportToken(transportToken, tranportTokenIdentities, authPolicy))
{
policyToEliminate = authPolicy;
break;
}
}
if (policyToEliminate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4271, transportToken));
}
baseAuthorizationPolicies.Remove(policyToEliminate);
}
/// <summary>
/// Returns true if the IAuthorizationPolicy could have been created from the given Transport token.
/// The method can handle only X509SecurityToken and WindowsSecurityToken.
/// </summary>
/// <param name="transportToken">Client's Security Token provided at the transport layer.</param>
/// <param name="tranportTokenIdentities">A collection of <see cref="ClaimsIdentity"/> to match.</param>
/// <param name="authPolicy">IAuthorizationPolicy to check.</param>
/// <returns>True if the IAuthorizationPolicy could have been created from the given Transpor token.</returns>
static bool DoesPolicyMatchTransportToken(
SecurityToken transportToken,
IEnumerable<ClaimsIdentity> tranportTokenIdentities,
IAuthorizationPolicy authPolicy
)
{
if (transportToken == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("transportToken");
}
if (tranportTokenIdentities == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tranportTokenIdentities");
}
if (authPolicy == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authPolicy");
}
//////////////////////////////////////////////////////////////////////////////////////////
//
// There are 5 Client Authentication types at the transport layer. Each of these will
// result either in a WindowsSecurityToken, X509SecurityToken or UserNameSecurityToken.
//
// ClientCredential Type || Transport Token Type
// -------------------------------------------------------------------
// Basic -> UserNameSecurityToken (In Self-hosted case)
// Basic -> WindowsSecurityToken (In Web-Hosted case)
// NTLM -> WindowsSecurityToken
// Negotiate -> WindowsSecurityToken
// Windows -> WindowsSecurityToken
// Certificate -> X509SecurityToken
//
//////////////////////////////////////////////////////////////////////////////////////////
X509SecurityToken x509SecurityToken = transportToken as X509SecurityToken;
SysAuthorizationContext defaultAuthContext = SysAuthorizationContext.CreateDefaultAuthorizationContext(new List<IAuthorizationPolicy>() { authPolicy });
foreach (System.IdentityModel.Claims.ClaimSet claimset in defaultAuthContext.ClaimSets)
{
if (x509SecurityToken != null)
{
// Check if the claimset contains a claim that matches the X.509 certificate thumbprint.
if (claimset.ContainsClaim(new System.IdentityModel.Claims.Claim(
System.IdentityModel.Claims.ClaimTypes.Thumbprint,
x509SecurityToken.Certificate.GetCertHash(),
System.IdentityModel.Claims.Rights.PossessProperty)))
{
return true;
}
}
else
{
// For WindowsSecurityToken and UserNameSecurityToken check that IClaimsdentity.Name
// matches the Name Claim in the ClaimSet.
// In most cases, we will have only one Identity in the ClaimsIdentityCollection
// generated from transport token.
foreach (ClaimsIdentity transportTokenIdentity in tranportTokenIdentities)
{
if (claimset.ContainsClaim(new System.IdentityModel.Claims.Claim(
System.IdentityModel.Claims.ClaimTypes.Name,
transportTokenIdentity.Name,
System.IdentityModel.Claims.Rights.PossessProperty), new ClaimStringValueComparer()))
{
return true;
}
}
}
}
return false;
}
/// <summary>
/// Converts a given set of WCF IAuthorizationPolicy to WIF ClaimIdentities.
/// </summary>
/// <param name="authorizationPolicies">Set of AuthorizationPolicies to convert to IDFx.</param>
/// <param name="securityTokenHandlerCollection">The SecurityTokenHandlerCollection to use.</param>
/// <returns>ClaimsIdentityCollection</returns>
static ReadOnlyCollection<ClaimsIdentity> ConvertToIDFxIdentities(IList<IAuthorizationPolicy> authorizationPolicies,
SecurityTokenHandlerCollection securityTokenHandlerCollection)
{
if (authorizationPolicies == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies");
}
if (securityTokenHandlerCollection == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenHandlerCollection");
}
List<ClaimsIdentity> identities = new List<ClaimsIdentity>();
SecurityTokenSpecification kerberosTokenSpecification = null;
SysAuthorizationContext kerberosAuthContext = null;
if ((OperationContext.Current != null) &&
(OperationContext.Current.IncomingMessageProperties != null) &&
(OperationContext.Current.IncomingMessageProperties.Security != null))
{
SecurityMessageProperty securityMessageProperty = OperationContext.Current.IncomingMessageProperties.Security;
foreach (SecurityTokenSpecification tokenSpecification in new SecurityTokenSpecificationEnumerable(securityMessageProperty))
{
if (tokenSpecification.SecurityToken is KerberosReceiverSecurityToken)
{
kerberosTokenSpecification = tokenSpecification;
kerberosAuthContext = SysAuthorizationContext.CreateDefaultAuthorizationContext(kerberosTokenSpecification.SecurityTokenPolicies);
break;
}
}
}
bool hasKerberosTokenPolicyMatched = false;
foreach (IAuthorizationPolicy policy in authorizationPolicies)
{
bool authPolicyHandled = false;
if ((kerberosTokenSpecification != null) && !hasKerberosTokenPolicyMatched)
{
if (kerberosTokenSpecification.SecurityTokenPolicies.Contains(policy))
{
hasKerberosTokenPolicyMatched = true;
}
else
{
SysAuthorizationContext authContext = SysAuthorizationContext.CreateDefaultAuthorizationContext(new List<IAuthorizationPolicy>() { policy });
// Kerberos creates only one ClaimSet. So any more ClaimSet would mean that this is not a Policy created from Kerberos.
if (authContext.ClaimSets.Count == 1)
{
bool allClaimsMatched = true;
foreach (System.IdentityModel.Claims.Claim c in authContext.ClaimSets[0])
{
if (!kerberosAuthContext.ClaimSets[0].ContainsClaim(c))
{
allClaimsMatched = false;
break;
}
}
hasKerberosTokenPolicyMatched = allClaimsMatched;
}
}
if (hasKerberosTokenPolicyMatched)
{
SecurityTokenHandler tokenHandler = securityTokenHandlerCollection[kerberosTokenSpecification.SecurityToken];
if ((tokenHandler != null) && tokenHandler.CanValidateToken)
{
identities.AddRange(tokenHandler.ValidateToken(kerberosTokenSpecification.SecurityToken));
authPolicyHandled = true;
}
}
}
if (!authPolicyHandled)
{
SysAuthorizationContext defaultAuthContext = SysAuthorizationContext.CreateDefaultAuthorizationContext(new List<IAuthorizationPolicy>() { policy });
//
// Merge all ClaimSets to IClaimsIdentity.
//
identities.Add(ConvertToIDFxIdentity(defaultAuthContext.ClaimSets, securityTokenHandlerCollection.Configuration));
}
}
return identities.AsReadOnly();
}
/// <summary>
/// Converts a given set of WCF ClaimSets to IDFx ClaimsIdentity.
/// </summary>
/// <param name="claimSets">Collection of <see cref="ClaimSet"/> to convert to IDFx.</param>
/// <param name="securityTokenHandlerConfiguration">The SecurityTokenHandlerConfiguration to use.</param>
/// <returns>ClaimsIdentity</returns>
static ClaimsIdentity ConvertToIDFxIdentity(IList<ClaimSet> claimSets, SecurityTokenHandlerConfiguration securityTokenHandlerConfiguration)
{
if (claimSets == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claimSets");
}
ClaimsIdentity claimsIdentity = null;
foreach (System.IdentityModel.Claims.ClaimSet claimSet in claimSets)
{
WindowsClaimSet windowsClaimSet = claimSet as WindowsClaimSet;
if (windowsClaimSet != null)
{
//
// The ClaimSet in the authorizationContext is simply a reflection of the NT Token.
// The WindowsClaimsIdentity will generate that information properly. So ignore the ClaimSets.
//
//
// WCF does not propogate the WindowsIdentity.AuthenticationType properly.
// To avoid WindowsClaimsIdentity.AuthenticationType from throwing, specify
// this authenticationType value. Since we only have to handle SPNEGO specify Negotiate.
//
claimsIdentity = MergeClaims(claimsIdentity, new WindowsIdentity(windowsClaimSet.WindowsIdentity.Token,
AuthenticationTypes.Negotiate));
AddAuthenticationMethod(claimsIdentity, AuthenticationMethods.Windows);
AddAuthenticationInstantClaim(claimsIdentity, XmlConvert.ToString(DateTime.UtcNow, DateTimeFormats.Generated));
}
else
{
claimsIdentity = MergeClaims(claimsIdentity, ClaimsConversionHelper.CreateClaimsIdentityFromClaimSet(claimSet));
AddAuthenticationInstantClaim(claimsIdentity, XmlConvert.ToString(DateTime.UtcNow, DateTimeFormats.Generated));
}
}
return claimsIdentity;
}
/// <summary>
/// Gets the ServiceCredentials from the OperationContext.
/// </summary>
/// <returns>ServiceCredentials</returns>
static ServiceCredentials GetServiceCredentials()
{
ServiceCredentials serviceCredentials = null;
if (OperationContext.Current != null &&
OperationContext.Current.Host != null &&
OperationContext.Current.Host.Description != null &&
OperationContext.Current.Host.Description.Behaviors != null)
{
serviceCredentials = OperationContext.Current.Host.Description.Behaviors.Find<ServiceCredentials>();
}
return serviceCredentials;
}
// Adds an Authentication Method claims to the given ClaimsIdentity if one is not already present.
static void AddAuthenticationMethod(ClaimsIdentity claimsIdentity, string authenticationMethod)
{
System.Security.Claims.Claim authenticationMethodClaim =
claimsIdentity.Claims.FirstOrDefault(claim => claim.Type == System.Security.Claims.ClaimTypes.AuthenticationMethod);
if (authenticationMethodClaim == null)
{
// AuthenticationMethod claims does not exist. Add one.
claimsIdentity.AddClaim(
new System.Security.Claims.Claim(
System.Security.Claims.ClaimTypes.AuthenticationMethod, authenticationMethod));
}
}
// Adds an Authentication Method claims to the given ClaimsIdentity if one is not already present.
static void AddAuthenticationInstantClaim(ClaimsIdentity claimsIdentity, string authenticationInstant)
{
// the issuer for this claim should always be the default issuer.
string issuerName = ClaimsIdentity.DefaultIssuer;
System.Security.Claims.Claim authenticationInstantClaim =
claimsIdentity.Claims.FirstOrDefault(claim => claim.Type == System.Security.Claims.ClaimTypes.AuthenticationInstant);
if (authenticationInstantClaim == null)
{
// AuthenticationInstance claims does not exist. Add one.
claimsIdentity.AddClaim(
new System.Security.Claims.Claim(
System.Security.Claims.ClaimTypes.AuthenticationInstant, authenticationInstant, ClaimValueTypes.DateTime,
issuerName));
}
}
// When a token creates more than one Identity we have to merge these identities.
// The below method takes two Identities and will return a single identity. If one of the
// Identities is a WindowsIdentity then all claims from the other identity are
// merged into the WindowsIdentity. If neither are WindowsIdentity then it
// selects 'identity1' and merges all the claims from 'identity2' into 'identity1'.
//
// It is not clear how we can handler duplicate name claim types and delegates.
// So, we are just cloning the claims from one identity and adding it to another.
internal static ClaimsIdentity MergeClaims(ClaimsIdentity identity1, ClaimsIdentity identity2)
{
if ((identity1 == null) && (identity2 == null))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4268));
}
if (identity1 == null)
{
return identity2;
}
if (identity2 == null)
{
return identity1;
}
WindowsIdentity windowsIdentity = identity1 as WindowsIdentity;
if (windowsIdentity != null)
{
windowsIdentity.AddClaims(identity2.Claims);
return windowsIdentity;
}
windowsIdentity = identity2 as WindowsIdentity;
if (windowsIdentity != null)
{
windowsIdentity.AddClaims(identity1.Claims);
return windowsIdentity;
}
identity1.AddClaims(identity2.Claims);
return identity1;
}
/// <summary>
/// Checks authorization for the given operation context based on policy evaluation.
/// </summary>
/// <param name="operationContext">The OperationContext for the current authorization request.</param>
/// <returns>true if authorized, false otherwise</returns>
protected override bool CheckAccessCore(OperationContext operationContext)
{
if (operationContext == null)
{
return false;
}
string action = string.Empty;
// WebRequests will not always have an action specified in the operation context.
// If action is null or empty, check the httpRequest.
if (!string.IsNullOrEmpty(operationContext.IncomingMessageHeaders.Action))
{
action = operationContext.IncomingMessageHeaders.Action;
}
else
{
HttpRequestMessageProperty request = operationContext.IncomingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
if (request != null)
{
action = request.Method;
}
}
System.Uri resource = operationContext.IncomingMessageHeaders.To;
ServiceCredentials credentials = GetServiceCredentials();
if ((credentials == null) || string.IsNullOrEmpty(action) || (resource == null))
{
return false;
}
//
// CheckAccess is called prior to impersonation in WCF, so we need to pull
// the ClaimsPrincipal from the OperationContext.ServiceSecurityContext.AuthorizationContext.Properties[ "Principal" ].
//
ClaimsPrincipal claimsPrincipal = operationContext.ServiceSecurityContext.AuthorizationContext.Properties[AuthorizationPolicy.ClaimsPrincipalKey] as ClaimsPrincipal;
claimsPrincipal = credentials.IdentityConfiguration.ClaimsAuthenticationManager.Authenticate(resource.AbsoluteUri, claimsPrincipal);
operationContext.ServiceSecurityContext.AuthorizationContext.Properties[AuthorizationPolicy.ClaimsPrincipalKey] = claimsPrincipal;
if ((claimsPrincipal == null) || (claimsPrincipal.Identities == null))
{
return false;
}
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(
TraceEventType.Information,
TraceCode.Security,
SR.GetString(SR.TraceAuthorize),
new System.IdentityModel.Diagnostics.AuthorizeTraceRecord(claimsPrincipal, resource.AbsoluteUri, action));
}
bool authorized = credentials.IdentityConfiguration.ClaimsAuthorizationManager.CheckAccess(
new System.Security.Claims.AuthorizationContext(
claimsPrincipal, resource.AbsoluteUri, action
)
);
if (DiagnosticUtility.ShouldTraceInformation)
{
if (authorized)
{
System.IdentityModel.Diagnostics.TraceUtility.TraceString(
TraceEventType.Information,
SR.GetString(SR.TraceOnAuthorizeRequestSucceed));
}
else
{
System.IdentityModel.Diagnostics.TraceUtility.TraceString(
TraceEventType.Information,
SR.GetString(SR.TraceOnAuthorizeRequestFailed));
}
}
return authorized;
}
}
class ClaimStringValueComparer : IEqualityComparer<System.IdentityModel.Claims.Claim>
{
#region IEqualityComparer<System.IdentityModel.Claims.Claim> Members
public bool Equals(System.IdentityModel.Claims.Claim claim1, System.IdentityModel.Claims.Claim claim2)
{
if (ReferenceEquals(claim1, claim2))
{
return true;
}
if (claim1 == null || claim2 == null)
{
return false;
}
if (claim1.ClaimType != claim2.ClaimType || claim1.Right != claim2.Right)
{
return false;
}
return StringComparer.OrdinalIgnoreCase.Equals(claim1.Resource, claim2.Resource);
}
public int GetHashCode(System.IdentityModel.Claims.Claim claim)
{
if (claim == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claim");
}
return claim.ClaimType.GetHashCode() ^ claim.Right.GetHashCode()
^ ((claim.Resource == null) ? 0 : claim.Resource.GetHashCode());
}
#endregion
}
class SecurityTokenSpecificationEnumerable : IEnumerable<SecurityTokenSpecification>
{
SecurityMessageProperty _securityMessageProperty;
public SecurityTokenSpecificationEnumerable(SecurityMessageProperty securityMessageProperty)
{
if (securityMessageProperty == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityMessageProperty");
}
_securityMessageProperty = securityMessageProperty;
}
public IEnumerator<SecurityTokenSpecification> GetEnumerator()
{
if (_securityMessageProperty.InitiatorToken != null)
{
yield return _securityMessageProperty.InitiatorToken;
}
if (_securityMessageProperty.ProtectionToken != null)
{
yield return _securityMessageProperty.ProtectionToken;
}
if (_securityMessageProperty.HasIncomingSupportingTokens)
{
foreach (SecurityTokenSpecification tokenSpecification in _securityMessageProperty.IncomingSupportingTokens)
{
if (tokenSpecification != null)
{
yield return tokenSpecification;
}
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.WindowsAzure.Management.SiteRecovery;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;
namespace Microsoft.WindowsAzure.Management.SiteRecovery
{
/// <summary>
/// Definition of virtual machine operations for the Site Recovery
/// extension.
/// </summary>
internal partial class VirtualMachineOperations : IServiceOperations<SiteRecoveryManagementClient>, IVirtualMachineOperations
{
/// <summary>
/// Initializes a new instance of the VirtualMachineOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal VirtualMachineOperations(SiteRecoveryManagementClient client)
{
this._client = client;
}
private SiteRecoveryManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.SiteRecoveryManagementClient.
/// </summary>
public SiteRecoveryManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Get the VM object by Id.
/// </summary>
/// <param name='protectionContainerId'>
/// Required. Parent Protection Container ID.
/// </param>
/// <param name='virtualMachineId'>
/// Required. VM ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Vm object.
/// </returns>
public async Task<VirtualMachineResponse> GetAsync(string protectionContainerId, string virtualMachineId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (protectionContainerId == null)
{
throw new ArgumentNullException("protectionContainerId");
}
if (virtualMachineId == null)
{
throw new ArgumentNullException("virtualMachineId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("protectionContainerId", protectionContainerId);
tracingParameters.Add("virtualMachineId", virtualMachineId);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + "WAHyperVRecoveryManager";
url = url + "/~/";
url = url + "HyperVRecoveryManagerVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/ProtectionContainers/";
url = url + Uri.EscapeDataString(protectionContainerId);
url = url + "/VirtualMachines/";
url = url + Uri.EscapeDataString(virtualMachineId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-04-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement virtualMachineElement = responseDoc.Element(XName.Get("VirtualMachine", "http://schemas.microsoft.com/windowsazure"));
if (virtualMachineElement != null)
{
VirtualMachine virtualMachineInstance = new VirtualMachine();
result.Vm = virtualMachineInstance;
XElement replicationProviderSettingsElement = virtualMachineElement.Element(XName.Get("ReplicationProviderSettings", "http://schemas.microsoft.com/windowsazure"));
if (replicationProviderSettingsElement != null)
{
string replicationProviderSettingsInstance = replicationProviderSettingsElement.Value;
virtualMachineInstance.ReplicationProviderSettings = replicationProviderSettingsInstance;
}
XElement typeElement = virtualMachineElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
virtualMachineInstance.Type = typeInstance;
}
XElement fabricObjectIdElement = virtualMachineElement.Element(XName.Get("FabricObjectId", "http://schemas.microsoft.com/windowsazure"));
if (fabricObjectIdElement != null)
{
string fabricObjectIdInstance = fabricObjectIdElement.Value;
virtualMachineInstance.FabricObjectId = fabricObjectIdInstance;
}
XElement serverIdElement = virtualMachineElement.Element(XName.Get("ServerId", "http://schemas.microsoft.com/windowsazure"));
if (serverIdElement != null)
{
string serverIdInstance = serverIdElement.Value;
virtualMachineInstance.ServerId = serverIdInstance;
}
XElement protectionContainerIdElement = virtualMachineElement.Element(XName.Get("ProtectionContainerId", "http://schemas.microsoft.com/windowsazure"));
if (protectionContainerIdElement != null)
{
string protectionContainerIdInstance = protectionContainerIdElement.Value;
virtualMachineInstance.ProtectionContainerId = protectionContainerIdInstance;
}
XElement protectedElement = virtualMachineElement.Element(XName.Get("Protected", "http://schemas.microsoft.com/windowsazure"));
if (protectedElement != null)
{
bool protectedInstance = bool.Parse(protectedElement.Value);
virtualMachineInstance.Protected = protectedInstance;
}
XElement protectionStateDescriptionElement = virtualMachineElement.Element(XName.Get("ProtectionStateDescription", "http://schemas.microsoft.com/windowsazure"));
if (protectionStateDescriptionElement != null)
{
string protectionStateDescriptionInstance = protectionStateDescriptionElement.Value;
virtualMachineInstance.ProtectionStateDescription = protectionStateDescriptionInstance;
}
XElement activeLocationElement = virtualMachineElement.Element(XName.Get("ActiveLocation", "http://schemas.microsoft.com/windowsazure"));
if (activeLocationElement != null)
{
string activeLocationInstance = activeLocationElement.Value;
virtualMachineInstance.ActiveLocation = activeLocationInstance;
}
XElement testFailoverStateDescriptionElement = virtualMachineElement.Element(XName.Get("TestFailoverStateDescription", "http://schemas.microsoft.com/windowsazure"));
if (testFailoverStateDescriptionElement != null)
{
string testFailoverStateDescriptionInstance = testFailoverStateDescriptionElement.Value;
virtualMachineInstance.TestFailoverStateDescription = testFailoverStateDescriptionInstance;
}
XElement canFailoverElement = virtualMachineElement.Element(XName.Get("CanFailover", "http://schemas.microsoft.com/windowsazure"));
if (canFailoverElement != null)
{
bool canFailoverInstance = bool.Parse(canFailoverElement.Value);
virtualMachineInstance.CanFailover = canFailoverInstance;
}
XElement canReverseReplicateElement = virtualMachineElement.Element(XName.Get("CanReverseReplicate", "http://schemas.microsoft.com/windowsazure"));
if (canReverseReplicateElement != null)
{
bool canReverseReplicateInstance = bool.Parse(canReverseReplicateElement.Value);
virtualMachineInstance.CanReverseReplicate = canReverseReplicateInstance;
}
XElement canCommitElement = virtualMachineElement.Element(XName.Get("CanCommit", "http://schemas.microsoft.com/windowsazure"));
if (canCommitElement != null)
{
bool canCommitInstance = bool.Parse(canCommitElement.Value);
virtualMachineInstance.CanCommit = canCommitInstance;
}
XElement replicationHealthElement = virtualMachineElement.Element(XName.Get("ReplicationHealth", "http://schemas.microsoft.com/windowsazure"));
if (replicationHealthElement != null)
{
string replicationHealthInstance = replicationHealthElement.Value;
virtualMachineInstance.ReplicationHealth = replicationHealthInstance;
}
XElement replicationProviderElement = virtualMachineElement.Element(XName.Get("ReplicationProvider", "http://schemas.microsoft.com/windowsazure"));
if (replicationProviderElement != null)
{
string replicationProviderInstance = replicationProviderElement.Value;
virtualMachineInstance.ReplicationProvider = replicationProviderInstance;
}
XElement protectionProfileElement = virtualMachineElement.Element(XName.Get("ProtectionProfile", "http://schemas.microsoft.com/windowsazure"));
if (protectionProfileElement != null)
{
ProtectionProfile protectionProfileInstance = new ProtectionProfile();
virtualMachineInstance.ProtectionProfile = protectionProfileInstance;
XElement protectedEntityCountElement = protectionProfileElement.Element(XName.Get("ProtectedEntityCount", "http://schemas.microsoft.com/windowsazure"));
if (protectedEntityCountElement != null)
{
int protectedEntityCountInstance = int.Parse(protectedEntityCountElement.Value, CultureInfo.InvariantCulture);
protectionProfileInstance.ProtectedEntityCount = protectedEntityCountInstance;
}
XElement replicationProviderElement2 = protectionProfileElement.Element(XName.Get("ReplicationProvider", "http://schemas.microsoft.com/windowsazure"));
if (replicationProviderElement2 != null)
{
string replicationProviderInstance2 = replicationProviderElement2.Value;
protectionProfileInstance.ReplicationProvider = replicationProviderInstance2;
}
XElement replicationProviderSettingElement = protectionProfileElement.Element(XName.Get("ReplicationProviderSetting", "http://schemas.microsoft.com/windowsazure"));
if (replicationProviderSettingElement != null)
{
string replicationProviderSettingInstance = replicationProviderSettingElement.Value;
protectionProfileInstance.ReplicationProviderSetting = replicationProviderSettingInstance;
}
XElement canDissociateElement = protectionProfileElement.Element(XName.Get("CanDissociate", "http://schemas.microsoft.com/windowsazure"));
if (canDissociateElement != null)
{
bool canDissociateInstance = bool.Parse(canDissociateElement.Value);
protectionProfileInstance.CanDissociate = canDissociateInstance;
}
XElement associationDetailSequenceElement = protectionProfileElement.Element(XName.Get("AssociationDetail", "http://schemas.microsoft.com/windowsazure"));
if (associationDetailSequenceElement != null)
{
foreach (XElement associationDetailElement in associationDetailSequenceElement.Elements(XName.Get("ProtectionProfileAssociationDetails", "http://schemas.microsoft.com/windowsazure")))
{
ProtectionProfileAssociationDetails protectionProfileAssociationDetailsInstance = new ProtectionProfileAssociationDetails();
protectionProfileInstance.AssociationDetail.Add(protectionProfileAssociationDetailsInstance);
XElement primaryProtectionContainerIdElement = associationDetailElement.Element(XName.Get("PrimaryProtectionContainerId", "http://schemas.microsoft.com/windowsazure"));
if (primaryProtectionContainerIdElement != null)
{
string primaryProtectionContainerIdInstance = primaryProtectionContainerIdElement.Value;
protectionProfileAssociationDetailsInstance.PrimaryProtectionContainerId = primaryProtectionContainerIdInstance;
}
XElement recoveryProtectionContainerIdElement = associationDetailElement.Element(XName.Get("RecoveryProtectionContainerId", "http://schemas.microsoft.com/windowsazure"));
if (recoveryProtectionContainerIdElement != null)
{
string recoveryProtectionContainerIdInstance = recoveryProtectionContainerIdElement.Value;
protectionProfileAssociationDetailsInstance.RecoveryProtectionContainerId = recoveryProtectionContainerIdInstance;
}
XElement associationStatusElement = associationDetailElement.Element(XName.Get("AssociationStatus", "http://schemas.microsoft.com/windowsazure"));
if (associationStatusElement != null)
{
string associationStatusInstance = associationStatusElement.Value;
protectionProfileAssociationDetailsInstance.AssociationStatus = associationStatusInstance;
}
}
}
XElement nameElement = protectionProfileElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
protectionProfileInstance.Name = nameInstance;
}
XElement idElement = protectionProfileElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
protectionProfileInstance.ID = idInstance;
}
}
XElement nameElement2 = virtualMachineElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance2 = nameElement2.Value;
virtualMachineInstance.Name = nameInstance2;
}
XElement idElement2 = virtualMachineElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement2 != null)
{
string idInstance2 = idElement2.Value;
virtualMachineInstance.ID = idInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of all Vms.
/// </summary>
/// <param name='protectionContainerId'>
/// Required. Parent Protection Container ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list Vm operation.
/// </returns>
public async Task<VirtualMachineListResponse> ListAsync(string protectionContainerId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (protectionContainerId == null)
{
throw new ArgumentNullException("protectionContainerId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("protectionContainerId", protectionContainerId);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + "WAHyperVRecoveryManager";
url = url + "/~/";
url = url + "HyperVRecoveryManagerVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/ProtectionContainers/";
url = url + Uri.EscapeDataString(protectionContainerId);
url = url + "/VirtualMachines";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-04-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement arrayOfVirtualMachineSequenceElement = responseDoc.Element(XName.Get("ArrayOfVirtualMachine", "http://schemas.microsoft.com/windowsazure"));
if (arrayOfVirtualMachineSequenceElement != null)
{
foreach (XElement arrayOfVirtualMachineElement in arrayOfVirtualMachineSequenceElement.Elements(XName.Get("VirtualMachine", "http://schemas.microsoft.com/windowsazure")))
{
VirtualMachine virtualMachineInstance = new VirtualMachine();
result.Vms.Add(virtualMachineInstance);
XElement replicationProviderSettingsElement = arrayOfVirtualMachineElement.Element(XName.Get("ReplicationProviderSettings", "http://schemas.microsoft.com/windowsazure"));
if (replicationProviderSettingsElement != null)
{
string replicationProviderSettingsInstance = replicationProviderSettingsElement.Value;
virtualMachineInstance.ReplicationProviderSettings = replicationProviderSettingsInstance;
}
XElement typeElement = arrayOfVirtualMachineElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
virtualMachineInstance.Type = typeInstance;
}
XElement fabricObjectIdElement = arrayOfVirtualMachineElement.Element(XName.Get("FabricObjectId", "http://schemas.microsoft.com/windowsazure"));
if (fabricObjectIdElement != null)
{
string fabricObjectIdInstance = fabricObjectIdElement.Value;
virtualMachineInstance.FabricObjectId = fabricObjectIdInstance;
}
XElement serverIdElement = arrayOfVirtualMachineElement.Element(XName.Get("ServerId", "http://schemas.microsoft.com/windowsazure"));
if (serverIdElement != null)
{
string serverIdInstance = serverIdElement.Value;
virtualMachineInstance.ServerId = serverIdInstance;
}
XElement protectionContainerIdElement = arrayOfVirtualMachineElement.Element(XName.Get("ProtectionContainerId", "http://schemas.microsoft.com/windowsazure"));
if (protectionContainerIdElement != null)
{
string protectionContainerIdInstance = protectionContainerIdElement.Value;
virtualMachineInstance.ProtectionContainerId = protectionContainerIdInstance;
}
XElement protectedElement = arrayOfVirtualMachineElement.Element(XName.Get("Protected", "http://schemas.microsoft.com/windowsazure"));
if (protectedElement != null)
{
bool protectedInstance = bool.Parse(protectedElement.Value);
virtualMachineInstance.Protected = protectedInstance;
}
XElement protectionStateDescriptionElement = arrayOfVirtualMachineElement.Element(XName.Get("ProtectionStateDescription", "http://schemas.microsoft.com/windowsazure"));
if (protectionStateDescriptionElement != null)
{
string protectionStateDescriptionInstance = protectionStateDescriptionElement.Value;
virtualMachineInstance.ProtectionStateDescription = protectionStateDescriptionInstance;
}
XElement activeLocationElement = arrayOfVirtualMachineElement.Element(XName.Get("ActiveLocation", "http://schemas.microsoft.com/windowsazure"));
if (activeLocationElement != null)
{
string activeLocationInstance = activeLocationElement.Value;
virtualMachineInstance.ActiveLocation = activeLocationInstance;
}
XElement testFailoverStateDescriptionElement = arrayOfVirtualMachineElement.Element(XName.Get("TestFailoverStateDescription", "http://schemas.microsoft.com/windowsazure"));
if (testFailoverStateDescriptionElement != null)
{
string testFailoverStateDescriptionInstance = testFailoverStateDescriptionElement.Value;
virtualMachineInstance.TestFailoverStateDescription = testFailoverStateDescriptionInstance;
}
XElement canFailoverElement = arrayOfVirtualMachineElement.Element(XName.Get("CanFailover", "http://schemas.microsoft.com/windowsazure"));
if (canFailoverElement != null)
{
bool canFailoverInstance = bool.Parse(canFailoverElement.Value);
virtualMachineInstance.CanFailover = canFailoverInstance;
}
XElement canReverseReplicateElement = arrayOfVirtualMachineElement.Element(XName.Get("CanReverseReplicate", "http://schemas.microsoft.com/windowsazure"));
if (canReverseReplicateElement != null)
{
bool canReverseReplicateInstance = bool.Parse(canReverseReplicateElement.Value);
virtualMachineInstance.CanReverseReplicate = canReverseReplicateInstance;
}
XElement canCommitElement = arrayOfVirtualMachineElement.Element(XName.Get("CanCommit", "http://schemas.microsoft.com/windowsazure"));
if (canCommitElement != null)
{
bool canCommitInstance = bool.Parse(canCommitElement.Value);
virtualMachineInstance.CanCommit = canCommitInstance;
}
XElement replicationHealthElement = arrayOfVirtualMachineElement.Element(XName.Get("ReplicationHealth", "http://schemas.microsoft.com/windowsazure"));
if (replicationHealthElement != null)
{
string replicationHealthInstance = replicationHealthElement.Value;
virtualMachineInstance.ReplicationHealth = replicationHealthInstance;
}
XElement replicationProviderElement = arrayOfVirtualMachineElement.Element(XName.Get("ReplicationProvider", "http://schemas.microsoft.com/windowsazure"));
if (replicationProviderElement != null)
{
string replicationProviderInstance = replicationProviderElement.Value;
virtualMachineInstance.ReplicationProvider = replicationProviderInstance;
}
XElement protectionProfileElement = arrayOfVirtualMachineElement.Element(XName.Get("ProtectionProfile", "http://schemas.microsoft.com/windowsazure"));
if (protectionProfileElement != null)
{
ProtectionProfile protectionProfileInstance = new ProtectionProfile();
virtualMachineInstance.ProtectionProfile = protectionProfileInstance;
XElement protectedEntityCountElement = protectionProfileElement.Element(XName.Get("ProtectedEntityCount", "http://schemas.microsoft.com/windowsazure"));
if (protectedEntityCountElement != null)
{
int protectedEntityCountInstance = int.Parse(protectedEntityCountElement.Value, CultureInfo.InvariantCulture);
protectionProfileInstance.ProtectedEntityCount = protectedEntityCountInstance;
}
XElement replicationProviderElement2 = protectionProfileElement.Element(XName.Get("ReplicationProvider", "http://schemas.microsoft.com/windowsazure"));
if (replicationProviderElement2 != null)
{
string replicationProviderInstance2 = replicationProviderElement2.Value;
protectionProfileInstance.ReplicationProvider = replicationProviderInstance2;
}
XElement replicationProviderSettingElement = protectionProfileElement.Element(XName.Get("ReplicationProviderSetting", "http://schemas.microsoft.com/windowsazure"));
if (replicationProviderSettingElement != null)
{
string replicationProviderSettingInstance = replicationProviderSettingElement.Value;
protectionProfileInstance.ReplicationProviderSetting = replicationProviderSettingInstance;
}
XElement canDissociateElement = protectionProfileElement.Element(XName.Get("CanDissociate", "http://schemas.microsoft.com/windowsazure"));
if (canDissociateElement != null)
{
bool canDissociateInstance = bool.Parse(canDissociateElement.Value);
protectionProfileInstance.CanDissociate = canDissociateInstance;
}
XElement associationDetailSequenceElement = protectionProfileElement.Element(XName.Get("AssociationDetail", "http://schemas.microsoft.com/windowsazure"));
if (associationDetailSequenceElement != null)
{
foreach (XElement associationDetailElement in associationDetailSequenceElement.Elements(XName.Get("ProtectionProfileAssociationDetails", "http://schemas.microsoft.com/windowsazure")))
{
ProtectionProfileAssociationDetails protectionProfileAssociationDetailsInstance = new ProtectionProfileAssociationDetails();
protectionProfileInstance.AssociationDetail.Add(protectionProfileAssociationDetailsInstance);
XElement primaryProtectionContainerIdElement = associationDetailElement.Element(XName.Get("PrimaryProtectionContainerId", "http://schemas.microsoft.com/windowsazure"));
if (primaryProtectionContainerIdElement != null)
{
string primaryProtectionContainerIdInstance = primaryProtectionContainerIdElement.Value;
protectionProfileAssociationDetailsInstance.PrimaryProtectionContainerId = primaryProtectionContainerIdInstance;
}
XElement recoveryProtectionContainerIdElement = associationDetailElement.Element(XName.Get("RecoveryProtectionContainerId", "http://schemas.microsoft.com/windowsazure"));
if (recoveryProtectionContainerIdElement != null)
{
string recoveryProtectionContainerIdInstance = recoveryProtectionContainerIdElement.Value;
protectionProfileAssociationDetailsInstance.RecoveryProtectionContainerId = recoveryProtectionContainerIdInstance;
}
XElement associationStatusElement = associationDetailElement.Element(XName.Get("AssociationStatus", "http://schemas.microsoft.com/windowsazure"));
if (associationStatusElement != null)
{
string associationStatusInstance = associationStatusElement.Value;
protectionProfileAssociationDetailsInstance.AssociationStatus = associationStatusInstance;
}
}
}
XElement nameElement = protectionProfileElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
protectionProfileInstance.Name = nameInstance;
}
XElement idElement = protectionProfileElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
protectionProfileInstance.ID = idInstance;
}
}
XElement nameElement2 = arrayOfVirtualMachineElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance2 = nameElement2.Value;
virtualMachineInstance.Name = nameInstance2;
}
XElement idElement2 = arrayOfVirtualMachineElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement2 != null)
{
string idInstance2 = idElement2.Value;
virtualMachineInstance.ID = idInstance2;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates VM properties.
/// </summary>
/// <param name='protectionContainerId'>
/// Required. Parent Protection Container ID.
/// </param>
/// <param name='virtualMachineId'>
/// Required. VM ID.
/// </param>
/// <param name='parameters'>
/// Required. Update VM properties input.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public async Task<JobResponse> UpdateVmPropertiesAsync(string protectionContainerId, string virtualMachineId, VMProperties parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (protectionContainerId == null)
{
throw new ArgumentNullException("protectionContainerId");
}
if (virtualMachineId == null)
{
throw new ArgumentNullException("virtualMachineId");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("protectionContainerId", protectionContainerId);
tracingParameters.Add("virtualMachineId", virtualMachineId);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "UpdateVmPropertiesAsync", tracingParameters);
}
// Construct URL
string url = "";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + "WAHyperVRecoveryManager";
url = url + "/~/";
url = url + "HyperVRecoveryManagerVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/ProtectionContainers/";
url = url + Uri.EscapeDataString(protectionContainerId);
url = url + "/VirtualMachines/";
url = url + Uri.EscapeDataString(virtualMachineId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-04-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("Agent-Authentication", customRequestHeaders.AgentAuthenticationHeader);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement vMPropertiesElement = new XElement(XName.Get("VMProperties", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(vMPropertiesElement);
if (parameters.RecoveryAzureVMName != null)
{
XElement recoveryAzureVMNameElement = new XElement(XName.Get("RecoveryAzureVMName", "http://schemas.microsoft.com/windowsazure"));
recoveryAzureVMNameElement.Value = parameters.RecoveryAzureVMName;
vMPropertiesElement.Add(recoveryAzureVMNameElement);
}
if (parameters.RecoveryAzureVMSize != null)
{
XElement recoveryAzureVMSizeElement = new XElement(XName.Get("RecoveryAzureVMSize", "http://schemas.microsoft.com/windowsazure"));
recoveryAzureVMSizeElement.Value = parameters.RecoveryAzureVMSize;
vMPropertiesElement.Add(recoveryAzureVMSizeElement);
}
if (parameters.SelectedRecoveryAzureNetworkId != null)
{
XElement selectedRecoveryAzureNetworkIdElement = new XElement(XName.Get("SelectedRecoveryAzureNetworkId", "http://schemas.microsoft.com/windowsazure"));
selectedRecoveryAzureNetworkIdElement.Value = parameters.SelectedRecoveryAzureNetworkId;
vMPropertiesElement.Add(selectedRecoveryAzureNetworkIdElement);
}
if (parameters.VMNics != null)
{
if (parameters.VMNics is ILazyCollection == false || ((ILazyCollection)parameters.VMNics).IsInitialized)
{
XElement vMNicsSequenceElement = new XElement(XName.Get("VMNics", "http://schemas.microsoft.com/windowsazure"));
foreach (VMNicDetails vMNicsItem in parameters.VMNics)
{
XElement vMNicDetailsElement = new XElement(XName.Get("VMNicDetails", "http://schemas.microsoft.com/windowsazure"));
vMNicsSequenceElement.Add(vMNicDetailsElement);
if (vMNicsItem.NicId != null)
{
XElement nicIdElement = new XElement(XName.Get("NicId", "http://schemas.microsoft.com/windowsazure"));
nicIdElement.Value = vMNicsItem.NicId;
vMNicDetailsElement.Add(nicIdElement);
}
if (vMNicsItem.VMSubnetName != null)
{
XElement vMSubnetNameElement = new XElement(XName.Get("VMSubnetName", "http://schemas.microsoft.com/windowsazure"));
vMSubnetNameElement.Value = vMNicsItem.VMSubnetName;
vMNicDetailsElement.Add(vMSubnetNameElement);
}
if (vMNicsItem.VMNetworkName != null)
{
XElement vMNetworkNameElement = new XElement(XName.Get("VMNetworkName", "http://schemas.microsoft.com/windowsazure"));
vMNetworkNameElement.Value = vMNicsItem.VMNetworkName;
vMNicDetailsElement.Add(vMNetworkNameElement);
}
if (vMNicsItem.RecoveryVMNetworkId != null)
{
XElement recoveryVMNetworkIdElement = new XElement(XName.Get("RecoveryVMNetworkId", "http://schemas.microsoft.com/windowsazure"));
recoveryVMNetworkIdElement.Value = vMNicsItem.RecoveryVMNetworkId;
vMNicDetailsElement.Add(recoveryVMNetworkIdElement);
}
if (vMNicsItem.RecoveryVMSubnetName != null)
{
XElement recoveryVMSubnetNameElement = new XElement(XName.Get("RecoveryVMSubnetName", "http://schemas.microsoft.com/windowsazure"));
recoveryVMSubnetNameElement.Value = vMNicsItem.RecoveryVMSubnetName;
vMNicDetailsElement.Add(recoveryVMSubnetNameElement);
}
if (vMNicsItem.ReplicaNicStaticIPAddress != null)
{
XElement replicaNicStaticIPAddressElement = new XElement(XName.Get("ReplicaNicStaticIPAddress", "http://schemas.microsoft.com/windowsazure"));
replicaNicStaticIPAddressElement.Value = vMNicsItem.ReplicaNicStaticIPAddress;
vMNicDetailsElement.Add(replicaNicStaticIPAddressElement);
}
}
vMPropertiesElement.Add(vMNicsSequenceElement);
}
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement jobElement = responseDoc.Element(XName.Get("Job", "http://schemas.microsoft.com/windowsazure"));
if (jobElement != null)
{
Job jobInstance = new Job();
result.Job = jobInstance;
XElement activityIdElement = jobElement.Element(XName.Get("ActivityId", "http://schemas.microsoft.com/windowsazure"));
if (activityIdElement != null)
{
string activityIdInstance = activityIdElement.Value;
jobInstance.ActivityId = activityIdInstance;
}
XElement startTimeElement = jobElement.Element(XName.Get("StartTime", "http://schemas.microsoft.com/windowsazure"));
if (startTimeElement != null && !string.IsNullOrEmpty(startTimeElement.Value))
{
DateTime startTimeInstance = DateTime.Parse(startTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
jobInstance.StartTime = startTimeInstance;
}
XElement endTimeElement = jobElement.Element(XName.Get("EndTime", "http://schemas.microsoft.com/windowsazure"));
if (endTimeElement != null && !string.IsNullOrEmpty(endTimeElement.Value))
{
DateTime endTimeInstance = DateTime.Parse(endTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
jobInstance.EndTime = endTimeInstance;
}
XElement displayNameElement = jobElement.Element(XName.Get("DisplayName", "http://schemas.microsoft.com/windowsazure"));
if (displayNameElement != null)
{
string displayNameInstance = displayNameElement.Value;
jobInstance.DisplayName = displayNameInstance;
}
XElement targetObjectIdElement = jobElement.Element(XName.Get("TargetObjectId", "http://schemas.microsoft.com/windowsazure"));
if (targetObjectIdElement != null)
{
string targetObjectIdInstance = targetObjectIdElement.Value;
jobInstance.TargetObjectId = targetObjectIdInstance;
}
XElement targetObjectTypeElement = jobElement.Element(XName.Get("TargetObjectType", "http://schemas.microsoft.com/windowsazure"));
if (targetObjectTypeElement != null)
{
string targetObjectTypeInstance = targetObjectTypeElement.Value;
jobInstance.TargetObjectType = targetObjectTypeInstance;
}
XElement targetObjectNameElement = jobElement.Element(XName.Get("TargetObjectName", "http://schemas.microsoft.com/windowsazure"));
if (targetObjectNameElement != null)
{
string targetObjectNameInstance = targetObjectNameElement.Value;
jobInstance.TargetObjectName = targetObjectNameInstance;
}
XElement allowedActionsSequenceElement = jobElement.Element(XName.Get("AllowedActions", "http://schemas.microsoft.com/windowsazure"));
if (allowedActionsSequenceElement != null)
{
foreach (XElement allowedActionsElement in allowedActionsSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")))
{
jobInstance.AllowedActions.Add(allowedActionsElement.Value);
}
}
XElement stateElement = jobElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
jobInstance.State = stateInstance;
}
XElement stateDescriptionElement = jobElement.Element(XName.Get("StateDescription", "http://schemas.microsoft.com/windowsazure"));
if (stateDescriptionElement != null)
{
string stateDescriptionInstance = stateDescriptionElement.Value;
jobInstance.StateDescription = stateDescriptionInstance;
}
XElement tasksSequenceElement = jobElement.Element(XName.Get("Tasks", "http://schemas.microsoft.com/windowsazure"));
if (tasksSequenceElement != null)
{
foreach (XElement tasksElement in tasksSequenceElement.Elements(XName.Get("Task", "http://schemas.microsoft.com/windowsazure")))
{
AsrTask taskInstance = new AsrTask();
jobInstance.Tasks.Add(taskInstance);
XElement startTimeElement2 = tasksElement.Element(XName.Get("StartTime", "http://schemas.microsoft.com/windowsazure"));
if (startTimeElement2 != null)
{
DateTime startTimeInstance2 = DateTime.Parse(startTimeElement2.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
taskInstance.StartTime = startTimeInstance2;
}
XElement endTimeElement2 = tasksElement.Element(XName.Get("EndTime", "http://schemas.microsoft.com/windowsazure"));
if (endTimeElement2 != null)
{
DateTime endTimeInstance2 = DateTime.Parse(endTimeElement2.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
taskInstance.EndTime = endTimeInstance2;
}
XElement actionsSequenceElement = tasksElement.Element(XName.Get("Actions", "http://schemas.microsoft.com/windowsazure"));
if (actionsSequenceElement != null)
{
foreach (XElement actionsElement in actionsSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")))
{
taskInstance.Actions.Add(actionsElement.Value);
}
}
XElement taskTypeElement = tasksElement.Element(XName.Get("TaskType", "http://schemas.microsoft.com/windowsazure"));
if (taskTypeElement != null)
{
string taskTypeInstance = taskTypeElement.Value;
taskInstance.TaskType = taskTypeInstance;
}
XElement taskNameElement = tasksElement.Element(XName.Get("TaskName", "http://schemas.microsoft.com/windowsazure"));
if (taskNameElement != null)
{
string taskNameInstance = taskNameElement.Value;
taskInstance.TaskName = taskNameInstance;
}
XElement stateElement2 = tasksElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement2 != null)
{
string stateInstance2 = stateElement2.Value;
taskInstance.State = stateInstance2;
}
XElement stateDescriptionElement2 = tasksElement.Element(XName.Get("StateDescription", "http://schemas.microsoft.com/windowsazure"));
if (stateDescriptionElement2 != null)
{
string stateDescriptionInstance2 = stateDescriptionElement2.Value;
taskInstance.StateDescription = stateDescriptionInstance2;
}
XElement extendedDetailsElement = tasksElement.Element(XName.Get("ExtendedDetails", "http://schemas.microsoft.com/windowsazure"));
if (extendedDetailsElement != null)
{
string extendedDetailsInstance = extendedDetailsElement.Value;
taskInstance.ExtendedDetails = extendedDetailsInstance;
}
XElement nameElement = tasksElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
taskInstance.Name = nameInstance;
}
XElement idElement = tasksElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
taskInstance.ID = idInstance;
}
}
}
XElement errorsSequenceElement = jobElement.Element(XName.Get("Errors", "http://schemas.microsoft.com/windowsazure"));
if (errorsSequenceElement != null)
{
foreach (XElement errorsElement in errorsSequenceElement.Elements(XName.Get("ErrorDetails", "http://schemas.microsoft.com/windowsazure")))
{
ErrorDetails errorDetailsInstance = new ErrorDetails();
jobInstance.Errors.Add(errorDetailsInstance);
XElement serviceErrorDetailsElement = errorsElement.Element(XName.Get("ServiceErrorDetails", "http://schemas.microsoft.com/windowsazure"));
if (serviceErrorDetailsElement != null)
{
ServiceError serviceErrorDetailsInstance = new ServiceError();
errorDetailsInstance.ServiceErrorDetails = serviceErrorDetailsInstance;
XElement codeElement = serviceErrorDetailsElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
serviceErrorDetailsInstance.Code = codeInstance;
}
XElement messageElement = serviceErrorDetailsElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
serviceErrorDetailsInstance.Message = messageInstance;
}
XElement possibleCausesElement = serviceErrorDetailsElement.Element(XName.Get("PossibleCauses", "http://schemas.microsoft.com/windowsazure"));
if (possibleCausesElement != null)
{
string possibleCausesInstance = possibleCausesElement.Value;
serviceErrorDetailsInstance.PossibleCauses = possibleCausesInstance;
}
XElement recommendedActionElement = serviceErrorDetailsElement.Element(XName.Get("RecommendedAction", "http://schemas.microsoft.com/windowsazure"));
if (recommendedActionElement != null)
{
string recommendedActionInstance = recommendedActionElement.Value;
serviceErrorDetailsInstance.RecommendedAction = recommendedActionInstance;
}
XElement activityIdElement2 = serviceErrorDetailsElement.Element(XName.Get("ActivityId", "http://schemas.microsoft.com/windowsazure"));
if (activityIdElement2 != null)
{
string activityIdInstance2 = activityIdElement2.Value;
serviceErrorDetailsInstance.ActivityId = activityIdInstance2;
}
}
XElement providerErrorDetailsElement = errorsElement.Element(XName.Get("ProviderErrorDetails", "http://schemas.microsoft.com/windowsazure"));
if (providerErrorDetailsElement != null)
{
ProviderError providerErrorDetailsInstance = new ProviderError();
errorDetailsInstance.ProviderErrorDetails = providerErrorDetailsInstance;
XElement errorCodeElement = providerErrorDetailsElement.Element(XName.Get("ErrorCode", "http://schemas.microsoft.com/windowsazure"));
if (errorCodeElement != null)
{
int errorCodeInstance = int.Parse(errorCodeElement.Value, CultureInfo.InvariantCulture);
providerErrorDetailsInstance.ErrorCode = errorCodeInstance;
}
XElement errorMessageElement = providerErrorDetailsElement.Element(XName.Get("ErrorMessage", "http://schemas.microsoft.com/windowsazure"));
if (errorMessageElement != null)
{
string errorMessageInstance = errorMessageElement.Value;
providerErrorDetailsInstance.ErrorMessage = errorMessageInstance;
}
XElement errorIdElement = providerErrorDetailsElement.Element(XName.Get("ErrorId", "http://schemas.microsoft.com/windowsazure"));
if (errorIdElement != null)
{
string errorIdInstance = errorIdElement.Value;
providerErrorDetailsInstance.ErrorId = errorIdInstance;
}
XElement workflowIdElement = providerErrorDetailsElement.Element(XName.Get("WorkflowId", "http://schemas.microsoft.com/windowsazure"));
if (workflowIdElement != null)
{
string workflowIdInstance = workflowIdElement.Value;
providerErrorDetailsInstance.WorkflowId = workflowIdInstance;
}
XElement creationTimeUtcElement = providerErrorDetailsElement.Element(XName.Get("CreationTimeUtc", "http://schemas.microsoft.com/windowsazure"));
if (creationTimeUtcElement != null)
{
DateTime creationTimeUtcInstance = DateTime.Parse(creationTimeUtcElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
providerErrorDetailsInstance.CreationTimeUtc = creationTimeUtcInstance;
}
XElement errorLevelElement = providerErrorDetailsElement.Element(XName.Get("ErrorLevel", "http://schemas.microsoft.com/windowsazure"));
if (errorLevelElement != null)
{
string errorLevelInstance = errorLevelElement.Value;
providerErrorDetailsInstance.ErrorLevel = errorLevelInstance;
}
XElement affectedObjectsSequenceElement = providerErrorDetailsElement.Element(XName.Get("AffectedObjects", "http://schemas.microsoft.com/windowsazure"));
if (affectedObjectsSequenceElement != null)
{
foreach (XElement affectedObjectsElement in affectedObjectsSequenceElement.Elements(XName.Get("KeyValueOfstringstring", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")))
{
string affectedObjectsKey = affectedObjectsElement.Element(XName.Get("Key", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")).Value;
string affectedObjectsValue = affectedObjectsElement.Element(XName.Get("Value", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")).Value;
providerErrorDetailsInstance.AffectedObjects.Add(affectedObjectsKey, affectedObjectsValue);
}
}
}
XElement taskIdElement = errorsElement.Element(XName.Get("TaskId", "http://schemas.microsoft.com/windowsazure"));
if (taskIdElement != null)
{
string taskIdInstance = taskIdElement.Value;
errorDetailsInstance.TaskId = taskIdInstance;
}
}
}
XElement nameElement2 = jobElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance2 = nameElement2.Value;
jobInstance.Name = nameInstance2;
}
XElement idElement2 = jobElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement2 != null)
{
string idInstance2 = idElement2.Value;
jobInstance.ID = idInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the route53domains-2014-05-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Route53Domains.Model
{
/// <summary>
/// Container for the parameters to the TransferDomain operation.
/// This operation transfers a domain from another registrar to Amazon Route 53. When
/// the transfer is complete, the domain is registered with the AWS registrar partner,
/// Gandi.
///
///
/// <para>
/// For transfer requirements, a detailed procedure, and information about viewing the
/// status of a domain transfer, see <a href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-transfer-to-route-53.html">Transferring
/// Registration for a Domain to Amazon Route 53</a> in the Amazon Route 53 Developer
/// Guide.
/// </para>
///
/// <para>
/// If the registrar for your domain is also the DNS service provider for the domain,
/// we highly recommend that you consider transferring your DNS service to Amazon Route
/// 53 or to another DNS service provider before you transfer your registration. Some
/// registrars provide free DNS service when you purchase a domain registration. When
/// you transfer the registration, the previous registrar will not renew your domain registration
/// and could end your DNS service at any time.
/// </para>
/// <note>Caution! If the registrar for your domain is also the DNS service provider
/// for the domain and you don't transfer DNS service to another provider, your website,
/// email, and the web applications associated with the domain might become unavailable.</note>
///
/// <para>
/// If the transfer is successful, this method returns an operation ID that you can use
/// to track the progress and completion of the action. If the transfer doesn't complete
/// successfully, the domain registrant will be notified by email.
/// </para>
/// </summary>
public partial class TransferDomainRequest : AmazonRoute53DomainsRequest
{
private ContactDetail _adminContact;
private string _authCode;
private bool? _autoRenew;
private string _domainName;
private int? _durationInYears;
private string _idnLangCode;
private List<Nameserver> _nameservers = new List<Nameserver>();
private bool? _privacyProtectAdminContact;
private bool? _privacyProtectRegistrantContact;
private bool? _privacyProtectTechContact;
private ContactDetail _registrantContact;
private ContactDetail _techContact;
/// <summary>
/// Gets and sets the property AdminContact.
/// <para>
/// Provides detailed contact information.
/// </para>
///
/// <para>
/// Type: Complex
/// </para>
///
/// <para>
/// Children: <code>FirstName</code>, <code>MiddleName</code>, <code>LastName</code>,
/// <code>ContactType</code>, <code>OrganizationName</code>, <code>AddressLine1</code>,
/// <code>AddressLine2</code>, <code>City</code>, <code>State</code>, <code>CountryCode</code>,
/// <code>ZipCode</code>, <code>PhoneNumber</code>, <code>Email</code>, <code>Fax</code>,
/// <code>ExtraParams</code>
/// </para>
///
/// <para>
/// Required: Yes
/// </para>
/// </summary>
public ContactDetail AdminContact
{
get { return this._adminContact; }
set { this._adminContact = value; }
}
// Check to see if AdminContact property is set
internal bool IsSetAdminContact()
{
return this._adminContact != null;
}
/// <summary>
/// Gets and sets the property AuthCode.
/// <para>
/// The authorization code for the domain. You get this value from the current registrar.
/// </para>
///
/// <para>
/// Type: String
/// </para>
///
/// <para>
/// Required: Yes
/// </para>
/// </summary>
public string AuthCode
{
get { return this._authCode; }
set { this._authCode = value; }
}
// Check to see if AuthCode property is set
internal bool IsSetAuthCode()
{
return this._authCode != null;
}
/// <summary>
/// Gets and sets the property AutoRenew.
/// <para>
/// Indicates whether the domain will be automatically renewed (true) or not (false).
/// Autorenewal only takes effect after the account is charged.
/// </para>
///
/// <para>
/// Type: Boolean
/// </para>
///
/// <para>
/// Valid values: <code>true</code> | <code>false</code>
/// </para>
///
/// <para>
/// Default: true
/// </para>
///
/// <para>
/// Required: No
/// </para>
/// </summary>
public bool AutoRenew
{
get { return this._autoRenew.GetValueOrDefault(); }
set { this._autoRenew = value; }
}
// Check to see if AutoRenew property is set
internal bool IsSetAutoRenew()
{
return this._autoRenew.HasValue;
}
/// <summary>
/// Gets and sets the property DomainName.
/// <para>
/// The name of a domain.
/// </para>
///
/// <para>
/// Type: String
/// </para>
///
/// <para>
/// Default: None
/// </para>
///
/// <para>
/// Constraints: The domain name can contain only the letters a through z, the numbers
/// 0 through 9, and hyphen (-). Internationalized Domain Names are not supported.
/// </para>
///
/// <para>
/// Required: Yes
/// </para>
/// </summary>
public string DomainName
{
get { return this._domainName; }
set { this._domainName = value; }
}
// Check to see if DomainName property is set
internal bool IsSetDomainName()
{
return this._domainName != null;
}
/// <summary>
/// Gets and sets the property DurationInYears.
/// <para>
/// The number of years the domain will be registered. Domains are registered for a minimum
/// of one year. The maximum period depends on the top-level domain.
/// </para>
///
/// <para>
/// Type: Integer
/// </para>
///
/// <para>
/// Default: 1
/// </para>
///
/// <para>
/// Valid values: Integer from 1 to 10
/// </para>
///
/// <para>
/// Required: Yes
/// </para>
/// </summary>
public int DurationInYears
{
get { return this._durationInYears.GetValueOrDefault(); }
set { this._durationInYears = value; }
}
// Check to see if DurationInYears property is set
internal bool IsSetDurationInYears()
{
return this._durationInYears.HasValue;
}
/// <summary>
/// Gets and sets the property IdnLangCode.
/// <para>
/// Reserved for future use.
/// </para>
/// </summary>
public string IdnLangCode
{
get { return this._idnLangCode; }
set { this._idnLangCode = value; }
}
// Check to see if IdnLangCode property is set
internal bool IsSetIdnLangCode()
{
return this._idnLangCode != null;
}
/// <summary>
/// Gets and sets the property Nameservers.
/// <para>
/// Contains details for the host and glue IP addresses.
/// </para>
///
/// <para>
/// Type: Complex
/// </para>
///
/// <para>
/// Children: <code>GlueIps</code>, <code>Name</code>
/// </para>
///
/// <para>
/// Required: No
/// </para>
/// </summary>
public List<Nameserver> Nameservers
{
get { return this._nameservers; }
set { this._nameservers = value; }
}
// Check to see if Nameservers property is set
internal bool IsSetNameservers()
{
return this._nameservers != null && this._nameservers.Count > 0;
}
/// <summary>
/// Gets and sets the property PrivacyProtectAdminContact.
/// <para>
/// Whether you want to conceal contact information from WHOIS queries. If you specify
/// true, WHOIS ("who is") queries will return contact information for our registrar partner,
/// Gandi, instead of the contact information that you enter.
/// </para>
///
/// <para>
/// Type: Boolean
/// </para>
///
/// <para>
/// Default: <code>true</code>
/// </para>
///
/// <para>
/// Valid values: <code>true</code> | <code>false</code>
/// </para>
///
/// <para>
/// Required: No
/// </para>
/// </summary>
public bool PrivacyProtectAdminContact
{
get { return this._privacyProtectAdminContact.GetValueOrDefault(); }
set { this._privacyProtectAdminContact = value; }
}
// Check to see if PrivacyProtectAdminContact property is set
internal bool IsSetPrivacyProtectAdminContact()
{
return this._privacyProtectAdminContact.HasValue;
}
/// <summary>
/// Gets and sets the property PrivacyProtectRegistrantContact.
/// <para>
/// Whether you want to conceal contact information from WHOIS queries. If you specify
/// true, WHOIS ("who is") queries will return contact information for our registrar partner,
/// Gandi, instead of the contact information that you enter.
/// </para>
///
/// <para>
/// Type: Boolean
/// </para>
///
/// <para>
/// Default: <code>true</code>
/// </para>
///
/// <para>
/// Valid values: <code>true</code> | <code>false</code>
/// </para>
///
/// <para>
/// Required: No
/// </para>
/// </summary>
public bool PrivacyProtectRegistrantContact
{
get { return this._privacyProtectRegistrantContact.GetValueOrDefault(); }
set { this._privacyProtectRegistrantContact = value; }
}
// Check to see if PrivacyProtectRegistrantContact property is set
internal bool IsSetPrivacyProtectRegistrantContact()
{
return this._privacyProtectRegistrantContact.HasValue;
}
/// <summary>
/// Gets and sets the property PrivacyProtectTechContact.
/// <para>
/// Whether you want to conceal contact information from WHOIS queries. If you specify
/// true, WHOIS ("who is") queries will return contact information for our registrar partner,
/// Gandi, instead of the contact information that you enter.
/// </para>
///
/// <para>
/// Type: Boolean
/// </para>
///
/// <para>
/// Default: <code>true</code>
/// </para>
///
/// <para>
/// Valid values: <code>true</code> | <code>false</code>
/// </para>
///
/// <para>
/// Required: No
/// </para>
/// </summary>
public bool PrivacyProtectTechContact
{
get { return this._privacyProtectTechContact.GetValueOrDefault(); }
set { this._privacyProtectTechContact = value; }
}
// Check to see if PrivacyProtectTechContact property is set
internal bool IsSetPrivacyProtectTechContact()
{
return this._privacyProtectTechContact.HasValue;
}
/// <summary>
/// Gets and sets the property RegistrantContact.
/// <para>
/// Provides detailed contact information.
/// </para>
///
/// <para>
/// Type: Complex
/// </para>
///
/// <para>
/// Children: <code>FirstName</code>, <code>MiddleName</code>, <code>LastName</code>,
/// <code>ContactType</code>, <code>OrganizationName</code>, <code>AddressLine1</code>,
/// <code>AddressLine2</code>, <code>City</code>, <code>State</code>, <code>CountryCode</code>,
/// <code>ZipCode</code>, <code>PhoneNumber</code>, <code>Email</code>, <code>Fax</code>,
/// <code>ExtraParams</code>
/// </para>
///
/// <para>
/// Required: Yes
/// </para>
/// </summary>
public ContactDetail RegistrantContact
{
get { return this._registrantContact; }
set { this._registrantContact = value; }
}
// Check to see if RegistrantContact property is set
internal bool IsSetRegistrantContact()
{
return this._registrantContact != null;
}
/// <summary>
/// Gets and sets the property TechContact.
/// <para>
/// Provides detailed contact information.
/// </para>
///
/// <para>
/// Type: Complex
/// </para>
///
/// <para>
/// Children: <code>FirstName</code>, <code>MiddleName</code>, <code>LastName</code>,
/// <code>ContactType</code>, <code>OrganizationName</code>, <code>AddressLine1</code>,
/// <code>AddressLine2</code>, <code>City</code>, <code>State</code>, <code>CountryCode</code>,
/// <code>ZipCode</code>, <code>PhoneNumber</code>, <code>Email</code>, <code>Fax</code>,
/// <code>ExtraParams</code>
/// </para>
///
/// <para>
/// Required: Yes
/// </para>
/// </summary>
public ContactDetail TechContact
{
get { return this._techContact; }
set { this._techContact = value; }
}
// Check to see if TechContact property is set
internal bool IsSetTechContact()
{
return this._techContact != null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
#if !NET_STANDARD
using System.Reflection.Emit;
#endif
namespace BatMap {
public static class Helper {
#if !NET_STANDARD
private static int _typeCounter;
private static readonly ModuleBuilder _moduleBuilder;
static Helper() {
#if NO_AssemblyBuilder
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("BatMap_DynamicAssembly"), AssemblyBuilderAccess.Run);
#else
var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("BatMap_DynamicAssembly"), AssemblyBuilderAccess.Run);
#endif
_moduleBuilder = assembly.DefineDynamicModule("BatMap_DynamicModule");
}
#endif
public static bool IsPrimitive(Type type) {
#if NET_STANDARD
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
type = type.GenericTypeArguments[0];
typeInfo = type.GetTypeInfo();
}
return !typeInfo.IsGenericType && (typeInfo.IsValueType || type == typeof(string));
#else
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
type = type.GetGenericArguments()[0];
}
return !type.IsGenericType && (type.IsValueType || type == typeof(string));
#endif
}
public static bool TypesCastable(Type from, Type to) {
#if NET_STANDARD
var fromTypeInfo = from.GetTypeInfo();
var toTypeInfo = to.GetTypeInfo();
if (toTypeInfo.IsAssignableFrom(fromTypeInfo)) return true;
return from.GetRuntimeMethods()
.Any(m =>
m.IsStatic &&
m.IsPublic &&
m.ReturnType == to &&
(m.Name == "op_Implicit" || m.Name == "op_Explicit")
);
#else
if (to.IsAssignableFrom(from)) return true;
return from.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Any(m =>
m.ReturnType == to &&
(m.Name == "op_Implicit" || m.Name == "op_Explicit")
);
#endif
}
public static object GetPropertyValue(object obj, string propName) {
#if NET_STANDARD
var propertyInfo = obj.GetType()
.GetRuntimeProperties()
.FirstOrDefault(p => p.Name == propName);
#else
var propertyInfo = obj.GetType()
.GetProperty(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
#endif
return propertyInfo?.GetValue(obj, null);
}
public static object GetFieldValue(object obj, string fieldName) {
#if NET_STANDARD
var fieldInfo = obj.GetType()
.GetRuntimeFields()
.FirstOrDefault(f => f.Name == fieldName);
#else
var fieldInfo = obj.GetType()
.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
#endif
return fieldInfo?.GetValue(obj);
}
public static IEnumerable<MapMember> GetMapFields(Type type, bool onlyWritable = false) {
#if NET_STANDARD
var properties = type.GetRuntimeProperties()
.Where(p => p.GetMethod.IsPublic && !p.GetMethod.IsStatic);
if (onlyWritable) {
properties = properties.Where(p => p.CanWrite && p.SetMethod.IsPublic);
}
var fields = type.GetRuntimeFields()
.Where(f => f.IsPublic && !f.IsStatic);
#else
IEnumerable<PropertyInfo> properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
if (onlyWritable) {
properties = properties.Where(p => p.CanWrite);
}
var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
#endif
return fields
.Select(f => new MapMember(f.Name, f.FieldType, f))
.Concat(properties.Select(p => new MapMember(p.Name, p.PropertyType, p)));
}
public static List<string> GetMemberPath(Expression exp) {
var retVal = new List<string>();
if (exp is MethodCallExpression callExp && callExp.Method.DeclaringType == typeof(Enumerable) && callExp.Method.Name == "Select") {
retVal.AddRange(GetMemberPath(callExp.Arguments[0]));
retVal.AddRange(GetMemberPath(((LambdaExpression)callExp.Arguments[1]).Body));
return retVal;
}
if (exp is MemberExpression memberExp) {
retVal.AddRange(GetMemberPath(memberExp.Expression));
retVal.Add(memberExp.Member.Name);
return retVal;
}
if (exp is UnaryExpression unaryExp)
return GetMemberPath(unaryExp.Operand);
if (exp is LambdaExpression lambdaExp)
return GetMemberPath(lambdaExp.Body);
return retVal;
}
public static IEnumerable<IncludePath> ParseIncludes(IEnumerable<IEnumerable<string>> includes) {
return includes
.Where(i => i.Any())
.GroupBy(i => i.First(), i => i.Skip(1))
.Select(g => new IncludePath(g.Key, ParseIncludes(g.ToList())));
}
public static IEnumerable<IncludePath> ParseIncludes<TIn>(IEnumerable<Expression<Func<TIn, object>>> expressions) {
return ParseIncludes(expressions.Select(e => GetMemberPath(e.Body)));
}
public static IEnumerable<IncludePath> GetIncludes(IQueryable query) {
return new IncludeVisitor().GetIncludes(query);
}
public static int GenerateHashCode(object o1, object o2) {
var h1 = o1.GetHashCode();
var h2 = o2.GetHashCode();
return ((h1 << 5) + h1) ^ h2;
}
public static int GenerateHashCode(object o1, object o2, object o3) {
return GenerateHashCode(GenerateHashCode(o1, o2), o3);
}
public static Func<TIn, TOut, MapContext, TOut> CreatePopulator<TIn, TOut>(Expression<Func<TIn, TOut, MapContext, TOut>> expression) {
#if NET_STANDARD
return expression.Compile();
#else
return (Func<TIn, TOut, MapContext, TOut>)CreateDynamicDelegate(expression, typeof(Func<TIn, TOut, MapContext, TOut>));
#endif
}
public static Func<TIn, MapContext, TOut> CreateMapper<TIn, TOut>(Expression<Func<TIn, MapContext, TOut>> expression) {
#if NET_STANDARD
return expression.Compile();
#else
return (Func<TIn, MapContext, TOut>)CreateDynamicDelegate(expression, typeof(Func<TIn, MapContext, TOut>));
#endif
}
public static Func<TIn, TOut> CreateProjector<TIn, TOut>(Expression<Func<TIn, TOut>> expression) {
#if NET_STANDARD
return expression.Compile();
#else
return (Func<TIn, TOut>)CreateDynamicDelegate(expression, typeof(Func<TIn, TOut>));
#endif
}
#if !NET_STANDARD
public static Delegate CreateDynamicDelegate(LambdaExpression expression, Type delegateType) {
var typeBuilder = _moduleBuilder.DefineType("BatMap_DynamicType" + _typeCounter++, TypeAttributes.Public);
var methodBuilder = typeBuilder.DefineMethod("BatMap_DynamicMethod", MethodAttributes.Public | MethodAttributes.Static);
expression.CompileToMethod(methodBuilder);
var type = typeBuilder.CreateType();
return Delegate.CreateDelegate(delegateType, type.GetMethod("BatMap_DynamicMethod"));
}
#endif
}
}
| |
// 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.Net.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public sealed class SocketsHttpHandler : HttpMessageHandler
{
private readonly HttpConnectionSettings _settings = new HttpConnectionSettings();
private HttpMessageHandler _handler;
private bool _disposed;
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(SocketsHttpHandler));
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_handler != null)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
public bool UseCookies
{
get => _settings._useCookies;
set
{
CheckDisposedOrStarted();
_settings._useCookies = value;
}
}
public CookieContainer CookieContainer
{
get => _settings._cookieContainer ?? (_settings._cookieContainer = new CookieContainer());
set
{
CheckDisposedOrStarted();
_settings._cookieContainer = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get => _settings._automaticDecompression;
set
{
CheckDisposedOrStarted();
_settings._automaticDecompression = value;
}
}
public bool UseProxy
{
get => _settings._useProxy;
set
{
CheckDisposedOrStarted();
_settings._useProxy = value;
}
}
public IWebProxy Proxy
{
get => _settings._proxy;
set
{
CheckDisposedOrStarted();
_settings._proxy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get => _settings._defaultProxyCredentials;
set
{
CheckDisposedOrStarted();
_settings._defaultProxyCredentials = value;
}
}
public bool PreAuthenticate
{
get => _settings._preAuthenticate;
set
{
CheckDisposedOrStarted();
_settings._preAuthenticate = value;
}
}
public ICredentials Credentials
{
get => _settings._credentials;
set
{
CheckDisposedOrStarted();
_settings._credentials = value;
}
}
public bool AllowAutoRedirect
{
get => _settings._allowAutoRedirect;
set
{
CheckDisposedOrStarted();
_settings._allowAutoRedirect = value;
}
}
public int MaxAutomaticRedirections
{
get => _settings._maxAutomaticRedirections;
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_settings._maxAutomaticRedirections = value;
}
}
public int MaxConnectionsPerServer
{
get => _settings._maxConnectionsPerServer;
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_settings._maxConnectionsPerServer = value;
}
}
public int MaxResponseHeadersLength
{
get => _settings._maxResponseHeadersLength;
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_settings._maxResponseHeadersLength = value;
}
}
public SslClientAuthenticationOptions SslOptions
{
get => _settings._sslOptions ?? (_settings._sslOptions = new SslClientAuthenticationOptions());
set
{
CheckDisposedOrStarted();
_settings._sslOptions = value;
}
}
public TimeSpan PooledConnectionLifetime
{
get => _settings._pooledConnectionLifetime;
set
{
if (value < TimeSpan.Zero && value != Timeout.InfiniteTimeSpan)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._pooledConnectionLifetime = value;
}
}
public TimeSpan PooledConnectionIdleTimeout
{
get => _settings._pooledConnectionIdleTimeout;
set
{
if (value < TimeSpan.Zero && value != Timeout.InfiniteTimeSpan)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._pooledConnectionIdleTimeout = value;
}
}
public TimeSpan ConnectTimeout
{
get => _settings._connectTimeout;
set
{
if ((value <= TimeSpan.Zero && value != Timeout.InfiniteTimeSpan) ||
(value.TotalMilliseconds > int.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._connectTimeout = value;
}
}
public TimeSpan Expect100ContinueTimeout
{
get => _settings._expect100ContinueTimeout;
set
{
if ((value < TimeSpan.Zero && value != Timeout.InfiniteTimeSpan) ||
(value.TotalMilliseconds > int.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._expect100ContinueTimeout = value;
}
}
public IDictionary<string, object> Properties =>
_settings._properties ?? (_settings._properties = new Dictionary<string, object>());
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
_handler?.Dispose();
}
base.Dispose(disposing);
}
private HttpMessageHandler SetupHandlerChain()
{
// Clone the settings to get a relatively consistent view that won't change after this point.
// (This isn't entirely complete, as some of the collections it contains aren't currently deeply cloned.)
HttpConnectionSettings settings = _settings.Clone();
HttpConnectionPoolManager poolManager = new HttpConnectionPoolManager(settings);
HttpMessageHandler handler = new HttpConnectionHandler(poolManager);
if (settings._useProxy && (settings._proxy != null || HttpProxyConnectionHandler.DefaultProxyConfigured))
{
handler = new HttpProxyConnectionHandler(poolManager, settings._proxy, settings._defaultProxyCredentials, handler);
}
HttpMessageHandler unauthenticatedHandler = handler;
if (settings._credentials != null)
{
handler = new AuthenticationHandler(settings._preAuthenticate, settings._credentials, handler);
}
if (settings._allowAutoRedirect)
{
// Just as with WinHttpHandler and CurlHandler, for security reasons, we do not support authentication on redirects
// if the credential is anything other than a CredentialCache.
// We allow credentials in a CredentialCache since they are specifically tied to URIs.
HttpMessageHandler redirectHandler = (settings._credentials is CredentialCache ? handler : unauthenticatedHandler);
handler = new RedirectHandler(settings._maxAutomaticRedirections, handler, redirectHandler);
}
if (settings._automaticDecompression != DecompressionMethods.None)
{
handler = new DecompressionHandler(settings._automaticDecompression, handler);
}
// Ensure a single handler is used for all requests.
if (Interlocked.CompareExchange(ref _handler, handler, null) != null)
{
handler.Dispose();
}
return _handler;
}
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
CheckDisposed();
HttpMessageHandler handler = _handler ?? SetupHandlerChain();
Exception error = ValidateAndNormalizeRequest(request);
if (error != null)
{
return Task.FromException<HttpResponseMessage>(error);
}
return handler.SendAsync(request, cancellationToken);
}
private Exception ValidateAndNormalizeRequest(HttpRequestMessage request)
{
if (request.Version.Major == 0)
{
return new NotSupportedException(SR.net_http_unsupported_version);
}
// Add headers to define content transfer, if not present
if (request.HasHeaders && request.Headers.TransferEncodingChunked.GetValueOrDefault())
{
if (request.Content == null)
{
return new HttpRequestException(SR.net_http_client_execution_error,
new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content));
}
// Since the user explicitly set TransferEncodingChunked to true, we need to remove
// the Content-Length header if present, as sending both is invalid.
request.Content.Headers.ContentLength = null;
}
else if (request.Content != null && request.Content.Headers.ContentLength == null)
{
// We have content, but neither Transfer-Encoding nor Content-Length is set.
request.Headers.TransferEncodingChunked = true;
}
if (request.Version.Minor == 0 && request.Version.Major == 1 && request.HasHeaders)
{
// HTTP 1.0 does not support chunking
if (request.Headers.TransferEncodingChunked == true)
{
return new NotSupportedException(SR.net_http_unsupported_chunking);
}
// HTTP 1.0 does not support Expect: 100-continue; just disable it.
if (request.Headers.ExpectContinue == true)
{
request.Headers.ExpectContinue = false;
}
}
return null;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Utils;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Tests.Visual;
using osuTK;
using osuTK.Input;
namespace osu.Game.Rulesets.Osu.Tests
{
public class TestSceneSliderPlacementBlueprint : PlacementBlueprintTestScene
{
[SetUp]
public void Setup() => Schedule(() =>
{
HitObjectContainer.Clear();
ResetPlacement();
});
[Test]
public void TestBeginPlacementWithoutFinishing()
{
addMovementStep(new Vector2(200));
addClickStep(MouseButton.Left);
assertPlaced(false);
}
[Test]
public void TestPlaceWithoutMovingMouse()
{
addMovementStep(new Vector2(200));
addClickStep(MouseButton.Left);
addClickStep(MouseButton.Right);
assertPlaced(true);
assertLength(0);
assertControlPointType(0, PathType.Linear);
}
[Test]
public void TestPlaceWithMouseMovement()
{
addMovementStep(new Vector2(200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(400, 200));
addClickStep(MouseButton.Right);
assertPlaced(true);
assertLength(200);
assertControlPointCount(2);
assertControlPointType(0, PathType.Linear);
}
[Test]
public void TestPlaceNormalControlPoint()
{
addMovementStep(new Vector2(200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300, 200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300));
addClickStep(MouseButton.Right);
assertPlaced(true);
assertControlPointCount(3);
assertControlPointPosition(1, new Vector2(100, 0));
assertControlPointType(0, PathType.PerfectCurve);
}
[Test]
public void TestPlaceTwoNormalControlPoints()
{
addMovementStep(new Vector2(200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300, 200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(400, 300));
addClickStep(MouseButton.Right);
assertPlaced(true);
assertControlPointCount(4);
assertControlPointPosition(1, new Vector2(100, 0));
assertControlPointPosition(2, new Vector2(100, 100));
assertControlPointType(0, PathType.Bezier);
}
[Test]
public void TestPlaceSegmentControlPoint()
{
addMovementStep(new Vector2(200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300, 200));
addClickStep(MouseButton.Left);
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300));
addClickStep(MouseButton.Right);
assertPlaced(true);
assertControlPointCount(3);
assertControlPointPosition(1, new Vector2(100, 0));
assertControlPointType(0, PathType.Linear);
assertControlPointType(1, PathType.Linear);
}
[Test]
public void TestMoveToPerfectCurveThenPlaceLinear()
{
addMovementStep(new Vector2(200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300, 200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300));
addMovementStep(new Vector2(300, 200));
addClickStep(MouseButton.Right);
assertPlaced(true);
assertControlPointCount(2);
assertControlPointType(0, PathType.Linear);
assertLength(100);
}
[Test]
public void TestMoveToBezierThenPlacePerfectCurve()
{
addMovementStep(new Vector2(200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300, 200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(400, 300));
addMovementStep(new Vector2(300));
addClickStep(MouseButton.Right);
assertPlaced(true);
assertControlPointCount(3);
assertControlPointType(0, PathType.PerfectCurve);
}
[Test]
public void TestMoveToFourthOrderBezierThenPlaceThirdOrderBezier()
{
addMovementStep(new Vector2(200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300, 200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(400, 300));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(400));
addMovementStep(new Vector2(400, 300));
addClickStep(MouseButton.Right);
assertPlaced(true);
assertControlPointCount(4);
assertControlPointType(0, PathType.Bezier);
}
[Test]
public void TestPlaceLinearSegmentThenPlaceLinearSegment()
{
addMovementStep(new Vector2(200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300, 200));
addClickStep(MouseButton.Left);
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300, 300));
addClickStep(MouseButton.Right);
assertPlaced(true);
assertControlPointCount(3);
assertControlPointPosition(1, new Vector2(100, 0));
assertControlPointPosition(2, new Vector2(100));
assertControlPointType(0, PathType.Linear);
assertControlPointType(1, PathType.Linear);
}
[Test]
public void TestPlaceLinearSegmentThenPlacePerfectCurveSegment()
{
addMovementStep(new Vector2(200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300, 200));
addClickStep(MouseButton.Left);
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300, 300));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(400, 300));
addClickStep(MouseButton.Right);
assertPlaced(true);
assertControlPointCount(4);
assertControlPointPosition(1, new Vector2(100, 0));
assertControlPointPosition(2, new Vector2(100));
assertControlPointType(0, PathType.Linear);
assertControlPointType(1, PathType.PerfectCurve);
}
[Test]
public void TestPlacePerfectCurveSegmentThenPlacePerfectCurveSegment()
{
addMovementStep(new Vector2(200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300, 200));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(300, 300));
addClickStep(MouseButton.Left);
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(400, 300));
addClickStep(MouseButton.Left);
addMovementStep(new Vector2(400));
addClickStep(MouseButton.Right);
assertPlaced(true);
assertControlPointCount(5);
assertControlPointPosition(1, new Vector2(100, 0));
assertControlPointPosition(2, new Vector2(100));
assertControlPointPosition(3, new Vector2(200, 100));
assertControlPointPosition(4, new Vector2(200));
assertControlPointType(0, PathType.PerfectCurve);
assertControlPointType(2, PathType.PerfectCurve);
}
private void addMovementStep(Vector2 position) => AddStep($"move mouse to {position}", () => InputManager.MoveMouseTo(InputManager.ToScreenSpace(position)));
private void addClickStep(MouseButton button)
{
AddStep($"press {button}", () => InputManager.PressButton(button));
AddStep($"release {button}", () => InputManager.ReleaseButton(button));
}
private void assertPlaced(bool expected) => AddAssert($"slider {(expected ? "placed" : "not placed")}", () => (getSlider() != null) == expected);
private void assertLength(double expected) => AddAssert($"slider length is {expected}", () => Precision.AlmostEquals(expected, getSlider().Distance, 1));
private void assertControlPointCount(int expected) => AddAssert($"has {expected} control points", () => getSlider().Path.ControlPoints.Count == expected);
private void assertControlPointType(int index, PathType type) => AddAssert($"control point {index} is {type}", () => getSlider().Path.ControlPoints[index].Type.Value == type);
private void assertControlPointPosition(int index, Vector2 position) =>
AddAssert($"control point {index} at {position}", () => Precision.AlmostEquals(position, getSlider().Path.ControlPoints[index].Position.Value, 1));
private Slider getSlider() => HitObjectContainer.Count > 0 ? (Slider)((DrawableSlider)HitObjectContainer[0]).HitObject : null;
protected override DrawableHitObject CreateHitObject(HitObject hitObject) => new DrawableSlider((Slider)hitObject);
protected override PlacementBlueprint CreateBlueprint() => new SliderPlacementBlueprint();
}
}
| |
// Copyright (C) 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Runtime.InteropServices;
using System;
using System.Collections.Generic;
/// <summary>
/// Plays video using Exoplayer rendering it on the main texture.
/// </summary>
public class GvrVideoPlayerTexture : MonoBehaviour {
private const int MIN_BUFFER_SIZE = 3;
private const int MAX_BUFFER_SIZE = 15;
/// <summary>
/// The video texture array used as a circular buffer to get the video image.
/// </summary>
private Texture2D[] videoTextures;
private int currentTexture;
/// <summary>
/// The video player pointer used to uniquely identify the player instance.
/// </summary>
private IntPtr videoPlayerPtr;
/// <summary>
/// The video player event base.
/// </summary>
/// <remarks>This is added to the event id when issues events to
/// the plugin.
/// </remarks>
private int videoPlayerEventBase;
private Texture initialTexture;
private bool initialized;
private int texWidth = 1024;
private int texHeight = 1024;
private long lastBufferedPosition;
private float framecount = 0;
private Graphic graphicComponent;
private Renderer rendererComponent;
/// <summary>
/// The render event function.
/// </summary>
private IntPtr renderEventFunction;
private bool processingRunning;
private bool exitProcessing;
private bool playOnResume;
/// <summary>List of callbacks to invoke when the video is ready.</summary>
private List<Action<int>> onEventCallbacks;
/// <summary>List of callbacks to invoke on exception.</summary>
/// <remarks>The first parameter is the type of exception,
/// the second is the message.
/// </remarks>
private List<Action<string, string>> onExceptionCallbacks;
private readonly static Queue<Action> ExecuteOnMainThread = new Queue<Action>();
// Attach a text component to get some debug status info.
public Text statusText;
/// <summary>
/// Video type.
/// </summary>
public enum VideoType {
Dash = 0,
HLS = 2,
Other = 3
};
public enum VideoResolution {
Lowest = 1,
_720 = 720,
_1080 = 1080,
_2048 = 2048,
Highest = 4096
};
/// <summary>
/// Video player state.
/// </summary>
public enum VideoPlayerState {
Idle = 1,
Preparing = 2,
Buffering = 3,
Ready = 4,
Ended = 5
};
public enum VideoEvents {
VideoReady = 1,
VideoStartPlayback = 2,
VideoFormatChanged = 3,
VideoSurfaceSet = 4,
VideoSizeChanged = 5
};
/// <summary>
/// Plugin render commands.
/// </summary>
/// <remarks>
/// These are added to the eventbase for the specific player object and
/// issued to the plugin.
/// </remarks>
private enum RenderCommand {
None = -1,
InitializePlayer = 0,
UpdateVideo = 1,
RenderMono = 2,
RenderLeftEye = 3,
RenderRightEye = 4,
Shutdown = 5
};
// The circular buffer has to be at least 2,
// but in some cases that is too small, so set some reasonable range
// so a slider shows up in the property inspector.
[Range(MIN_BUFFER_SIZE, MAX_BUFFER_SIZE)]
public int bufferSize;
/// <summary>
/// The type of the video.
/// </summary>
public VideoType videoType;
public string videoURL;
public string videoContentID;
public string videoProviderId;
public VideoResolution initialResolution = VideoResolution.Highest;
/// <summary>
/// True for adjusting the aspect ratio of the renderer.
/// </summary>
public bool adjustAspectRatio;
/// <summary>
/// The use secure path for DRM protected video.
/// </summary>
public bool useSecurePath;
public bool VideoReady {
get {
return videoPlayerPtr != IntPtr.Zero && IsVideoReady(videoPlayerPtr);
}
}
public long CurrentPosition {
get {
return videoPlayerPtr != IntPtr.Zero ? GetCurrentPosition(videoPlayerPtr) : 0;
}
set {
// If the position is being set to 0, reset the framecount as well.
// This allows the texture swapping to work correctly at the beginning
// of the stream.
if (value == 0) {
framecount = 0;
}
SetCurrentPosition(videoPlayerPtr, value);
}
}
public long VideoDuration {
get {
return videoPlayerPtr != IntPtr.Zero ? GetDuration(videoPlayerPtr) : 0;
}
}
public long BufferedPosition {
get {
return videoPlayerPtr != IntPtr.Zero ? GetBufferedPosition(videoPlayerPtr) : 0;
}
}
public int BufferedPercentage {
get {
return videoPlayerPtr != IntPtr.Zero ? GetBufferedPercentage(videoPlayerPtr) : 0;
}
}
public bool IsPaused {
get {
return !initialized || videoPlayerPtr == IntPtr.Zero || IsVideoPaused(videoPlayerPtr);
}
}
public VideoPlayerState PlayerState {
get {
return videoPlayerPtr != IntPtr.Zero ? (VideoPlayerState)GetPlayerState(videoPlayerPtr) : VideoPlayerState.Idle;
}
}
public int MaxVolume {
get {
return videoPlayerPtr != IntPtr.Zero ? GetMaxVolume(videoPlayerPtr) : 0;
}
}
public int CurrentVolume {
get {
return videoPlayerPtr != IntPtr.Zero ? GetCurrentVolume(videoPlayerPtr) : 0;
}
set {
SetCurrentVolume(value);
}
}
/// Create the video player instance and the event base id.
void Awake() {
// Find the components on which to set the video texture.
graphicComponent = GetComponent<Graphic>();
rendererComponent = GetComponent<Renderer>();
CreatePlayer();
}
void CreatePlayer() {
bufferSize = bufferSize < MIN_BUFFER_SIZE ? MIN_BUFFER_SIZE : bufferSize;
if (videoTextures != null) {
DestroyVideoTextures();
}
videoTextures = new Texture2D[bufferSize];
currentTexture = 0;
videoPlayerPtr = CreateVideoPlayer();
videoPlayerEventBase = GetVideoPlayerEventBase(videoPlayerPtr);
Debug.Log(" -- " + gameObject.name + " created with base " +
videoPlayerEventBase);
SetOnVideoEventCallback((eventId) => {
Debug.Log("------------- E V E N T " + eventId + " -----------------");
UpdateStatusText();
});
SetOnExceptionCallback((type, msg) => {
Debug.LogError("Exception: " + type + ": " + msg);
});
initialized = false;
if (rendererComponent != null) {
initialTexture = rendererComponent.material.mainTexture;
} else if (graphicComponent) {
initialTexture = graphicComponent.mainTexture;
}
}
IEnumerator Start() {
CreateTextureForVideoMaybe();
renderEventFunction = GetRenderEventFunc();
if (renderEventFunction != IntPtr.Zero) {
IssuePlayerEvent(RenderCommand.InitializePlayer);
yield return StartCoroutine(CallPluginAtEndOfFrames());
}
}
void OnDisable() {
if (videoPlayerPtr != IntPtr.Zero) {
if (GetPlayerState(videoPlayerPtr) == (int)VideoPlayerState.Ready) {
PauseVideo(videoPlayerPtr);
}
}
}
/// <summary>
/// Sets the display texture.
/// </summary>
/// <param name="texture">Texture to display.
// If null, the initial texture of the renderer is used.</param>
public void SetDisplayTexture(Texture texture) {
if (texture == null) {
texture = initialTexture;
}
if (texture == null) {
return;
}
if (rendererComponent != null) {
rendererComponent.sharedMaterial.mainTexture = initialTexture;
} else if (graphicComponent != null) {
graphicComponent.material.mainTexture = initialTexture;
}
}
public void CleanupVideo() {
Debug.Log("Cleaning Up video!");
exitProcessing = true;
if (videoPlayerPtr != IntPtr.Zero) {
DestroyVideoPlayer(videoPlayerPtr);
videoPlayerPtr = IntPtr.Zero;
}
DestroyVideoTextures();
if (rendererComponent != null) {
rendererComponent.sharedMaterial.mainTexture = initialTexture;
} else if (graphicComponent != null) {
graphicComponent.material.mainTexture = initialTexture;
}
}
public void ReInitializeVideo() {
if (rendererComponent != null) {
rendererComponent.sharedMaterial.mainTexture = initialTexture;
} else if (graphicComponent != null) {
graphicComponent.material.mainTexture = initialTexture;
}
if (videoPlayerPtr == IntPtr.Zero) {
CreatePlayer();
IssuePlayerEvent(RenderCommand.InitializePlayer);
}
if (Init()) {
StartCoroutine(CallPluginAtEndOfFrames());
}
}
void DestroyVideoTextures() {
if (videoTextures != null) {
foreach (Texture2D t in videoTextures) {
if (t != null) {
// Free GPU memory immediately.
t.Resize(1, 1);
t.Apply();
// Unity's destroy is lazy.
Destroy(t);
}
}
videoTextures = null;
}
}
void OnEnable() {
if (videoPlayerPtr != IntPtr.Zero) {
StartCoroutine(CallPluginAtEndOfFrames());
}
}
void OnDestroy() {
if (videoPlayerPtr != IntPtr.Zero) {
DestroyVideoPlayer(videoPlayerPtr);
}
DestroyVideoTextures();
}
void OnValidate() {
Renderer r = GetComponent<Renderer>();
Graphic g = GetComponent<Graphic>();
if (g == null && r == null) {
Debug.LogError("TexturePlayer object must have either " +
"a Renderer component or a Graphic component.");
}
}
void OnApplicationPause(bool bPause) {
if (videoPlayerPtr != IntPtr.Zero) {
if (bPause) {
playOnResume = !IsPaused;
PauseVideo(videoPlayerPtr);
} else {
if (playOnResume) {
PlayVideo(videoPlayerPtr);
}
}
}
}
void OnRenderObject() {
// Don't render if not initialized.
if (videoPlayerPtr == IntPtr.Zero || videoTextures[0] == null) {
return;
}
Texture newTex = videoTextures[currentTexture];
// Handle either the renderer component or the graphic component.
if (rendererComponent != null) {
// Don't render the first texture from the player, it is unitialized.
if (currentTexture <= 1 && framecount <= 1) {
return;
}
// Don't swap the textures if the video ended.
if (PlayerState == VideoPlayerState.Ended) {
return;
}
// Unity may build new a new material instance when assigning
// material.x which can lead to duplicating materials each frame
// whereas using the shared material will modify the original material.
if (rendererComponent.material.mainTexture != null) {
IntPtr currentTexId =
rendererComponent.sharedMaterial.mainTexture.GetNativeTexturePtr();
// Update the material's texture if it is different.
if (currentTexId != newTex.GetNativeTexturePtr()) {
rendererComponent.sharedMaterial.mainTexture = newTex;
framecount += 1f;
}
} else {
rendererComponent.sharedMaterial.mainTexture = newTex;
}
} else if (graphicComponent != null) {
if (graphicComponent.material.mainTexture != null) {
IntPtr currentTexId =
graphicComponent.material.mainTexture.GetNativeTexturePtr();
// Update the material's texture if it is different.
if (currentTexId != newTex.GetNativeTexturePtr()) {
graphicComponent.material.mainTexture = newTex;
framecount += 1f;
}
} else {
graphicComponent.material.mainTexture = newTex;
}
} else {
Debug.LogError("GvrVideoPlayerTexture: No render or graphic component.");
}
}
private void OnRestartVideoEvent(int eventId) {
if (eventId == (int)VideoEvents.VideoReady) {
Debug.Log("Restarting video complete.");
RemoveOnVideoEventCallback(OnRestartVideoEvent);
}
}
/// <summary>
/// Resets the video player.
/// </summary>
public void RestartVideo() {
SetOnVideoEventCallback(OnRestartVideoEvent);
string theUrl = ProcessURL();
InitVideoPlayer(videoPlayerPtr, (int) videoType, theUrl,
videoContentID,
videoProviderId,
useSecurePath,
true);
framecount = 0;
}
public void SetCurrentVolume(int val) {
SetCurrentVolume(videoPlayerPtr, val);
}
/// <summary>
/// Initialize the video player.
/// </summary>
/// <returns>true if successful</returns>
public bool Init() {
if (initialized) {
Debug.Log("Skipping initialization: video player already loaded");
return true;
}
if (videoURL == null || videoURL.Length == 0) {
Debug.LogError("Cannot initialize with null videoURL");
return false;
}
videoURL = videoURL == null ? "" : videoURL.Trim();
videoContentID = videoContentID == null ? "" : videoContentID.Trim();
videoProviderId = videoProviderId == null ? "" : videoProviderId.Trim();
SetInitialResolution(videoPlayerPtr, (int) initialResolution);
string theUrl = ProcessURL();
Debug.Log("Playing " + videoType + " " + theUrl);
Debug.Log("videoContentID = " + videoContentID);
Debug.Log("videoProviderId = " + videoProviderId);
videoPlayerPtr = InitVideoPlayer(videoPlayerPtr, (int) videoType, theUrl,
videoContentID, videoProviderId,
useSecurePath, false);
initialized = true;
framecount = 0;
return videoPlayerPtr != IntPtr.Zero;
}
public bool Play() {
if (!initialized) {
Init();
} else if (!processingRunning) {
StartCoroutine(CallPluginAtEndOfFrames());
}
if (videoPlayerPtr != IntPtr.Zero && IsVideoReady(videoPlayerPtr)) {
return PlayVideo(videoPlayerPtr) == 0;
} else {
Debug.LogError("Video player not ready to Play!");
return false;
}
}
public bool Pause() {
if (!initialized) {
Init();
}
if (VideoReady) {
return PauseVideo(videoPlayerPtr) == 0;
} else {
Debug.LogError("Video player not ready to Pause!");
return false;
}
}
/// <summary>
/// Adjusts the aspect ratio.
/// </summary>
/// <remarks>
/// This adjusts the transform scale to match the aspect
/// ratio of the texture.
/// </remarks>
private void AdjustAspectRatio() {
float aspectRatio = texWidth / texHeight;
// set the y scale based on the x value
Vector3 newscale = transform.localScale;
newscale.y = Mathf.Min(newscale.y, newscale.x / aspectRatio);
transform.localScale = newscale;
}
/// <summary>
/// Creates the texture for video if needed.
/// </summary>
private void CreateTextureForVideoMaybe() {
if (videoTextures[0] == null || (texWidth != videoTextures[0].width ||
texHeight != videoTextures[0].height)) {
// Check the dimensions to make sure they are valid.
if (texWidth < 0 || texHeight < 0) {
// Maybe use the last dimension. This happens when re-initializing the player.
if (videoTextures != null && videoTextures[0].width > 0) {
texWidth = videoTextures[0].width;
texHeight = videoTextures[0].height;
}
}
int[] tex_ids = new int[videoTextures.Length];
for (int idx = 0; idx < videoTextures.Length; idx++) {
// Resize the existing texture if there, otherwise create it.
if (videoTextures[idx] != null) {
if (videoTextures[idx].width != texWidth
|| videoTextures[idx].height != texHeight)
{
videoTextures[idx].Resize(texWidth, texHeight);
videoTextures[idx].Apply();
}
} else {
videoTextures[idx] = new Texture2D(texWidth, texHeight,
TextureFormat.RGBA32, false);
videoTextures[idx].filterMode = FilterMode.Bilinear;
videoTextures[idx].wrapMode = TextureWrapMode.Clamp;
}
tex_ids[idx] = videoTextures[idx].GetNativeTexturePtr().ToInt32();
}
SetExternalTextures(videoPlayerPtr, tex_ids, tex_ids.Length,
texWidth, texHeight);
currentTexture = 0;
UpdateStatusText();
}
if (adjustAspectRatio) {
AdjustAspectRatio();
}
}
private void UpdateStatusText() {
float fps = CurrentPosition > 0 ?
(framecount / (CurrentPosition / 1000f)) : CurrentPosition;
string status = texWidth + " x " + texHeight + " buffer: " +
(BufferedPosition / 1000) + " " + PlayerState + " fps: " + fps;
if (statusText != null) {
if (statusText.text != status) {
statusText.text = status;
Debug.Log("STATUS: " + status);
}
}
}
/// <summary>
/// Issues the player event.
/// </summary>
/// <param name="evt">The event to send to the video player
/// instance.
/// </param>
private void IssuePlayerEvent(RenderCommand evt) {
if (renderEventFunction != IntPtr.Zero && evt != RenderCommand.None) {
GL.IssuePluginEvent(renderEventFunction,
videoPlayerEventBase + (int) evt);
}
}
void Update() {
while (ExecuteOnMainThread.Count > 0) {
ExecuteOnMainThread.Dequeue().Invoke();
}
}
private IEnumerator CallPluginAtEndOfFrames() {
if (processingRunning) {
Debug.LogError("CallPluginAtEndOfFrames invoked while already running.");
yield break;
}
// Only run while the video is playing.
bool running = true;
processingRunning = true;
exitProcessing = false;
WaitForEndOfFrame wfeof = new WaitForEndOfFrame();
while (running) {
// Wait until all frame rendering is done
yield return wfeof;
if (exitProcessing) {
running = false;
break;
}
if (videoPlayerPtr != IntPtr.Zero) {
CreateTextureForVideoMaybe();
}
IntPtr tex = GetRenderableTextureId(videoPlayerPtr);
currentTexture = 0;
for (int i = 0; i < videoTextures.Length; i++) {
if (tex == videoTextures[i].GetNativeTexturePtr()) {
currentTexture = i;
}
}
if (!VideoReady) {
continue;
} else if (framecount > 1 && PlayerState == VideoPlayerState.Ended) {
running = false;
}
IssuePlayerEvent(RenderCommand.UpdateVideo);
IssuePlayerEvent(RenderCommand.RenderMono);
int w = GetWidth(videoPlayerPtr);
int h = GetHeight(videoPlayerPtr);
// Limit total pixel count to the same as 2160p.
// 3840 * 2160 == 2880 * 2880
if (w * h > 2880 * 2880) {
// Clamp the max resolution preserving aspect ratio.
float aspectRoot = (float) Math.Sqrt(w / h);
w = (int) (2880 * aspectRoot);
h = (int) (2880 / aspectRoot);
}
texWidth = w;
texHeight = h;
if ((int) framecount % 30 == 0) {
UpdateStatusText();
}
long bp = BufferedPosition;
if (bp != lastBufferedPosition) {
lastBufferedPosition = bp;
UpdateStatusText();
}
}
processingRunning = false;
}
public void RemoveOnVideoEventCallback(Action<int> callback) {
if (onEventCallbacks != null) {
onEventCallbacks.Remove(callback);
}
}
public void SetOnVideoEventCallback(Action<int> callback) {
if (onEventCallbacks == null) {
onEventCallbacks = new List<Action<int>>();
}
onEventCallbacks.Add(callback);
SetOnVideoEventCallback(videoPlayerPtr, InternalOnVideoEventCallback,
ToIntPtr(this));
}
internal void FireVideoEvent(int eventId) {
if (onEventCallbacks == null) {
return;
}
// Copy the collection so the callbacks can remove themselves from the list.
Action<int>[] cblist = onEventCallbacks.ToArray();
foreach (Action<int> cb in cblist) {
try {
cb(eventId);
} catch (Exception e) {
Debug.LogError("exception calling callback: " + e);
}
}
}
[AOT.MonoPInvokeCallback(typeof(OnVideoEventCallback))]
static void InternalOnVideoEventCallback(IntPtr cbdata, int eventId) {
if (cbdata == IntPtr.Zero) {
return;
}
GvrVideoPlayerTexture player;
var gcHandle = GCHandle.FromIntPtr(cbdata);
try {
player = (GvrVideoPlayerTexture) gcHandle.Target;
}
catch (InvalidCastException e) {
Debug.LogError("GC Handle pointed to unexpected type: " +
gcHandle.Target + ". Expected " +
typeof(GvrVideoPlayerTexture));
throw e;
}
if (player != null) {
ExecuteOnMainThread.Enqueue(() => player.FireVideoEvent(eventId));
}
}
public void SetOnExceptionCallback(Action<string, string> callback) {
if (onExceptionCallbacks == null) {
onExceptionCallbacks = new List<Action<string, string>>();
SetOnExceptionCallback(videoPlayerPtr, InternalOnExceptionCallback,
ToIntPtr(this));
}
onExceptionCallbacks.Add(callback);
}
[AOT.MonoPInvokeCallback(typeof(OnExceptionCallback))]
static void InternalOnExceptionCallback(string type, string msg,
IntPtr cbdata) {
if (cbdata == IntPtr.Zero) {
return;
}
GvrVideoPlayerTexture player;
var gcHandle = GCHandle.FromIntPtr(cbdata);
try {
player = (GvrVideoPlayerTexture) gcHandle.Target;
}
catch (InvalidCastException e) {
Debug.LogError("GC Handle pointed to unexpected type: " +
gcHandle.Target + ". Expected " +
typeof(GvrVideoPlayerTexture));
throw e;
}
if (player != null) {
ExecuteOnMainThread.Enqueue(() => player.FireOnException(type, msg));
}
}
internal void FireOnException(string type, string msg) {
if (onExceptionCallbacks == null) {
return;
}
foreach (Action<string, string> cb in onExceptionCallbacks) {
try {
cb(type, msg);
} catch (Exception e) {
Debug.LogError("exception calling callback: " + e);
}
}
}
internal static IntPtr ToIntPtr(System.Object obj) {
GCHandle handle = GCHandle.Alloc(obj);
return GCHandle.ToIntPtr(handle);
}
internal string ProcessURL() {
return videoURL.Replace("${Application.dataPath}", Application.dataPath);
}
internal delegate void OnVideoEventCallback(IntPtr cbdata, int eventId);
internal delegate void OnExceptionCallback(string type, string msg,
IntPtr cbdata);
#if UNITY_ANDROID && !UNITY_EDITOR
private const string dllName = "gvrvideo";
[DllImport(dllName)]
private static extern IntPtr GetRenderEventFunc();
[DllImport(dllName)]
private static extern void SetExternalTextures(IntPtr videoPlayerPtr,
int[] texIds,
int size,
int w,
int h);
[DllImport(dllName)]
private static extern IntPtr GetRenderableTextureId(IntPtr videoPlayerPtr);
// Keep public so we can check for the dll being present at runtime.
[DllImport(dllName)]
public static extern IntPtr CreateVideoPlayer();
// Keep public so we can check for the dll being present at runtime.
[DllImport(dllName)]
public static extern void DestroyVideoPlayer(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern int GetVideoPlayerEventBase(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern IntPtr InitVideoPlayer(IntPtr videoPlayerPtr,
int videoType,
string videoURL,
string contentID,
string providerId,
bool useSecurePath,
bool useExisting);
[DllImport(dllName)]
private static extern void SetInitialResolution(IntPtr videoPlayerPtr,
int initialResolution);
[DllImport(dllName)]
private static extern int GetPlayerState(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern int GetWidth(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern int GetHeight(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern int PlayVideo(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern int PauseVideo(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern bool IsVideoReady(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern bool IsVideoPaused(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern long GetDuration(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern long GetBufferedPosition(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern long GetCurrentPosition(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern void SetCurrentPosition(IntPtr videoPlayerPtr,
long pos);
[DllImport(dllName)]
private static extern int GetBufferedPercentage(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern int GetMaxVolume(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern int GetCurrentVolume(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern void SetCurrentVolume(IntPtr videoPlayerPtr,
int value);
[DllImport(dllName)]
private static extern bool SetVideoPlayerSupportClassname(
IntPtr videoPlayerPtr,
string classname);
[DllImport(dllName)]
private static extern IntPtr GetRawPlayer(IntPtr videoPlayerPtr);
[DllImport(dllName)]
private static extern void SetOnVideoEventCallback(IntPtr videoPlayerPtr,
OnVideoEventCallback callback,
IntPtr callback_arg);
[DllImport(dllName)]
private static extern void SetOnExceptionCallback(IntPtr videoPlayerPtr,
OnExceptionCallback callback,
IntPtr callback_arg);
#else
private const string NOT_IMPLEMENTED_MSG =
"Not implemented on this platform";
private static IntPtr GetRenderEventFunc() {
Debug.Log(NOT_IMPLEMENTED_MSG);
return IntPtr.Zero;
}
private static void SetExternalTextures(IntPtr videoPlayerPtr,
int[] texIds,
int size,
int w,
int h) {
Debug.Log(NOT_IMPLEMENTED_MSG);
}
private static IntPtr GetRenderableTextureId(IntPtr videoPlayerPtr) {
return IntPtr.Zero;
}
// Make this public so we can test the loading of the DLL.
public static IntPtr CreateVideoPlayer() {
Debug.Log(NOT_IMPLEMENTED_MSG);
return IntPtr.Zero;
}
// Make this public so we can test the loading of the DLL.
public static void DestroyVideoPlayer(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
}
private static int GetVideoPlayerEventBase(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return 0;
}
private static IntPtr InitVideoPlayer(IntPtr videoPlayerPtr, int videoType,
string videoURL,
string contentID,
string providerId,
bool useSecurePath,
bool useExisting) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return IntPtr.Zero;
}
private static void SetInitialResolution(IntPtr videoPlayerPtr,
int initialResolution) {
Debug.Log(NOT_IMPLEMENTED_MSG);
}
private static int GetPlayerState(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return -1;
}
private static int GetWidth(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return -1;
}
private static int GetHeight(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return -1;
}
private static int PlayVideo(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return 0;
}
private static int PauseVideo(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return 0;
}
private static bool IsVideoReady(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return false;
}
private static bool IsVideoPaused(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return true;
}
private static long GetDuration(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return -1;
}
private static long GetBufferedPosition(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return -1;
}
private static long GetCurrentPosition(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return -1;
}
private static void SetCurrentPosition(IntPtr videoPlayerPtr, long pos) {
Debug.Log(NOT_IMPLEMENTED_MSG);
}
private static int GetBufferedPercentage(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return 0;
}
private static int GetMaxVolume(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return 0;
}
private static int GetCurrentVolume(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return 0;
}
private static void SetCurrentVolume(IntPtr videoPlayerPtr, int value) {
Debug.Log(NOT_IMPLEMENTED_MSG);
}
private static bool SetVideoPlayerSupportClassname(IntPtr videoPlayerPtr,
string classname) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return false;
}
private static IntPtr GetRawPlayer(IntPtr videoPlayerPtr) {
Debug.Log(NOT_IMPLEMENTED_MSG);
return IntPtr.Zero;
}
private static void SetOnVideoEventCallback(IntPtr videoPlayerPtr,
OnVideoEventCallback callback,
IntPtr callback_arg) {
Debug.Log(NOT_IMPLEMENTED_MSG);
}
private static void SetOnExceptionCallback(IntPtr videoPlayerPtr,
OnExceptionCallback callback,
IntPtr callback_arg) {
Debug.Log(NOT_IMPLEMENTED_MSG);
}
#endif // UNITY_ANDROID && !UNITY_EDITOR
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>AdGroupAdLabel</c> resource.</summary>
public sealed partial class AdGroupAdLabelName : gax::IResourceName, sys::IEquatable<AdGroupAdLabelName>
{
/// <summary>The possible contents of <see cref="AdGroupAdLabelName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>
/// .
/// </summary>
CustomerAdGroupAdLabel = 1,
}
private static gax::PathTemplate s_customerAdGroupAdLabel = new gax::PathTemplate("customers/{customer_id}/adGroupAdLabels/{ad_group_id_ad_id_label_id}");
/// <summary>Creates a <see cref="AdGroupAdLabelName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AdGroupAdLabelName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AdGroupAdLabelName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AdGroupAdLabelName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AdGroupAdLabelName"/> with the pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AdGroupAdLabelName"/> constructed from the provided ids.</returns>
public static AdGroupAdLabelName FromCustomerAdGroupAdLabel(string customerId, string adGroupId, string adId, string labelId) =>
new AdGroupAdLabelName(ResourceNameType.CustomerAdGroupAdLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), adId: gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupAdLabelName"/> with pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdGroupAdLabelName"/> with pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </returns>
public static string Format(string customerId, string adGroupId, string adId, string labelId) =>
FormatCustomerAdGroupAdLabel(customerId, adGroupId, adId, labelId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupAdLabelName"/> with pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdGroupAdLabelName"/> with pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </returns>
public static string FormatCustomerAdGroupAdLabel(string customerId, string adGroupId, string adId, string labelId) =>
s_customerAdGroupAdLabel.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="AdGroupAdLabelName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adGroupAdLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AdGroupAdLabelName"/> if successful.</returns>
public static AdGroupAdLabelName Parse(string adGroupAdLabelName) => Parse(adGroupAdLabelName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AdGroupAdLabelName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupAdLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AdGroupAdLabelName"/> if successful.</returns>
public static AdGroupAdLabelName Parse(string adGroupAdLabelName, bool allowUnparsed) =>
TryParse(adGroupAdLabelName, allowUnparsed, out AdGroupAdLabelName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdGroupAdLabelName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adGroupAdLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdGroupAdLabelName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adGroupAdLabelName, out AdGroupAdLabelName result) =>
TryParse(adGroupAdLabelName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdGroupAdLabelName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupAdLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdGroupAdLabelName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adGroupAdLabelName, bool allowUnparsed, out AdGroupAdLabelName result)
{
gax::GaxPreconditions.CheckNotNull(adGroupAdLabelName, nameof(adGroupAdLabelName));
gax::TemplatedResourceName resourceName;
if (s_customerAdGroupAdLabel.TryParseName(adGroupAdLabelName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerAdGroupAdLabel(resourceName[0], split1[0], split1[1], split1[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(adGroupAdLabelName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private AdGroupAdLabelName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adId = null, string adGroupId = null, string customerId = null, string labelId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AdId = adId;
AdGroupId = adGroupId;
CustomerId = customerId;
LabelId = labelId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AdGroupAdLabelName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
public AdGroupAdLabelName(string customerId, string adGroupId, string adId, string labelId) : this(ResourceNameType.CustomerAdGroupAdLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), adId: gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Ad</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdId { get; }
/// <summary>
/// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdGroupId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>Label</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LabelId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerAdGroupAdLabel: return s_customerAdGroupAdLabel.Expand(CustomerId, $"{AdGroupId}~{AdId}~{LabelId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AdGroupAdLabelName);
/// <inheritdoc/>
public bool Equals(AdGroupAdLabelName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AdGroupAdLabelName a, AdGroupAdLabelName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AdGroupAdLabelName a, AdGroupAdLabelName b) => !(a == b);
}
public partial class AdGroupAdLabel
{
/// <summary>
/// <see cref="AdGroupAdLabelName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal AdGroupAdLabelName ResourceNameAsAdGroupAdLabelName
{
get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupAdLabelName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupAdName"/>-typed view over the <see cref="AdGroupAd"/> resource name property.
/// </summary>
internal AdGroupAdName AdGroupAdAsAdGroupAdName
{
get => string.IsNullOrEmpty(AdGroupAd) ? null : AdGroupAdName.Parse(AdGroupAd, allowUnparsed: true);
set => AdGroupAd = value?.ToString() ?? "";
}
/// <summary><see cref="LabelName"/>-typed view over the <see cref="Label"/> resource name property.</summary>
internal LabelName LabelAsLabelName
{
get => string.IsNullOrEmpty(Label) ? null : LabelName.Parse(Label, allowUnparsed: true);
set => Label = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.IO.Pipelines;
using System.Threading;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Http.Features;
namespace Orleans.Networking.Shared
{
internal interface IConnectionIdFeature
{
string ConnectionId { get; set; }
}
internal interface IConnectionTransportFeature
{
IDuplexPipe Transport { get; set; }
}
internal interface IConnectionItemsFeature
{
IDictionary<object, object> Items { get; set; }
}
internal interface IMemoryPoolFeature
{
MemoryPool<byte> MemoryPool { get; }
}
internal partial class TransportConnection : IConnectionIdFeature,
IConnectionTransportFeature,
IConnectionItemsFeature,
IMemoryPoolFeature,
IConnectionLifetimeFeature
{
// NOTE: When feature interfaces are added to or removed from this TransportConnection class implementation,
// then the list of `features` in the generated code project MUST also be updated.
// See also: tools/CodeGenerator/TransportConnectionFeatureCollection.cs
MemoryPool<byte> IMemoryPoolFeature.MemoryPool => MemoryPool;
IDuplexPipe IConnectionTransportFeature.Transport
{
get => Transport;
set => Transport = value;
}
IDictionary<object, object> IConnectionItemsFeature.Items
{
get => Items;
set => Items = value;
}
CancellationToken IConnectionLifetimeFeature.ConnectionClosed
{
get => ConnectionClosed;
set => ConnectionClosed = value;
}
void IConnectionLifetimeFeature.Abort() => Abort(new ConnectionAbortedException("The connection was aborted by the application via IConnectionLifetimeFeature.Abort()."));
}
internal partial class TransportConnection : IFeatureCollection
{
private static readonly Type IConnectionIdFeatureType = typeof(IConnectionIdFeature);
private static readonly Type IConnectionTransportFeatureType = typeof(IConnectionTransportFeature);
private static readonly Type IConnectionItemsFeatureType = typeof(IConnectionItemsFeature);
private static readonly Type IMemoryPoolFeatureType = typeof(IMemoryPoolFeature);
private static readonly Type IConnectionLifetimeFeatureType = typeof(IConnectionLifetimeFeature);
private object _currentIConnectionIdFeature;
private object _currentIConnectionTransportFeature;
private object _currentIConnectionItemsFeature;
private object _currentIMemoryPoolFeature;
private object _currentIConnectionLifetimeFeature;
private int _featureRevision;
private List<KeyValuePair<Type, object>> MaybeExtra;
private void FastReset()
{
_currentIConnectionIdFeature = this;
_currentIConnectionTransportFeature = this;
_currentIConnectionItemsFeature = this;
_currentIMemoryPoolFeature = this;
_currentIConnectionLifetimeFeature = this;
}
// Internal for testing
internal void ResetFeatureCollection()
{
FastReset();
MaybeExtra?.Clear();
_featureRevision++;
}
private object ExtraFeatureGet(Type key)
{
if (MaybeExtra == null)
{
return null;
}
for (var i = 0; i < MaybeExtra.Count; i++)
{
var kv = MaybeExtra[i];
if (kv.Key == key)
{
return kv.Value;
}
}
return null;
}
private void ExtraFeatureSet(Type key, object value)
{
if (MaybeExtra == null)
{
MaybeExtra = new List<KeyValuePair<Type, object>>(2);
}
for (var i = 0; i < MaybeExtra.Count; i++)
{
if (MaybeExtra[i].Key == key)
{
MaybeExtra[i] = new KeyValuePair<Type, object>(key, value);
return;
}
}
MaybeExtra.Add(new KeyValuePair<Type, object>(key, value));
}
bool IFeatureCollection.IsReadOnly => false;
int IFeatureCollection.Revision => _featureRevision;
object IFeatureCollection.this[Type key]
{
get
{
object feature = null;
if (key == IConnectionIdFeatureType)
{
feature = _currentIConnectionIdFeature;
}
else if (key == IConnectionTransportFeatureType)
{
feature = _currentIConnectionTransportFeature;
}
else if (key == IConnectionItemsFeatureType)
{
feature = _currentIConnectionItemsFeature;
}
else if (key == IMemoryPoolFeatureType)
{
feature = _currentIMemoryPoolFeature;
}
else if (key == IConnectionLifetimeFeatureType)
{
feature = _currentIConnectionLifetimeFeature;
}
else if (MaybeExtra != null)
{
feature = ExtraFeatureGet(key);
}
return feature;
}
set
{
_featureRevision++;
if (key == IConnectionIdFeatureType)
{
_currentIConnectionIdFeature = value;
}
else if (key == IConnectionTransportFeatureType)
{
_currentIConnectionTransportFeature = value;
}
else if (key == IConnectionItemsFeatureType)
{
_currentIConnectionItemsFeature = value;
}
else if (key == IMemoryPoolFeatureType)
{
_currentIMemoryPoolFeature = value;
}
else if (key == IConnectionLifetimeFeatureType)
{
_currentIConnectionLifetimeFeature = value;
}
else
{
ExtraFeatureSet(key, value);
}
}
}
TFeature IFeatureCollection.Get<TFeature>()
{
TFeature feature = default;
if (typeof(TFeature) == typeof(IConnectionIdFeature))
{
feature = (TFeature)_currentIConnectionIdFeature;
}
else if (typeof(TFeature) == typeof(IConnectionTransportFeature))
{
feature = (TFeature)_currentIConnectionTransportFeature;
}
else if (typeof(TFeature) == typeof(IConnectionItemsFeature))
{
feature = (TFeature)_currentIConnectionItemsFeature;
}
else if (typeof(TFeature) == typeof(IMemoryPoolFeature))
{
feature = (TFeature)_currentIMemoryPoolFeature;
}
else if (typeof(TFeature) == typeof(IConnectionLifetimeFeature))
{
feature = (TFeature)_currentIConnectionLifetimeFeature;
}
else if (MaybeExtra != null)
{
feature = (TFeature)(ExtraFeatureGet(typeof(TFeature)));
}
return feature;
}
void IFeatureCollection.Set<TFeature>(TFeature feature)
{
_featureRevision++;
if (typeof(TFeature) == typeof(IConnectionIdFeature))
{
_currentIConnectionIdFeature = feature;
}
else if (typeof(TFeature) == typeof(IConnectionTransportFeature))
{
_currentIConnectionTransportFeature = feature;
}
else if (typeof(TFeature) == typeof(IConnectionItemsFeature))
{
_currentIConnectionItemsFeature = feature;
}
else if (typeof(TFeature) == typeof(IMemoryPoolFeature))
{
_currentIMemoryPoolFeature = feature;
}
else if (typeof(TFeature) == typeof(IConnectionLifetimeFeature))
{
_currentIConnectionLifetimeFeature = feature;
}
else
{
ExtraFeatureSet(typeof(TFeature), feature);
}
}
private IEnumerable<KeyValuePair<Type, object>> FastEnumerable()
{
if (_currentIConnectionIdFeature != null)
{
yield return new KeyValuePair<Type, object>(IConnectionIdFeatureType, _currentIConnectionIdFeature);
}
if (_currentIConnectionTransportFeature != null)
{
yield return new KeyValuePair<Type, object>(IConnectionTransportFeatureType, _currentIConnectionTransportFeature);
}
if (_currentIConnectionItemsFeature != null)
{
yield return new KeyValuePair<Type, object>(IConnectionItemsFeatureType, _currentIConnectionItemsFeature);
}
if (_currentIMemoryPoolFeature != null)
{
yield return new KeyValuePair<Type, object>(IMemoryPoolFeatureType, _currentIMemoryPoolFeature);
}
if (_currentIConnectionLifetimeFeature != null)
{
yield return new KeyValuePair<Type, object>(IConnectionLifetimeFeatureType, _currentIConnectionLifetimeFeature);
}
if (MaybeExtra != null)
{
foreach (var item in MaybeExtra)
{
yield return item;
}
}
}
IEnumerator<KeyValuePair<Type, object>> IEnumerable<KeyValuePair<Type, object>>.GetEnumerator() => FastEnumerable().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => FastEnumerable().GetEnumerator();
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using SharpDX.DXGI;
using SharpDX.IO;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// An unmanaged buffer of pixels.
/// </summary>
public sealed class PixelBuffer
{
private int width;
private int height;
private DXGI.Format format;
private int rowStride;
private int bufferStride;
private readonly IntPtr dataPointer;
private int pixelSize;
/// <summary>
/// True when RowStride == sizeof(pixelformat) * width
/// </summary>
private bool isStrictRowStride;
/// <summary>
/// Initializes a new instance of the <see cref="PixelBuffer" /> struct.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="format">The format.</param>
/// <param name="rowStride">The row pitch.</param>
/// <param name="bufferStride">The slice pitch.</param>
/// <param name="dataPointer">The pixels.</param>
public PixelBuffer(int width, int height, Format format, int rowStride, int bufferStride, IntPtr dataPointer)
{
if (dataPointer == IntPtr.Zero)
throw new ArgumentException("Pointer cannot be equal to IntPtr.Zero", "dataPointer");
this.width = width;
this.height = height;
this.format = format;
this.rowStride = rowStride;
this.bufferStride = bufferStride;
this.dataPointer = dataPointer;
this.pixelSize = (int)FormatHelper.SizeOfInBytes(this.format);
this.isStrictRowStride = (pixelSize * width) == rowStride;
}
/// <summary>
/// Gets the width.
/// </summary>
/// <value>The width.</value>
public int Width { get { return width; } }
/// <summary>
/// Gets the height.
/// </summary>
/// <value>The height.</value>
public int Height { get { return height; } }
/// <summary>
/// Gets the format (this value can be changed)
/// </summary>
/// <value>The format.</value>
public Format Format
{
get
{
return format;
}
set
{
if (PixelSize != (int)FormatHelper.SizeOfInBytes(value))
{
throw new ArgumentException(string.Format("Format [{0}] doesn't have same pixel size in bytes than current format [{1}]", value, format));
}
format = value;
}
}
/// <summary>
/// Gets the pixel size in bytes.
/// </summary>
/// <value>The pixel size in bytes.</value>
public int PixelSize { get { return this.pixelSize; } }
/// <summary>
/// Gets the row stride in number of bytes.
/// </summary>
/// <value>The row stride in number of bytes.</value>
public int RowStride { get { return this.rowStride; } }
/// <summary>
/// Gets the total size in bytes of this pixel buffer.
/// </summary>
/// <value>The size in bytes of the pixel buffer.</value>
public int BufferStride { get { return this.bufferStride; } }
/// <summary>
/// Gets the pointer to the pixel buffer.
/// </summary>
/// <value>The pointer to the pixel buffer.</value>
public IntPtr DataPointer { get { return this.dataPointer; } }
/// <summary>
/// Copies this pixel buffer to a destination pixel buffer.
/// </summary>
/// <param name="pixelBuffer">The destination pixel buffer.</param>
/// <remarks>
/// The destination pixel buffer must have exactly the same dimensions (width, height) and format than this instance.
/// Destination buffer can have different row stride.
/// </remarks>
public unsafe void CopyTo(PixelBuffer pixelBuffer)
{
// Check that buffers are identical
if (this.Width != pixelBuffer.Width
|| this.Height != pixelBuffer.Height
|| PixelSize != (int)FormatHelper.SizeOfInBytes(pixelBuffer.Format))
{
throw new ArgumentException("Invalid destination pixelBufferArray. Mush have same Width, Height and Format", "pixelBuffer");
}
// If buffers have same size, than we can copy it directly
if (this.BufferStride == pixelBuffer.BufferStride)
{
Utilities.CopyMemory(pixelBuffer.DataPointer, this.DataPointer, this.BufferStride);
}
else
{
var srcPointer = (byte*)this.DataPointer;
var dstPointer = (byte*)pixelBuffer.DataPointer;
var rowStride = Math.Min(RowStride, pixelBuffer.RowStride);
// Copy per scanline
for(int i = 0; i < Height; i++)
{
Utilities.CopyMemory(new IntPtr(dstPointer), new IntPtr(srcPointer), rowStride);
srcPointer += this.RowStride;
dstPointer += pixelBuffer.RowStride;
}
}
}
/// <summary>
/// Saves this pixel buffer to a file.
/// </summary>
/// <param name="fileName">The destination file.</param>
/// <param name="fileType">Specify the output format.</param>
/// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks>
public void Save(string fileName, ImageFileType fileType)
{
using (var imageStream = new NativeFileStream(fileName, NativeFileMode.Create, NativeFileAccess.Write))
{
Save(imageStream, fileType);
}
}
/// <summary>
/// Saves this pixel buffer to a stream.
/// </summary>
/// <param name="imageStream">The destination stream.</param>
/// <param name="fileType">Specify the output format.</param>
/// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks>
public void Save(Stream imageStream, ImageFileType fileType)
{
var description = new ImageDescription()
{
Width = this.width,
Height = this.height,
Depth = 1,
ArraySize = 1,
Dimension = TextureDimension.Texture2D,
Format = this.format,
MipLevels = 1,
};
Image.Save(new [] {this}, 1, description, imageStream, fileType);
}
/// <summary>
/// Gets the pixel value at a specified position.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="x">The x-coordinate.</param>
/// <param name="y">The y-coordinate.</param>
/// <returns>The pixel value.</returns>
/// <remarks>
/// Caution, this method doesn't check bounding.
/// </remarks>
public unsafe T GetPixel<T>(int x, int y) where T : struct
{
return Utilities.Read<T>(new IntPtr(((byte*)this.DataPointer + RowStride * y + x * PixelSize)));
}
/// <summary>
/// Gets the pixel value at a specified position.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="x">The x-coordinate.</param>
/// <param name="y">The y-coordinate.</param>
/// <param name="value">The pixel value.</param>
/// <remarks>
/// Caution, this method doesn't check bounding.
/// </remarks>
public unsafe void SetPixel<T>(int x, int y, T value) where T : struct
{
Utilities.Write(new IntPtr((byte*)this.DataPointer + RowStride * y + x * PixelSize), ref value);
}
/// <summary>
/// Gets scanline pixels from the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="yOffset">The y line offset.</param>
/// <returns>Scanline pixels from the buffer</returns>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <see cref="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public T[] GetPixels<T>(int yOffset = 0) where T : struct
{
var sizeOfOutputPixel = Utilities.SizeOf<T>();
var totalSize = Width * Height * pixelSize;
if ((totalSize % sizeOfOutputPixel) != 0)
throw new ArgumentException(string.Format("Invalid sizeof(T), not a multiple of current size [{0}]in bytes ", totalSize));
var buffer = new T[totalSize / sizeOfOutputPixel];
GetPixels(buffer, yOffset);
return buffer;
}
/// <summary>
/// Gets scanline pixels from the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="pixels">An allocated scanline pixel buffer</param>
/// <param name="yOffset">The y line offset.</param>
/// <returns>Scanline pixels from the buffer</returns>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <see cref="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public void GetPixels<T>(T[] pixels, int yOffset = 0) where T : struct
{
GetPixels(pixels, yOffset, 0, pixels.Length);
}
/// <summary>
/// Gets scanline pixels from the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="pixels">An allocated scanline pixel buffer</param>
/// <param name="yOffset">The y line offset.</param>
/// <param name="pixelIndex">Offset into the destination <see cref="pixels"/> buffer.</param>
/// <param name="pixelCount">Number of pixels to write into the destination <see cref="pixels"/> buffer.</param>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <see cref="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public unsafe void GetPixels<T>(T[] pixels, int yOffset, int pixelIndex, int pixelCount) where T : struct
{
var pixelPointer = (byte*)this.DataPointer + yOffset * rowStride;
if (isStrictRowStride)
{
Utilities.Read(new IntPtr(pixelPointer), pixels, 0, pixelCount);
}
else
{
var sizeOfOutputPixel = Utilities.SizeOf<T>() * pixelCount;
var sizePerWidth = sizeOfOutputPixel / Width;
var remainingPixels = sizeOfOutputPixel % Width;
for(int i = 0; i < sizePerWidth; i++)
{
Utilities.Read(new IntPtr(pixelPointer), pixels, pixelIndex, Width);
pixelPointer += rowStride;
pixelIndex += Width;
}
if (remainingPixels > 0)
{
Utilities.Read(new IntPtr(pixelPointer), pixels, pixelIndex, remainingPixels);
}
}
}
/// <summary>
/// Sets scanline pixels to the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="sourcePixels">Source pixel buffer</param>
/// <param name="yOffset">The y line offset.</param>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <see cref="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public void SetPixels<T>(T[] sourcePixels, int yOffset = 0) where T : struct
{
SetPixels(sourcePixels, yOffset, 0, sourcePixels.Length);
}
/// <summary>
/// Sets scanline pixels to the buffer.
/// </summary>
/// <typeparam name="T">Type of the pixel data</typeparam>
/// <param name="sourcePixels">Source pixel buffer</param>
/// <param name="yOffset">The y line offset.</param>
/// <param name="pixelIndex">Offset into the source <see cref="sourcePixels"/> buffer.</param>
/// <param name="pixelCount">Number of pixels to write into the source <see cref="sourcePixels"/> buffer.</param>
/// <exception cref="System.ArgumentException">If the sizeof(T) is an invalid size</exception>
/// <remarks>
/// This method is working on a row basis. The <see cref="yOffset"/> is specifying the first row to get
/// the pixels from.
/// </remarks>
public unsafe void SetPixels<T>(T[] sourcePixels, int yOffset, int pixelIndex, int pixelCount) where T : struct
{
var pixelPointer = (byte*)this.DataPointer + yOffset * rowStride;
if (isStrictRowStride)
{
Utilities.Write(new IntPtr(pixelPointer), sourcePixels, 0, pixelCount);
}
else
{
var sizeOfOutputPixel = Utilities.SizeOf<T>() * pixelCount;
var sizePerWidth = sizeOfOutputPixel / Width;
var remainingPixels = sizeOfOutputPixel % Width;
for (int i = 0; i < sizePerWidth; i++)
{
Utilities.Write(new IntPtr(pixelPointer), sourcePixels, pixelIndex, Width);
pixelPointer += rowStride;
pixelIndex += Width;
}
if (remainingPixels > 0)
{
Utilities.Write(new IntPtr(pixelPointer), sourcePixels, pixelIndex, remainingPixels);
}
}
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, 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.
//
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD
namespace NLog.LayoutRenderers
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Text;
using Microsoft.Win32;
using NLog.Common;
using NLog.Internal;
using NLog.Config;
using NLog.Layouts;
/// <summary>
/// A value from the Registry.
/// </summary>
[LayoutRenderer("registry")]
public class RegistryLayoutRenderer : LayoutRenderer
{
/// <summary>
/// Create new renderer
/// </summary>
public RegistryLayoutRenderer()
{
RequireEscapingSlashesInDefaultValue = true;
}
/// <summary>
/// Gets or sets the registry value name.
/// </summary>
/// <docgen category='Registry Options' order='10' />
public Layout Value { get; set; }
/// <summary>
/// Gets or sets the value to be output when the specified registry key or value is not found.
/// </summary>
/// <docgen category='Registry Options' order='10' />
public Layout DefaultValue { get; set; }
/// <summary>
/// Require escaping backward slashes in <see cref="DefaultValue"/>. Need to be backwards-compatible.
///
/// When true:
///
/// `\` in value should be configured as `\\`
/// `\\` in value should be configured as `\\\\`.
/// </summary>
/// <remarks>Default value wasn't a Layout before and needed an escape of the slash</remarks>
/// <docgen category='Registry Options' order='50' />
[DefaultValue(true)]
public bool RequireEscapingSlashesInDefaultValue { get; set; }
#if !NET3_5
/// <summary>
/// Gets or sets the registry view (see: https://msdn.microsoft.com/de-de/library/microsoft.win32.registryview.aspx).
/// Allowed values: Registry32, Registry64, Default
/// </summary>
/// <docgen category='Registry Options' order='10' />
[DefaultValue("Default")]
public RegistryView View { get; set; }
#endif
/// <summary>
/// Gets or sets the registry key.
/// </summary>
/// <example>
/// HKCU\Software\NLogTest
/// </example>
/// <remarks>
/// Possible keys:
/// <ul>
///<li>HKEY_LOCAL_MACHINE</li>
///<li>HKLM</li>
///<li>HKEY_CURRENT_USER</li>
///<li>HKCU</li>
///<li>HKEY_CLASSES_ROOT</li>
///<li>HKEY_USERS</li>
///<li>HKEY_CURRENT_CONFIG</li>
///<li>HKEY_DYN_DATA</li>
///<li>HKEY_PERFORMANCE_DATA</li>
/// </ul>
/// </remarks>
/// <docgen category='Registry Options' order='10' />
[RequiredParameter]
public Layout Key { get; set; }
/// <summary>
/// Reads the specified registry key and value and appends it to
/// the passed <see cref="StringBuilder"/>.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event. Ignored.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
object registryValue = null;
// Value = null is necessary for querying "unnamed values"
string renderedValue = Value?.Render(logEvent);
var parseResult = ParseKey(Key.Render(logEvent));
try
{
#if !NET3_5
using (RegistryKey rootKey = RegistryKey.OpenBaseKey(parseResult.Hive, View))
#else
var rootKey = MapHiveToKey(parseResult.Hive);
#endif
{
if (parseResult.HasSubKey)
{
using (RegistryKey registryKey = rootKey.OpenSubKey(parseResult.SubKey))
{
if (registryKey != null) registryValue = registryKey.GetValue(renderedValue);
}
}
else
{
registryValue = rootKey.GetValue(renderedValue);
}
}
}
catch (Exception ex)
{
InternalLogger.Error("Error when writing to registry");
if (ex.MustBeRethrown())
{
throw;
}
}
string value = null;
if (registryValue != null) // valid value returned from registry will never be null
{
value = Convert.ToString(registryValue, CultureInfo.InvariantCulture);
}
else if (DefaultValue != null)
{
value = DefaultValue.Render(logEvent);
if (RequireEscapingSlashesInDefaultValue)
{
//remove escape slash
value = value.Replace("\\\\", "\\");
}
}
builder.Append(value);
}
private class ParseResult
{
public string SubKey { get; set; }
public RegistryHive Hive { get; set; }
/// <summary>
/// Has <see cref="SubKey"/>?
/// </summary>
public bool HasSubKey => !string.IsNullOrEmpty(SubKey);
}
/// <summary>
/// Parse key to <see cref="RegistryHive"/> and subkey.
/// </summary>
/// <param name="key">full registry key name</param>
/// <returns>Result of parsing, never <c>null</c>.</returns>
private static ParseResult ParseKey(string key)
{
string hiveName;
int pos = key.IndexOfAny(new char[] { '\\', '/' });
string subkey = null;
if (pos >= 0)
{
hiveName = key.Substring(0, pos);
//normalize slashes
subkey = key.Substring(pos + 1).Replace('/', '\\');
//remove starting slashes
subkey = subkey.TrimStart('\\');
//replace double slashes from pre-layout times
subkey = subkey.Replace("\\\\", "\\");
}
else
{
hiveName = key;
}
var hive = ParseHiveName(hiveName);
return new ParseResult
{
SubKey = subkey,
Hive = hive,
};
}
/// <summary>
/// Aliases for the hives. See https://msdn.microsoft.com/en-us/library/ctb3kd86(v=vs.110).aspx
/// </summary>
private static readonly Dictionary<string, RegistryHive> HiveAliases = new Dictionary<string, RegistryHive>(StringComparer.InvariantCultureIgnoreCase)
{
{"HKEY_LOCAL_MACHINE", RegistryHive.LocalMachine},
{"HKLM", RegistryHive.LocalMachine},
{"HKEY_CURRENT_USER", RegistryHive.CurrentUser},
{"HKCU", RegistryHive.CurrentUser},
{"HKEY_CLASSES_ROOT", RegistryHive.ClassesRoot},
{"HKEY_USERS", RegistryHive.Users},
{"HKEY_CURRENT_CONFIG", RegistryHive.CurrentConfig},
{"HKEY_DYN_DATA", RegistryHive.DynData},
{"HKEY_PERFORMANCE_DATA", RegistryHive.PerformanceData},
};
private static RegistryHive ParseHiveName(string hiveName)
{
RegistryHive hive;
if (HiveAliases.TryGetValue(hiveName, out hive))
{
return hive;
}
//ArgumentException is consistent
throw new ArgumentException($"Key name is not supported. Root hive '{hiveName}' not recognized.");
}
#if NET3_5
private static RegistryKey MapHiveToKey(RegistryHive hive)
{
switch (hive)
{
case RegistryHive.LocalMachine:
return Registry.LocalMachine;
case RegistryHive.CurrentUser:
return Registry.CurrentUser;
default:
throw new ArgumentException("Only RegistryHive.LocalMachine and RegistryHive.CurrentUser are supported.", nameof(hive));
}
}
#endif
}
}
#endif
| |
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocket.Portable.Interfaces;
using WebSocket.Portable.Internal;
using WebSocket.Portable.Tasks;
namespace WebSocket.Portable
{
public abstract class WebSocketClientBase<TWebSocket> : IDisposable, ICanLog
where TWebSocket : class, IWebSocket, new()
{
protected TWebSocket _webSocket;
private CancellationTokenSource _cts;
private int _maxFrameDataLength = Consts.MaxDefaultFrameDataLength;
public event Action Opened;
public event Action Closed;
public event Action<Exception> Error;
public event Action<IWebSocketFrame> FrameReceived;
public event Action<IWebSocketMessage> MessageReceived;
protected WebSocketClientBase()
{
this.AutoSendPongResponse = true;
}
~WebSocketClientBase()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
_webSocket.Dispose();
}
/// <summary>
/// Gets or sets a value indicating whether to send automatically pong frames when a ping is received.
/// </summary>
/// <value>
/// <c>true</c> if pong frames are send automatically; otherwise, <c>false</c>.
/// </value>
public bool AutoSendPongResponse { get; set; }
/// <summary>
/// Gets or sets the maximum length of data to be send in a single frame. If data is to be send is bigger, data will be fragmented.
/// </summary>
/// <value>
/// The maximum length of the frame data.
/// </value>
/// <exception cref="System.ArgumentOutOfRangeException">value</exception>
public int MaxFrameDataLength
{
get { return _maxFrameDataLength; }
set
{
if (_maxFrameDataLength == value)
return;
if (value <= 0 || value > Consts.MaxAllowedFrameDataLength)
throw new ArgumentOutOfRangeException("value", string.Format("Value must be between 1 and {0}", Consts.MaxAllowedFrameDataLength));
_maxFrameDataLength = value;
}
}
public Task OpenAsync(string uri)
{
return this.OpenAsync(uri, CancellationToken.None);
}
public async Task OpenAsync(string uri, CancellationToken cancellationToken)
{
if (_webSocket != null)
throw new InvalidOperationException("Client has been opened before.");
_webSocket = new TWebSocket();
await _webSocket.ConnectAsync(uri, cancellationToken);
await _webSocket.SendHandshakeAsync(cancellationToken);
this.ReceiveLoop();
this.OnOpened();
}
public Task CloseAsync()
{
return CloseInternal();
}
public Task CloseAsync(CancellationToken cancellationToken)
{
return CloseInternal();
}
private async Task CloseInternal()
{
if (_cts != null)
{
_cts.Cancel();
}
if (_webSocket != null)
{
await _webSocket.CloseAsync(WebSocketErrorCode.CloseNormal);
if (Closed != null)
{
Closed();
}
}
}
public Task SendAsync(string text)
{
return this.SendAsync(text, CancellationToken.None);
}
public Task SendAsync(string text, CancellationToken cancellationToken)
{
if (text == null)
throw new ArgumentNullException("text");
var bytes = Encoding.UTF8.GetBytes(text);
return SendAsync(false, bytes, 0, bytes.Length, cancellationToken);
}
public Task SendAsync(byte[] bytes, int offset, int length)
{
return SendAsync(bytes, offset, length, CancellationToken.None);
}
public Task SendAsync(byte[] bytes, int offset, int length, CancellationToken cancellationToken)
{
return SendAsync(true, bytes, offset, length, cancellationToken);
}
private Task SendAsync(bool isBinary, byte[] bytes, int offset, int length, CancellationToken cancellationToken)
{
var task = TaskAsyncHelper.Empty;
var max = MaxFrameDataLength;
var opcode = isBinary ? WebSocketOpcode.Binary : WebSocketOpcode.Text;
while (length > 0)
{
var size = Math.Min(length, max);
length -= size;
var frame = new WebSocketClientFrame
{
Opcode = opcode,
IsFin = length == 0,
};
frame.Payload = new WebSocketPayload(frame, bytes, offset, size);
offset += size;
opcode = WebSocketOpcode.Continuation;
task = task.Then(f => SendAsync(f, cancellationToken), frame);
}
return task;
}
private Task SendAsync(IWebSocketFrame frame, CancellationToken cancellationToken)
{
return _webSocket.SendFrameAsync(frame, cancellationToken);
}
protected virtual void OnError(Exception exception)
{
var handler = Error;
if (handler != null)
handler(exception);
}
protected virtual void OnOpened()
{
var handler = Opened;
if (handler != null)
handler();
}
protected virtual void OnFrameReceived(IWebSocketFrame frame)
{
var handler = this.FrameReceived;
if (handler != null)
handler(frame);
}
protected virtual void OnMessageReceived(IWebSocketMessage message)
{
var handler = this.MessageReceived;
if (handler != null)
handler(message);
}
void IDisposable.Dispose()
{
Dispose();
}
private async void ReceiveLoop()
{
_cts = new CancellationTokenSource();
WebSocketMessage currentMessage = null;
while (!_cts.IsCancellationRequested)
{
try
{
//BADREAD : Starting point.
var frame = await _webSocket.ReceiveFrameAsync(_cts.Token);
if (frame == null)
{
// todo
break;
}
OnFrameReceived(frame);
if (frame.Opcode == WebSocketOpcode.Close)
{
if (Closed != null)
{
await CloseAsync();
}
break;
}
if (frame.IsControlFrame)
{
// Handle ping frame
if (frame.Opcode == WebSocketOpcode.Ping && this.AutoSendPongResponse)
{
var pongFrame = new WebSocketClientFrame
{
Opcode = WebSocketOpcode.Pong,
Payload = frame.Payload
};
await SendAsync(pongFrame, _cts.Token);
}
}
else if (frame.IsDataFrame)
{
if (currentMessage != null)
throw new WebSocketException(WebSocketErrorCode.CloseInconstistentData);
currentMessage = new WebSocketMessage();
currentMessage.AddFrame(frame);
}
else if (frame.Opcode == WebSocketOpcode.Continuation)
{
if (currentMessage == null)
throw new WebSocketException(WebSocketErrorCode.CloseInconstistentData);
currentMessage.AddFrame(frame);
}
else
{
System.Diagnostics.Debug.WriteLine(String.Format("Other frame received: {0}", frame.Opcode));
this.LogDebug("Other frame received: {0}", frame.Opcode);
}
if (currentMessage != null && currentMessage.IsComplete)
{
OnMessageReceived(currentMessage);
currentMessage = null;
}
}
catch (WebSocketException wsex)
{
this.LogError("An web socket error occurred.", wsex);
this.OnError(wsex);
break;
}
catch (Exception ex)
{
this.LogError("An unexpected error occurred.", ex);
this.OnError(ex);
break;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Test.EditorUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public partial class TestWorkspaceFactory
{
/// <summary>
/// This place-holder value is used to set a project's file path to be null. It was explicitly chosen to be
/// convoluted to avoid any accidental usage (e.g., what if I really wanted FilePath to be the string "null"?),
/// obvious to anybody debugging that it is a special value, and invalid as an actual file path.
/// </summary>
public const string NullFilePath = "NullFilePath::{AFA13775-BB7D-4020-9E58-C68CF43D8A68}";
private class TestDocumentationProvider : DocumentationProvider
{
protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken))
{
return string.Format("<member name='{0}'><summary>{0}</summary></member>", documentationMemberID);
}
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj);
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
}
public static TestWorkspace CreateWorkspace(string xmlDefinition, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null)
{
return CreateWorkspace(XElement.Parse(xmlDefinition), completed, openDocuments, exportProvider);
}
public static TestWorkspace CreateWorkspace(
XElement workspaceElement,
bool completed = true,
bool openDocuments = true,
ExportProvider exportProvider = null,
string workspaceKind = null)
{
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
if (workspaceElement.Name != WorkspaceElementName)
{
throw new ArgumentException();
}
exportProvider = exportProvider ?? TestExportProvider.ExportProviderWithCSharpAndVisualBasic;
var workspace = new TestWorkspace(exportProvider, workspaceKind);
var projectMap = new Dictionary<string, TestHostProject>();
var documentElementToFilePath = new Dictionary<XElement, string>();
var projectElementToAssemblyName = new Dictionary<XElement, string>();
var filePathToTextBufferMap = new Dictionary<string, ITextBuffer>();
int projectIdentifier = 0;
int documentIdentifier = 0;
foreach (var projectElement in workspaceElement.Elements(ProjectElementName))
{
var project = CreateProject(
workspaceElement,
projectElement,
exportProvider,
workspace,
projectElementToAssemblyName,
documentElementToFilePath,
filePathToTextBufferMap,
ref projectIdentifier,
ref documentIdentifier);
Assert.False(projectMap.ContainsKey(project.AssemblyName));
projectMap.Add(project.AssemblyName, project);
workspace.Projects.Add(project);
}
var documentFilePaths = new HashSet<string>();
foreach (var project in projectMap.Values)
{
foreach (var document in project.Documents)
{
Assert.True(document.IsLinkFile || documentFilePaths.Add(document.FilePath));
}
}
var submissions = CreateSubmissions(workspace, workspaceElement.Elements(SubmissionElementName), exportProvider);
foreach (var submission in submissions)
{
projectMap.Add(submission.AssemblyName, submission);
}
var solution = new TestHostSolution(projectMap.Values.ToArray());
workspace.AddTestSolution(solution);
foreach (var projectElement in workspaceElement.Elements(ProjectElementName))
{
foreach (var projectReference in projectElement.Elements(ProjectReferenceElementName))
{
var fromName = projectElementToAssemblyName[projectElement];
var toName = projectReference.Value;
var fromProject = projectMap[fromName];
var toProject = projectMap[toName];
var aliases = projectReference.Attributes(AliasAttributeName).Select(a => a.Value).ToImmutableArray();
workspace.OnProjectReferenceAdded(fromProject.Id, new ProjectReference(toProject.Id, aliases.Any() ? aliases : default(ImmutableArray<string>)));
}
}
for (int i = 1; i < submissions.Count; i++)
{
if (submissions[i].CompilationOptions == null)
{
continue;
}
for (int j = i - 1; j >= 0; j--)
{
if (submissions[j].CompilationOptions != null)
{
workspace.OnProjectReferenceAdded(submissions[i].Id, new ProjectReference(submissions[j].Id));
break;
}
}
}
foreach (var project in projectMap.Values)
{
foreach (var document in project.Documents)
{
if (openDocuments)
{
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer(), isCurrentContext: !document.IsLinkFile);
}
workspace.Documents.Add(document);
}
}
return workspace;
}
private static IList<TestHostProject> CreateSubmissions(
TestWorkspace workspace,
IEnumerable<XElement> submissionElements,
ExportProvider exportProvider)
{
var submissions = new List<TestHostProject>();
var submissionIndex = 0;
foreach (var submissionElement in submissionElements)
{
var submissionName = "Submission" + (submissionIndex++);
var languageName = GetLanguage(workspace, submissionElement);
// The document
var markupCode = submissionElement.NormalizedValue();
string code;
int? cursorPosition;
IDictionary<string, IList<TextSpan>> spans;
MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans);
var languageServices = workspace.Services.GetLanguageServices(languageName);
var contentTypeLanguageService = languageServices.GetService<IContentTypeLanguageService>();
var contentType = contentTypeLanguageService.GetDefaultContentType();
var textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code);
// The project
var document = new TestHostDocument(exportProvider, languageServices, textBuffer, submissionName, cursorPosition, spans, SourceCodeKind.Interactive);
var documents = new List<TestHostDocument> { document };
if (languageName == NoCompilationConstants.LanguageName)
{
submissions.Add(
new TestHostProject(
languageServices,
compilationOptions: null,
parseOptions: null,
assemblyName: submissionName,
references: null,
documents: documents,
isSubmission: true));
continue;
}
var syntaxFactory = languageServices.GetService<ISyntaxTreeFactoryService>();
var compilationFactory = languageServices.GetService<ICompilationFactoryService>();
var compilationOptions = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary);
var parseOptions = syntaxFactory.GetDefaultParseOptions().WithKind(SourceCodeKind.Interactive);
var references = CreateCommonReferences(workspace, submissionElement);
var project = new TestHostProject(
languageServices,
compilationOptions,
parseOptions,
submissionName,
references,
documents,
isSubmission: true);
submissions.Add(project);
}
return submissions;
}
private static TestHostProject CreateProject(
XElement workspaceElement,
XElement projectElement,
ExportProvider exportProvider,
TestWorkspace workspace,
Dictionary<XElement, string> projectElementToAssemblyName,
Dictionary<XElement, string> documentElementToFilePath,
Dictionary<string, ITextBuffer> filePathToTextBufferMap,
ref int projectId,
ref int documentId)
{
var language = GetLanguage(workspace, projectElement);
var assemblyName = GetAssemblyName(workspace, projectElement, ref projectId);
projectElementToAssemblyName.Add(projectElement, assemblyName);
string filePath;
if (projectElement.Attribute(FilePathAttributeName) != null)
{
filePath = projectElement.Attribute(FilePathAttributeName).Value;
if (string.Compare(filePath, NullFilePath, StringComparison.Ordinal) == 0)
{
// allow explicit null file path
filePath = null;
}
}
else
{
filePath = assemblyName +
(language == LanguageNames.CSharp ? ".csproj" :
language == LanguageNames.VisualBasic ? ".vbproj" : ("." + language));
}
var contentTypeRegistryService = exportProvider.GetExportedValue<IContentTypeRegistryService>();
var languageServices = workspace.Services.GetLanguageServices(language);
var compilationOptions = CreateCompilationOptions(workspace, projectElement, language);
var parseOptions = GetParseOptions(projectElement, language, languageServices);
var references = CreateReferenceList(workspace, projectElement);
var analyzers = CreateAnalyzerList(workspace, projectElement);
var documents = new List<TestHostDocument>();
var documentElements = projectElement.Elements(DocumentElementName).ToList();
foreach (var documentElement in documentElements)
{
var document = CreateDocument(
workspace,
workspaceElement,
documentElement,
language,
exportProvider,
languageServices,
filePathToTextBufferMap,
ref documentId);
documents.Add(document);
documentElementToFilePath.Add(documentElement, document.FilePath);
}
return new TestHostProject(languageServices, compilationOptions, parseOptions, assemblyName, references, documents, filePath: filePath, analyzerReferences: analyzers);
}
private static ParseOptions GetParseOptions(XElement projectElement, string language, HostLanguageServices languageServices)
{
return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic
? GetParseOptionsWorker(projectElement, language, languageServices)
: null;
}
private static ParseOptions GetParseOptionsWorker(XElement projectElement, string language, HostLanguageServices languageServices)
{
ParseOptions parseOptions;
var preprocessorSymbolsAttribute = projectElement.Attribute(PreprocessorSymbolsAttributeName);
if (preprocessorSymbolsAttribute != null)
{
parseOptions = GetPreProcessorParseOptions(language, preprocessorSymbolsAttribute);
}
else
{
parseOptions = languageServices.GetService<ISyntaxTreeFactoryService>().GetDefaultParseOptions();
}
var languageVersionAttribute = projectElement.Attribute(LanguageVersionAttributeName);
if (languageVersionAttribute != null)
{
parseOptions = GetParseOptionsWithLanguageVersion(language, parseOptions, languageVersionAttribute);
}
var documentationMode = GetDocumentationMode(projectElement);
if (documentationMode != null)
{
parseOptions = parseOptions.WithDocumentationMode(documentationMode.Value);
}
return parseOptions;
}
private static ParseOptions GetPreProcessorParseOptions(string language, XAttribute preprocessorSymbolsAttribute)
{
if (language == LanguageNames.CSharp)
{
return new CSharpParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value.Split(','));
}
else if (language == LanguageNames.VisualBasic)
{
return new VisualBasicParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value
.Split(',').Select(v => KeyValuePair.Create(v.Split('=').ElementAt(0), (object)v.Split('=').ElementAt(1))).ToImmutableArray());
}
else
{
throw new ArgumentException("Unexpected language '{0}' for generating custom parse options.", language);
}
}
private static ParseOptions GetParseOptionsWithLanguageVersion(string language, ParseOptions parseOptions, XAttribute languageVersionAttribute)
{
if (language == LanguageNames.CSharp)
{
var languageVersion = (CodeAnalysis.CSharp.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.CSharp.LanguageVersion), languageVersionAttribute.Value);
parseOptions = ((CSharpParseOptions)parseOptions).WithLanguageVersion(languageVersion);
}
else if (language == LanguageNames.VisualBasic)
{
var languageVersion = (CodeAnalysis.VisualBasic.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.VisualBasic.LanguageVersion), languageVersionAttribute.Value);
parseOptions = ((VisualBasicParseOptions)parseOptions).WithLanguageVersion(languageVersion);
}
return parseOptions;
}
private static DocumentationMode? GetDocumentationMode(XElement projectElement)
{
var documentationModeAttribute = projectElement.Attribute(DocumentationModeAttributeName);
if (documentationModeAttribute != null)
{
return (DocumentationMode)Enum.Parse(typeof(DocumentationMode), documentationModeAttribute.Value);
}
else
{
return null;
}
}
private static string GetAssemblyName(TestWorkspace workspace, XElement projectElement, ref int projectId)
{
var assemblyNameAttribute = projectElement.Attribute(AssemblyNameAttributeName);
if (assemblyNameAttribute != null)
{
return assemblyNameAttribute.Value;
}
var language = GetLanguage(workspace, projectElement);
projectId++;
return language == LanguageNames.CSharp ? "CSharpAssembly" + projectId :
language == LanguageNames.VisualBasic ? "VisualBasicAssembly" + projectId :
language + "Assembly" + projectId;
}
private static string GetLanguage(TestWorkspace workspace, XElement projectElement)
{
string languageName = projectElement.Attribute(LanguageAttributeName).Value;
if (!workspace.Services.SupportedLanguages.Contains(languageName))
{
throw new ArgumentException(string.Format("Language should be one of '{0}' and it is {1}",
string.Join(", ", workspace.Services.SupportedLanguages),
languageName));
}
return languageName;
}
private static CompilationOptions CreateCompilationOptions(
TestWorkspace workspace,
XElement projectElement,
string language)
{
var compilationOptionsElement = projectElement.Element(CompilationOptionsElementName);
return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic
? CreateCompilationOptions(workspace, language, compilationOptionsElement)
: null;
}
private static CompilationOptions CreateCompilationOptions(TestWorkspace workspace, string language, XElement compilationOptionsElement)
{
var rootNamespace = new VisualBasicCompilationOptions(OutputKind.ConsoleApplication).RootNamespace;
var globalImports = new List<GlobalImport>();
var reportDiagnostic = ReportDiagnostic.Default;
if (compilationOptionsElement != null)
{
globalImports = compilationOptionsElement.Elements(GlobalImportElementName)
.Select(x => GlobalImport.Parse(x.Value)).ToList();
var rootNamespaceAttribute = compilationOptionsElement.Attribute(RootNamespaceAttributeName);
if (rootNamespaceAttribute != null)
{
rootNamespace = rootNamespaceAttribute.Value;
}
var reportDiagnosticAttribute = compilationOptionsElement.Attribute(ReportDiagnosticAttributeName);
if (reportDiagnosticAttribute != null)
{
reportDiagnostic = (ReportDiagnostic)Enum.Parse(typeof(ReportDiagnostic), (string)reportDiagnosticAttribute);
}
var outputTypeAttribute = compilationOptionsElement.Attribute(OutputTypeAttributeName);
if (outputTypeAttribute != null
&& outputTypeAttribute.Value == "WindowsRuntimeMetadata")
{
if (rootNamespaceAttribute == null)
{
rootNamespace = new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).RootNamespace;
}
return language == LanguageNames.CSharp
? (CompilationOptions)new CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata)
: new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).WithGlobalImports(globalImports)
.WithRootNamespace(rootNamespace);
}
}
else
{
// Add some common global imports by default for VB
globalImports.Add(GlobalImport.Parse("System"));
globalImports.Add(GlobalImport.Parse("System.Collections.Generic"));
globalImports.Add(GlobalImport.Parse("System.Linq"));
}
// TODO: Allow these to be specified.
var languageServices = workspace.Services.GetLanguageServices(language);
var compilationOptions = languageServices.GetService<ICompilationFactoryService>().GetDefaultCompilationOptions();
compilationOptions = compilationOptions.WithOutputKind(OutputKind.DynamicallyLinkedLibrary)
.WithGeneralDiagnosticOption(reportDiagnostic)
.WithSourceReferenceResolver(SourceFileResolver.Default)
.WithXmlReferenceResolver(XmlFileResolver.Default)
.WithMetadataReferenceResolver(new AssemblyReferenceResolver(MetadataFileReferenceResolver.Default, MetadataFileReferenceProvider.Default))
.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
if (language == LanguageNames.VisualBasic)
{
compilationOptions = ((VisualBasicCompilationOptions)compilationOptions).WithRootNamespace(rootNamespace)
.WithGlobalImports(globalImports);
}
return compilationOptions;
}
private static TestHostDocument CreateDocument(
TestWorkspace workspace,
XElement workspaceElement,
XElement documentElement,
string language,
ExportProvider exportProvider,
HostLanguageServices languageServiceProvider,
Dictionary<string, ITextBuffer> filePathToTextBufferMap,
ref int documentId)
{
string markupCode;
string filePath;
var isLinkFileAttribute = documentElement.Attribute(IsLinkFileAttributeName);
bool isLinkFile = isLinkFileAttribute != null && ((bool?)isLinkFileAttribute).HasValue && ((bool?)isLinkFileAttribute).Value;
if (isLinkFile)
{
// This is a linked file. Use the filePath and markup from the referenced document.
var originalProjectName = documentElement.Attribute(LinkAssemblyNameAttributeName);
var originalDocumentPath = documentElement.Attribute(LinkFilePathAttributeName);
if (originalProjectName == null || originalDocumentPath == null)
{
throw new ArgumentException("Linked file specified without LinkAssemblyName or LinkFilePath.");
}
var originalProjectNameStr = originalProjectName.Value;
var originalDocumentPathStr = originalDocumentPath.Value;
var originalProject = workspaceElement.Elements(ProjectElementName).First(p =>
{
var assemblyName = p.Attribute(AssemblyNameAttributeName);
return assemblyName != null && assemblyName.Value == originalProjectNameStr;
});
if (originalProject == null)
{
throw new ArgumentException("Linked file's LinkAssemblyName '{0}' project not found.", originalProjectNameStr);
}
var originalDocument = originalProject.Elements(DocumentElementName).First(d =>
{
var documentPath = d.Attribute(FilePathAttributeName);
return documentPath != null && documentPath.Value == originalDocumentPathStr;
});
if (originalDocument == null)
{
throw new ArgumentException("Linked file's LinkFilePath '{0}' file not found.", originalDocumentPathStr);
}
markupCode = originalDocument.NormalizedValue();
filePath = GetFilePath(workspace, originalDocument, ref documentId);
}
else
{
markupCode = documentElement.NormalizedValue();
filePath = GetFilePath(workspace, documentElement, ref documentId);
}
var folders = GetFolders(documentElement);
var optionsElement = documentElement.Element(ParseOptionsElementName);
// TODO: Allow these to be specified.
var codeKind = SourceCodeKind.Regular;
if (optionsElement != null)
{
var attr = optionsElement.Attribute(KindAttributeName);
codeKind = attr == null
? SourceCodeKind.Regular
: (SourceCodeKind)Enum.Parse(typeof(SourceCodeKind), attr.Value);
}
var contentTypeLanguageService = languageServiceProvider.GetService<IContentTypeLanguageService>();
var contentType = contentTypeLanguageService.GetDefaultContentType();
string code;
int? cursorPosition;
IDictionary<string, IList<TextSpan>> spans;
MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans);
// For linked files, use the same ITextBuffer for all linked documents
ITextBuffer textBuffer;
if (!filePathToTextBufferMap.TryGetValue(filePath, out textBuffer))
{
textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code);
filePathToTextBufferMap.Add(filePath, textBuffer);
}
return new TestHostDocument(exportProvider, languageServiceProvider, textBuffer, filePath, cursorPosition, spans, codeKind, folders, isLinkFile);
}
private static string GetFilePath(
TestWorkspace workspace,
XElement documentElement,
ref int documentId)
{
var filePathAttribute = documentElement.Attribute(FilePathAttributeName);
if (filePathAttribute != null)
{
return filePathAttribute.Value;
}
var language = GetLanguage(workspace, documentElement.Ancestors(ProjectElementName).Single());
documentId++;
var name = "Test" + documentId;
return language == LanguageNames.CSharp ? name + ".cs" : name + ".vb";
}
private static IReadOnlyList<string> GetFolders(XElement documentElement)
{
var folderAttribute = documentElement.Attribute(FoldersAttributeName);
if (folderAttribute == null)
{
return null;
}
var folderContainers = folderAttribute.Value.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
return new ReadOnlyCollection<string>(folderContainers.ToList());
}
/// <summary>
/// Takes completely valid code, compiles it, and emits it to a MetadataReference without using
/// the file system
/// </summary>
private static MetadataReference CreateMetadataReferenceFromSource(TestWorkspace workspace, XElement referencedSource)
{
var compilation = CreateCompilation(workspace, referencedSource);
var aliasElement = referencedSource.Attribute("Aliases") != null ? referencedSource.Attribute("Aliases").Value : null;
var aliases = aliasElement != null ? aliasElement.Split(',').Select(s => s.Trim()).ToImmutableArray() : default(ImmutableArray<string>);
bool includeXmlDocComments = false;
var includeXmlDocCommentsAttribute = referencedSource.Attribute(IncludeXmlDocCommentsAttributeName);
if (includeXmlDocCommentsAttribute != null &&
((bool?)includeXmlDocCommentsAttribute).HasValue &&
((bool?)includeXmlDocCommentsAttribute).Value)
{
includeXmlDocComments = true;
}
return MetadataReference.CreateFromImage(compilation.EmitToArray(), new MetadataReferenceProperties(aliases: aliases), includeXmlDocComments ? new DeferredDocumentationProvider(compilation) : null);
}
private static Compilation CreateCompilation(TestWorkspace workspace, XElement referencedSource)
{
string languageName = GetLanguage(workspace, referencedSource);
string assemblyName = "ReferencedAssembly";
var assemblyNameAttribute = referencedSource.Attribute(AssemblyNameAttributeName);
if (assemblyNameAttribute != null)
{
assemblyName = assemblyNameAttribute.Value;
}
var languageServices = workspace.Services.GetLanguageServices(languageName);
var compilationFactory = languageServices.GetService<ICompilationFactoryService>();
var options = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary);
var compilation = compilationFactory.CreateCompilation(assemblyName, options);
var documentElements = referencedSource.Elements(DocumentElementName).ToList();
foreach (var documentElement in documentElements)
{
compilation = compilation.AddSyntaxTrees(CreateSyntaxTree(languageName, documentElement.Value));
}
foreach (var reference in CreateReferenceList(workspace, referencedSource))
{
compilation = compilation.AddReferences(reference);
}
return compilation;
}
private static SyntaxTree CreateSyntaxTree(string languageName, string referencedCode)
{
if (LanguageNames.CSharp == languageName)
{
return Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(referencedCode);
}
else
{
return Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseSyntaxTree(referencedCode);
}
}
private static IList<MetadataReference> CreateReferenceList(TestWorkspace workspace, XElement element)
{
var references = CreateCommonReferences(workspace, element);
foreach (var reference in element.Elements(MetadataReferenceElementName))
{
references.Add(MetadataReference.CreateFromFile(reference.Value));
}
foreach (var metadataReferenceFromSource in element.Elements(MetadataReferenceFromSourceElementName))
{
references.Add(CreateMetadataReferenceFromSource(workspace, metadataReferenceFromSource));
}
return references;
}
private static IList<AnalyzerReference> CreateAnalyzerList(TestWorkspace workspace, XElement projectElement)
{
var analyzers = new List<AnalyzerReference>();
foreach (var analyzer in projectElement.Elements(AnalyzerElementName))
{
analyzers.Add(
new AnalyzerImageReference(
ImmutableArray<DiagnosticAnalyzer>.Empty,
display: (string)analyzer.Attribute(AnalyzerDisplayAttributeName),
fullPath: (string)analyzer.Attribute(AnalyzerFullPathAttributeName)));
}
return analyzers;
}
private static IList<MetadataReference> CreateCommonReferences(TestWorkspace workspace, XElement element)
{
var references = new List<MetadataReference>();
var net45 = element.Attribute(CommonReferencesNet45AttributeName);
if (net45 != null &&
((bool?)net45).HasValue &&
((bool?)net45).Value)
{
references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 };
if (GetLanguage(workspace, element) == LanguageNames.VisualBasic)
{
references.Add(TestBase.MsvbRef);
references.Add(TestBase.SystemXmlRef);
references.Add(TestBase.SystemXmlLinqRef);
}
}
var commonReferencesAttribute = element.Attribute(CommonReferencesAttributeName);
if (commonReferencesAttribute != null &&
((bool?)commonReferencesAttribute).HasValue &&
((bool?)commonReferencesAttribute).Value)
{
references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 };
if (GetLanguage(workspace, element) == LanguageNames.VisualBasic)
{
references.Add(TestBase.MsvbRef_v4_0_30319_17929);
references.Add(TestBase.SystemXmlRef);
references.Add(TestBase.SystemXmlLinqRef);
}
}
var winRT = element.Attribute(CommonReferencesWinRTAttributeName);
if (winRT != null &&
((bool?)winRT).HasValue &&
((bool?)winRT).Value)
{
references = new List<MetadataReference>(TestBase.WinRtRefs.Length);
references.AddRange(TestBase.WinRtRefs);
if (GetLanguage(workspace, element) == LanguageNames.VisualBasic)
{
references.Add(TestBase.MsvbRef_v4_0_30319_17929);
references.Add(TestBase.SystemXmlRef);
references.Add(TestBase.SystemXmlLinqRef);
}
}
var portable = element.Attribute(CommonReferencesPortableAttributeName);
if (portable != null &&
((bool?)portable).HasValue &&
((bool?)portable).Value)
{
references = new List<MetadataReference>(TestBase.PortableRefsMinimal.Length);
references.AddRange(TestBase.PortableRefsMinimal);
}
var systemRuntimeFacade = element.Attribute(CommonReferenceFacadeSystemRuntimeAttributeName);
if (systemRuntimeFacade != null &&
((bool?)systemRuntimeFacade).HasValue &&
((bool?)systemRuntimeFacade).Value)
{
references.Add(TestBase.SystemRuntimeFacadeRef);
}
return references;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc;
using FluentSecurity.Caching;
using FluentSecurity.Configuration;
using FluentSecurity.Diagnostics;
using FluentSecurity.Internals;
using FluentSecurity.Policy.ViolationHandlers.Conventions;
using FluentSecurity.Scanning;
using FluentSecurity.Scanning.TypeScanners;
using FluentSecurity.ServiceLocation;
namespace FluentSecurity
{
public abstract class ConfigurationExpression
{
public AdvancedConfiguration Advanced { get; private set; }
internal SecurityRuntime Runtime { get; private set; }
internal IPolicyAppender PolicyAppender { get; set; }
internal void Initialize(SecurityRuntime runtime)
{
Runtime = runtime;
Advanced = new AdvancedConfiguration(Runtime);
PolicyAppender = new DefaultPolicyAppender();
}
public IPolicyContainerConfiguration For<TController>(Expression<Func<TController, object>> actionExpression) where TController : Controller
{
var controllerName = typeof(TController).GetControllerName();
var actionName = actionExpression.GetActionName();
return AddPolicyContainerFor(controllerName, actionName);
}
public IPolicyContainerConfiguration For<TController>(Expression<Action<TController>> actionExpression) where TController : Controller
{
var controllerName = typeof(TController).GetControllerName();
var actionName = actionExpression.GetActionName();
return AddPolicyContainerFor(controllerName, actionName);
}
public IPolicyContainerConfiguration For<TController>() where TController : Controller
{
var controllerType = typeof(TController);
var controllerTypes = new[] { controllerType };
return CreateConventionPolicyContainerFor(controllerTypes, defaultCacheLevel: By.Controller);
}
public virtual IPolicyContainerConfiguration ForAllControllers()
{
var assemblyScanner = new AssemblyScanner();
assemblyScanner.TheCallingAssembly();
assemblyScanner.With<ControllerTypeScanner>();
var controllerTypes = assemblyScanner.Scan();
return CreateConventionPolicyContainerFor(controllerTypes);
}
public IPolicyContainerConfiguration ForAllControllersInAssembly(params Assembly[] assemblies)
{
var assemblyScanner = new AssemblyScanner();
assemblyScanner.Assemblies(assemblies);
assemblyScanner.With<ControllerTypeScanner>();
var controllerTypes = assemblyScanner.Scan();
return CreateConventionPolicyContainerFor(controllerTypes);
}
public IPolicyContainerConfiguration ForAllControllersInAssemblyContainingType<TType>()
{
var assembly = typeof (TType).Assembly;
return ForAllControllersInAssembly(assembly);
}
public IPolicyContainerConfiguration ForAllControllersInheriting<TController>(Expression<Func<TController, object>> actionExpression, params Assembly[] assemblies) where TController : Controller
{
if (actionExpression == null) throw new ArgumentNullException("actionExpression");
var actionName = actionExpression.GetActionName();
return ForAllControllersInheriting<TController>(action => action == actionName, assemblies);
}
public IPolicyContainerConfiguration ForAllControllersInheriting<TController>(params Assembly[] assemblies) where TController : Controller
{
Func<string, bool> actionFilter = actionName => true;
return ForAllControllersInheriting<TController>(actionFilter, assemblies);
}
private IPolicyContainerConfiguration ForAllControllersInheriting<TController>(Func<string, bool> actionFilter, IEnumerable<Assembly> assemblies) where TController : Controller
{
var controllerType = typeof (TController);
var assembliesToScan = assemblies.ToList();
if (!assembliesToScan.Any())
assembliesToScan.Add(controllerType.Assembly);
var assemblyScanner = new AssemblyScanner();
assemblyScanner.Assemblies(assembliesToScan);
assemblyScanner.With(new ControllerTypeScanner(controllerType));
var controllerTypes = assemblyScanner.Scan();
Func<ControllerActionInfo, bool> filter = info => actionFilter.Invoke(info.ActionName);
return CreateConventionPolicyContainerFor(controllerTypes, filter);
}
public IPolicyContainerConfiguration ForAllControllersInNamespaceContainingType<TType>()
{
var assembly = typeof (TType).Assembly;
var assemblyScanner = new AssemblyScanner();
assemblyScanner.Assembly(assembly);
assemblyScanner.With<ControllerTypeScanner>();
assemblyScanner.IncludeNamespaceContainingType<TType>();
var controllerTypes = assemblyScanner.Scan();
return CreateConventionPolicyContainerFor(controllerTypes);
}
public IPolicyContainerConfiguration ForActionsMatching(Func<ControllerActionInfo, bool> actionFilter, params Assembly[] assemblies)
{
var assemblyScanner = new AssemblyScanner();
var assembliesToScan = assemblies.ToList();
if (assembliesToScan.Any())
assemblyScanner.Assemblies(assemblies);
else
assemblyScanner.TheCallingAssembly();
assemblyScanner.With<ControllerTypeScanner>();
var controllerTypes = assemblyScanner.Scan();
return CreateConventionPolicyContainerFor(controllerTypes, actionFilter);
}
public void Scan(Action<ProfileScanner> scan)
{
Publish.ConfigurationEvent(() => "Scanning for profiles");
var profileScanner = new ProfileScanner();
scan.Invoke(profileScanner);
var profiles = profileScanner.Scan().ToList();
profiles.ForEach(ApplyProfile);
}
public void ApplyProfile<TSecurityProfile>() where TSecurityProfile : SecurityProfile, new()
{
var profile = new TSecurityProfile();
Publish.ConfigurationEvent(() => "Applying profile {0}.".FormatWith(profile.GetType().FullName));
Runtime.ApplyConfiguration(profile);
}
private void ApplyProfile(Type profileType)
{
var profile = Activator.CreateInstance(profileType) as SecurityProfile;
if (profile != null)
{
Publish.ConfigurationEvent(() => "Applying profile {0}.".FormatWith(profile.GetType().FullName));
Runtime.ApplyConfiguration(profile);
}
}
internal IPolicyContainerConfiguration CreateConventionPolicyContainerFor(IEnumerable<Type> controllerTypes, Func<ControllerActionInfo, bool> actionFilter = null, By defaultCacheLevel = By.Policy)
{
var policyContainers = new List<IPolicyContainerConfiguration>();
foreach (var controllerType in controllerTypes)
{
var controllerName = controllerType.GetControllerName();
var actionMethods = controllerType.GetActionMethods(actionFilter);
policyContainers.AddRange(
actionMethods.Select(actionMethod => AddPolicyContainerFor(controllerName, actionMethod.GetActionName()))
);
}
return new ConventionPolicyContainer(policyContainers, defaultCacheLevel);
}
private PolicyContainer AddPolicyContainerFor(string controllerName, string actionName)
{
return Runtime.AddPolicyContainer(new PolicyContainer(controllerName, actionName, PolicyAppender));
}
public void GetAuthenticationStatusFrom(Func<bool> authenticationExpression)
{
if (authenticationExpression == null)
throw new ArgumentNullException("authenticationExpression");
Runtime.IsAuthenticated = authenticationExpression;
}
public void GetRolesFrom(Func<IEnumerable<object>> rolesExpression)
{
if (rolesExpression == null)
throw new ArgumentNullException("rolesExpression");
if (Runtime.PolicyContainers.Any())
throw new ConfigurationErrorsException("You must set the rolesfunction before adding policies.");
Runtime.Roles = rolesExpression;
}
public void SetPolicyAppender(IPolicyAppender policyAppender)
{
if (policyAppender == null)
throw new ArgumentNullException("policyAppender");
PolicyAppender = policyAppender;
}
public void ResolveServicesUsing(Func<Type, IEnumerable<object>> servicesLocator, Func<Type, object> singleServiceLocator = null)
{
if (servicesLocator == null)
throw new ArgumentNullException("servicesLocator");
ResolveServicesUsing(new ExternalServiceLocator(servicesLocator, singleServiceLocator));
}
public void ResolveServicesUsing(ISecurityServiceLocator securityServiceLocator)
{
if (securityServiceLocator == null)
throw new ArgumentNullException("securityServiceLocator");
Runtime.ExternalServiceLocator = securityServiceLocator;
}
public void DefaultPolicyViolationHandlerIs<TPolicyViolationHandler>() where TPolicyViolationHandler : class, IPolicyViolationHandler
{
RemoveDefaultPolicyViolationHandlerConventions();
Advanced.Conventions(conventions =>
conventions.Add(new DefaultPolicyViolationHandlerIsOfTypeConvention<TPolicyViolationHandler>())
);
}
public void DefaultPolicyViolationHandlerIs<TPolicyViolationHandler>(Func<TPolicyViolationHandler> policyViolationHandler) where TPolicyViolationHandler : class, IPolicyViolationHandler
{
RemoveDefaultPolicyViolationHandlerConventions();
Advanced.Conventions(conventions =>
conventions.Add(new DefaultPolicyViolationHandlerIsInstanceConvention<TPolicyViolationHandler>(policyViolationHandler))
);
}
private void RemoveDefaultPolicyViolationHandlerConventions()
{
Advanced.Conventions(conventions =>
{
conventions.RemoveAll(c => c is FindDefaultPolicyViolationHandlerByNameConvention);
conventions.RemoveAll(c => c.IsMatchForGenericType(typeof (DefaultPolicyViolationHandlerIsOfTypeConvention<>)));
conventions.RemoveAll(c => c.IsMatchForGenericType(typeof (DefaultPolicyViolationHandlerIsInstanceConvention<>)));
});
}
}
}
| |
// Zlib.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2009-November-07 05:26:55>
//
// ------------------------------------------------------------------
//
// This module defines classes for ZLIB compression and
// decompression. This code is derived from the jzlib implementation of
// zlib, but significantly modified. The object model is not the same,
// and many of the behaviors are new or different. Nonetheless, in
// keeping with the license for jzlib, the copyright to that code is
// included below.
//
// ------------------------------------------------------------------
//
// Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the distribution.
//
// 3. The names of the authors may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
// INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// -----------------------------------------------------------------------
//
// This program is based on zlib-1.1.3; credit to authors
// Jean-loup Gailly([email protected]) and Mark Adler([email protected])
// and contributors of zlib.
//
// -----------------------------------------------------------------------
namespace SharpCompress.Compressor.Deflate
{
/// <summary>
/// The compression level to be used when using a DeflateStream or ZlibStream with CompressionMode.Compress.
/// </summary>
public enum CompressionLevel
{
/// <summary>
/// None means that the data will be simply stored, with no change at all.
/// If you are producing ZIPs for use on Mac OSX, be aware that archives produced with CompressionLevel.None
/// cannot be opened with the default zip reader. Use a different CompressionLevel.
/// </summary>
None = 0,
/// <summary>
/// Same as None.
/// </summary>
Level0 = 0,
/// <summary>
/// The fastest but least effective compression.
/// </summary>
BestSpeed = 1,
/// <summary>
/// A synonym for BestSpeed.
/// </summary>
Level1 = 1,
/// <summary>
/// A little slower, but better, than level 1.
/// </summary>
Level2 = 2,
/// <summary>
/// A little slower, but better, than level 2.
/// </summary>
Level3 = 3,
/// <summary>
/// A little slower, but better, than level 3.
/// </summary>
Level4 = 4,
/// <summary>
/// A little slower than level 4, but with better compression.
/// </summary>
Level5 = 5,
/// <summary>
/// The default compression level, with a good balance of speed and compression efficiency.
/// </summary>
Default = 6,
/// <summary>
/// A synonym for Default.
/// </summary>
Level6 = 6,
/// <summary>
/// Pretty good compression!
/// </summary>
Level7 = 7,
/// <summary>
/// Better compression than Level7!
/// </summary>
Level8 = 8,
/// <summary>
/// The "best" compression, where best means greatest reduction in size of the input data stream.
/// This is also the slowest compression.
/// </summary>
BestCompression = 9,
/// <summary>
/// A synonym for BestCompression.
/// </summary>
Level9 = 9,
}
/// <summary>
/// Describes options for how the compression algorithm is executed. Different strategies
/// work better on different sorts of data. The strategy parameter can affect the compression
/// ratio and the speed of compression but not the correctness of the compresssion.
/// </summary>
public enum CompressionStrategy
{
/// <summary>
/// The default strategy is probably the best for normal data.
/// </summary>
Default = 0,
/// <summary>
/// The <c>Filtered</c> strategy is intended to be used most effectively with data produced by a
/// filter or predictor. By this definition, filtered data consists mostly of small
/// values with a somewhat random distribution. In this case, the compression algorithm
/// is tuned to compress them better. The effect of <c>Filtered</c> is to force more Huffman
/// coding and less string matching; it is a half-step between <c>Default</c> and <c>HuffmanOnly</c>.
/// </summary>
Filtered = 1,
/// <summary>
/// Using <c>HuffmanOnly</c> will force the compressor to do Huffman encoding only, with no
/// string matching.
/// </summary>
HuffmanOnly = 2,
}
/// <summary>
/// A general purpose exception class for exceptions in the Zlib library.
/// </summary>
public class ZlibException : System.Exception
{
/// <summary>
/// The ZlibException class captures exception information generated
/// by the Zlib library.
/// </summary>
public ZlibException()
: base()
{
}
/// <summary>
/// This ctor collects a message attached to the exception.
/// </summary>
/// <param name="s"></param>
public ZlibException(System.String s)
: base(s)
{
}
}
internal class SharedUtils
{
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static int URShift(int number, int bits)
{
return (int) ((uint) number >> bits);
}
#if NOT
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static long URShift(long number, int bits)
{
return (long) ((UInt64)number >> bits);
}
#endif
/// <summary>
/// Reads a number of characters from the current source TextReader and writes
/// the data to the target array at the specified index.
/// </summary>
///
/// <param name="sourceTextReader">The source TextReader to read from</param>
/// <param name="target">Contains the array of characteres read from the source TextReader.</param>
/// <param name="start">The starting index of the target array.</param>
/// <param name="count">The maximum number of characters to read from the source TextReader.</param>
///
/// <returns>
/// The number of characters read. The number will be less than or equal to
/// count depending on the data available in the source TextReader. Returns -1
/// if the end of the stream is reached.
/// </returns>
public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count)
{
// Returns 0 bytes if not enough space in target
if (target.Length == 0) return 0;
char[] charArray = new char[target.Length];
int bytesRead = sourceTextReader.Read(charArray, start, count);
// Returns -1 if EOF
if (bytesRead == 0) return -1;
for (int index = start; index < start + bytesRead; index++)
target[index] = (byte) charArray[index];
return bytesRead;
}
}
internal static class InternalConstants
{
internal static readonly int MAX_BITS = 15;
internal static readonly int BL_CODES = 19;
internal static readonly int D_CODES = 30;
internal static readonly int LITERALS = 256;
internal static readonly int LENGTH_CODES = 29;
internal static readonly int L_CODES = (LITERALS + 1 + LENGTH_CODES);
// Bit length codes must not exceed MAX_BL_BITS bits
internal static readonly int MAX_BL_BITS = 7;
// repeat previous bit length 3-6 times (2 bits of repeat count)
internal static readonly int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
internal static readonly int REPZ_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
internal static readonly int REPZ_11_138 = 18;
}
internal sealed class StaticTree
{
internal static readonly short[] lengthAndLiteralsTreeCodes = new short[]
{
12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172,
8, 108, 8, 236, 8,
28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188,
8, 124, 8, 252, 8,
2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8
, 98, 8, 226, 8,
18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178,
8, 114, 8, 242, 8,
10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170,
8, 106, 8, 234, 8,
26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186,
8, 122, 8, 250, 8,
6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8
, 102, 8, 230, 8,
22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182,
8, 118, 8, 246, 8,
14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174,
8, 110, 8, 238, 8,
30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190,
8, 126, 8, 254, 8,
1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8
, 97, 8, 225, 8,
17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177,
8, 113, 8, 241, 8,
9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8
, 105, 8, 233, 8,
25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185,
8, 121, 8, 249, 8,
5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8
, 101, 8, 229, 8,
21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181,
8, 117, 8, 245, 8,
13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173,
8, 109, 8, 237, 8,
29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189,
8, 125, 8, 253, 8,
19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339,
9, 211, 9, 467, 9,
51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371
, 9, 243, 9, 499, 9,
11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331,
9, 203, 9, 459, 9,
43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363
, 9, 235, 9, 491, 9,
27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347,
9, 219, 9, 475, 9,
59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379
, 9, 251, 9, 507, 9,
7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327,
9, 199, 9, 455, 9,
39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359
, 9, 231, 9, 487, 9,
23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343,
9, 215, 9, 471, 9,
55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375
, 9, 247, 9, 503, 9,
15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335,
9, 207, 9, 463, 9,
47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367
, 9, 239, 9, 495, 9,
31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351,
9, 223, 9, 479, 9,
63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383
, 9, 255, 9, 511, 9,
0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7,
48, 7, 112, 7,
8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7,
56, 7, 120, 7,
4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7,
52, 7, 116, 7,
3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8
, 99, 8, 227, 8
};
internal static readonly short[] distTreeCodes = new short[]
{
0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5,
2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5,
1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5,
3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5
};
// extra bits for each bit length code
internal static readonly int[] extra_blbits = new int[]
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7};
internal static readonly StaticTree Literals;
internal static readonly StaticTree Distances;
internal static readonly StaticTree BitLengths;
internal short[] treeCodes; // static tree or null
internal int[] extraBits; // extra bits for each code or null
internal int extraBase; // base index for extra_bits
internal int elems; // max number of elements in the tree
internal int maxLength; // max bit length for the codes
private StaticTree(short[] treeCodes, int[] extraBits, int extraBase, int elems, int maxLength)
{
this.treeCodes = treeCodes;
this.extraBits = extraBits;
this.extraBase = extraBase;
this.elems = elems;
this.maxLength = maxLength;
}
static StaticTree()
{
Literals = new StaticTree(lengthAndLiteralsTreeCodes, DeflateManager.ExtraLengthBits,
InternalConstants.LITERALS + 1, InternalConstants.L_CODES,
InternalConstants.MAX_BITS);
Distances = new StaticTree(distTreeCodes, DeflateManager.ExtraDistanceBits, 0, InternalConstants.D_CODES,
InternalConstants.MAX_BITS);
BitLengths = new StaticTree(null, extra_blbits, 0, InternalConstants.BL_CODES, InternalConstants.MAX_BL_BITS);
}
}
/// <summary>
/// Computes an Adler-32 checksum.
/// </summary>
/// <remarks>
/// The Adler checksum is similar to a CRC checksum, but faster to compute, though less
/// reliable. It is used in producing RFC1950 compressed streams. The Adler checksum
/// is a required part of the "ZLIB" standard. Applications will almost never need to
/// use this class directly.
/// </remarks>
internal sealed class Adler
{
// largest prime smaller than 65536
private static readonly int BASE = 65521;
// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
private static readonly int NMAX = 5552;
internal static uint Adler32(uint adler, byte[] buf, int index, int len)
{
if (buf == null)
return 1;
int s1 = (int) (adler & 0xffff);
int s2 = (int) ((adler >> 16) & 0xffff);
while (len > 0)
{
int k = len < NMAX ? len : NMAX;
len -= k;
while (k >= 16)
{
//s1 += (buf[index++] & 0xff); s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
k -= 16;
}
if (k != 0)
{
do
{
s1 += buf[index++];
s2 += s1;
} while (--k != 0);
}
s1 %= BASE;
s2 %= BASE;
}
return (uint) ((s2 << 16) | s1);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using Xunit;
using System.Reflection;
namespace System.Diagnostics.TraceSourceTests
{
public sealed class TraceListenerCollectionClassTests
: ListBaseTests<TraceListenerCollection>
{
public override TraceListenerCollection Create(int count = 0)
{
// TraceListenerCollection has an internal constructor
// so we use a TraceSource to create one for us.
var list = new TraceSource("Test").Listeners;
list.Clear();
for (int i = 0; i < count; i++)
{
list.Add(CreateListener());
}
return list;
}
public TraceListener CreateListener()
{
return new TestTraceListener();
}
public override object CreateItem()
{
return CreateListener();
}
public override bool IsReadOnly
{
get { return false; }
}
public override bool IsFixedSize
{
get { return false; }
}
public override bool IsSynchronized
{
get { return true; }
}
[Fact]
public void TraceListenerIndexerTest()
{
var list = Create();
var item = CreateListener();
list.Add(item);
Assert.Equal(item, list[0]);
item = CreateListener();
list[0] = item;
Assert.Equal(item, list[0]);
}
[Fact]
public void TraceListenerNameIndexerTest()
{
var list = Create();
var item = CreateListener();
item.Name = "TestListener";
list.Add(item);
Assert.Equal(item, list["TestListener"]);
Assert.Equal(null, list["NO_EXIST"]);
}
[Fact]
public void AddListenerTest()
{
var list = Create();
var item = CreateListener();
list.Add(item);
Assert.Equal(item, list[0]);
Assert.Throws<ArgumentNullException>(() => list.Add(null));
Assert.Equal(1, list.Count);
}
[Fact]
public void AddRangeArrayTest()
{
var list = Create();
Assert.Throws<ArgumentNullException>(() => list.AddRange((TraceListener[])null));
var items =
new TraceListener[] {
CreateListener(),
CreateListener(),
};
list.AddRange(items);
Assert.Equal(items[0], list[0]);
Assert.Equal(items[1], list[1]);
}
[Fact]
public void AddRangeCollectionTest()
{
var list = Create();
Assert.Throws<ArgumentNullException>(() => list.AddRange((TraceListenerCollection)null));
var items = Create();
var item0 = CreateListener();
var item1 = CreateListener();
items.Add(item0);
items.Add(item1);
list.AddRange(items);
Assert.Equal(item0, list[0]);
Assert.Equal(item1, list[1]);
}
[Fact]
public void ContainsTest()
{
var list = Create();
var item = CreateListener();
list.Add(item);
Assert.True(list.Contains(item));
item = CreateListener();
Assert.False(list.Contains(item));
Assert.False(list.Contains(null));
}
[Fact]
public void CopyToListenerTest()
{
var list = Create(2);
var arr = new TraceListener[4];
list.CopyTo(arr, 1);
Assert.Null(arr[0]);
Assert.Equal(arr[1], list[0]);
Assert.Equal(arr[2], list[1]);
Assert.Null(arr[3]);
}
[Fact]
public void IndexOfListenerTest()
{
var list = Create(2);
var item = CreateListener();
list.Insert(1, item);
var idx = list.IndexOf(item);
Assert.Equal(1, idx);
idx = list.IndexOf(null);
Assert.Equal(-1, idx);
item = CreateListener();
idx = list.IndexOf(item);
Assert.Equal(-1, idx);
}
[Fact]
public void InsertListenerTest()
{
var list = Create(2);
var item = CreateListener();
list.Insert(1, item);
Assert.Equal(3, list.Count);
Assert.Equal(item, list[1]);
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(5, item));
}
[Fact]
public void RemoveListenerTest()
{
var list = Create();
var item = new TestTraceListener("Test1");
list.Add(item);
Assert.Equal(1, list.Count);
list.Remove(item);
Assert.Equal(0, list.Count);
}
[Fact]
public void RemoveAtTest()
{
var list = Create();
var item = new TestTraceListener("Test1");
list.Add(item);
list.RemoveAt(0);
Assert.False(list.Contains(item));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1));
}
[Fact]
public void RemoveByNameTest()
{
var list = Create();
var item = new TestTraceListener("Test1");
list.Add(item);
Assert.Equal(1, list.Count);
list.Remove("NO_EXIST");
Assert.Equal(1, list.Count);
list.Remove("Test1");
Assert.Equal(0, list.Count);
}
}
public abstract class ListBaseTests<T> : CollectionBaseTests<T>
where T : IList
{
public abstract bool IsReadOnly { get; }
public abstract bool IsFixedSize { get; }
public virtual Object CreateNonItem()
{
return new Object();
}
[Fact]
public virtual void AddTest()
{
var list = Create();
var item = CreateItem();
if (IsReadOnly || IsFixedSize)
{
Assert.Throws<NotSupportedException>(() => list.Add(item));
}
else
{
list.Add(item);
Assert.Equal(item, list[0]);
}
}
[Fact]
public virtual void AddExceptionTest()
{
var list = Create();
var item = CreateNonItem();
if (IsReadOnly || IsFixedSize)
{
Assert.Throws<NotSupportedException>(() => list.Add(item));
}
else
{
Assert.Throws<ArgumentException>(() => list.Add(item));
}
}
[Fact]
public virtual void IndexerGetTest()
{
var list = Create();
var item = CreateItem();
list.Add(item);
Assert.Equal(item, list[0]);
var item2 = CreateItem();
list[0] = item2;
Assert.Equal(item2, list[0]);
}
[Fact]
public virtual void IndexerSetTest()
{
var list = Create(3);
var item = CreateItem();
if (IsReadOnly)
{
Assert.Throws<NotSupportedException>(() => list[1] = item);
}
else
{
list[1] = item;
Assert.Equal(item, list[1]);
var nonItem = CreateNonItem();
Assert.Throws<ArgumentException>(() => list[1] = nonItem);
}
}
[Fact]
public virtual void IndexOfTest()
{
var list = Create();
var item0 = CreateItem();
list.Add(item0);
var item1 = CreateItem();
list.Add(item1);
Assert.Equal(0, list.IndexOf(item0));
Assert.Equal(1, list.IndexOf(item1));
var itemN = CreateItem();
Assert.Equal(-1, list.IndexOf(itemN));
}
[Fact]
public virtual void InsertTest()
{
var list = Create(2);
var item = CreateItem();
list.Insert(1, item);
Assert.Equal(3, list.Count);
Assert.Equal(item, list[1]);
}
[Fact]
public virtual void InsertExceptionTest()
{
var list = Create(2);
Assert.Throws<ArgumentException>(() => list.Insert(1, null));
}
[Fact]
public virtual void InsertExceptionTest2()
{
var list = Create(2);
var item = CreateItem();
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, item));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(4, item));
}
[Fact]
public virtual void RemoveTest()
{
var list = Create();
var item = CreateItem();
list.Add(item);
Assert.True(list.Contains(item));
list.Remove(item);
Assert.False(list.Contains(item));
}
[Fact]
public virtual void IsReadOnlyTest()
{
var list = Create();
Assert.Equal(IsReadOnly, list.IsReadOnly);
}
[Fact]
public virtual void IsFixedSizeTest()
{
var list = Create();
Assert.Equal(IsFixedSize, list.IsFixedSize);
}
}
public abstract class CollectionBaseTests<T>
: EnumerableBaseTests<T>
where T : ICollection
{
public abstract bool IsSynchronized { get; }
[Fact]
public virtual void CountTest()
{
var list = Create();
Assert.Equal(0, list.Count);
}
[Fact]
public virtual void SyncRootTest()
{
var list = Create();
var sync1 = list.SyncRoot;
Assert.NotNull(sync1);
var sync2 = list.SyncRoot;
Assert.NotNull(sync2);
Assert.Equal(sync1, sync2);
}
[Fact]
public virtual void IsSynchronizedTest()
{
var list = Create();
var value = list.IsSynchronized;
var expected = IsSynchronized;
Assert.Equal(expected, value);
}
[Fact]
public virtual void CopyToTest()
{
var list = Create(4);
var arr = new Object[4];
list.CopyTo(arr, 0);
}
[Fact]
public virtual void CopyToTest2()
{
var list = Create(4);
var arr = new Object[6];
list.CopyTo(arr, 2);
Assert.Null(arr[0]);
Assert.Null(arr[1]);
}
[Fact]
public virtual void CopyToExceptionTest()
{
var list = Create(4);
var arr = new Object[2];
Assert.Throws<ArgumentException>(() => list.CopyTo(arr, 0));
}
}
public abstract class EnumerableBaseTests<T>
where T : IEnumerable
{
public abstract T Create(int count = 0);
public abstract Object CreateItem();
[Fact]
public virtual void GetEnumeratorEmptyTest()
{
var list = Create();
var enumerator = list.GetEnumerator();
Assert.NotNull(enumerator);
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
var more = enumerator.MoveNext();
Assert.False(more);
more = enumerator.MoveNext();
Assert.False(more);
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
[Fact]
public virtual void GetEnumeratorTest()
{
var list = Create(2);
var enumerator = list.GetEnumerator();
Assert.NotNull(enumerator);
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
var more = enumerator.MoveNext();
Assert.True(more);
var item = enumerator.Current;
more = enumerator.MoveNext();
Assert.True(more);
more = enumerator.MoveNext();
Assert.False(more);
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
}
}
| |
using System;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ChargeBee.Internal;
using ChargeBee.Api;
using ChargeBee.Models.Enums;
using ChargeBee.Filters.Enums;
namespace ChargeBee.Models
{
public class ItemPrice : Resource
{
public ItemPrice() { }
public ItemPrice(Stream stream)
{
using (StreamReader reader = new StreamReader(stream))
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
}
public ItemPrice(TextReader reader)
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
public ItemPrice(String jsonString)
{
JObj = JToken.Parse(jsonString);
apiVersionCheck (JObj);
}
#region Methods
public static CreateRequest Create()
{
string url = ApiUtil.BuildUrl("item_prices");
return new CreateRequest(url, HttpMethod.POST);
}
public static EntityRequest<Type> Retrieve(string id)
{
string url = ApiUtil.BuildUrl("item_prices", CheckNull(id));
return new EntityRequest<Type>(url, HttpMethod.GET);
}
public static UpdateRequest Update(string id)
{
string url = ApiUtil.BuildUrl("item_prices", CheckNull(id));
return new UpdateRequest(url, HttpMethod.POST);
}
public static ItemPriceListRequest List()
{
string url = ApiUtil.BuildUrl("item_prices");
return new ItemPriceListRequest(url);
}
public static EntityRequest<Type> Delete(string id)
{
string url = ApiUtil.BuildUrl("item_prices", CheckNull(id), "delete");
return new EntityRequest<Type>(url, HttpMethod.POST);
}
public static ItemPriceFindApplicableItemsRequest FindApplicableItems(string id)
{
string url = ApiUtil.BuildUrl("item_prices", CheckNull(id), "applicable_items");
return new ItemPriceFindApplicableItemsRequest(url);
}
public static ItemPriceFindApplicableItemPricesRequest FindApplicableItemPrices(string id)
{
string url = ApiUtil.BuildUrl("item_prices", CheckNull(id), "applicable_item_prices");
return new ItemPriceFindApplicableItemPricesRequest(url);
}
#endregion
#region Properties
public string Id
{
get { return GetValue<string>("id", true); }
}
public string Name
{
get { return GetValue<string>("name", true); }
}
public string ItemFamilyId
{
get { return GetValue<string>("item_family_id", false); }
}
public string ItemId
{
get { return GetValue<string>("item_id", false); }
}
public string Description
{
get { return GetValue<string>("description", false); }
}
public StatusEnum? Status
{
get { return GetEnum<StatusEnum>("status", false); }
}
public string ExternalName
{
get { return GetValue<string>("external_name", false); }
}
public PricingModelEnum PricingModel
{
get { return GetEnum<PricingModelEnum>("pricing_model", true); }
}
public int? Price
{
get { return GetValue<int?>("price", false); }
}
public string PriceInDecimal
{
get { return GetValue<string>("price_in_decimal", false); }
}
public int? Period
{
get { return GetValue<int?>("period", false); }
}
public string CurrencyCode
{
get { return GetValue<string>("currency_code", true); }
}
public PeriodUnitEnum? PeriodUnit
{
get { return GetEnum<PeriodUnitEnum>("period_unit", false); }
}
public int? TrialPeriod
{
get { return GetValue<int?>("trial_period", false); }
}
public TrialPeriodUnitEnum? TrialPeriodUnit
{
get { return GetEnum<TrialPeriodUnitEnum>("trial_period_unit", false); }
}
public TrialEndActionEnum? TrialEndAction
{
get { return GetEnum<TrialEndActionEnum>("trial_end_action", false); }
}
public int? ShippingPeriod
{
get { return GetValue<int?>("shipping_period", false); }
}
public ShippingPeriodUnitEnum? ShippingPeriodUnit
{
get { return GetEnum<ShippingPeriodUnitEnum>("shipping_period_unit", false); }
}
public int? BillingCycles
{
get { return GetValue<int?>("billing_cycles", false); }
}
public int FreeQuantity
{
get { return GetValue<int>("free_quantity", true); }
}
public string FreeQuantityInDecimal
{
get { return GetValue<string>("free_quantity_in_decimal", false); }
}
public long? ResourceVersion
{
get { return GetValue<long?>("resource_version", false); }
}
public DateTime? UpdatedAt
{
get { return GetDateTime("updated_at", false); }
}
public DateTime CreatedAt
{
get { return (DateTime)GetDateTime("created_at", true); }
}
public DateTime? ArchivedAt
{
get { return GetDateTime("archived_at", false); }
}
public string InvoiceNotes
{
get { return GetValue<string>("invoice_notes", false); }
}
public List<ItemPriceTier> Tiers
{
get { return GetResourceList<ItemPriceTier>("tiers"); }
}
public bool? IsTaxable
{
get { return GetValue<bool?>("is_taxable", false); }
}
public ItemPriceTaxDetail TaxDetail
{
get { return GetSubResource<ItemPriceTaxDetail>("tax_detail"); }
}
public ItemPriceAccountingDetail AccountingDetail
{
get { return GetSubResource<ItemPriceAccountingDetail>("accounting_detail"); }
}
public JToken Metadata
{
get { return GetJToken("metadata", false); }
}
public ItemTypeEnum? ItemType
{
get { return GetEnum<ItemTypeEnum>("item_type", false); }
}
[Obsolete]
public bool? Archivable
{
get { return GetValue<bool?>("archivable", false); }
}
[Obsolete]
public string ParentItemId
{
get { return GetValue<string>("parent_item_id", false); }
}
public bool? ShowDescriptionInInvoices
{
get { return GetValue<bool?>("show_description_in_invoices", false); }
}
public bool? ShowDescriptionInQuotes
{
get { return GetValue<bool?>("show_description_in_quotes", false); }
}
#endregion
#region Requests
public class CreateRequest : EntityRequest<CreateRequest>
{
public CreateRequest(string url, HttpMethod method)
: base(url, method)
{
}
public CreateRequest Id(string id)
{
m_params.Add("id", id);
return this;
}
public CreateRequest Name(string name)
{
m_params.Add("name", name);
return this;
}
public CreateRequest Description(string description)
{
m_params.AddOpt("description", description);
return this;
}
public CreateRequest ItemId(string itemId)
{
m_params.Add("item_id", itemId);
return this;
}
public CreateRequest InvoiceNotes(string invoiceNotes)
{
m_params.AddOpt("invoice_notes", invoiceNotes);
return this;
}
public CreateRequest ExternalName(string externalName)
{
m_params.AddOpt("external_name", externalName);
return this;
}
public CreateRequest CurrencyCode(string currencyCode)
{
m_params.AddOpt("currency_code", currencyCode);
return this;
}
public CreateRequest IsTaxable(bool isTaxable)
{
m_params.AddOpt("is_taxable", isTaxable);
return this;
}
public CreateRequest FreeQuantity(int freeQuantity)
{
m_params.AddOpt("free_quantity", freeQuantity);
return this;
}
public CreateRequest FreeQuantityInDecimal(string freeQuantityInDecimal)
{
m_params.AddOpt("free_quantity_in_decimal", freeQuantityInDecimal);
return this;
}
public CreateRequest Metadata(JToken metadata)
{
m_params.AddOpt("metadata", metadata);
return this;
}
public CreateRequest ShowDescriptionInInvoices(bool showDescriptionInInvoices)
{
m_params.AddOpt("show_description_in_invoices", showDescriptionInInvoices);
return this;
}
public CreateRequest ShowDescriptionInQuotes(bool showDescriptionInQuotes)
{
m_params.AddOpt("show_description_in_quotes", showDescriptionInQuotes);
return this;
}
public CreateRequest PricingModel(ChargeBee.Models.Enums.PricingModelEnum pricingModel)
{
m_params.AddOpt("pricing_model", pricingModel);
return this;
}
public CreateRequest Price(int price)
{
m_params.AddOpt("price", price);
return this;
}
public CreateRequest PriceInDecimal(string priceInDecimal)
{
m_params.AddOpt("price_in_decimal", priceInDecimal);
return this;
}
public CreateRequest PeriodUnit(ItemPrice.PeriodUnitEnum periodUnit)
{
m_params.AddOpt("period_unit", periodUnit);
return this;
}
public CreateRequest Period(int period)
{
m_params.AddOpt("period", period);
return this;
}
public CreateRequest TrialPeriodUnit(ItemPrice.TrialPeriodUnitEnum trialPeriodUnit)
{
m_params.AddOpt("trial_period_unit", trialPeriodUnit);
return this;
}
public CreateRequest TrialPeriod(int trialPeriod)
{
m_params.AddOpt("trial_period", trialPeriod);
return this;
}
public CreateRequest ShippingPeriod(int shippingPeriod)
{
m_params.AddOpt("shipping_period", shippingPeriod);
return this;
}
public CreateRequest ShippingPeriodUnit(ItemPrice.ShippingPeriodUnitEnum shippingPeriodUnit)
{
m_params.AddOpt("shipping_period_unit", shippingPeriodUnit);
return this;
}
public CreateRequest BillingCycles(int billingCycles)
{
m_params.AddOpt("billing_cycles", billingCycles);
return this;
}
public CreateRequest TrialEndAction(ItemPrice.TrialEndActionEnum trialEndAction)
{
m_params.AddOpt("trial_end_action", trialEndAction);
return this;
}
public CreateRequest TaxDetailTaxProfileId(string taxDetailTaxProfileId)
{
m_params.AddOpt("tax_detail[tax_profile_id]", taxDetailTaxProfileId);
return this;
}
public CreateRequest TaxDetailAvalaraTaxCode(string taxDetailAvalaraTaxCode)
{
m_params.AddOpt("tax_detail[avalara_tax_code]", taxDetailAvalaraTaxCode);
return this;
}
public CreateRequest TaxDetailHsnCode(string taxDetailHsnCode)
{
m_params.AddOpt("tax_detail[hsn_code]", taxDetailHsnCode);
return this;
}
public CreateRequest TaxDetailAvalaraSaleType(ChargeBee.Models.Enums.AvalaraSaleTypeEnum taxDetailAvalaraSaleType)
{
m_params.AddOpt("tax_detail[avalara_sale_type]", taxDetailAvalaraSaleType);
return this;
}
public CreateRequest TaxDetailAvalaraTransactionType(int taxDetailAvalaraTransactionType)
{
m_params.AddOpt("tax_detail[avalara_transaction_type]", taxDetailAvalaraTransactionType);
return this;
}
public CreateRequest TaxDetailAvalaraServiceType(int taxDetailAvalaraServiceType)
{
m_params.AddOpt("tax_detail[avalara_service_type]", taxDetailAvalaraServiceType);
return this;
}
public CreateRequest TaxDetailTaxjarProductCode(string taxDetailTaxjarProductCode)
{
m_params.AddOpt("tax_detail[taxjar_product_code]", taxDetailTaxjarProductCode);
return this;
}
public CreateRequest AccountingDetailSku(string accountingDetailSku)
{
m_params.AddOpt("accounting_detail[sku]", accountingDetailSku);
return this;
}
public CreateRequest AccountingDetailAccountingCode(string accountingDetailAccountingCode)
{
m_params.AddOpt("accounting_detail[accounting_code]", accountingDetailAccountingCode);
return this;
}
public CreateRequest AccountingDetailAccountingCategory1(string accountingDetailAccountingCategory1)
{
m_params.AddOpt("accounting_detail[accounting_category1]", accountingDetailAccountingCategory1);
return this;
}
public CreateRequest AccountingDetailAccountingCategory2(string accountingDetailAccountingCategory2)
{
m_params.AddOpt("accounting_detail[accounting_category2]", accountingDetailAccountingCategory2);
return this;
}
public CreateRequest AccountingDetailAccountingCategory3(string accountingDetailAccountingCategory3)
{
m_params.AddOpt("accounting_detail[accounting_category3]", accountingDetailAccountingCategory3);
return this;
}
public CreateRequest AccountingDetailAccountingCategory4(string accountingDetailAccountingCategory4)
{
m_params.AddOpt("accounting_detail[accounting_category4]", accountingDetailAccountingCategory4);
return this;
}
public CreateRequest TierStartingUnit(int index, int tierStartingUnit)
{
m_params.AddOpt("tiers[starting_unit][" + index + "]", tierStartingUnit);
return this;
}
public CreateRequest TierEndingUnit(int index, int tierEndingUnit)
{
m_params.AddOpt("tiers[ending_unit][" + index + "]", tierEndingUnit);
return this;
}
public CreateRequest TierPrice(int index, int tierPrice)
{
m_params.AddOpt("tiers[price][" + index + "]", tierPrice);
return this;
}
public CreateRequest TierStartingUnitInDecimal(int index, string tierStartingUnitInDecimal)
{
m_params.AddOpt("tiers[starting_unit_in_decimal][" + index + "]", tierStartingUnitInDecimal);
return this;
}
public CreateRequest TierEndingUnitInDecimal(int index, string tierEndingUnitInDecimal)
{
m_params.AddOpt("tiers[ending_unit_in_decimal][" + index + "]", tierEndingUnitInDecimal);
return this;
}
public CreateRequest TierPriceInDecimal(int index, string tierPriceInDecimal)
{
m_params.AddOpt("tiers[price_in_decimal][" + index + "]", tierPriceInDecimal);
return this;
}
}
public class UpdateRequest : EntityRequest<UpdateRequest>
{
public UpdateRequest(string url, HttpMethod method)
: base(url, method)
{
}
public UpdateRequest Name(string name)
{
m_params.AddOpt("name", name);
return this;
}
public UpdateRequest Description(string description)
{
m_params.AddOpt("description", description);
return this;
}
public UpdateRequest Status(ItemPrice.StatusEnum status)
{
m_params.AddOpt("status", status);
return this;
}
public UpdateRequest ExternalName(string externalName)
{
m_params.AddOpt("external_name", externalName);
return this;
}
public UpdateRequest CurrencyCode(string currencyCode)
{
m_params.AddOpt("currency_code", currencyCode);
return this;
}
public UpdateRequest InvoiceNotes(string invoiceNotes)
{
m_params.AddOpt("invoice_notes", invoiceNotes);
return this;
}
public UpdateRequest IsTaxable(bool isTaxable)
{
m_params.AddOpt("is_taxable", isTaxable);
return this;
}
public UpdateRequest FreeQuantity(int freeQuantity)
{
m_params.AddOpt("free_quantity", freeQuantity);
return this;
}
public UpdateRequest FreeQuantityInDecimal(string freeQuantityInDecimal)
{
m_params.AddOpt("free_quantity_in_decimal", freeQuantityInDecimal);
return this;
}
public UpdateRequest Metadata(JToken metadata)
{
m_params.AddOpt("metadata", metadata);
return this;
}
public UpdateRequest PricingModel(ChargeBee.Models.Enums.PricingModelEnum pricingModel)
{
m_params.AddOpt("pricing_model", pricingModel);
return this;
}
public UpdateRequest Price(int price)
{
m_params.AddOpt("price", price);
return this;
}
public UpdateRequest PriceInDecimal(string priceInDecimal)
{
m_params.AddOpt("price_in_decimal", priceInDecimal);
return this;
}
public UpdateRequest PeriodUnit(ItemPrice.PeriodUnitEnum periodUnit)
{
m_params.AddOpt("period_unit", periodUnit);
return this;
}
public UpdateRequest Period(int period)
{
m_params.AddOpt("period", period);
return this;
}
public UpdateRequest TrialPeriodUnit(ItemPrice.TrialPeriodUnitEnum trialPeriodUnit)
{
m_params.AddOpt("trial_period_unit", trialPeriodUnit);
return this;
}
public UpdateRequest TrialPeriod(int trialPeriod)
{
m_params.AddOpt("trial_period", trialPeriod);
return this;
}
public UpdateRequest ShippingPeriod(int shippingPeriod)
{
m_params.AddOpt("shipping_period", shippingPeriod);
return this;
}
public UpdateRequest ShippingPeriodUnit(ItemPrice.ShippingPeriodUnitEnum shippingPeriodUnit)
{
m_params.AddOpt("shipping_period_unit", shippingPeriodUnit);
return this;
}
public UpdateRequest BillingCycles(int billingCycles)
{
m_params.AddOpt("billing_cycles", billingCycles);
return this;
}
public UpdateRequest TrialEndAction(ItemPrice.TrialEndActionEnum trialEndAction)
{
m_params.AddOpt("trial_end_action", trialEndAction);
return this;
}
public UpdateRequest ShowDescriptionInInvoices(bool showDescriptionInInvoices)
{
m_params.AddOpt("show_description_in_invoices", showDescriptionInInvoices);
return this;
}
public UpdateRequest ShowDescriptionInQuotes(bool showDescriptionInQuotes)
{
m_params.AddOpt("show_description_in_quotes", showDescriptionInQuotes);
return this;
}
public UpdateRequest TaxDetailTaxProfileId(string taxDetailTaxProfileId)
{
m_params.AddOpt("tax_detail[tax_profile_id]", taxDetailTaxProfileId);
return this;
}
public UpdateRequest TaxDetailAvalaraTaxCode(string taxDetailAvalaraTaxCode)
{
m_params.AddOpt("tax_detail[avalara_tax_code]", taxDetailAvalaraTaxCode);
return this;
}
public UpdateRequest TaxDetailHsnCode(string taxDetailHsnCode)
{
m_params.AddOpt("tax_detail[hsn_code]", taxDetailHsnCode);
return this;
}
public UpdateRequest TaxDetailAvalaraSaleType(ChargeBee.Models.Enums.AvalaraSaleTypeEnum taxDetailAvalaraSaleType)
{
m_params.AddOpt("tax_detail[avalara_sale_type]", taxDetailAvalaraSaleType);
return this;
}
public UpdateRequest TaxDetailAvalaraTransactionType(int taxDetailAvalaraTransactionType)
{
m_params.AddOpt("tax_detail[avalara_transaction_type]", taxDetailAvalaraTransactionType);
return this;
}
public UpdateRequest TaxDetailAvalaraServiceType(int taxDetailAvalaraServiceType)
{
m_params.AddOpt("tax_detail[avalara_service_type]", taxDetailAvalaraServiceType);
return this;
}
public UpdateRequest TaxDetailTaxjarProductCode(string taxDetailTaxjarProductCode)
{
m_params.AddOpt("tax_detail[taxjar_product_code]", taxDetailTaxjarProductCode);
return this;
}
public UpdateRequest AccountingDetailSku(string accountingDetailSku)
{
m_params.AddOpt("accounting_detail[sku]", accountingDetailSku);
return this;
}
public UpdateRequest AccountingDetailAccountingCode(string accountingDetailAccountingCode)
{
m_params.AddOpt("accounting_detail[accounting_code]", accountingDetailAccountingCode);
return this;
}
public UpdateRequest AccountingDetailAccountingCategory1(string accountingDetailAccountingCategory1)
{
m_params.AddOpt("accounting_detail[accounting_category1]", accountingDetailAccountingCategory1);
return this;
}
public UpdateRequest AccountingDetailAccountingCategory2(string accountingDetailAccountingCategory2)
{
m_params.AddOpt("accounting_detail[accounting_category2]", accountingDetailAccountingCategory2);
return this;
}
public UpdateRequest AccountingDetailAccountingCategory3(string accountingDetailAccountingCategory3)
{
m_params.AddOpt("accounting_detail[accounting_category3]", accountingDetailAccountingCategory3);
return this;
}
public UpdateRequest AccountingDetailAccountingCategory4(string accountingDetailAccountingCategory4)
{
m_params.AddOpt("accounting_detail[accounting_category4]", accountingDetailAccountingCategory4);
return this;
}
public UpdateRequest TierStartingUnit(int index, int tierStartingUnit)
{
m_params.AddOpt("tiers[starting_unit][" + index + "]", tierStartingUnit);
return this;
}
public UpdateRequest TierEndingUnit(int index, int tierEndingUnit)
{
m_params.AddOpt("tiers[ending_unit][" + index + "]", tierEndingUnit);
return this;
}
public UpdateRequest TierPrice(int index, int tierPrice)
{
m_params.AddOpt("tiers[price][" + index + "]", tierPrice);
return this;
}
public UpdateRequest TierStartingUnitInDecimal(int index, string tierStartingUnitInDecimal)
{
m_params.AddOpt("tiers[starting_unit_in_decimal][" + index + "]", tierStartingUnitInDecimal);
return this;
}
public UpdateRequest TierEndingUnitInDecimal(int index, string tierEndingUnitInDecimal)
{
m_params.AddOpt("tiers[ending_unit_in_decimal][" + index + "]", tierEndingUnitInDecimal);
return this;
}
public UpdateRequest TierPriceInDecimal(int index, string tierPriceInDecimal)
{
m_params.AddOpt("tiers[price_in_decimal][" + index + "]", tierPriceInDecimal);
return this;
}
}
public class ItemPriceListRequest : ListRequestBase<ItemPriceListRequest>
{
public ItemPriceListRequest(string url)
: base(url)
{
}
public StringFilter<ItemPriceListRequest> Id()
{
return new StringFilter<ItemPriceListRequest>("id", this).SupportsMultiOperators(true);
}
public StringFilter<ItemPriceListRequest> Name()
{
return new StringFilter<ItemPriceListRequest>("name", this).SupportsMultiOperators(true);
}
public EnumFilter<ChargeBee.Models.Enums.PricingModelEnum, ItemPriceListRequest> PricingModel()
{
return new EnumFilter<ChargeBee.Models.Enums.PricingModelEnum, ItemPriceListRequest>("pricing_model", this);
}
public StringFilter<ItemPriceListRequest> ItemId()
{
return new StringFilter<ItemPriceListRequest>("item_id", this).SupportsMultiOperators(true);
}
public StringFilter<ItemPriceListRequest> ItemFamilyId()
{
return new StringFilter<ItemPriceListRequest>("item_family_id", this).SupportsMultiOperators(true);
}
public EnumFilter<ChargeBee.Models.Enums.ItemTypeEnum, ItemPriceListRequest> ItemType()
{
return new EnumFilter<ChargeBee.Models.Enums.ItemTypeEnum, ItemPriceListRequest>("item_type", this);
}
public StringFilter<ItemPriceListRequest> CurrencyCode()
{
return new StringFilter<ItemPriceListRequest>("currency_code", this).SupportsMultiOperators(true);
}
public NumberFilter<int, ItemPriceListRequest> TrialPeriod()
{
return new NumberFilter<int, ItemPriceListRequest>("trial_period", this);
}
public EnumFilter<ItemPrice.TrialPeriodUnitEnum, ItemPriceListRequest> TrialPeriodUnit()
{
return new EnumFilter<ItemPrice.TrialPeriodUnitEnum, ItemPriceListRequest>("trial_period_unit", this);
}
public EnumFilter<ItemPrice.StatusEnum, ItemPriceListRequest> Status()
{
return new EnumFilter<ItemPrice.StatusEnum, ItemPriceListRequest>("status", this);
}
public TimestampFilter<ItemPriceListRequest> UpdatedAt()
{
return new TimestampFilter<ItemPriceListRequest>("updated_at", this);
}
public EnumFilter<ItemPrice.PeriodUnitEnum, ItemPriceListRequest> PeriodUnit()
{
return new EnumFilter<ItemPrice.PeriodUnitEnum, ItemPriceListRequest>("period_unit", this);
}
public NumberFilter<int, ItemPriceListRequest> Period()
{
return new NumberFilter<int, ItemPriceListRequest>("period", this);
}
public ItemPriceListRequest SortByName(SortOrderEnum order) {
m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","name");
return this;
}
public ItemPriceListRequest SortById(SortOrderEnum order) {
m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","id");
return this;
}
public ItemPriceListRequest SortByUpdatedAt(SortOrderEnum order) {
m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","updated_at");
return this;
}
}
public class ItemPriceFindApplicableItemsRequest : ListRequestBase<ItemPriceFindApplicableItemsRequest>
{
public ItemPriceFindApplicableItemsRequest(string url)
: base(url)
{
}
public ItemPriceFindApplicableItemsRequest SortByName(SortOrderEnum order) {
m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","name");
return this;
}
public ItemPriceFindApplicableItemsRequest SortById(SortOrderEnum order) {
m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","id");
return this;
}
public ItemPriceFindApplicableItemsRequest SortByUpdatedAt(SortOrderEnum order) {
m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","updated_at");
return this;
}
}
public class ItemPriceFindApplicableItemPricesRequest : ListRequestBase<ItemPriceFindApplicableItemPricesRequest>
{
public ItemPriceFindApplicableItemPricesRequest(string url)
: base(url)
{
}
public ItemPriceFindApplicableItemPricesRequest ItemId(string itemId)
{
m_params.AddOpt("item_id", itemId);
return this;
}
public ItemPriceFindApplicableItemPricesRequest SortByName(SortOrderEnum order) {
m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","name");
return this;
}
public ItemPriceFindApplicableItemPricesRequest SortById(SortOrderEnum order) {
m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","id");
return this;
}
public ItemPriceFindApplicableItemPricesRequest SortByUpdatedAt(SortOrderEnum order) {
m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","updated_at");
return this;
}
}
#endregion
public enum StatusEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "active")]
Active,
[EnumMember(Value = "archived")]
Archived,
[EnumMember(Value = "deleted")]
Deleted,
}
public enum PeriodUnitEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "day")]
Day,
[EnumMember(Value = "week")]
Week,
[EnumMember(Value = "month")]
Month,
[EnumMember(Value = "year")]
Year,
}
public enum TrialPeriodUnitEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "day")]
Day,
[EnumMember(Value = "month")]
Month,
}
public enum TrialEndActionEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "site_default")]
SiteDefault,
[EnumMember(Value = "activate_subscription")]
ActivateSubscription,
[EnumMember(Value = "cancel_subscription")]
CancelSubscription,
}
public enum ShippingPeriodUnitEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "day")]
Day,
[EnumMember(Value = "week")]
Week,
[EnumMember(Value = "month")]
Month,
[EnumMember(Value = "year")]
Year,
}
#region Subclasses
public class ItemPriceTier : Resource
{
public int StartingUnit {
get { return GetValue<int>("starting_unit", true); }
}
public int? EndingUnit {
get { return GetValue<int?>("ending_unit", false); }
}
public int Price {
get { return GetValue<int>("price", true); }
}
public string StartingUnitInDecimal {
get { return GetValue<string>("starting_unit_in_decimal", false); }
}
public string EndingUnitInDecimal {
get { return GetValue<string>("ending_unit_in_decimal", false); }
}
public string PriceInDecimal {
get { return GetValue<string>("price_in_decimal", false); }
}
}
public class ItemPriceTaxDetail : Resource
{
public string TaxProfileId {
get { return GetValue<string>("tax_profile_id", false); }
}
public AvalaraSaleTypeEnum? AvalaraSaleType {
get { return GetEnum<AvalaraSaleTypeEnum>("avalara_sale_type", false); }
}
public int? AvalaraTransactionType {
get { return GetValue<int?>("avalara_transaction_type", false); }
}
public int? AvalaraServiceType {
get { return GetValue<int?>("avalara_service_type", false); }
}
public string AvalaraTaxCode {
get { return GetValue<string>("avalara_tax_code", false); }
}
public string HsnCode {
get { return GetValue<string>("hsn_code", false); }
}
public string TaxjarProductCode {
get { return GetValue<string>("taxjar_product_code", false); }
}
}
public class ItemPriceAccountingDetail : Resource
{
public string Sku {
get { return GetValue<string>("sku", false); }
}
public string AccountingCode {
get { return GetValue<string>("accounting_code", false); }
}
public string AccountingCategory1 {
get { return GetValue<string>("accounting_category1", false); }
}
public string AccountingCategory2 {
get { return GetValue<string>("accounting_category2", false); }
}
public string AccountingCategory3 {
get { return GetValue<string>("accounting_category3", false); }
}
public string AccountingCategory4 {
get { return GetValue<string>("accounting_category4", false); }
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MultiplySubtractNegatedScalarSingle()
{
var test = new SimpleTernaryOpTest__MultiplySubtractNegatedScalarSingle();
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 SimpleTernaryOpTest__MultiplySubtractNegatedScalarSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] inArray3, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, 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);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Single, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.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 Vector128<Single> _fld2;
public Vector128<Single> _fld3;
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>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplySubtractNegatedScalarSingle testClass)
{
var result = Fma.MultiplySubtractNegatedScalar(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplySubtractNegatedScalarSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
fixed (Vector128<Single>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtractNegatedScalar(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2)),
Sse.LoadVector128((Single*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op3ElementCount = 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 Single[] _data2 = new Single[Op2ElementCount];
private static Single[] _data3 = new Single[Op3ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private static Vector128<Single> _clsVar3;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private Vector128<Single> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplySubtractNegatedScalarSingle()
{
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>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleTernaryOpTest__MultiplySubtractNegatedScalarSingle()
{
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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Fma.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Fma.MultiplySubtractNegatedScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Fma.MultiplySubtractNegatedScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Fma.MultiplySubtractNegatedScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractNegatedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractNegatedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractNegatedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Fma.MultiplySubtractNegatedScalar(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
fixed (Vector128<Single>* pClsVar3 = &_clsVar3)
{
var result = Fma.MultiplySubtractNegatedScalar(
Sse.LoadVector128((Single*)(pClsVar1)),
Sse.LoadVector128((Single*)(pClsVar2)),
Sse.LoadVector128((Single*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr);
var result = Fma.MultiplySubtractNegatedScalar(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var op3 = Sse.LoadVector128((Single*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtractNegatedScalar(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var op3 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtractNegatedScalar(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplySubtractNegatedScalarSingle();
var result = Fma.MultiplySubtractNegatedScalar(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplySubtractNegatedScalarSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
fixed (Vector128<Single>* pFld3 = &test._fld3)
{
var result = Fma.MultiplySubtractNegatedScalar(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2)),
Sse.LoadVector128((Single*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Fma.MultiplySubtractNegatedScalar(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
fixed (Vector128<Single>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtractNegatedScalar(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2)),
Sse.LoadVector128((Single*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Fma.MultiplySubtractNegatedScalar(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Fma.MultiplySubtractNegatedScalar(
Sse.LoadVector128((Single*)(&test._fld1)),
Sse.LoadVector128((Single*)(&test._fld2)),
Sse.LoadVector128((Single*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _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, Vector128<Single> op2, Vector128<Single> op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
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 inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (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, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(MathF.Round(-(firstOp[0] * secondOp[0]) - thirdOp[0], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[0], 3)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(firstOp[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtractNegatedScalar)}<Single>(Vector128<Single>, Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyFormData
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Formdata operations.
/// </summary>
public partial class Formdata : IServiceOperations<AutoRestSwaggerBATFormDataService>, IFormdata
{
/// <summary>
/// Initializes a new instance of the Formdata class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Formdata(AutoRestSwaggerBATFormDataService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestSwaggerBATFormDataService
/// </summary>
public AutoRestSwaggerBATFormDataService Client { get; private set; }
/// <summary>
/// Upload file
/// </summary>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// File name to upload. Name has to be spelled exactly as written here.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.IO.Stream>> UploadFileWithHttpMessagesAsync(System.IO.Stream fileContent, string fileName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (fileContent == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fileContent");
}
if (fileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fileName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fileContent", fileContent);
tracingParameters.Add("fileName", fileName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "UploadFile", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "formdata/stream/uploadfile").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new 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;
MultipartFormDataContent _multiPartContent = new MultipartFormDataContent();
if (fileContent != null)
{
StreamContent _fileContent = new StreamContent(fileContent);
_fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
System.IO.FileStream _fileContentAsFileStream = fileContent as System.IO.FileStream;
if (_fileContentAsFileStream != null)
{
ContentDispositionHeaderValue _contentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data");
_contentDispositionHeaderValue.Name = "fileContent";
_contentDispositionHeaderValue.FileName = _fileContentAsFileStream.Name;
_fileContent.Headers.ContentDisposition = _contentDispositionHeaderValue;
}
_multiPartContent.Add(_fileContent, "fileContent");
}
if (fileName != null)
{
StringContent _fileName = new StringContent(fileName, Encoding.UTF8);
_multiPartContent.Add(_fileName, "fileName");
}
_httpRequest.Content = _multiPartContent;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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<System.IO.Stream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Upload file
/// </summary>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// File name to upload. Name has to be spelled exactly as written here.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.IO.Stream>> UploadFileViaBodyWithHttpMessagesAsync(System.IO.Stream fileContent, string fileName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (fileContent == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fileContent");
}
if (fileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fileName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fileContent", fileContent);
tracingParameters.Add("fileName", fileName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "UploadFileViaBody", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "formdata/stream/uploadfile").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new 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;
StreamContent _fileStreamContent = new StreamContent(fileContent);
_httpRequest.Content = _fileStreamContent;
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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<System.IO.Stream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, 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.IO;
namespace NLog.UnitTests.Config
{
using NLog.Conditions;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System;
using System.Globalization;
using System.Text;
using Xunit;
public class TargetConfigurationTests : NLogTestBase
{
[Fact]
public void SimpleTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d' type='Debug' layout='${message}' />
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal(t.Name, "d");
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message}", l.Text);
Assert.NotNull(t.Layout);
Assert.Equal(1, l.Renderers.Count);
Assert.IsType(typeof(MessageLayoutRenderer), l.Renderers[0]);
}
[Fact]
public void SimpleElementSyntaxTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='Debug'>
<name>d</name>
<layout>${message}</layout>
</target>
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal(t.Name, "d");
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message}", l.Text);
Assert.NotNull(t.Layout);
Assert.Equal(1, l.Renderers.Count);
Assert.IsType(typeof(MessageLayoutRenderer), l.Renderers[0]);
}
[Fact]
public void NestedXmlConfigElementTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<extensions>
<add type='" + typeof(StructuredDebugTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='StructuredDebugTarget'>
<name>structuredTgt</name>
<layout>${message}</layout>
<config platform='any'>
<parameter name='param1' />
</config>
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("structuredTgt") as StructuredDebugTarget;
Assert.NotNull(t);
Assert.Equal("any", t.Config.Platform);
Assert.Equal("param1", t.Config.Parameter.Name);
}
[Fact]
public void ArrayParameterTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='MethodCall' name='mct'>
<parameter name='p1' layout='${message}' />
<parameter name='p2' layout='${level}' />
<parameter name='p3' layout='${logger}' />
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("mct") as MethodCallTarget;
Assert.NotNull(t);
Assert.Equal(3, t.Parameters.Count);
Assert.Equal("p1", t.Parameters[0].Name);
Assert.Equal("'${message}'", t.Parameters[0].Layout.ToString());
Assert.Equal("p2", t.Parameters[1].Name);
Assert.Equal("'${level}'", t.Parameters[1].Layout.ToString());
Assert.Equal("p3", t.Parameters[2].Name);
Assert.Equal("'${logger}'", t.Parameters[2].Layout.ToString());
}
[Fact]
public void ArrayElementParameterTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='MethodCall' name='mct'>
<parameter>
<name>p1</name>
<layout>${message}</layout>
</parameter>
<parameter>
<name>p2</name>
<layout type='CsvLayout'>
<column name='x' layout='${message}' />
<column name='y' layout='${level}' />
</layout>
</parameter>
<parameter>
<name>p3</name>
<layout>${logger}</layout>
</parameter>
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("mct") as MethodCallTarget;
Assert.NotNull(t);
Assert.Equal(3, t.Parameters.Count);
Assert.Equal("p1", t.Parameters[0].Name);
Assert.Equal("'${message}'", t.Parameters[0].Layout.ToString());
Assert.Equal("p2", t.Parameters[1].Name);
CsvLayout csvLayout = t.Parameters[1].Layout as CsvLayout;
Assert.NotNull(csvLayout);
Assert.Equal(2, csvLayout.Columns.Count);
Assert.Equal("x", csvLayout.Columns[0].Name);
Assert.Equal("y", csvLayout.Columns[1].Name);
Assert.Equal("p3", t.Parameters[2].Name);
Assert.Equal("'${logger}'", t.Parameters[2].Layout.ToString());
}
[Fact]
public void SimpleTest2()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d' type='Debug' layout='${message} ${level}' />
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal(t.Name, "d");
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message} ${level}", l.Text);
Assert.NotNull(l);
Assert.Equal(3, l.Renderers.Count);
Assert.IsType(typeof(MessageLayoutRenderer), l.Renderers[0]);
Assert.IsType(typeof(LiteralLayoutRenderer), l.Renderers[1]);
Assert.IsType(typeof(LevelLayoutRenderer), l.Renderers[2]);
Assert.Equal(" ", ((LiteralLayoutRenderer)l.Renderers[1]).Text);
}
[Fact]
public void WrapperTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<wrapper-target name='b' type='BufferingWrapper' bufferSize='19'>
<wrapper name='a' type='AsyncWrapper'>
<target name='c' type='Debug' layout='${message}' />
</wrapper>
</wrapper-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("a"));
Assert.NotNull(c.FindTargetByName("b"));
Assert.NotNull(c.FindTargetByName("c"));
Assert.IsType(typeof(BufferingTargetWrapper), c.FindTargetByName("b"));
Assert.IsType(typeof(AsyncTargetWrapper), c.FindTargetByName("a"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("c"));
BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper;
AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper;
DebugTarget dt = c.FindTargetByName("c") as DebugTarget;
Assert.Same(atw, btw.WrappedTarget);
Assert.Same(dt, atw.WrappedTarget);
Assert.Equal(19, btw.BufferSize);
}
[Fact]
public void WrapperRefTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='c' type='Debug' layout='${message}' />
<wrapper name='a' type='AsyncWrapper'>
<target-ref name='c' />
</wrapper>
<wrapper-target name='b' type='BufferingWrapper' bufferSize='19'>
<wrapper-target-ref name='a' />
</wrapper-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("a"));
Assert.NotNull(c.FindTargetByName("b"));
Assert.NotNull(c.FindTargetByName("c"));
Assert.IsType(typeof(BufferingTargetWrapper), c.FindTargetByName("b"));
Assert.IsType(typeof(AsyncTargetWrapper), c.FindTargetByName("a"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("c"));
BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper;
AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper;
DebugTarget dt = c.FindTargetByName("c") as DebugTarget;
Assert.Same(atw, btw.WrappedTarget);
Assert.Same(dt, atw.WrappedTarget);
Assert.Equal(19, btw.BufferSize);
}
[Fact]
public void CompoundTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<compound-target name='rr' type='RoundRobinGroup'>
<target name='d1' type='Debug' layout='${message}1' />
<target name='d2' type='Debug' layout='${message}2' />
<target name='d3' type='Debug' layout='${message}3' />
<target name='d4' type='Debug' layout='${message}4' />
</compound-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("rr"));
Assert.NotNull(c.FindTargetByName("d1"));
Assert.NotNull(c.FindTargetByName("d2"));
Assert.NotNull(c.FindTargetByName("d3"));
Assert.NotNull(c.FindTargetByName("d4"));
Assert.IsType(typeof(RoundRobinGroupTarget), c.FindTargetByName("rr"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d1"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d2"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d3"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d4"));
RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget;
DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget;
DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget;
DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget;
Assert.Equal(4, rr.Targets.Count);
Assert.Same(d1, rr.Targets[0]);
Assert.Same(d2, rr.Targets[1]);
Assert.Same(d3, rr.Targets[2]);
Assert.Same(d4, rr.Targets[3]);
Assert.Equal(((SimpleLayout)d1.Layout).Text, "${message}1");
Assert.Equal(((SimpleLayout)d2.Layout).Text, "${message}2");
Assert.Equal(((SimpleLayout)d3.Layout).Text, "${message}3");
Assert.Equal(((SimpleLayout)d4.Layout).Text, "${message}4");
}
[Fact]
public void CompoundRefTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}1' />
<target name='d2' type='Debug' layout='${message}2' />
<target name='d3' type='Debug' layout='${message}3' />
<target name='d4' type='Debug' layout='${message}4' />
<compound-target name='rr' type='RoundRobinGroup'>
<target-ref name='d1' />
<target-ref name='d2' />
<target-ref name='d3' />
<target-ref name='d4' />
</compound-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("rr"));
Assert.NotNull(c.FindTargetByName("d1"));
Assert.NotNull(c.FindTargetByName("d2"));
Assert.NotNull(c.FindTargetByName("d3"));
Assert.NotNull(c.FindTargetByName("d4"));
Assert.IsType(typeof(RoundRobinGroupTarget), c.FindTargetByName("rr"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d1"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d2"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d3"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d4"));
RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget;
DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget;
DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget;
DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget;
Assert.Equal(4, rr.Targets.Count);
Assert.Same(d1, rr.Targets[0]);
Assert.Same(d2, rr.Targets[1]);
Assert.Same(d3, rr.Targets[2]);
Assert.Same(d4, rr.Targets[3]);
Assert.Equal(((SimpleLayout)d1.Layout).Text, "${message}1");
Assert.Equal(((SimpleLayout)d2.Layout).Text, "${message}2");
Assert.Equal(((SimpleLayout)d3.Layout).Text, "${message}3");
Assert.Equal(((SimpleLayout)d4.Layout).Text, "${message}4");
}
[Fact]
public void AsyncWrappersTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets async='true'>
<target type='Debug' name='d' />
<target type='Debug' name='d2' />
</targets>
</nlog>");
var t = c.FindTargetByName("d") as AsyncTargetWrapper;
Assert.NotNull(t);
Assert.Equal(t.Name, "d");
var wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.NotNull(wrappedTarget);
Assert.Equal("d_wrapped", wrappedTarget.Name);
t = c.FindTargetByName("d2") as AsyncTargetWrapper;
Assert.NotNull(t);
Assert.Equal(t.Name, "d2");
wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.NotNull(wrappedTarget);
Assert.Equal("d2_wrapped", wrappedTarget.Name);
}
[Fact]
public void DefaultTargetParametersTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<default-target-parameters type='Debug' layout='x${message}x' />
<target type='Debug' name='d' />
<target type='Debug' name='d2' />
</targets>
</nlog>");
var t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("'x${message}x'", t.Layout.ToString());
t = c.FindTargetByName("d2") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("'x${message}x'", t.Layout.ToString());
}
[Fact]
public void DefaultWrapperTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<default-wrapper type='BufferingWrapper'>
<wrapper type='RetryingWrapper' />
</default-wrapper>
<target type='Debug' name='d' layout='${level}' />
<target type='Debug' name='d2' layout='${level}' />
</targets>
</nlog>");
var bufferingTargetWrapper = c.FindTargetByName("d") as BufferingTargetWrapper;
Assert.NotNull(bufferingTargetWrapper);
var retryingTargetWrapper = bufferingTargetWrapper.WrappedTarget as RetryingTargetWrapper;
Assert.NotNull(retryingTargetWrapper);
Assert.Null(retryingTargetWrapper.Name);
var debugTarget = retryingTargetWrapper.WrappedTarget as DebugTarget;
Assert.NotNull(debugTarget);
Assert.Equal("d_wrapped", debugTarget.Name);
Assert.Equal("'${level}'", debugTarget.Layout.ToString());
}
[Fact]
public void DontThrowExceptionWhenArchiveEverySetByDefaultParameters()
{
var configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<targets>
<default-target-parameters
type='File'
concurrentWrites='true'
keepFileOpen='true'
maxArchiveFiles='5'
archiveNumbering='Rolling'
archiveEvery='Day' />
<target fileName='" + Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + @".log'
name = 'file'
type = 'File'
layout = '${message}' />
</targets>
<rules>
<logger name='*' writeTo='file'/>
</rules>
</nlog> ");
LogManager.Configuration = configuration;
LogManager.GetLogger("TestLogger").Info("DefaultFileTargetParametersTests.DontThrowExceptionWhenArchiveEverySetByDefaultParameters is true");
}
[Fact]
public void DataTypesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<extensions>
<add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='MyTarget' name='myTarget'
byteProperty='42'
int16Property='42'
int32Property='42'
int64Property='42000000000'
stringProperty='foobar'
boolProperty='true'
doubleProperty='3.14159'
floatProperty='3.14159'
enumProperty='Value3'
flagsEnumProperty='Value1,Value3'
encodingProperty='utf-8'
cultureProperty='en-US'
typeProperty='System.Int32'
layoutProperty='${level}'
conditionProperty=""starts-with(message, 'x')""
uriProperty='http://nlog-project.org'
lineEndingModeProperty='default'
/>
</targets>
</nlog>");
var myTarget = c.FindTargetByName("myTarget") as MyTarget;
Assert.NotNull(myTarget);
Assert.Equal((byte)42, myTarget.ByteProperty);
Assert.Equal((short)42, myTarget.Int16Property);
Assert.Equal(42, myTarget.Int32Property);
Assert.Equal(42000000000L, myTarget.Int64Property);
Assert.Equal("foobar", myTarget.StringProperty);
Assert.Equal(true, myTarget.BoolProperty);
Assert.Equal(3.14159, myTarget.DoubleProperty);
Assert.Equal(3.14159f, myTarget.FloatProperty);
Assert.Equal(MyEnum.Value3, myTarget.EnumProperty);
Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty);
Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty);
Assert.Equal("en-US", myTarget.CultureProperty.Name);
Assert.Equal(typeof(int), myTarget.TypeProperty);
Assert.Equal("'${level}'", myTarget.LayoutProperty.ToString());
Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString());
Assert.Equal(new Uri("http://nlog-project.org"), myTarget.UriProperty);
Assert.Equal(LineEndingMode.Default, myTarget.LineEndingModeProperty);
}
[Fact]
public void NullableDataTypesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<extensions>
<add type='" + typeof(MyNullableTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='MyNullableTarget' name='myTarget'
byteProperty='42'
int16Property='42'
int32Property='42'
int64Property='42000000000'
stringProperty='foobar'
boolProperty='true'
doubleProperty='3.14159'
floatProperty='3.14159'
enumProperty='Value3'
flagsEnumProperty='Value1,Value3'
encodingProperty='utf-8'
cultureProperty='en-US'
typeProperty='System.Int32'
layoutProperty='${level}'
conditionProperty=""starts-with(message, 'x')""
/>
</targets>
</nlog>");
var myTarget = c.FindTargetByName("myTarget") as MyNullableTarget;
Assert.NotNull(myTarget);
Assert.Equal((byte)42, myTarget.ByteProperty);
Assert.Equal((short)42, myTarget.Int16Property);
Assert.Equal(42, myTarget.Int32Property);
Assert.Equal(42000000000L, myTarget.Int64Property);
Assert.Equal("foobar", myTarget.StringProperty);
Assert.Equal(true, myTarget.BoolProperty);
Assert.Equal(3.14159, myTarget.DoubleProperty);
Assert.Equal(3.14159f, myTarget.FloatProperty);
Assert.Equal(MyEnum.Value3, myTarget.EnumProperty);
Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty);
Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty);
Assert.Equal("en-US", myTarget.CultureProperty.Name);
Assert.Equal(typeof(int), myTarget.TypeProperty);
Assert.Equal("'${level}'", myTarget.LayoutProperty.ToString());
Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString());
}
[Target("MyTarget")]
public class MyTarget : Target
{
public byte ByteProperty { get; set; }
public short Int16Property { get; set; }
public int Int32Property { get; set; }
public long Int64Property { get; set; }
public string StringProperty { get; set; }
public bool BoolProperty { get; set; }
public double DoubleProperty { get; set; }
public float FloatProperty { get; set; }
public MyEnum EnumProperty { get; set; }
public MyFlagsEnum FlagsEnumProperty { get; set; }
public Encoding EncodingProperty { get; set; }
public CultureInfo CultureProperty { get; set; }
public Type TypeProperty { get; set; }
public Layout LayoutProperty { get; set; }
public ConditionExpression ConditionProperty { get; set; }
public Uri UriProperty { get; set; }
public LineEndingMode LineEndingModeProperty { get; set; }
public MyTarget() : base()
{
}
public MyTarget(string name) : this()
{
this.Name = name;
}
}
[Target("MyNullableTarget")]
public class MyNullableTarget : Target
{
public byte? ByteProperty { get; set; }
public short? Int16Property { get; set; }
public int? Int32Property { get; set; }
public long? Int64Property { get; set; }
public string StringProperty { get; set; }
public bool? BoolProperty { get; set; }
public double? DoubleProperty { get; set; }
public float? FloatProperty { get; set; }
public MyEnum? EnumProperty { get; set; }
public MyFlagsEnum? FlagsEnumProperty { get; set; }
public Encoding EncodingProperty { get; set; }
public CultureInfo CultureProperty { get; set; }
public Type TypeProperty { get; set; }
public Layout LayoutProperty { get; set; }
public ConditionExpression ConditionProperty { get; set; }
public MyNullableTarget() : base()
{
}
public MyNullableTarget(string name) : this()
{
this.Name = name;
}
}
public enum MyEnum
{
Value1,
Value2,
Value3,
}
[Flags]
public enum MyFlagsEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 4,
}
[Target("StructuredDebugTarget")]
public class StructuredDebugTarget : TargetWithLayout
{
public StructuredDebugTargetConfig Config { get; set; }
public StructuredDebugTarget()
{
Config = new StructuredDebugTargetConfig();
}
}
public class StructuredDebugTargetConfig
{
public string Platform { get; set; }
public StructuredDebugTargetParameter Parameter { get; set; }
public StructuredDebugTargetConfig()
{
Parameter = new StructuredDebugTargetParameter();
}
}
public class StructuredDebugTargetParameter
{
public string Name { get; set; }
}
}
}
| |
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using LanguageExt.Common;
namespace LanguageExt.Thunks
{
/// <summary>
/// Lazily evaluates an asynchronous function and then memoizes the value
/// Runs at most once
/// </summary>
public class ThunkAsync<A>
{
internal readonly Func<ValueTask<Fin<A>>> fun;
internal volatile int state;
internal Error error;
internal A value;
/// <summary>
/// Construct a lazy thunk
/// </summary>
[Pure, MethodImpl(Thunk.mops)]
public static ThunkAsync<A> Lazy(Func<ValueTask<Fin<A>>> fun) =>
new ThunkAsync<A>(fun);
/// <summary>
/// Construct a lazy ThunkAsync
/// </summary>
[Pure, MethodImpl(Thunk.mops)]
public static ThunkAsync<A> Lazy(Func<ValueTask<A>> fun) =>
new ThunkAsync<A>(async () => Fin<A>.Succ(await fun().ConfigureAwait(false)));
/// <summary>
/// Construct an error ThunkAsync
/// </summary>
[Pure, MethodImpl(Thunk.mops)]
public static ThunkAsync<A> Fail(Error error) =>
new ThunkAsync<A>(Thunk.IsFailed, error);
/// <summary>
/// Construct a success thunk
/// </summary>
[Pure, MethodImpl(Thunk.mops)]
public static ThunkAsync<A> Success(A value) =>
new ThunkAsync<A>(value);
/// <summary>
/// Construct a cancelled thunk
/// </summary>
[Pure, MethodImpl(Thunk.mops)]
public static ThunkAsync<A> Cancelled() =>
new ThunkAsync<A>(Thunk.IsCancelled, Errors.Cancelled);
/// <summary>
/// Success ctor
/// </summary>
[MethodImpl(Thunk.mops)]
ThunkAsync(A value) =>
(this.state, this.value) = (Thunk.IsSuccess, value);
/// <summary>
/// Failed / Cancelled constructor
/// </summary>
[MethodImpl(Thunk.mops)]
ThunkAsync(int state, Error error) =>
(this.state, this.error) = (state, error);
/// <summary>
/// Lazy constructor
/// </summary>
[MethodImpl(Thunk.mops)]
ThunkAsync(Func<ValueTask<Fin<A>>> fun) =>
this.fun = fun ?? throw new ArgumentNullException(nameof(value));
/// <summary>
/// Clone the thunk
/// </summary>
/// <remarks>For thunks that were created as pre-failed/pre-cancelled values (i.e. no delegate to run, just
/// in a pure error state), then the clone will copy that state exactly. For thunks that have been evaluated
/// then a cloned thunk will reset the thunk to a non-evaluated state. This also means any thunk that has been
/// evaluated and failed would lose the failed status</remarks>
/// <returns></returns>
[Pure, MethodImpl(Thunk.mops)]
public ThunkAsync<A> Clone() =>
fun == null
? new ThunkAsync<A>(state, error)
: new ThunkAsync<A>(fun);
/// <summary>
/// Value accessor
/// </summary>
[Pure, MethodImpl(Thunk.mops)]
public ValueTask<Fin<A>> Value() =>
Eval();
/// <summary>
/// Value accessor (clearing the memoised value)
/// </summary>
[Pure, MethodImpl(Thunk.mops)]
public ValueTask<Fin<A>> ReValue()
{
if (this.fun != null && (state & Thunk.HasEvaluated) != 0)
{
state = Thunk.NotEvaluated;
}
return Eval();
}
/// <summary>
/// Functor map
/// </summary>
[Pure, MethodImpl(Thunk.mops)]
public ThunkAsync<B> Map<B>(Func<A, B> f)
{
try
{
SpinWait sw = default;
while (true)
{
switch (state)
{
case Thunk.IsSuccess:
return ThunkAsync<B>.Success(f(value));
case Thunk.NotEvaluated:
return ThunkAsync<B>.Lazy(async () =>
{
var ev = await Eval().ConfigureAwait(false);
if (ev.IsSucc)
{
return Fin<B>.Succ(f(ev.value));
}
else
{
return ev.Cast<B>();
}
});
case Thunk.IsCancelled:
return ThunkAsync<B>.Cancelled();
case Thunk.IsFailed:
return ThunkAsync<B>.Fail(error);
}
sw.SpinOnce();
}
}
catch (Exception e)
{
return ThunkAsync<B>.Fail(e);
}
}
/// <summary>
/// Functor map
/// </summary>
[Pure, MethodImpl(Thunk.mops)]
public ThunkAsync<B> BiMap<B>(Func<A, B> Succ, Func<Error, Error> Fail)
{
try
{
SpinWait sw = default;
while (true)
{
switch (state)
{
case Thunk.IsSuccess:
return ThunkAsync<B>.Success(Succ(value));
case Thunk.NotEvaluated:
return ThunkAsync<B>.Lazy(async () =>
{
var ev = await Eval().ConfigureAwait(false);
if (ev.IsSucc)
{
return Fin<B>.Succ(Succ(ev.value));
}
else
{
return Fail(ev.Error);
}
});
case Thunk.IsCancelled:
return ThunkAsync<B>.Fail(Errors.Cancelled);
case Thunk.IsFailed:
return ThunkAsync<B>.Fail(Fail(error));
}
sw.SpinOnce();
}
}
catch (Exception e)
{
return ThunkAsync<B>.Fail(Fail(e));
}
}
/// <summary>
/// Functor map
/// </summary>
[Pure]
public ThunkAsync<B> MapAsync<B>(Func<A, ValueTask<B>> f)
{
try
{
SpinWait sw = default;
while (true)
{
switch (state)
{
case Thunk.IsSuccess:
return ThunkAsync<B>.Lazy(async () => await f(value).ConfigureAwait(false));
case Thunk.NotEvaluated:
return ThunkAsync<B>.Lazy(async () =>
{
var ev = await Eval().ConfigureAwait(false);
if (ev.IsSucc)
{
return Fin<B>.Succ(await f(ev.value).ConfigureAwait(false));
}
else
{
return ev.Cast<B>();
}
});
case Thunk.IsCancelled:
return ThunkAsync<B>.Cancelled();
case Thunk.IsFailed:
return ThunkAsync<B>.Fail(error);
}
sw.SpinOnce();
}
}
catch (Exception e)
{
return ThunkAsync<B>.Fail(e);
}
}
/// <summary>
/// Functor map
/// </summary>
[Pure]
public ThunkAsync<B> BiMapAsync<B>(Func<A, ValueTask<B>> Succ, Func<Error, ValueTask<Error>> Fail)
{
SpinWait sw = default;
while (true)
{
switch (state)
{
case Thunk.IsSuccess:
return ThunkAsync<B>.Lazy(async () => await Succ(value).ConfigureAwait(false));
case Thunk.NotEvaluated:
return ThunkAsync<B>.Lazy(async () =>
{
var ev = await Eval().ConfigureAwait(false);
if (ev.IsSucc)
{
return Fin<B>.Succ(await Succ(ev.value).ConfigureAwait(false));
}
else
{
return Fin<B>.Fail(await Fail(ev.Error).ConfigureAwait(false));
}
});
case Thunk.IsCancelled:
return ThunkAsync<B>.Lazy(async () => await Fail(Errors.Cancelled).ConfigureAwait(false));
case Thunk.IsFailed:
return ThunkAsync<B>.Lazy(async () => await Fail(error).ConfigureAwait(false));
}
sw.SpinOnce();
}
}
/// <summary>
/// Evaluates the lazy function if necessary, returns the result if it's previously been evaluated
/// The thread goes into a spin-loop if more than one thread tries to access the lazy value at once.
/// This is to protect against multiple evaluations. This technique allows for a lock free access
/// the vast majority of the time.
/// </summary>
[Pure, MethodImpl(Thunk.mops)]
async ValueTask<Fin<A>> Eval()
{
SpinWait sw = default;
while (true)
{
if (Interlocked.CompareExchange(ref state, Thunk.Evaluating, Thunk.NotEvaluated) == Thunk.NotEvaluated)
{
try
{
var vt = fun();
var fa = await vt.ConfigureAwait(false);
if (fa.IsFail)
{
error = fa.Error;
state = Thunk.IsFailed; // state update must be last thing before return
return fa;
}
else
{
value = fa.Value;
state = Thunk.IsSuccess; // state update must be last thing before return
return fa;
}
}
catch (OperationCanceledException e)
{
state = Thunk.IsCancelled; // state update must be last thing before return
return Fin<A>.Fail(Error.New(e));
}
catch (Exception e)
{
error = e;
state = e.Message == Errors.CancelledText // state update must be last thing before return
? Thunk.IsCancelled
: Thunk.IsFailed;
return Fin<A>.Fail(Error.New(e));
}
}
else
{
sw.SpinOnce();
// Once we're here we should have a result from the eval thread and
// so we can use `value` to return
switch (state)
{
case Thunk.NotEvaluated:
case Thunk.Evaluating:
continue;
case Thunk.IsSuccess:
return Fin<A>.Succ(value);
case Thunk.IsCancelled:
return Fin<A>.Fail(Errors.Cancelled);
case Thunk.IsFailed:
return Fin<A>.Fail(error);
default:
throw new InvalidOperationException("should never happen");
}
}
}
}
[Pure, MethodImpl(Thunk.mops)]
public override string ToString() =>
state switch
{
Thunk.NotEvaluated => "Not evaluated",
Thunk.Evaluating => "Evaluating",
Thunk.IsSuccess => $"Success({value})",
Thunk.IsCancelled => $"Cancelled",
Thunk.IsFailed => $"Failed({error})",
_ => ""
};
}
}
| |
// Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DotNetCore.CAP.Internal;
using DotNetCore.CAP.Messages;
using DotNetCore.CAP.Monitoring;
using DotNetCore.CAP.Persistence;
using DotNetCore.CAP.Serialization;
using Microsoft.Extensions.Options;
namespace DotNetCore.CAP.InMemoryStorage
{
internal class InMemoryStorage : IDataStorage
{
private readonly IOptions<CapOptions> _capOptions;
private readonly ISerializer _serializer;
public InMemoryStorage(IOptions<CapOptions> capOptions, ISerializer serializer)
{
_capOptions = capOptions;
_serializer = serializer;
}
public static Dictionary<string, MemoryMessage> PublishedMessages { get; } = new();
public static Dictionary<string, MemoryMessage> ReceivedMessages { get; } = new();
public Task ChangePublishStateAsync(MediumMessage message, StatusName state)
{
PublishedMessages[message.DbId].StatusName = state;
PublishedMessages[message.DbId].ExpiresAt = message.ExpiresAt;
PublishedMessages[message.DbId].Content = _serializer.Serialize(message.Origin);
return Task.CompletedTask;
}
public Task ChangeReceiveStateAsync(MediumMessage message, StatusName state)
{
ReceivedMessages[message.DbId].StatusName = state;
ReceivedMessages[message.DbId].ExpiresAt = message.ExpiresAt;
ReceivedMessages[message.DbId].Content = _serializer.Serialize(message.Origin);
return Task.CompletedTask;
}
public MediumMessage StoreMessage(string name, Message content, object? dbTransaction = null)
{
var message = new MediumMessage
{
DbId = content.GetId(),
Origin = content,
Content = _serializer.Serialize(content),
Added = DateTime.Now,
ExpiresAt = null,
Retries = 0
};
lock (PublishedMessages)
{
PublishedMessages[message.DbId] = new MemoryMessage
{
DbId = message.DbId,
Name = name,
Content = message.Content,
Retries = message.Retries,
Added = message.Added,
ExpiresAt = message.ExpiresAt,
StatusName = StatusName.Scheduled
};
}
return message;
}
public void StoreReceivedExceptionMessage(string name, string group, string content)
{
var id = SnowflakeId.Default().NextId().ToString();
lock (ReceivedMessages)
{
ReceivedMessages[id] = new MemoryMessage
{
DbId = id,
Group = group,
Origin = null!,
Name = name,
Content = content,
Retries = _capOptions.Value.FailedRetryCount,
Added = DateTime.Now,
ExpiresAt = DateTime.Now.AddDays(15),
StatusName = StatusName.Failed
};
}
}
public MediumMessage StoreReceivedMessage(string name, string @group, Message message)
{
var mdMessage = new MediumMessage
{
DbId = SnowflakeId.Default().NextId().ToString(),
Origin = message,
Added = DateTime.Now,
ExpiresAt = null,
Retries = 0
};
lock (ReceivedMessages)
{
ReceivedMessages[mdMessage.DbId] = new MemoryMessage
{
DbId = mdMessage.DbId,
Origin = mdMessage.Origin,
Group = group,
Name = name,
Content = _serializer.Serialize(mdMessage.Origin),
Retries = mdMessage.Retries,
Added = mdMessage.Added,
ExpiresAt = mdMessage.ExpiresAt,
StatusName = StatusName.Scheduled
};
}
return mdMessage;
}
public Task<int> DeleteExpiresAsync(string table, DateTime timeout, int batchCount = 1000, CancellationToken token = default)
{
var removed = 0;
if (table == nameof(PublishedMessages))
{
lock (PublishedMessages)
{
var ids = PublishedMessages.Values
.Where(x => x.ExpiresAt < timeout)
.Select(x => x.DbId)
.Take(batchCount);
foreach (var id in ids)
{
if (PublishedMessages.Remove(id))
{
removed++;
}
}
}
}
else
{
lock (ReceivedMessages)
{
var ids = ReceivedMessages.Values
.Where(x => x.ExpiresAt < timeout)
.Select(x => x.DbId)
.Take(batchCount);
foreach (var id in ids)
{
if (ReceivedMessages.Remove(id))
{
removed++;
}
}
}
}
return Task.FromResult(removed);
}
public Task<IEnumerable<MediumMessage>> GetPublishedMessagesOfNeedRetry()
{
IEnumerable<MediumMessage> result;
lock (PublishedMessages)
{
result = PublishedMessages.Values
.Where(x => x.Retries < _capOptions.Value.FailedRetryCount
&& x.Added < DateTime.Now.AddSeconds(-10)
&& (x.StatusName == StatusName.Scheduled || x.StatusName == StatusName.Failed))
.Take(200)
.Select(x => (MediumMessage)x).ToList();
}
foreach (var message in result)
{
message.Origin = _serializer.Deserialize(message.Content)!;
}
return Task.FromResult(result);
}
public Task<IEnumerable<MediumMessage>> GetReceivedMessagesOfNeedRetry()
{
IEnumerable<MediumMessage> result;
lock (ReceivedMessages)
{
result = ReceivedMessages.Values
.Where(x => x.Retries < _capOptions.Value.FailedRetryCount
&& x.Added < DateTime.Now.AddSeconds(-10)
&& (x.StatusName == StatusName.Scheduled || x.StatusName == StatusName.Failed))
.Take(200)
.Select(x => (MediumMessage)x).ToList();
}
foreach (var message in result)
{
message.Origin = _serializer.Deserialize(message.Content)!;
}
return Task.FromResult(result);
}
public IMonitoringApi GetMonitoringApi()
{
return new InMemoryMonitoringApi();
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// 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.
// This file was automatically generated and should not be edited directly.
using System.Runtime.InteropServices;
namespace SharpVk
{
/// <summary>
///
/// </summary>
internal partial struct CommandCacheStruct
{
/// <summary>
///
/// </summary>
public readonly Interop.VkInstanceCreateDelegate vkCreateInstance;
/// <summary>
///
/// </summary>
public readonly Interop.VkInstanceDestroyDelegate vkDestroyInstance;
/// <summary>
///
/// </summary>
public readonly Interop.VkInstanceEnumeratePhysicalDevicesDelegate vkEnumeratePhysicalDevices;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetFeaturesDelegate vkGetPhysicalDeviceFeatures;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetFormatPropertiesDelegate vkGetPhysicalDeviceFormatProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetImageFormatPropertiesDelegate vkGetPhysicalDeviceImageFormatProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetPropertiesDelegate vkGetPhysicalDeviceProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetQueueFamilyPropertiesDelegate vkGetPhysicalDeviceQueueFamilyProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetMemoryPropertiesDelegate vkGetPhysicalDeviceMemoryProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkInstanceGetProcedureAddressDelegate vkGetInstanceProcAddr;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceGetProcedureAddressDelegate vkGetDeviceProcAddr;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceCreateDeviceDelegate vkCreateDevice;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceDestroyDelegate vkDestroyDevice;
/// <summary>
///
/// </summary>
public readonly Interop.VkInstanceEnumerateExtensionPropertiesDelegate vkEnumerateInstanceExtensionProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceEnumerateDeviceExtensionPropertiesDelegate vkEnumerateDeviceExtensionProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkInstanceEnumerateLayerPropertiesDelegate vkEnumerateInstanceLayerProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceEnumerateDeviceLayerPropertiesDelegate vkEnumerateDeviceLayerProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceGetQueueDelegate vkGetDeviceQueue;
/// <summary>
///
/// </summary>
public readonly Interop.VkQueueSubmitDelegate vkQueueSubmit;
/// <summary>
///
/// </summary>
public readonly Interop.VkQueueWaitIdleDelegate vkQueueWaitIdle;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceWaitIdleDelegate vkDeviceWaitIdle;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceAllocateMemoryDelegate vkAllocateMemory;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceMemoryFreeDelegate vkFreeMemory;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceMemoryMapDelegate vkMapMemory;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceMemoryUnmapDelegate vkUnmapMemory;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceFlushMappedMemoryRangesDelegate vkFlushMappedMemoryRanges;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceInvalidateMappedMemoryRangesDelegate vkInvalidateMappedMemoryRanges;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceMemoryGetCommitmentDelegate vkGetDeviceMemoryCommitment;
/// <summary>
///
/// </summary>
public readonly Interop.VkBufferBindMemoryDelegate vkBindBufferMemory;
/// <summary>
///
/// </summary>
public readonly Interop.VkImageBindMemoryDelegate vkBindImageMemory;
/// <summary>
///
/// </summary>
public readonly Interop.VkBufferGetMemoryRequirementsDelegate vkGetBufferMemoryRequirements;
/// <summary>
///
/// </summary>
public readonly Interop.VkImageGetMemoryRequirementsDelegate vkGetImageMemoryRequirements;
/// <summary>
///
/// </summary>
public readonly Interop.VkImageGetSparseMemoryRequirementsDelegate vkGetImageSparseMemoryRequirements;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetSparseImageFormatPropertiesDelegate vkGetPhysicalDeviceSparseImageFormatProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkQueueBindSparseDelegate vkQueueBindSparse;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateFenceDelegate vkCreateFence;
/// <summary>
///
/// </summary>
public readonly Interop.VkFenceDestroyDelegate vkDestroyFence;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceResetFencesDelegate vkResetFences;
/// <summary>
///
/// </summary>
public readonly Interop.VkFenceGetStatusDelegate vkGetFenceStatus;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceWaitForFencesDelegate vkWaitForFences;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateSemaphoreDelegate vkCreateSemaphore;
/// <summary>
///
/// </summary>
public readonly Interop.VkSemaphoreDestroyDelegate vkDestroySemaphore;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateEventDelegate vkCreateEvent;
/// <summary>
///
/// </summary>
public readonly Interop.VkEventDestroyDelegate vkDestroyEvent;
/// <summary>
///
/// </summary>
public readonly Interop.VkEventGetStatusDelegate vkGetEventStatus;
/// <summary>
///
/// </summary>
public readonly Interop.VkEventSetDelegate vkSetEvent;
/// <summary>
///
/// </summary>
public readonly Interop.VkEventResetDelegate vkResetEvent;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateQueryPoolDelegate vkCreateQueryPool;
/// <summary>
///
/// </summary>
public readonly Interop.VkQueryPoolDestroyDelegate vkDestroyQueryPool;
/// <summary>
///
/// </summary>
public readonly Interop.VkQueryPoolGetResultsDelegate vkGetQueryPoolResults;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateBufferDelegate vkCreateBuffer;
/// <summary>
///
/// </summary>
public readonly Interop.VkBufferDestroyDelegate vkDestroyBuffer;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateBufferViewDelegate vkCreateBufferView;
/// <summary>
///
/// </summary>
public readonly Interop.VkBufferViewDestroyDelegate vkDestroyBufferView;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateImageDelegate vkCreateImage;
/// <summary>
///
/// </summary>
public readonly Interop.VkImageDestroyDelegate vkDestroyImage;
/// <summary>
///
/// </summary>
public readonly Interop.VkImageGetSubresourceLayoutDelegate vkGetImageSubresourceLayout;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateImageViewDelegate vkCreateImageView;
/// <summary>
///
/// </summary>
public readonly Interop.VkImageViewDestroyDelegate vkDestroyImageView;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateShaderModuleDelegate vkCreateShaderModule;
/// <summary>
///
/// </summary>
public readonly Interop.VkShaderModuleDestroyDelegate vkDestroyShaderModule;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreatePipelineCacheDelegate vkCreatePipelineCache;
/// <summary>
///
/// </summary>
public readonly Interop.VkPipelineCacheDestroyDelegate vkDestroyPipelineCache;
/// <summary>
///
/// </summary>
public readonly Interop.VkPipelineCacheGetDataDelegate vkGetPipelineCacheData;
/// <summary>
///
/// </summary>
public readonly Interop.VkPipelineCacheMergePipelineCachesDelegate vkMergePipelineCaches;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateGraphicsPipelinesDelegate vkCreateGraphicsPipelines;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateComputePipelinesDelegate vkCreateComputePipelines;
/// <summary>
///
/// </summary>
public readonly Interop.VkPipelineDestroyDelegate vkDestroyPipeline;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreatePipelineLayoutDelegate vkCreatePipelineLayout;
/// <summary>
///
/// </summary>
public readonly Interop.VkPipelineLayoutDestroyDelegate vkDestroyPipelineLayout;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateSamplerDelegate vkCreateSampler;
/// <summary>
///
/// </summary>
public readonly Interop.VkSamplerDestroyDelegate vkDestroySampler;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateDescriptorSetLayoutDelegate vkCreateDescriptorSetLayout;
/// <summary>
///
/// </summary>
public readonly Interop.VkDescriptorSetLayoutDestroyDelegate vkDestroyDescriptorSetLayout;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateDescriptorPoolDelegate vkCreateDescriptorPool;
/// <summary>
///
/// </summary>
public readonly Interop.VkDescriptorPoolDestroyDelegate vkDestroyDescriptorPool;
/// <summary>
///
/// </summary>
public readonly Interop.VkDescriptorPoolResetDelegate vkResetDescriptorPool;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceAllocateDescriptorSetsDelegate vkAllocateDescriptorSets;
/// <summary>
///
/// </summary>
public readonly Interop.VkDescriptorPoolFreeDescriptorSetsDelegate vkFreeDescriptorSets;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceUpdateDescriptorSetsDelegate vkUpdateDescriptorSets;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateFramebufferDelegate vkCreateFramebuffer;
/// <summary>
///
/// </summary>
public readonly Interop.VkFramebufferDestroyDelegate vkDestroyFramebuffer;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateRenderPassDelegate vkCreateRenderPass;
/// <summary>
///
/// </summary>
public readonly Interop.VkRenderPassDestroyDelegate vkDestroyRenderPass;
/// <summary>
///
/// </summary>
public readonly Interop.VkRenderPassGetRenderAreaGranularityDelegate vkGetRenderAreaGranularity;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateCommandPoolDelegate vkCreateCommandPool;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandPoolDestroyDelegate vkDestroyCommandPool;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandPoolResetDelegate vkResetCommandPool;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceAllocateCommandBuffersDelegate vkAllocateCommandBuffers;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandPoolFreeCommandBuffersDelegate vkFreeCommandBuffers;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferBeginDelegate vkBeginCommandBuffer;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferEndDelegate vkEndCommandBuffer;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferResetDelegate vkResetCommandBuffer;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferBindPipelineDelegate vkCmdBindPipeline;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferSetViewportDelegate vkCmdSetViewport;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferSetScissorDelegate vkCmdSetScissor;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferSetLineWidthDelegate vkCmdSetLineWidth;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferSetDepthBiasDelegate vkCmdSetDepthBias;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferSetBlendConstantsDelegate vkCmdSetBlendConstants;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferSetDepthBoundsDelegate vkCmdSetDepthBounds;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferSetStencilCompareMaskDelegate vkCmdSetStencilCompareMask;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferSetStencilWriteMaskDelegate vkCmdSetStencilWriteMask;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferSetStencilReferenceDelegate vkCmdSetStencilReference;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferBindDescriptorSetsDelegate vkCmdBindDescriptorSets;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferBindIndexBufferDelegate vkCmdBindIndexBuffer;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferBindVertexBuffersDelegate vkCmdBindVertexBuffers;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferDrawDelegate vkCmdDraw;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferDrawIndexedDelegate vkCmdDrawIndexed;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferDrawIndirectDelegate vkCmdDrawIndirect;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferDrawIndexedIndirectDelegate vkCmdDrawIndexedIndirect;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferDispatchDelegate vkCmdDispatch;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferDispatchIndirectDelegate vkCmdDispatchIndirect;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferCopyBufferDelegate vkCmdCopyBuffer;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferCopyImageDelegate vkCmdCopyImage;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferBlitImageDelegate vkCmdBlitImage;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferCopyBufferToImageDelegate vkCmdCopyBufferToImage;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferCopyImageToBufferDelegate vkCmdCopyImageToBuffer;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferUpdateBufferDelegate vkCmdUpdateBuffer;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferFillBufferDelegate vkCmdFillBuffer;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferClearColorImageDelegate vkCmdClearColorImage;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferClearDepthStencilImageDelegate vkCmdClearDepthStencilImage;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferClearAttachmentsDelegate vkCmdClearAttachments;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferResolveImageDelegate vkCmdResolveImage;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferSetEventDelegate vkCmdSetEvent;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferResetEventDelegate vkCmdResetEvent;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferWaitEventsDelegate vkCmdWaitEvents;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferPipelineBarrierDelegate vkCmdPipelineBarrier;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferBeginQueryDelegate vkCmdBeginQuery;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferEndQueryDelegate vkCmdEndQuery;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferResetQueryPoolDelegate vkCmdResetQueryPool;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferWriteTimestampDelegate vkCmdWriteTimestamp;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferCopyQueryPoolResultsDelegate vkCmdCopyQueryPoolResults;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferPushConstantsDelegate vkCmdPushConstants;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferBeginRenderPassDelegate vkCmdBeginRenderPass;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferNextSubpassDelegate vkCmdNextSubpass;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferEndRenderPassDelegate vkCmdEndRenderPass;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferExecuteCommandsDelegate vkCmdExecuteCommands;
/// <summary>
///
/// </summary>
public readonly Interop.VkInstanceEnumerateVersionDelegate vkEnumerateInstanceVersion;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceBindBufferMemory2Delegate vkBindBufferMemory2;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceBindImageMemory2Delegate vkBindImageMemory2;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceGetGroupPeerMemoryFeaturesDelegate vkGetDeviceGroupPeerMemoryFeatures;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferSetDeviceMaskDelegate vkCmdSetDeviceMask;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferDispatchBaseDelegate vkCmdDispatchBase;
/// <summary>
///
/// </summary>
public readonly Interop.VkInstanceEnumeratePhysicalDeviceGroupsDelegate vkEnumeratePhysicalDeviceGroups;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceGetImageMemoryRequirements2Delegate vkGetImageMemoryRequirements2;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceGetBufferMemoryRequirements2Delegate vkGetBufferMemoryRequirements2;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceGetImageSparseMemoryRequirements2Delegate vkGetImageSparseMemoryRequirements2;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetFeatures2Delegate vkGetPhysicalDeviceFeatures2;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetProperties2Delegate vkGetPhysicalDeviceProperties2;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetFormatProperties2Delegate vkGetPhysicalDeviceFormatProperties2;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetImageFormatProperties2Delegate vkGetPhysicalDeviceImageFormatProperties2;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetQueueFamilyProperties2Delegate vkGetPhysicalDeviceQueueFamilyProperties2;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetMemoryProperties2Delegate vkGetPhysicalDeviceMemoryProperties2;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetSparseImageFormatProperties2Delegate vkGetPhysicalDeviceSparseImageFormatProperties2;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandPoolTrimDelegate vkTrimCommandPool;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceGetQueue2Delegate vkGetDeviceQueue2;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateSamplerYcbcrConversionDelegate vkCreateSamplerYcbcrConversion;
/// <summary>
///
/// </summary>
public readonly Interop.VkSamplerYcbcrConversionDestroyDelegate vkDestroySamplerYcbcrConversion;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateDescriptorUpdateTemplateDelegate vkCreateDescriptorUpdateTemplate;
/// <summary>
///
/// </summary>
public readonly Interop.VkDescriptorUpdateTemplateDestroyDelegate vkDestroyDescriptorUpdateTemplate;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceUpdateDescriptorSetWithTemplateDelegate vkUpdateDescriptorSetWithTemplate;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetExternalBufferPropertiesDelegate vkGetPhysicalDeviceExternalBufferProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetExternalFencePropertiesDelegate vkGetPhysicalDeviceExternalFenceProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkPhysicalDeviceGetExternalSemaphorePropertiesDelegate vkGetPhysicalDeviceExternalSemaphoreProperties;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceGetDescriptorSetLayoutSupportDelegate vkGetDescriptorSetLayoutSupport;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferDrawIndirectCountDelegate vkCmdDrawIndirectCount;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferDrawIndexedIndirectCountDelegate vkCmdDrawIndexedIndirectCount;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceCreateRenderPass2Delegate vkCreateRenderPass2;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferBeginRenderPass2Delegate vkCmdBeginRenderPass2;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferNextSubpass2Delegate vkCmdNextSubpass2;
/// <summary>
///
/// </summary>
public readonly Interop.VkCommandBufferEndRenderPass2Delegate vkCmdEndRenderPass2;
/// <summary>
///
/// </summary>
public readonly Interop.VkQueryPoolResetDelegate vkResetQueryPool;
/// <summary>
///
/// </summary>
public readonly Interop.VkSemaphoreGetCounterValueDelegate vkGetSemaphoreCounterValue;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceWaitSemaphoresDelegate vkWaitSemaphores;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceSignalSemaphoreDelegate vkSignalSemaphore;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceGetBufferDeviceAddressDelegate vkGetBufferDeviceAddress;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceGetBufferOpaqueCaptureAddressDelegate vkGetBufferOpaqueCaptureAddress;
/// <summary>
///
/// </summary>
public readonly Interop.VkDeviceGetMemoryOpaqueCaptureAddressDelegate vkGetDeviceMemoryOpaqueCaptureAddress;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkSurfaceKHRDestroyDelegate vkDestroySurfaceKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetSurfaceSupportDelegate vkGetPhysicalDeviceSurfaceSupportKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetSurfaceCapabilitiesDelegate vkGetPhysicalDeviceSurfaceCapabilitiesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetSurfaceFormatsDelegate vkGetPhysicalDeviceSurfaceFormatsKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetSurfacePresentModesDelegate vkGetPhysicalDeviceSurfacePresentModesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceCreateSwapchainDelegate vkCreateSwapchainKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkSwapchainKHRDestroyDelegate vkDestroySwapchainKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkSwapchainKHRGetImagesDelegate vkGetSwapchainImagesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkSwapchainKHRAcquireNextImageDelegate vkAcquireNextImageKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkQueuePresentDelegate vkQueuePresentKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetGroupPresentCapabilitiesDelegate vkGetDeviceGroupPresentCapabilitiesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetGroupSurfacePresentModesDelegate vkGetDeviceGroupSurfacePresentModesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetPresentRectanglesDelegate vkGetPhysicalDevicePresentRectanglesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceAcquireNextImage2Delegate vkAcquireNextImage2KHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetDisplayPropertiesDelegate vkGetPhysicalDeviceDisplayPropertiesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetDisplayPlanePropertiesDelegate vkGetPhysicalDeviceDisplayPlanePropertiesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetDisplayPlaneSupportedDisplaysDelegate vkGetDisplayPlaneSupportedDisplaysKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetDisplayModePropertiesDelegate vkGetDisplayModePropertiesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceCreateDisplayModeDelegate vkCreateDisplayModeKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDisplayModeKHRGetDisplayPlaneCapabilitiesDelegate vkGetDisplayPlaneCapabilitiesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkInstanceCreateDisplayPlaneSurfaceDelegate vkCreateDisplayPlaneSurfaceKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceCreateSharedSwapchainsDelegate vkCreateSharedSwapchainsKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkInstanceCreateXlibSurfaceDelegate vkCreateXlibSurfaceKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetXlibPresentationSupportDelegate vkGetPhysicalDeviceXlibPresentationSupportKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkInstanceCreateXcbSurfaceDelegate vkCreateXcbSurfaceKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetXcbPresentationSupportDelegate vkGetPhysicalDeviceXcbPresentationSupportKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkInstanceCreateWaylandSurfaceDelegate vkCreateWaylandSurfaceKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetWaylandPresentationSupportDelegate vkGetPhysicalDeviceWaylandPresentationSupportKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkInstanceCreateAndroidSurfaceDelegate vkCreateAndroidSurfaceKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkInstanceCreateWin32SurfaceDelegate vkCreateWin32SurfaceKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetWin32PresentationSupportDelegate vkGetPhysicalDeviceWin32PresentationSupportKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkInstanceCreateDebugReportCallbackDelegate vkCreateDebugReportCallbackEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkDebugReportCallbackEXTDestroyDelegate vkDestroyDebugReportCallbackEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkInstanceDebugReportMessageDelegate vkDebugReportMessageEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferBindTransformFeedbackBuffersDelegate vkCmdBindTransformFeedbackBuffersEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferBeginTransformFeedbackDelegate vkCmdBeginTransformFeedbackEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferEndTransformFeedbackDelegate vkCmdEndTransformFeedbackEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferBeginQueryIndexedDelegate vkCmdBeginQueryIndexedEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferEndQueryIndexedDelegate vkCmdEndQueryIndexedEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferDrawIndirectByteCountDelegate vkCmdDrawIndirectByteCountEXT;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.Experimental.VkDeviceGetImageViewHandleDelegate vkGetImageViewHandleNVX;
/// <summary>
///
/// </summary>
public readonly Interop.Amd.VkPipelineGetShaderInfoDelegate vkGetShaderInfoAMD;
/// <summary>
///
/// </summary>
public readonly Interop.Ggp.VkInstanceCreateStreamDescriptorSurfaceDelegate vkCreateStreamDescriptorSurfaceGGP;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkPhysicalDeviceGetExternalImageFormatPropertiesDelegate vkGetPhysicalDeviceExternalImageFormatPropertiesNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkDeviceMemoryGetWin32HandleDelegate vkGetMemoryWin32HandleNV;
/// <summary>
///
/// </summary>
public readonly Interop.Nintendo.VkInstanceCreateViSurfaceDelegate vkCreateViSurfaceNN;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetMemoryWin32HandleDelegate vkGetMemoryWin32HandleKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetMemoryWin32HandlePropertiesDelegate vkGetMemoryWin32HandlePropertiesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetMemoryFileDescriptorDelegate vkGetMemoryFdKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetMemoryFileDescriptorPropertiesDelegate vkGetMemoryFdPropertiesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceImportSemaphoreWin32HandleDelegate vkImportSemaphoreWin32HandleKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetSemaphoreWin32HandleDelegate vkGetSemaphoreWin32HandleKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceImportSemaphoreFileDescriptorDelegate vkImportSemaphoreFdKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetSemaphoreFileDescriptorDelegate vkGetSemaphoreFdKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkCommandBufferPushDescriptorSetDelegate vkCmdPushDescriptorSetKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkCommandBufferPushDescriptorSetWithTemplateDelegate vkCmdPushDescriptorSetWithTemplateKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferBeginConditionalRenderingDelegate vkCmdBeginConditionalRenderingEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferEndConditionalRenderingDelegate vkCmdEndConditionalRenderingEXT;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.Experimental.VkCommandBufferProcessCommandsDelegate vkCmdProcessCommandsNVX;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.Experimental.VkCommandBufferReserveSpaceForCommandsDelegate vkCmdReserveSpaceForCommandsNVX;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.Experimental.VkDeviceCreateIndirectCommandsLayoutDelegate vkCreateIndirectCommandsLayoutNVX;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.Experimental.VkIndirectCommandsLayoutNVXDestroyDelegate vkDestroyIndirectCommandsLayoutNVX;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.Experimental.VkDeviceCreateObjectTableDelegate vkCreateObjectTableNVX;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.Experimental.VkObjectTableNVXDestroyDelegate vkDestroyObjectTableNVX;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.Experimental.VkObjectTableNVXRegisterObjectsDelegate vkRegisterObjectsNVX;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.Experimental.VkObjectTableNVXUnregisterObjectsDelegate vkUnregisterObjectsNVX;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.Experimental.VkPhysicalDeviceGetGeneratedCommandsPropertiesDelegate vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferSetViewportWScalingDelegate vkCmdSetViewportWScalingNV;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkPhysicalDeviceReleaseDisplayDelegate vkReleaseDisplayEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkPhysicalDeviceAcquireXlibDisplayDelegate vkAcquireXlibDisplayEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkPhysicalDeviceGetRandROutputDisplayDelegate vkGetRandROutputDisplayEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkPhysicalDeviceGetSurfaceCapabilities2Delegate vkGetPhysicalDeviceSurfaceCapabilities2EXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkDeviceDisplayPowerControlDelegate vkDisplayPowerControlEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkDeviceRegisterEventDelegate vkRegisterDeviceEventEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkDeviceRegisterDisplayEventDelegate vkRegisterDisplayEventEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkSwapchainKHRGetCounterDelegate vkGetSwapchainCounterEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Google.VkSwapchainKHRGetRefreshCycleDurationDelegate vkGetRefreshCycleDurationGOOGLE;
/// <summary>
///
/// </summary>
public readonly Interop.Google.VkSwapchainKHRGetPastPresentationTimingDelegate vkGetPastPresentationTimingGOOGLE;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferSetDiscardRectangleDelegate vkCmdSetDiscardRectangleEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkDeviceSetHdrMetadataDelegate vkSetHdrMetadataEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkSwapchainKHRGetStatusDelegate vkGetSwapchainStatusKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceImportFenceWin32HandleDelegate vkImportFenceWin32HandleKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetFenceWin32HandleDelegate vkGetFenceWin32HandleKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceImportFenceFileDescriptorDelegate vkImportFenceFdKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetFenceFileDescriptorDelegate vkGetFenceFdKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceEnumerateQueueFamilyPerformanceQueryCountersDelegate vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetQueueFamilyPerformanceQueryPassesDelegate vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceAcquireProfilingLockDelegate vkAcquireProfilingLockKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceReleaseProfilingLockDelegate vkReleaseProfilingLockKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetSurfaceCapabilities2Delegate vkGetPhysicalDeviceSurfaceCapabilities2KHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetSurfaceFormats2Delegate vkGetPhysicalDeviceSurfaceFormats2KHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetDisplayProperties2Delegate vkGetPhysicalDeviceDisplayProperties2KHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetDisplayPlaneProperties2Delegate vkGetPhysicalDeviceDisplayPlaneProperties2KHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetDisplayModeProperties2Delegate vkGetDisplayModeProperties2KHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkPhysicalDeviceGetDisplayPlaneCapabilities2Delegate vkGetDisplayPlaneCapabilities2KHR;
/// <summary>
///
/// </summary>
public readonly Interop.MoltenVk.VkInstanceCreateIOSSurfaceDelegate vkCreateIOSSurfaceMVK;
/// <summary>
///
/// </summary>
public readonly Interop.MoltenVk.VkInstanceCreateMacOSSurfaceDelegate vkCreateMacOSSurfaceMVK;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkDeviceSetDebugUtilsObjectNameDelegate vkSetDebugUtilsObjectNameEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkDeviceSetDebugUtilsObjectTagDelegate vkSetDebugUtilsObjectTagEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkQueueBeginDebugUtilsLabelDelegate vkQueueBeginDebugUtilsLabelEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkQueueEndDebugUtilsLabelDelegate vkQueueEndDebugUtilsLabelEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkQueueInsertDebugUtilsLabelDelegate vkQueueInsertDebugUtilsLabelEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferBeginDebugUtilsLabelDelegate vkCmdBeginDebugUtilsLabelEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferEndDebugUtilsLabelDelegate vkCmdEndDebugUtilsLabelEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferInsertDebugUtilsLabelDelegate vkCmdInsertDebugUtilsLabelEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkInstanceCreateDebugUtilsMessengerDelegate vkCreateDebugUtilsMessengerEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkDebugUtilsMessengerEXTDestroyDelegate vkDestroyDebugUtilsMessengerEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkInstanceSubmitDebugUtilsMessageDelegate vkSubmitDebugUtilsMessageEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Android.VkDeviceGetAndroidHardwareBufferPropertiesDelegate vkGetAndroidHardwareBufferPropertiesANDROID;
/// <summary>
///
/// </summary>
public readonly Interop.Android.VkDeviceGetMemoryAndroidHardwareBufferDelegate vkGetMemoryAndroidHardwareBufferANDROID;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferSetSampleLocationsDelegate vkCmdSetSampleLocationsEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkPhysicalDeviceGetMultisamplePropertiesDelegate vkGetPhysicalDeviceMultisamplePropertiesEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkImageGetDrmFormatModifierPropertiesDelegate vkGetImageDrmFormatModifierPropertiesEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkDeviceCreateValidationCacheDelegate vkCreateValidationCacheEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkValidationCacheEXTDestroyDelegate vkDestroyValidationCacheEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkValidationCacheEXTMergeValidationCachesDelegate vkMergeValidationCachesEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkValidationCacheEXTGetDataDelegate vkGetValidationCacheDataEXT;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferBindShadingRateImageDelegate vkCmdBindShadingRateImageNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferSetViewportShadingRatePaletteDelegate vkCmdSetViewportShadingRatePaletteNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferSetCoarseSampleOrderDelegate vkCmdSetCoarseSampleOrderNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkDeviceCreateAccelerationStructureDelegate vkCreateAccelerationStructureNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkAccelerationStructureNVDestroyDelegate vkDestroyAccelerationStructureNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkDeviceGetAccelerationStructureMemoryRequirementsDelegate vkGetAccelerationStructureMemoryRequirementsNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkDeviceBindAccelerationStructureMemoryDelegate vkBindAccelerationStructureMemoryNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferBuildAccelerationStructureDelegate vkCmdBuildAccelerationStructureNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferCopyAccelerationStructureDelegate vkCmdCopyAccelerationStructureNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferTraceRaysDelegate vkCmdTraceRaysNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkDeviceCreateRayTracingPipelinesDelegate vkCreateRayTracingPipelinesNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkPipelineGetRayTracingShaderGroupHandlesDelegate vkGetRayTracingShaderGroupHandlesNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkAccelerationStructureNVGetHandleDelegate vkGetAccelerationStructureHandleNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferWriteAccelerationStructuresPropertiesDelegate vkCmdWriteAccelerationStructuresPropertiesNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkPipelineCompileDeferredDelegate vkCompileDeferredNV;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkDeviceGetMemoryHostPointerPropertiesDelegate vkGetMemoryHostPointerPropertiesEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Amd.VkCommandBufferWriteBufferMarkerDelegate vkCmdWriteBufferMarkerAMD;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkPhysicalDeviceGetCalibrateableTimeDomainsDelegate vkGetPhysicalDeviceCalibrateableTimeDomainsEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkDeviceGetCalibratedTimestampsDelegate vkGetCalibratedTimestampsEXT;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferDrawMeshTasksDelegate vkCmdDrawMeshTasksNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferDrawMeshTasksIndirectDelegate vkCmdDrawMeshTasksIndirectNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferDrawMeshTasksIndirectCountDelegate vkCmdDrawMeshTasksIndirectCountNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferSetExclusiveScissorDelegate vkCmdSetExclusiveScissorNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkCommandBufferSetCheckpointDelegate vkCmdSetCheckpointNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkQueueGetCheckpointDataDelegate vkGetQueueCheckpointDataNV;
/// <summary>
///
/// </summary>
public readonly Interop.Intel.VkDeviceInitializePerformanceApiDelegate vkInitializePerformanceApiINTEL;
/// <summary>
///
/// </summary>
public readonly Interop.Intel.VkDeviceUninitializePerformanceApiDelegate vkUninitializePerformanceApiINTEL;
/// <summary>
///
/// </summary>
public readonly Interop.Intel.VkCommandBufferSetPerformanceMarkerDelegate vkCmdSetPerformanceMarkerINTEL;
/// <summary>
///
/// </summary>
public readonly Interop.Intel.VkCommandBufferSetPerformanceStreamMarkerDelegate vkCmdSetPerformanceStreamMarkerINTEL;
/// <summary>
///
/// </summary>
public readonly Interop.Intel.VkCommandBufferSetPerformanceOverrideDelegate vkCmdSetPerformanceOverrideINTEL;
/// <summary>
///
/// </summary>
public readonly Interop.Intel.VkDeviceAcquirePerformanceConfigurationDelegate vkAcquirePerformanceConfigurationINTEL;
/// <summary>
///
/// </summary>
public readonly Interop.Intel.VkPerformanceConfigurationINTELReleaseDelegate vkReleasePerformanceConfigurationINTEL;
/// <summary>
///
/// </summary>
public readonly Interop.Intel.VkQueueSetPerformanceConfigurationDelegate vkQueueSetPerformanceConfigurationINTEL;
/// <summary>
///
/// </summary>
public readonly Interop.Intel.VkDeviceGetPerformanceParameterDelegate vkGetPerformanceParameterINTEL;
/// <summary>
///
/// </summary>
public readonly Interop.Amd.VkSwapchainKHRSetLocalDimmingDelegate vkSetLocalDimmingAMD;
/// <summary>
///
/// </summary>
public readonly Interop.Fuchsia.VkInstanceCreateImagePipeSurfaceDelegate vkCreateImagePipeSurfaceFUCHSIA;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkInstanceCreateMetalSurfaceDelegate vkCreateMetalSurfaceEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkPhysicalDeviceGetToolPropertiesDelegate vkGetPhysicalDeviceToolPropertiesEXT;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkPhysicalDeviceGetCooperativeMatrixPropertiesDelegate vkGetPhysicalDeviceCooperativeMatrixPropertiesNV;
/// <summary>
///
/// </summary>
public readonly Interop.NVidia.VkPhysicalDeviceGetSupportedFramebufferMixedSamplesCombinationsDelegate vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkPhysicalDeviceGetSurfacePresentModes2Delegate vkGetPhysicalDeviceSurfacePresentModes2EXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkSwapchainKHRAcquireFullScreenExclusiveModeDelegate vkAcquireFullScreenExclusiveModeEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkSwapchainKHRReleaseFullScreenExclusiveModeDelegate vkReleaseFullScreenExclusiveModeEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkDeviceGetGroupSurfacePresentModes2Delegate vkGetDeviceGroupSurfacePresentModes2EXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkInstanceCreateHeadlessSurfaceDelegate vkCreateHeadlessSurfaceEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Multivendor.VkCommandBufferSetLineStippleDelegate vkCmdSetLineStippleEXT;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetPipelineExecutablePropertiesDelegate vkGetPipelineExecutablePropertiesKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetPipelineExecutableStatisticsDelegate vkGetPipelineExecutableStatisticsKHR;
/// <summary>
///
/// </summary>
public readonly Interop.Khronos.VkDeviceGetPipelineExecutableInternalRepresentationsDelegate vkGetPipelineExecutableInternalRepresentationsKHR;
/// <summary>
///
/// </summary>
public CommandCacheStruct(CommandCache cache)
{
this.vkCreateInstance = cache.GetCommandDelegate<Interop.VkInstanceCreateDelegate>("vkCreateInstance", "");
this.vkDestroyInstance = cache.GetCommandDelegate<Interop.VkInstanceDestroyDelegate>("vkDestroyInstance", "");
this.vkEnumeratePhysicalDevices = cache.GetCommandDelegate<Interop.VkInstanceEnumeratePhysicalDevicesDelegate>("vkEnumeratePhysicalDevices", "");
this.vkGetPhysicalDeviceFeatures = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetFeaturesDelegate>("vkGetPhysicalDeviceFeatures", "");
this.vkGetPhysicalDeviceFormatProperties = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetFormatPropertiesDelegate>("vkGetPhysicalDeviceFormatProperties", "");
this.vkGetPhysicalDeviceImageFormatProperties = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetImageFormatPropertiesDelegate>("vkGetPhysicalDeviceImageFormatProperties", "");
this.vkGetPhysicalDeviceProperties = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetPropertiesDelegate>("vkGetPhysicalDeviceProperties", "");
this.vkGetPhysicalDeviceQueueFamilyProperties = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetQueueFamilyPropertiesDelegate>("vkGetPhysicalDeviceQueueFamilyProperties", "");
this.vkGetPhysicalDeviceMemoryProperties = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetMemoryPropertiesDelegate>("vkGetPhysicalDeviceMemoryProperties", "");
this.vkGetInstanceProcAddr = cache.GetCommandDelegate<Interop.VkInstanceGetProcedureAddressDelegate>("vkGetInstanceProcAddr", "");
this.vkGetDeviceProcAddr = cache.GetCommandDelegate<Interop.VkDeviceGetProcedureAddressDelegate>("vkGetDeviceProcAddr", "");
this.vkCreateDevice = cache.GetCommandDelegate<Interop.VkPhysicalDeviceCreateDeviceDelegate>("vkCreateDevice", "");
this.vkDestroyDevice = cache.GetCommandDelegate<Interop.VkDeviceDestroyDelegate>("vkDestroyDevice", "");
this.vkEnumerateInstanceExtensionProperties = cache.GetCommandDelegate<Interop.VkInstanceEnumerateExtensionPropertiesDelegate>("vkEnumerateInstanceExtensionProperties", "");
this.vkEnumerateDeviceExtensionProperties = cache.GetCommandDelegate<Interop.VkPhysicalDeviceEnumerateDeviceExtensionPropertiesDelegate>("vkEnumerateDeviceExtensionProperties", "");
this.vkEnumerateInstanceLayerProperties = cache.GetCommandDelegate<Interop.VkInstanceEnumerateLayerPropertiesDelegate>("vkEnumerateInstanceLayerProperties", "");
this.vkEnumerateDeviceLayerProperties = cache.GetCommandDelegate<Interop.VkPhysicalDeviceEnumerateDeviceLayerPropertiesDelegate>("vkEnumerateDeviceLayerProperties", "");
this.vkGetDeviceQueue = cache.GetCommandDelegate<Interop.VkDeviceGetQueueDelegate>("vkGetDeviceQueue", "");
this.vkQueueSubmit = cache.GetCommandDelegate<Interop.VkQueueSubmitDelegate>("vkQueueSubmit", "");
this.vkQueueWaitIdle = cache.GetCommandDelegate<Interop.VkQueueWaitIdleDelegate>("vkQueueWaitIdle", "");
this.vkDeviceWaitIdle = cache.GetCommandDelegate<Interop.VkDeviceWaitIdleDelegate>("vkDeviceWaitIdle", "");
this.vkAllocateMemory = cache.GetCommandDelegate<Interop.VkDeviceAllocateMemoryDelegate>("vkAllocateMemory", "");
this.vkFreeMemory = cache.GetCommandDelegate<Interop.VkDeviceMemoryFreeDelegate>("vkFreeMemory", "");
this.vkMapMemory = cache.GetCommandDelegate<Interop.VkDeviceMemoryMapDelegate>("vkMapMemory", "");
this.vkUnmapMemory = cache.GetCommandDelegate<Interop.VkDeviceMemoryUnmapDelegate>("vkUnmapMemory", "");
this.vkFlushMappedMemoryRanges = cache.GetCommandDelegate<Interop.VkDeviceFlushMappedMemoryRangesDelegate>("vkFlushMappedMemoryRanges", "");
this.vkInvalidateMappedMemoryRanges = cache.GetCommandDelegate<Interop.VkDeviceInvalidateMappedMemoryRangesDelegate>("vkInvalidateMappedMemoryRanges", "");
this.vkGetDeviceMemoryCommitment = cache.GetCommandDelegate<Interop.VkDeviceMemoryGetCommitmentDelegate>("vkGetDeviceMemoryCommitment", "");
this.vkBindBufferMemory = cache.GetCommandDelegate<Interop.VkBufferBindMemoryDelegate>("vkBindBufferMemory", "");
this.vkBindImageMemory = cache.GetCommandDelegate<Interop.VkImageBindMemoryDelegate>("vkBindImageMemory", "");
this.vkGetBufferMemoryRequirements = cache.GetCommandDelegate<Interop.VkBufferGetMemoryRequirementsDelegate>("vkGetBufferMemoryRequirements", "");
this.vkGetImageMemoryRequirements = cache.GetCommandDelegate<Interop.VkImageGetMemoryRequirementsDelegate>("vkGetImageMemoryRequirements", "");
this.vkGetImageSparseMemoryRequirements = cache.GetCommandDelegate<Interop.VkImageGetSparseMemoryRequirementsDelegate>("vkGetImageSparseMemoryRequirements", "");
this.vkGetPhysicalDeviceSparseImageFormatProperties = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetSparseImageFormatPropertiesDelegate>("vkGetPhysicalDeviceSparseImageFormatProperties", "");
this.vkQueueBindSparse = cache.GetCommandDelegate<Interop.VkQueueBindSparseDelegate>("vkQueueBindSparse", "");
this.vkCreateFence = cache.GetCommandDelegate<Interop.VkDeviceCreateFenceDelegate>("vkCreateFence", "");
this.vkDestroyFence = cache.GetCommandDelegate<Interop.VkFenceDestroyDelegate>("vkDestroyFence", "");
this.vkResetFences = cache.GetCommandDelegate<Interop.VkDeviceResetFencesDelegate>("vkResetFences", "");
this.vkGetFenceStatus = cache.GetCommandDelegate<Interop.VkFenceGetStatusDelegate>("vkGetFenceStatus", "");
this.vkWaitForFences = cache.GetCommandDelegate<Interop.VkDeviceWaitForFencesDelegate>("vkWaitForFences", "");
this.vkCreateSemaphore = cache.GetCommandDelegate<Interop.VkDeviceCreateSemaphoreDelegate>("vkCreateSemaphore", "");
this.vkDestroySemaphore = cache.GetCommandDelegate<Interop.VkSemaphoreDestroyDelegate>("vkDestroySemaphore", "");
this.vkCreateEvent = cache.GetCommandDelegate<Interop.VkDeviceCreateEventDelegate>("vkCreateEvent", "");
this.vkDestroyEvent = cache.GetCommandDelegate<Interop.VkEventDestroyDelegate>("vkDestroyEvent", "");
this.vkGetEventStatus = cache.GetCommandDelegate<Interop.VkEventGetStatusDelegate>("vkGetEventStatus", "");
this.vkSetEvent = cache.GetCommandDelegate<Interop.VkEventSetDelegate>("vkSetEvent", "");
this.vkResetEvent = cache.GetCommandDelegate<Interop.VkEventResetDelegate>("vkResetEvent", "");
this.vkCreateQueryPool = cache.GetCommandDelegate<Interop.VkDeviceCreateQueryPoolDelegate>("vkCreateQueryPool", "");
this.vkDestroyQueryPool = cache.GetCommandDelegate<Interop.VkQueryPoolDestroyDelegate>("vkDestroyQueryPool", "");
this.vkGetQueryPoolResults = cache.GetCommandDelegate<Interop.VkQueryPoolGetResultsDelegate>("vkGetQueryPoolResults", "");
this.vkCreateBuffer = cache.GetCommandDelegate<Interop.VkDeviceCreateBufferDelegate>("vkCreateBuffer", "");
this.vkDestroyBuffer = cache.GetCommandDelegate<Interop.VkBufferDestroyDelegate>("vkDestroyBuffer", "");
this.vkCreateBufferView = cache.GetCommandDelegate<Interop.VkDeviceCreateBufferViewDelegate>("vkCreateBufferView", "");
this.vkDestroyBufferView = cache.GetCommandDelegate<Interop.VkBufferViewDestroyDelegate>("vkDestroyBufferView", "");
this.vkCreateImage = cache.GetCommandDelegate<Interop.VkDeviceCreateImageDelegate>("vkCreateImage", "");
this.vkDestroyImage = cache.GetCommandDelegate<Interop.VkImageDestroyDelegate>("vkDestroyImage", "");
this.vkGetImageSubresourceLayout = cache.GetCommandDelegate<Interop.VkImageGetSubresourceLayoutDelegate>("vkGetImageSubresourceLayout", "");
this.vkCreateImageView = cache.GetCommandDelegate<Interop.VkDeviceCreateImageViewDelegate>("vkCreateImageView", "");
this.vkDestroyImageView = cache.GetCommandDelegate<Interop.VkImageViewDestroyDelegate>("vkDestroyImageView", "");
this.vkCreateShaderModule = cache.GetCommandDelegate<Interop.VkDeviceCreateShaderModuleDelegate>("vkCreateShaderModule", "");
this.vkDestroyShaderModule = cache.GetCommandDelegate<Interop.VkShaderModuleDestroyDelegate>("vkDestroyShaderModule", "");
this.vkCreatePipelineCache = cache.GetCommandDelegate<Interop.VkDeviceCreatePipelineCacheDelegate>("vkCreatePipelineCache", "");
this.vkDestroyPipelineCache = cache.GetCommandDelegate<Interop.VkPipelineCacheDestroyDelegate>("vkDestroyPipelineCache", "");
this.vkGetPipelineCacheData = cache.GetCommandDelegate<Interop.VkPipelineCacheGetDataDelegate>("vkGetPipelineCacheData", "");
this.vkMergePipelineCaches = cache.GetCommandDelegate<Interop.VkPipelineCacheMergePipelineCachesDelegate>("vkMergePipelineCaches", "");
this.vkCreateGraphicsPipelines = cache.GetCommandDelegate<Interop.VkDeviceCreateGraphicsPipelinesDelegate>("vkCreateGraphicsPipelines", "");
this.vkCreateComputePipelines = cache.GetCommandDelegate<Interop.VkDeviceCreateComputePipelinesDelegate>("vkCreateComputePipelines", "");
this.vkDestroyPipeline = cache.GetCommandDelegate<Interop.VkPipelineDestroyDelegate>("vkDestroyPipeline", "");
this.vkCreatePipelineLayout = cache.GetCommandDelegate<Interop.VkDeviceCreatePipelineLayoutDelegate>("vkCreatePipelineLayout", "");
this.vkDestroyPipelineLayout = cache.GetCommandDelegate<Interop.VkPipelineLayoutDestroyDelegate>("vkDestroyPipelineLayout", "");
this.vkCreateSampler = cache.GetCommandDelegate<Interop.VkDeviceCreateSamplerDelegate>("vkCreateSampler", "");
this.vkDestroySampler = cache.GetCommandDelegate<Interop.VkSamplerDestroyDelegate>("vkDestroySampler", "");
this.vkCreateDescriptorSetLayout = cache.GetCommandDelegate<Interop.VkDeviceCreateDescriptorSetLayoutDelegate>("vkCreateDescriptorSetLayout", "");
this.vkDestroyDescriptorSetLayout = cache.GetCommandDelegate<Interop.VkDescriptorSetLayoutDestroyDelegate>("vkDestroyDescriptorSetLayout", "");
this.vkCreateDescriptorPool = cache.GetCommandDelegate<Interop.VkDeviceCreateDescriptorPoolDelegate>("vkCreateDescriptorPool", "");
this.vkDestroyDescriptorPool = cache.GetCommandDelegate<Interop.VkDescriptorPoolDestroyDelegate>("vkDestroyDescriptorPool", "");
this.vkResetDescriptorPool = cache.GetCommandDelegate<Interop.VkDescriptorPoolResetDelegate>("vkResetDescriptorPool", "");
this.vkAllocateDescriptorSets = cache.GetCommandDelegate<Interop.VkDeviceAllocateDescriptorSetsDelegate>("vkAllocateDescriptorSets", "");
this.vkFreeDescriptorSets = cache.GetCommandDelegate<Interop.VkDescriptorPoolFreeDescriptorSetsDelegate>("vkFreeDescriptorSets", "");
this.vkUpdateDescriptorSets = cache.GetCommandDelegate<Interop.VkDeviceUpdateDescriptorSetsDelegate>("vkUpdateDescriptorSets", "");
this.vkCreateFramebuffer = cache.GetCommandDelegate<Interop.VkDeviceCreateFramebufferDelegate>("vkCreateFramebuffer", "");
this.vkDestroyFramebuffer = cache.GetCommandDelegate<Interop.VkFramebufferDestroyDelegate>("vkDestroyFramebuffer", "");
this.vkCreateRenderPass = cache.GetCommandDelegate<Interop.VkDeviceCreateRenderPassDelegate>("vkCreateRenderPass", "");
this.vkDestroyRenderPass = cache.GetCommandDelegate<Interop.VkRenderPassDestroyDelegate>("vkDestroyRenderPass", "");
this.vkGetRenderAreaGranularity = cache.GetCommandDelegate<Interop.VkRenderPassGetRenderAreaGranularityDelegate>("vkGetRenderAreaGranularity", "");
this.vkCreateCommandPool = cache.GetCommandDelegate<Interop.VkDeviceCreateCommandPoolDelegate>("vkCreateCommandPool", "");
this.vkDestroyCommandPool = cache.GetCommandDelegate<Interop.VkCommandPoolDestroyDelegate>("vkDestroyCommandPool", "");
this.vkResetCommandPool = cache.GetCommandDelegate<Interop.VkCommandPoolResetDelegate>("vkResetCommandPool", "");
this.vkAllocateCommandBuffers = cache.GetCommandDelegate<Interop.VkDeviceAllocateCommandBuffersDelegate>("vkAllocateCommandBuffers", "");
this.vkFreeCommandBuffers = cache.GetCommandDelegate<Interop.VkCommandPoolFreeCommandBuffersDelegate>("vkFreeCommandBuffers", "");
this.vkBeginCommandBuffer = cache.GetCommandDelegate<Interop.VkCommandBufferBeginDelegate>("vkBeginCommandBuffer", "");
this.vkEndCommandBuffer = cache.GetCommandDelegate<Interop.VkCommandBufferEndDelegate>("vkEndCommandBuffer", "");
this.vkResetCommandBuffer = cache.GetCommandDelegate<Interop.VkCommandBufferResetDelegate>("vkResetCommandBuffer", "");
this.vkCmdBindPipeline = cache.GetCommandDelegate<Interop.VkCommandBufferBindPipelineDelegate>("vkCmdBindPipeline", "");
this.vkCmdSetViewport = cache.GetCommandDelegate<Interop.VkCommandBufferSetViewportDelegate>("vkCmdSetViewport", "");
this.vkCmdSetScissor = cache.GetCommandDelegate<Interop.VkCommandBufferSetScissorDelegate>("vkCmdSetScissor", "");
this.vkCmdSetLineWidth = cache.GetCommandDelegate<Interop.VkCommandBufferSetLineWidthDelegate>("vkCmdSetLineWidth", "");
this.vkCmdSetDepthBias = cache.GetCommandDelegate<Interop.VkCommandBufferSetDepthBiasDelegate>("vkCmdSetDepthBias", "");
this.vkCmdSetBlendConstants = cache.GetCommandDelegate<Interop.VkCommandBufferSetBlendConstantsDelegate>("vkCmdSetBlendConstants", "");
this.vkCmdSetDepthBounds = cache.GetCommandDelegate<Interop.VkCommandBufferSetDepthBoundsDelegate>("vkCmdSetDepthBounds", "");
this.vkCmdSetStencilCompareMask = cache.GetCommandDelegate<Interop.VkCommandBufferSetStencilCompareMaskDelegate>("vkCmdSetStencilCompareMask", "");
this.vkCmdSetStencilWriteMask = cache.GetCommandDelegate<Interop.VkCommandBufferSetStencilWriteMaskDelegate>("vkCmdSetStencilWriteMask", "");
this.vkCmdSetStencilReference = cache.GetCommandDelegate<Interop.VkCommandBufferSetStencilReferenceDelegate>("vkCmdSetStencilReference", "");
this.vkCmdBindDescriptorSets = cache.GetCommandDelegate<Interop.VkCommandBufferBindDescriptorSetsDelegate>("vkCmdBindDescriptorSets", "");
this.vkCmdBindIndexBuffer = cache.GetCommandDelegate<Interop.VkCommandBufferBindIndexBufferDelegate>("vkCmdBindIndexBuffer", "");
this.vkCmdBindVertexBuffers = cache.GetCommandDelegate<Interop.VkCommandBufferBindVertexBuffersDelegate>("vkCmdBindVertexBuffers", "");
this.vkCmdDraw = cache.GetCommandDelegate<Interop.VkCommandBufferDrawDelegate>("vkCmdDraw", "");
this.vkCmdDrawIndexed = cache.GetCommandDelegate<Interop.VkCommandBufferDrawIndexedDelegate>("vkCmdDrawIndexed", "");
this.vkCmdDrawIndirect = cache.GetCommandDelegate<Interop.VkCommandBufferDrawIndirectDelegate>("vkCmdDrawIndirect", "");
this.vkCmdDrawIndexedIndirect = cache.GetCommandDelegate<Interop.VkCommandBufferDrawIndexedIndirectDelegate>("vkCmdDrawIndexedIndirect", "");
this.vkCmdDispatch = cache.GetCommandDelegate<Interop.VkCommandBufferDispatchDelegate>("vkCmdDispatch", "");
this.vkCmdDispatchIndirect = cache.GetCommandDelegate<Interop.VkCommandBufferDispatchIndirectDelegate>("vkCmdDispatchIndirect", "");
this.vkCmdCopyBuffer = cache.GetCommandDelegate<Interop.VkCommandBufferCopyBufferDelegate>("vkCmdCopyBuffer", "");
this.vkCmdCopyImage = cache.GetCommandDelegate<Interop.VkCommandBufferCopyImageDelegate>("vkCmdCopyImage", "");
this.vkCmdBlitImage = cache.GetCommandDelegate<Interop.VkCommandBufferBlitImageDelegate>("vkCmdBlitImage", "");
this.vkCmdCopyBufferToImage = cache.GetCommandDelegate<Interop.VkCommandBufferCopyBufferToImageDelegate>("vkCmdCopyBufferToImage", "");
this.vkCmdCopyImageToBuffer = cache.GetCommandDelegate<Interop.VkCommandBufferCopyImageToBufferDelegate>("vkCmdCopyImageToBuffer", "");
this.vkCmdUpdateBuffer = cache.GetCommandDelegate<Interop.VkCommandBufferUpdateBufferDelegate>("vkCmdUpdateBuffer", "");
this.vkCmdFillBuffer = cache.GetCommandDelegate<Interop.VkCommandBufferFillBufferDelegate>("vkCmdFillBuffer", "");
this.vkCmdClearColorImage = cache.GetCommandDelegate<Interop.VkCommandBufferClearColorImageDelegate>("vkCmdClearColorImage", "");
this.vkCmdClearDepthStencilImage = cache.GetCommandDelegate<Interop.VkCommandBufferClearDepthStencilImageDelegate>("vkCmdClearDepthStencilImage", "");
this.vkCmdClearAttachments = cache.GetCommandDelegate<Interop.VkCommandBufferClearAttachmentsDelegate>("vkCmdClearAttachments", "");
this.vkCmdResolveImage = cache.GetCommandDelegate<Interop.VkCommandBufferResolveImageDelegate>("vkCmdResolveImage", "");
this.vkCmdSetEvent = cache.GetCommandDelegate<Interop.VkCommandBufferSetEventDelegate>("vkCmdSetEvent", "");
this.vkCmdResetEvent = cache.GetCommandDelegate<Interop.VkCommandBufferResetEventDelegate>("vkCmdResetEvent", "");
this.vkCmdWaitEvents = cache.GetCommandDelegate<Interop.VkCommandBufferWaitEventsDelegate>("vkCmdWaitEvents", "");
this.vkCmdPipelineBarrier = cache.GetCommandDelegate<Interop.VkCommandBufferPipelineBarrierDelegate>("vkCmdPipelineBarrier", "");
this.vkCmdBeginQuery = cache.GetCommandDelegate<Interop.VkCommandBufferBeginQueryDelegate>("vkCmdBeginQuery", "");
this.vkCmdEndQuery = cache.GetCommandDelegate<Interop.VkCommandBufferEndQueryDelegate>("vkCmdEndQuery", "");
this.vkCmdResetQueryPool = cache.GetCommandDelegate<Interop.VkCommandBufferResetQueryPoolDelegate>("vkCmdResetQueryPool", "");
this.vkCmdWriteTimestamp = cache.GetCommandDelegate<Interop.VkCommandBufferWriteTimestampDelegate>("vkCmdWriteTimestamp", "");
this.vkCmdCopyQueryPoolResults = cache.GetCommandDelegate<Interop.VkCommandBufferCopyQueryPoolResultsDelegate>("vkCmdCopyQueryPoolResults", "");
this.vkCmdPushConstants = cache.GetCommandDelegate<Interop.VkCommandBufferPushConstantsDelegate>("vkCmdPushConstants", "");
this.vkCmdBeginRenderPass = cache.GetCommandDelegate<Interop.VkCommandBufferBeginRenderPassDelegate>("vkCmdBeginRenderPass", "");
this.vkCmdNextSubpass = cache.GetCommandDelegate<Interop.VkCommandBufferNextSubpassDelegate>("vkCmdNextSubpass", "");
this.vkCmdEndRenderPass = cache.GetCommandDelegate<Interop.VkCommandBufferEndRenderPassDelegate>("vkCmdEndRenderPass", "");
this.vkCmdExecuteCommands = cache.GetCommandDelegate<Interop.VkCommandBufferExecuteCommandsDelegate>("vkCmdExecuteCommands", "");
this.vkEnumerateInstanceVersion = cache.GetCommandDelegate<Interop.VkInstanceEnumerateVersionDelegate>("vkEnumerateInstanceVersion", "");
this.vkBindBufferMemory2 = cache.GetCommandDelegate<Interop.VkDeviceBindBufferMemory2Delegate>("vkBindBufferMemory2", "");
this.vkBindImageMemory2 = cache.GetCommandDelegate<Interop.VkDeviceBindImageMemory2Delegate>("vkBindImageMemory2", "");
this.vkGetDeviceGroupPeerMemoryFeatures = cache.GetCommandDelegate<Interop.VkDeviceGetGroupPeerMemoryFeaturesDelegate>("vkGetDeviceGroupPeerMemoryFeatures", "");
this.vkCmdSetDeviceMask = cache.GetCommandDelegate<Interop.VkCommandBufferSetDeviceMaskDelegate>("vkCmdSetDeviceMask", "");
this.vkCmdDispatchBase = cache.GetCommandDelegate<Interop.VkCommandBufferDispatchBaseDelegate>("vkCmdDispatchBase", "");
this.vkEnumeratePhysicalDeviceGroups = cache.GetCommandDelegate<Interop.VkInstanceEnumeratePhysicalDeviceGroupsDelegate>("vkEnumeratePhysicalDeviceGroups", "");
this.vkGetImageMemoryRequirements2 = cache.GetCommandDelegate<Interop.VkDeviceGetImageMemoryRequirements2Delegate>("vkGetImageMemoryRequirements2", "");
this.vkGetBufferMemoryRequirements2 = cache.GetCommandDelegate<Interop.VkDeviceGetBufferMemoryRequirements2Delegate>("vkGetBufferMemoryRequirements2", "");
this.vkGetImageSparseMemoryRequirements2 = cache.GetCommandDelegate<Interop.VkDeviceGetImageSparseMemoryRequirements2Delegate>("vkGetImageSparseMemoryRequirements2", "");
this.vkGetPhysicalDeviceFeatures2 = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetFeatures2Delegate>("vkGetPhysicalDeviceFeatures2", "");
this.vkGetPhysicalDeviceProperties2 = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetProperties2Delegate>("vkGetPhysicalDeviceProperties2", "");
this.vkGetPhysicalDeviceFormatProperties2 = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetFormatProperties2Delegate>("vkGetPhysicalDeviceFormatProperties2", "");
this.vkGetPhysicalDeviceImageFormatProperties2 = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetImageFormatProperties2Delegate>("vkGetPhysicalDeviceImageFormatProperties2", "");
this.vkGetPhysicalDeviceQueueFamilyProperties2 = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetQueueFamilyProperties2Delegate>("vkGetPhysicalDeviceQueueFamilyProperties2", "");
this.vkGetPhysicalDeviceMemoryProperties2 = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetMemoryProperties2Delegate>("vkGetPhysicalDeviceMemoryProperties2", "");
this.vkGetPhysicalDeviceSparseImageFormatProperties2 = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetSparseImageFormatProperties2Delegate>("vkGetPhysicalDeviceSparseImageFormatProperties2", "");
this.vkTrimCommandPool = cache.GetCommandDelegate<Interop.VkCommandPoolTrimDelegate>("vkTrimCommandPool", "");
this.vkGetDeviceQueue2 = cache.GetCommandDelegate<Interop.VkDeviceGetQueue2Delegate>("vkGetDeviceQueue2", "");
this.vkCreateSamplerYcbcrConversion = cache.GetCommandDelegate<Interop.VkDeviceCreateSamplerYcbcrConversionDelegate>("vkCreateSamplerYcbcrConversion", "");
this.vkDestroySamplerYcbcrConversion = cache.GetCommandDelegate<Interop.VkSamplerYcbcrConversionDestroyDelegate>("vkDestroySamplerYcbcrConversion", "");
this.vkCreateDescriptorUpdateTemplate = cache.GetCommandDelegate<Interop.VkDeviceCreateDescriptorUpdateTemplateDelegate>("vkCreateDescriptorUpdateTemplate", "");
this.vkDestroyDescriptorUpdateTemplate = cache.GetCommandDelegate<Interop.VkDescriptorUpdateTemplateDestroyDelegate>("vkDestroyDescriptorUpdateTemplate", "");
this.vkUpdateDescriptorSetWithTemplate = cache.GetCommandDelegate<Interop.VkDeviceUpdateDescriptorSetWithTemplateDelegate>("vkUpdateDescriptorSetWithTemplate", "");
this.vkGetPhysicalDeviceExternalBufferProperties = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetExternalBufferPropertiesDelegate>("vkGetPhysicalDeviceExternalBufferProperties", "");
this.vkGetPhysicalDeviceExternalFenceProperties = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetExternalFencePropertiesDelegate>("vkGetPhysicalDeviceExternalFenceProperties", "");
this.vkGetPhysicalDeviceExternalSemaphoreProperties = cache.GetCommandDelegate<Interop.VkPhysicalDeviceGetExternalSemaphorePropertiesDelegate>("vkGetPhysicalDeviceExternalSemaphoreProperties", "");
this.vkGetDescriptorSetLayoutSupport = cache.GetCommandDelegate<Interop.VkDeviceGetDescriptorSetLayoutSupportDelegate>("vkGetDescriptorSetLayoutSupport", "");
this.vkCmdDrawIndirectCount = cache.GetCommandDelegate<Interop.VkCommandBufferDrawIndirectCountDelegate>("vkCmdDrawIndirectCount", "");
this.vkCmdDrawIndexedIndirectCount = cache.GetCommandDelegate<Interop.VkCommandBufferDrawIndexedIndirectCountDelegate>("vkCmdDrawIndexedIndirectCount", "");
this.vkCreateRenderPass2 = cache.GetCommandDelegate<Interop.VkDeviceCreateRenderPass2Delegate>("vkCreateRenderPass2", "");
this.vkCmdBeginRenderPass2 = cache.GetCommandDelegate<Interop.VkCommandBufferBeginRenderPass2Delegate>("vkCmdBeginRenderPass2", "");
this.vkCmdNextSubpass2 = cache.GetCommandDelegate<Interop.VkCommandBufferNextSubpass2Delegate>("vkCmdNextSubpass2", "");
this.vkCmdEndRenderPass2 = cache.GetCommandDelegate<Interop.VkCommandBufferEndRenderPass2Delegate>("vkCmdEndRenderPass2", "");
this.vkResetQueryPool = cache.GetCommandDelegate<Interop.VkQueryPoolResetDelegate>("vkResetQueryPool", "");
this.vkGetSemaphoreCounterValue = cache.GetCommandDelegate<Interop.VkSemaphoreGetCounterValueDelegate>("vkGetSemaphoreCounterValue", "");
this.vkWaitSemaphores = cache.GetCommandDelegate<Interop.VkDeviceWaitSemaphoresDelegate>("vkWaitSemaphores", "");
this.vkSignalSemaphore = cache.GetCommandDelegate<Interop.VkDeviceSignalSemaphoreDelegate>("vkSignalSemaphore", "");
this.vkGetBufferDeviceAddress = cache.GetCommandDelegate<Interop.VkDeviceGetBufferDeviceAddressDelegate>("vkGetBufferDeviceAddress", "");
this.vkGetBufferOpaqueCaptureAddress = cache.GetCommandDelegate<Interop.VkDeviceGetBufferOpaqueCaptureAddressDelegate>("vkGetBufferOpaqueCaptureAddress", "");
this.vkGetDeviceMemoryOpaqueCaptureAddress = cache.GetCommandDelegate<Interop.VkDeviceGetMemoryOpaqueCaptureAddressDelegate>("vkGetDeviceMemoryOpaqueCaptureAddress", "");
this.vkDestroySurfaceKHR = cache.GetCommandDelegate<Interop.Khronos.VkSurfaceKHRDestroyDelegate>("vkDestroySurfaceKHR", "instance");
this.vkGetPhysicalDeviceSurfaceSupportKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetSurfaceSupportDelegate>("vkGetPhysicalDeviceSurfaceSupportKHR", "instance");
this.vkGetPhysicalDeviceSurfaceCapabilitiesKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetSurfaceCapabilitiesDelegate>("vkGetPhysicalDeviceSurfaceCapabilitiesKHR", "instance");
this.vkGetPhysicalDeviceSurfaceFormatsKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetSurfaceFormatsDelegate>("vkGetPhysicalDeviceSurfaceFormatsKHR", "instance");
this.vkGetPhysicalDeviceSurfacePresentModesKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetSurfacePresentModesDelegate>("vkGetPhysicalDeviceSurfacePresentModesKHR", "instance");
this.vkCreateSwapchainKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceCreateSwapchainDelegate>("vkCreateSwapchainKHR", "device");
this.vkDestroySwapchainKHR = cache.GetCommandDelegate<Interop.Khronos.VkSwapchainKHRDestroyDelegate>("vkDestroySwapchainKHR", "device");
this.vkGetSwapchainImagesKHR = cache.GetCommandDelegate<Interop.Khronos.VkSwapchainKHRGetImagesDelegate>("vkGetSwapchainImagesKHR", "device");
this.vkAcquireNextImageKHR = cache.GetCommandDelegate<Interop.Khronos.VkSwapchainKHRAcquireNextImageDelegate>("vkAcquireNextImageKHR", "device");
this.vkQueuePresentKHR = cache.GetCommandDelegate<Interop.Khronos.VkQueuePresentDelegate>("vkQueuePresentKHR", "device");
this.vkGetDeviceGroupPresentCapabilitiesKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetGroupPresentCapabilitiesDelegate>("vkGetDeviceGroupPresentCapabilitiesKHR", "device");
this.vkGetDeviceGroupSurfacePresentModesKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetGroupSurfacePresentModesDelegate>("vkGetDeviceGroupSurfacePresentModesKHR", "device");
this.vkGetPhysicalDevicePresentRectanglesKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetPresentRectanglesDelegate>("vkGetPhysicalDevicePresentRectanglesKHR", "device");
this.vkAcquireNextImage2KHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceAcquireNextImage2Delegate>("vkAcquireNextImage2KHR", "device");
this.vkGetPhysicalDeviceDisplayPropertiesKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetDisplayPropertiesDelegate>("vkGetPhysicalDeviceDisplayPropertiesKHR", "instance");
this.vkGetPhysicalDeviceDisplayPlanePropertiesKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetDisplayPlanePropertiesDelegate>("vkGetPhysicalDeviceDisplayPlanePropertiesKHR", "instance");
this.vkGetDisplayPlaneSupportedDisplaysKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetDisplayPlaneSupportedDisplaysDelegate>("vkGetDisplayPlaneSupportedDisplaysKHR", "instance");
this.vkGetDisplayModePropertiesKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetDisplayModePropertiesDelegate>("vkGetDisplayModePropertiesKHR", "instance");
this.vkCreateDisplayModeKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceCreateDisplayModeDelegate>("vkCreateDisplayModeKHR", "instance");
this.vkGetDisplayPlaneCapabilitiesKHR = cache.GetCommandDelegate<Interop.Khronos.VkDisplayModeKHRGetDisplayPlaneCapabilitiesDelegate>("vkGetDisplayPlaneCapabilitiesKHR", "instance");
this.vkCreateDisplayPlaneSurfaceKHR = cache.GetCommandDelegate<Interop.Khronos.VkInstanceCreateDisplayPlaneSurfaceDelegate>("vkCreateDisplayPlaneSurfaceKHR", "instance");
this.vkCreateSharedSwapchainsKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceCreateSharedSwapchainsDelegate>("vkCreateSharedSwapchainsKHR", "device");
this.vkCreateXlibSurfaceKHR = cache.GetCommandDelegate<Interop.Khronos.VkInstanceCreateXlibSurfaceDelegate>("vkCreateXlibSurfaceKHR", "instance");
this.vkGetPhysicalDeviceXlibPresentationSupportKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetXlibPresentationSupportDelegate>("vkGetPhysicalDeviceXlibPresentationSupportKHR", "instance");
this.vkCreateXcbSurfaceKHR = cache.GetCommandDelegate<Interop.Khronos.VkInstanceCreateXcbSurfaceDelegate>("vkCreateXcbSurfaceKHR", "instance");
this.vkGetPhysicalDeviceXcbPresentationSupportKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetXcbPresentationSupportDelegate>("vkGetPhysicalDeviceXcbPresentationSupportKHR", "instance");
this.vkCreateWaylandSurfaceKHR = cache.GetCommandDelegate<Interop.Khronos.VkInstanceCreateWaylandSurfaceDelegate>("vkCreateWaylandSurfaceKHR", "instance");
this.vkGetPhysicalDeviceWaylandPresentationSupportKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetWaylandPresentationSupportDelegate>("vkGetPhysicalDeviceWaylandPresentationSupportKHR", "instance");
this.vkCreateAndroidSurfaceKHR = cache.GetCommandDelegate<Interop.Khronos.VkInstanceCreateAndroidSurfaceDelegate>("vkCreateAndroidSurfaceKHR", "instance");
this.vkCreateWin32SurfaceKHR = cache.GetCommandDelegate<Interop.Khronos.VkInstanceCreateWin32SurfaceDelegate>("vkCreateWin32SurfaceKHR", "instance");
this.vkGetPhysicalDeviceWin32PresentationSupportKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetWin32PresentationSupportDelegate>("vkGetPhysicalDeviceWin32PresentationSupportKHR", "instance");
this.vkCreateDebugReportCallbackEXT = cache.GetCommandDelegate<Interop.Multivendor.VkInstanceCreateDebugReportCallbackDelegate>("vkCreateDebugReportCallbackEXT", "instance");
this.vkDestroyDebugReportCallbackEXT = cache.GetCommandDelegate<Interop.Multivendor.VkDebugReportCallbackEXTDestroyDelegate>("vkDestroyDebugReportCallbackEXT", "instance");
this.vkDebugReportMessageEXT = cache.GetCommandDelegate<Interop.Multivendor.VkInstanceDebugReportMessageDelegate>("vkDebugReportMessageEXT", "instance");
this.vkCmdBindTransformFeedbackBuffersEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferBindTransformFeedbackBuffersDelegate>("vkCmdBindTransformFeedbackBuffersEXT", "device");
this.vkCmdBeginTransformFeedbackEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferBeginTransformFeedbackDelegate>("vkCmdBeginTransformFeedbackEXT", "device");
this.vkCmdEndTransformFeedbackEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferEndTransformFeedbackDelegate>("vkCmdEndTransformFeedbackEXT", "device");
this.vkCmdBeginQueryIndexedEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferBeginQueryIndexedDelegate>("vkCmdBeginQueryIndexedEXT", "device");
this.vkCmdEndQueryIndexedEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferEndQueryIndexedDelegate>("vkCmdEndQueryIndexedEXT", "device");
this.vkCmdDrawIndirectByteCountEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferDrawIndirectByteCountDelegate>("vkCmdDrawIndirectByteCountEXT", "device");
this.vkGetImageViewHandleNVX = cache.GetCommandDelegate<Interop.NVidia.Experimental.VkDeviceGetImageViewHandleDelegate>("vkGetImageViewHandleNVX", "device");
this.vkGetShaderInfoAMD = cache.GetCommandDelegate<Interop.Amd.VkPipelineGetShaderInfoDelegate>("vkGetShaderInfoAMD", "device");
this.vkCreateStreamDescriptorSurfaceGGP = cache.GetCommandDelegate<Interop.Ggp.VkInstanceCreateStreamDescriptorSurfaceDelegate>("vkCreateStreamDescriptorSurfaceGGP", "instance");
this.vkGetPhysicalDeviceExternalImageFormatPropertiesNV = cache.GetCommandDelegate<Interop.NVidia.VkPhysicalDeviceGetExternalImageFormatPropertiesDelegate>("vkGetPhysicalDeviceExternalImageFormatPropertiesNV", "instance");
this.vkGetMemoryWin32HandleNV = cache.GetCommandDelegate<Interop.NVidia.VkDeviceMemoryGetWin32HandleDelegate>("vkGetMemoryWin32HandleNV", "device");
this.vkCreateViSurfaceNN = cache.GetCommandDelegate<Interop.Nintendo.VkInstanceCreateViSurfaceDelegate>("vkCreateViSurfaceNN", "instance");
this.vkGetMemoryWin32HandleKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetMemoryWin32HandleDelegate>("vkGetMemoryWin32HandleKHR", "device");
this.vkGetMemoryWin32HandlePropertiesKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetMemoryWin32HandlePropertiesDelegate>("vkGetMemoryWin32HandlePropertiesKHR", "device");
this.vkGetMemoryFdKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetMemoryFileDescriptorDelegate>("vkGetMemoryFdKHR", "device");
this.vkGetMemoryFdPropertiesKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetMemoryFileDescriptorPropertiesDelegate>("vkGetMemoryFdPropertiesKHR", "device");
this.vkImportSemaphoreWin32HandleKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceImportSemaphoreWin32HandleDelegate>("vkImportSemaphoreWin32HandleKHR", "device");
this.vkGetSemaphoreWin32HandleKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetSemaphoreWin32HandleDelegate>("vkGetSemaphoreWin32HandleKHR", "device");
this.vkImportSemaphoreFdKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceImportSemaphoreFileDescriptorDelegate>("vkImportSemaphoreFdKHR", "device");
this.vkGetSemaphoreFdKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetSemaphoreFileDescriptorDelegate>("vkGetSemaphoreFdKHR", "device");
this.vkCmdPushDescriptorSetKHR = cache.GetCommandDelegate<Interop.Khronos.VkCommandBufferPushDescriptorSetDelegate>("vkCmdPushDescriptorSetKHR", "device");
this.vkCmdPushDescriptorSetWithTemplateKHR = cache.GetCommandDelegate<Interop.Khronos.VkCommandBufferPushDescriptorSetWithTemplateDelegate>("vkCmdPushDescriptorSetWithTemplateKHR", "device");
this.vkCmdBeginConditionalRenderingEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferBeginConditionalRenderingDelegate>("vkCmdBeginConditionalRenderingEXT", "device");
this.vkCmdEndConditionalRenderingEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferEndConditionalRenderingDelegate>("vkCmdEndConditionalRenderingEXT", "device");
this.vkCmdProcessCommandsNVX = cache.GetCommandDelegate<Interop.NVidia.Experimental.VkCommandBufferProcessCommandsDelegate>("vkCmdProcessCommandsNVX", "device");
this.vkCmdReserveSpaceForCommandsNVX = cache.GetCommandDelegate<Interop.NVidia.Experimental.VkCommandBufferReserveSpaceForCommandsDelegate>("vkCmdReserveSpaceForCommandsNVX", "device");
this.vkCreateIndirectCommandsLayoutNVX = cache.GetCommandDelegate<Interop.NVidia.Experimental.VkDeviceCreateIndirectCommandsLayoutDelegate>("vkCreateIndirectCommandsLayoutNVX", "device");
this.vkDestroyIndirectCommandsLayoutNVX = cache.GetCommandDelegate<Interop.NVidia.Experimental.VkIndirectCommandsLayoutNVXDestroyDelegate>("vkDestroyIndirectCommandsLayoutNVX", "device");
this.vkCreateObjectTableNVX = cache.GetCommandDelegate<Interop.NVidia.Experimental.VkDeviceCreateObjectTableDelegate>("vkCreateObjectTableNVX", "device");
this.vkDestroyObjectTableNVX = cache.GetCommandDelegate<Interop.NVidia.Experimental.VkObjectTableNVXDestroyDelegate>("vkDestroyObjectTableNVX", "device");
this.vkRegisterObjectsNVX = cache.GetCommandDelegate<Interop.NVidia.Experimental.VkObjectTableNVXRegisterObjectsDelegate>("vkRegisterObjectsNVX", "device");
this.vkUnregisterObjectsNVX = cache.GetCommandDelegate<Interop.NVidia.Experimental.VkObjectTableNVXUnregisterObjectsDelegate>("vkUnregisterObjectsNVX", "device");
this.vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX = cache.GetCommandDelegate<Interop.NVidia.Experimental.VkPhysicalDeviceGetGeneratedCommandsPropertiesDelegate>("vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX", "device");
this.vkCmdSetViewportWScalingNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferSetViewportWScalingDelegate>("vkCmdSetViewportWScalingNV", "device");
this.vkReleaseDisplayEXT = cache.GetCommandDelegate<Interop.Multivendor.VkPhysicalDeviceReleaseDisplayDelegate>("vkReleaseDisplayEXT", "instance");
this.vkAcquireXlibDisplayEXT = cache.GetCommandDelegate<Interop.Multivendor.VkPhysicalDeviceAcquireXlibDisplayDelegate>("vkAcquireXlibDisplayEXT", "instance");
this.vkGetRandROutputDisplayEXT = cache.GetCommandDelegate<Interop.Multivendor.VkPhysicalDeviceGetRandROutputDisplayDelegate>("vkGetRandROutputDisplayEXT", "instance");
this.vkGetPhysicalDeviceSurfaceCapabilities2EXT = cache.GetCommandDelegate<Interop.Multivendor.VkPhysicalDeviceGetSurfaceCapabilities2Delegate>("vkGetPhysicalDeviceSurfaceCapabilities2EXT", "instance");
this.vkDisplayPowerControlEXT = cache.GetCommandDelegate<Interop.Multivendor.VkDeviceDisplayPowerControlDelegate>("vkDisplayPowerControlEXT", "device");
this.vkRegisterDeviceEventEXT = cache.GetCommandDelegate<Interop.Multivendor.VkDeviceRegisterEventDelegate>("vkRegisterDeviceEventEXT", "device");
this.vkRegisterDisplayEventEXT = cache.GetCommandDelegate<Interop.Multivendor.VkDeviceRegisterDisplayEventDelegate>("vkRegisterDisplayEventEXT", "device");
this.vkGetSwapchainCounterEXT = cache.GetCommandDelegate<Interop.Multivendor.VkSwapchainKHRGetCounterDelegate>("vkGetSwapchainCounterEXT", "device");
this.vkGetRefreshCycleDurationGOOGLE = cache.GetCommandDelegate<Interop.Google.VkSwapchainKHRGetRefreshCycleDurationDelegate>("vkGetRefreshCycleDurationGOOGLE", "device");
this.vkGetPastPresentationTimingGOOGLE = cache.GetCommandDelegate<Interop.Google.VkSwapchainKHRGetPastPresentationTimingDelegate>("vkGetPastPresentationTimingGOOGLE", "device");
this.vkCmdSetDiscardRectangleEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferSetDiscardRectangleDelegate>("vkCmdSetDiscardRectangleEXT", "device");
this.vkSetHdrMetadataEXT = cache.GetCommandDelegate<Interop.Multivendor.VkDeviceSetHdrMetadataDelegate>("vkSetHdrMetadataEXT", "device");
this.vkGetSwapchainStatusKHR = cache.GetCommandDelegate<Interop.Khronos.VkSwapchainKHRGetStatusDelegate>("vkGetSwapchainStatusKHR", "device");
this.vkImportFenceWin32HandleKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceImportFenceWin32HandleDelegate>("vkImportFenceWin32HandleKHR", "device");
this.vkGetFenceWin32HandleKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetFenceWin32HandleDelegate>("vkGetFenceWin32HandleKHR", "device");
this.vkImportFenceFdKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceImportFenceFileDescriptorDelegate>("vkImportFenceFdKHR", "device");
this.vkGetFenceFdKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetFenceFileDescriptorDelegate>("vkGetFenceFdKHR", "device");
this.vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceEnumerateQueueFamilyPerformanceQueryCountersDelegate>("vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR", "device");
this.vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetQueueFamilyPerformanceQueryPassesDelegate>("vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR", "device");
this.vkAcquireProfilingLockKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceAcquireProfilingLockDelegate>("vkAcquireProfilingLockKHR", "device");
this.vkReleaseProfilingLockKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceReleaseProfilingLockDelegate>("vkReleaseProfilingLockKHR", "device");
this.vkGetPhysicalDeviceSurfaceCapabilities2KHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetSurfaceCapabilities2Delegate>("vkGetPhysicalDeviceSurfaceCapabilities2KHR", "instance");
this.vkGetPhysicalDeviceSurfaceFormats2KHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetSurfaceFormats2Delegate>("vkGetPhysicalDeviceSurfaceFormats2KHR", "instance");
this.vkGetPhysicalDeviceDisplayProperties2KHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetDisplayProperties2Delegate>("vkGetPhysicalDeviceDisplayProperties2KHR", "instance");
this.vkGetPhysicalDeviceDisplayPlaneProperties2KHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetDisplayPlaneProperties2Delegate>("vkGetPhysicalDeviceDisplayPlaneProperties2KHR", "instance");
this.vkGetDisplayModeProperties2KHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetDisplayModeProperties2Delegate>("vkGetDisplayModeProperties2KHR", "instance");
this.vkGetDisplayPlaneCapabilities2KHR = cache.GetCommandDelegate<Interop.Khronos.VkPhysicalDeviceGetDisplayPlaneCapabilities2Delegate>("vkGetDisplayPlaneCapabilities2KHR", "instance");
this.vkCreateIOSSurfaceMVK = cache.GetCommandDelegate<Interop.MoltenVk.VkInstanceCreateIOSSurfaceDelegate>("vkCreateIOSSurfaceMVK", "instance");
this.vkCreateMacOSSurfaceMVK = cache.GetCommandDelegate<Interop.MoltenVk.VkInstanceCreateMacOSSurfaceDelegate>("vkCreateMacOSSurfaceMVK", "instance");
this.vkSetDebugUtilsObjectNameEXT = cache.GetCommandDelegate<Interop.Multivendor.VkDeviceSetDebugUtilsObjectNameDelegate>("vkSetDebugUtilsObjectNameEXT", "instance");
this.vkSetDebugUtilsObjectTagEXT = cache.GetCommandDelegate<Interop.Multivendor.VkDeviceSetDebugUtilsObjectTagDelegate>("vkSetDebugUtilsObjectTagEXT", "instance");
this.vkQueueBeginDebugUtilsLabelEXT = cache.GetCommandDelegate<Interop.Multivendor.VkQueueBeginDebugUtilsLabelDelegate>("vkQueueBeginDebugUtilsLabelEXT", "instance");
this.vkQueueEndDebugUtilsLabelEXT = cache.GetCommandDelegate<Interop.Multivendor.VkQueueEndDebugUtilsLabelDelegate>("vkQueueEndDebugUtilsLabelEXT", "instance");
this.vkQueueInsertDebugUtilsLabelEXT = cache.GetCommandDelegate<Interop.Multivendor.VkQueueInsertDebugUtilsLabelDelegate>("vkQueueInsertDebugUtilsLabelEXT", "instance");
this.vkCmdBeginDebugUtilsLabelEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferBeginDebugUtilsLabelDelegate>("vkCmdBeginDebugUtilsLabelEXT", "instance");
this.vkCmdEndDebugUtilsLabelEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferEndDebugUtilsLabelDelegate>("vkCmdEndDebugUtilsLabelEXT", "instance");
this.vkCmdInsertDebugUtilsLabelEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferInsertDebugUtilsLabelDelegate>("vkCmdInsertDebugUtilsLabelEXT", "instance");
this.vkCreateDebugUtilsMessengerEXT = cache.GetCommandDelegate<Interop.Multivendor.VkInstanceCreateDebugUtilsMessengerDelegate>("vkCreateDebugUtilsMessengerEXT", "instance");
this.vkDestroyDebugUtilsMessengerEXT = cache.GetCommandDelegate<Interop.Multivendor.VkDebugUtilsMessengerEXTDestroyDelegate>("vkDestroyDebugUtilsMessengerEXT", "instance");
this.vkSubmitDebugUtilsMessageEXT = cache.GetCommandDelegate<Interop.Multivendor.VkInstanceSubmitDebugUtilsMessageDelegate>("vkSubmitDebugUtilsMessageEXT", "instance");
this.vkGetAndroidHardwareBufferPropertiesANDROID = cache.GetCommandDelegate<Interop.Android.VkDeviceGetAndroidHardwareBufferPropertiesDelegate>("vkGetAndroidHardwareBufferPropertiesANDROID", "device");
this.vkGetMemoryAndroidHardwareBufferANDROID = cache.GetCommandDelegate<Interop.Android.VkDeviceGetMemoryAndroidHardwareBufferDelegate>("vkGetMemoryAndroidHardwareBufferANDROID", "device");
this.vkCmdSetSampleLocationsEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferSetSampleLocationsDelegate>("vkCmdSetSampleLocationsEXT", "device");
this.vkGetPhysicalDeviceMultisamplePropertiesEXT = cache.GetCommandDelegate<Interop.Multivendor.VkPhysicalDeviceGetMultisamplePropertiesDelegate>("vkGetPhysicalDeviceMultisamplePropertiesEXT", "device");
this.vkGetImageDrmFormatModifierPropertiesEXT = cache.GetCommandDelegate<Interop.Multivendor.VkImageGetDrmFormatModifierPropertiesDelegate>("vkGetImageDrmFormatModifierPropertiesEXT", "device");
this.vkCreateValidationCacheEXT = cache.GetCommandDelegate<Interop.Multivendor.VkDeviceCreateValidationCacheDelegate>("vkCreateValidationCacheEXT", "device");
this.vkDestroyValidationCacheEXT = cache.GetCommandDelegate<Interop.Multivendor.VkValidationCacheEXTDestroyDelegate>("vkDestroyValidationCacheEXT", "device");
this.vkMergeValidationCachesEXT = cache.GetCommandDelegate<Interop.Multivendor.VkValidationCacheEXTMergeValidationCachesDelegate>("vkMergeValidationCachesEXT", "device");
this.vkGetValidationCacheDataEXT = cache.GetCommandDelegate<Interop.Multivendor.VkValidationCacheEXTGetDataDelegate>("vkGetValidationCacheDataEXT", "device");
this.vkCmdBindShadingRateImageNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferBindShadingRateImageDelegate>("vkCmdBindShadingRateImageNV", "device");
this.vkCmdSetViewportShadingRatePaletteNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferSetViewportShadingRatePaletteDelegate>("vkCmdSetViewportShadingRatePaletteNV", "device");
this.vkCmdSetCoarseSampleOrderNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferSetCoarseSampleOrderDelegate>("vkCmdSetCoarseSampleOrderNV", "device");
this.vkCreateAccelerationStructureNV = cache.GetCommandDelegate<Interop.NVidia.VkDeviceCreateAccelerationStructureDelegate>("vkCreateAccelerationStructureNV", "device");
this.vkDestroyAccelerationStructureNV = cache.GetCommandDelegate<Interop.NVidia.VkAccelerationStructureNVDestroyDelegate>("vkDestroyAccelerationStructureNV", "device");
this.vkGetAccelerationStructureMemoryRequirementsNV = cache.GetCommandDelegate<Interop.NVidia.VkDeviceGetAccelerationStructureMemoryRequirementsDelegate>("vkGetAccelerationStructureMemoryRequirementsNV", "device");
this.vkBindAccelerationStructureMemoryNV = cache.GetCommandDelegate<Interop.NVidia.VkDeviceBindAccelerationStructureMemoryDelegate>("vkBindAccelerationStructureMemoryNV", "device");
this.vkCmdBuildAccelerationStructureNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferBuildAccelerationStructureDelegate>("vkCmdBuildAccelerationStructureNV", "device");
this.vkCmdCopyAccelerationStructureNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferCopyAccelerationStructureDelegate>("vkCmdCopyAccelerationStructureNV", "device");
this.vkCmdTraceRaysNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferTraceRaysDelegate>("vkCmdTraceRaysNV", "device");
this.vkCreateRayTracingPipelinesNV = cache.GetCommandDelegate<Interop.NVidia.VkDeviceCreateRayTracingPipelinesDelegate>("vkCreateRayTracingPipelinesNV", "device");
this.vkGetRayTracingShaderGroupHandlesNV = cache.GetCommandDelegate<Interop.NVidia.VkPipelineGetRayTracingShaderGroupHandlesDelegate>("vkGetRayTracingShaderGroupHandlesNV", "device");
this.vkGetAccelerationStructureHandleNV = cache.GetCommandDelegate<Interop.NVidia.VkAccelerationStructureNVGetHandleDelegate>("vkGetAccelerationStructureHandleNV", "device");
this.vkCmdWriteAccelerationStructuresPropertiesNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferWriteAccelerationStructuresPropertiesDelegate>("vkCmdWriteAccelerationStructuresPropertiesNV", "device");
this.vkCompileDeferredNV = cache.GetCommandDelegate<Interop.NVidia.VkPipelineCompileDeferredDelegate>("vkCompileDeferredNV", "device");
this.vkGetMemoryHostPointerPropertiesEXT = cache.GetCommandDelegate<Interop.Multivendor.VkDeviceGetMemoryHostPointerPropertiesDelegate>("vkGetMemoryHostPointerPropertiesEXT", "device");
this.vkCmdWriteBufferMarkerAMD = cache.GetCommandDelegate<Interop.Amd.VkCommandBufferWriteBufferMarkerDelegate>("vkCmdWriteBufferMarkerAMD", "device");
this.vkGetPhysicalDeviceCalibrateableTimeDomainsEXT = cache.GetCommandDelegate<Interop.Multivendor.VkPhysicalDeviceGetCalibrateableTimeDomainsDelegate>("vkGetPhysicalDeviceCalibrateableTimeDomainsEXT", "device");
this.vkGetCalibratedTimestampsEXT = cache.GetCommandDelegate<Interop.Multivendor.VkDeviceGetCalibratedTimestampsDelegate>("vkGetCalibratedTimestampsEXT", "device");
this.vkCmdDrawMeshTasksNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferDrawMeshTasksDelegate>("vkCmdDrawMeshTasksNV", "device");
this.vkCmdDrawMeshTasksIndirectNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferDrawMeshTasksIndirectDelegate>("vkCmdDrawMeshTasksIndirectNV", "device");
this.vkCmdDrawMeshTasksIndirectCountNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferDrawMeshTasksIndirectCountDelegate>("vkCmdDrawMeshTasksIndirectCountNV", "device");
this.vkCmdSetExclusiveScissorNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferSetExclusiveScissorDelegate>("vkCmdSetExclusiveScissorNV", "device");
this.vkCmdSetCheckpointNV = cache.GetCommandDelegate<Interop.NVidia.VkCommandBufferSetCheckpointDelegate>("vkCmdSetCheckpointNV", "device");
this.vkGetQueueCheckpointDataNV = cache.GetCommandDelegate<Interop.NVidia.VkQueueGetCheckpointDataDelegate>("vkGetQueueCheckpointDataNV", "device");
this.vkInitializePerformanceApiINTEL = cache.GetCommandDelegate<Interop.Intel.VkDeviceInitializePerformanceApiDelegate>("vkInitializePerformanceApiINTEL", "device");
this.vkUninitializePerformanceApiINTEL = cache.GetCommandDelegate<Interop.Intel.VkDeviceUninitializePerformanceApiDelegate>("vkUninitializePerformanceApiINTEL", "device");
this.vkCmdSetPerformanceMarkerINTEL = cache.GetCommandDelegate<Interop.Intel.VkCommandBufferSetPerformanceMarkerDelegate>("vkCmdSetPerformanceMarkerINTEL", "device");
this.vkCmdSetPerformanceStreamMarkerINTEL = cache.GetCommandDelegate<Interop.Intel.VkCommandBufferSetPerformanceStreamMarkerDelegate>("vkCmdSetPerformanceStreamMarkerINTEL", "device");
this.vkCmdSetPerformanceOverrideINTEL = cache.GetCommandDelegate<Interop.Intel.VkCommandBufferSetPerformanceOverrideDelegate>("vkCmdSetPerformanceOverrideINTEL", "device");
this.vkAcquirePerformanceConfigurationINTEL = cache.GetCommandDelegate<Interop.Intel.VkDeviceAcquirePerformanceConfigurationDelegate>("vkAcquirePerformanceConfigurationINTEL", "device");
this.vkReleasePerformanceConfigurationINTEL = cache.GetCommandDelegate<Interop.Intel.VkPerformanceConfigurationINTELReleaseDelegate>("vkReleasePerformanceConfigurationINTEL", "device");
this.vkQueueSetPerformanceConfigurationINTEL = cache.GetCommandDelegate<Interop.Intel.VkQueueSetPerformanceConfigurationDelegate>("vkQueueSetPerformanceConfigurationINTEL", "device");
this.vkGetPerformanceParameterINTEL = cache.GetCommandDelegate<Interop.Intel.VkDeviceGetPerformanceParameterDelegate>("vkGetPerformanceParameterINTEL", "device");
this.vkSetLocalDimmingAMD = cache.GetCommandDelegate<Interop.Amd.VkSwapchainKHRSetLocalDimmingDelegate>("vkSetLocalDimmingAMD", "device");
this.vkCreateImagePipeSurfaceFUCHSIA = cache.GetCommandDelegate<Interop.Fuchsia.VkInstanceCreateImagePipeSurfaceDelegate>("vkCreateImagePipeSurfaceFUCHSIA", "instance");
this.vkCreateMetalSurfaceEXT = cache.GetCommandDelegate<Interop.Multivendor.VkInstanceCreateMetalSurfaceDelegate>("vkCreateMetalSurfaceEXT", "instance");
this.vkGetPhysicalDeviceToolPropertiesEXT = cache.GetCommandDelegate<Interop.Multivendor.VkPhysicalDeviceGetToolPropertiesDelegate>("vkGetPhysicalDeviceToolPropertiesEXT", "device");
this.vkGetPhysicalDeviceCooperativeMatrixPropertiesNV = cache.GetCommandDelegate<Interop.NVidia.VkPhysicalDeviceGetCooperativeMatrixPropertiesDelegate>("vkGetPhysicalDeviceCooperativeMatrixPropertiesNV", "device");
this.vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV = cache.GetCommandDelegate<Interop.NVidia.VkPhysicalDeviceGetSupportedFramebufferMixedSamplesCombinationsDelegate>("vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV", "device");
this.vkGetPhysicalDeviceSurfacePresentModes2EXT = cache.GetCommandDelegate<Interop.Multivendor.VkPhysicalDeviceGetSurfacePresentModes2Delegate>("vkGetPhysicalDeviceSurfacePresentModes2EXT", "device");
this.vkAcquireFullScreenExclusiveModeEXT = cache.GetCommandDelegate<Interop.Multivendor.VkSwapchainKHRAcquireFullScreenExclusiveModeDelegate>("vkAcquireFullScreenExclusiveModeEXT", "device");
this.vkReleaseFullScreenExclusiveModeEXT = cache.GetCommandDelegate<Interop.Multivendor.VkSwapchainKHRReleaseFullScreenExclusiveModeDelegate>("vkReleaseFullScreenExclusiveModeEXT", "device");
this.vkGetDeviceGroupSurfacePresentModes2EXT = cache.GetCommandDelegate<Interop.Multivendor.VkDeviceGetGroupSurfacePresentModes2Delegate>("vkGetDeviceGroupSurfacePresentModes2EXT", "device");
this.vkCreateHeadlessSurfaceEXT = cache.GetCommandDelegate<Interop.Multivendor.VkInstanceCreateHeadlessSurfaceDelegate>("vkCreateHeadlessSurfaceEXT", "instance");
this.vkCmdSetLineStippleEXT = cache.GetCommandDelegate<Interop.Multivendor.VkCommandBufferSetLineStippleDelegate>("vkCmdSetLineStippleEXT", "device");
this.vkGetPipelineExecutablePropertiesKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetPipelineExecutablePropertiesDelegate>("vkGetPipelineExecutablePropertiesKHR", "device");
this.vkGetPipelineExecutableStatisticsKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetPipelineExecutableStatisticsDelegate>("vkGetPipelineExecutableStatisticsKHR", "device");
this.vkGetPipelineExecutableInternalRepresentationsKHR = cache.GetCommandDelegate<Interop.Khronos.VkDeviceGetPipelineExecutableInternalRepresentationsDelegate>("vkGetPipelineExecutableInternalRepresentationsKHR", "device");
}
}
}
| |
/*
* CP861.cs - Icelandic (DOS) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ibm-861.ucm".
namespace I18N.West
{
using System;
using I18N.Common;
public class CP861 : ByteEncoding
{
public CP861()
: base(861, ToChars, "Icelandic (DOS)",
"ibm861", "ibm861", "ibm861",
false, false, false, false, 1252)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
'\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001C', '\u001B', '\u007F', '\u001D',
'\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
'\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029',
'\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
'\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041',
'\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D',
'\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059',
'\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065',
'\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
'\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071',
'\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'\u007E', '\u001A', '\u00C7', '\u00FC', '\u00E9', '\u00E2',
'\u00E4', '\u00E0', '\u00E5', '\u00E7', '\u00EA', '\u00EB',
'\u00E8', '\u00D0', '\u00F0', '\u00DE', '\u00C4', '\u00C5',
'\u00C9', '\u00E6', '\u00C6', '\u00F4', '\u00F6', '\u00FE',
'\u00FB', '\u00DD', '\u00FD', '\u00D6', '\u00DC', '\u00F8',
'\u00A3', '\u00D8', '\u20A7', '\u0192', '\u00E1', '\u00ED',
'\u00F3', '\u00FA', '\u00C1', '\u00CD', '\u00D3', '\u00DA',
'\u00BF', '\u2310', '\u00AC', '\u00BD', '\u00BC', '\u00A1',
'\u00AB', '\u00BB', '\u2591', '\u2592', '\u2593', '\u2502',
'\u2524', '\u2561', '\u2562', '\u2556', '\u2555', '\u2563',
'\u2551', '\u2557', '\u255D', '\u255C', '\u255B', '\u2510',
'\u2514', '\u2534', '\u252C', '\u251C', '\u2500', '\u253C',
'\u255E', '\u255F', '\u255A', '\u2554', '\u2569', '\u2566',
'\u2560', '\u2550', '\u256C', '\u2567', '\u2568', '\u2564',
'\u2565', '\u2559', '\u2558', '\u2552', '\u2553', '\u256B',
'\u256A', '\u2518', '\u250C', '\u2588', '\u2584', '\u258C',
'\u2590', '\u2580', '\u03B1', '\u00DF', '\u0393', '\u03C0',
'\u03A3', '\u03C3', '\u03BC', '\u03C4', '\u03A6', '\u0398',
'\u03A9', '\u03B4', '\u221E', '\u03C6', '\u03B5', '\u2229',
'\u2261', '\u00B1', '\u2265', '\u2264', '\u2320', '\u2321',
'\u00F7', '\u2248', '\u00B0', '\u2219', '\u00B7', '\u221A',
'\u207F', '\u00B2', '\u25A0', '\u00A0',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 26) switch(ch)
{
case 0x001B:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x0020:
case 0x0021:
case 0x0022:
case 0x0023:
case 0x0024:
case 0x0025:
case 0x0026:
case 0x0027:
case 0x0028:
case 0x0029:
case 0x002A:
case 0x002B:
case 0x002C:
case 0x002D:
case 0x002E:
case 0x002F:
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
case 0x003A:
case 0x003B:
case 0x003C:
case 0x003D:
case 0x003E:
case 0x003F:
case 0x0040:
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
case 0x005B:
case 0x005C:
case 0x005D:
case 0x005E:
case 0x005F:
case 0x0060:
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
case 0x007B:
case 0x007C:
case 0x007D:
case 0x007E:
break;
case 0x001A: ch = 0x7F; break;
case 0x001C: ch = 0x1A; break;
case 0x007F: ch = 0x1C; break;
case 0x00A0: ch = 0xFF; break;
case 0x00A1: ch = 0xAD; break;
case 0x00A3: ch = 0x9C; break;
case 0x00A7: ch = 0x15; break;
case 0x00AB: ch = 0xAE; break;
case 0x00AC: ch = 0xAA; break;
case 0x00B0: ch = 0xF8; break;
case 0x00B1: ch = 0xF1; break;
case 0x00B2: ch = 0xFD; break;
case 0x00B6: ch = 0x14; break;
case 0x00B7: ch = 0xFA; break;
case 0x00BB: ch = 0xAF; break;
case 0x00BC: ch = 0xAC; break;
case 0x00BD: ch = 0xAB; break;
case 0x00BF: ch = 0xA8; break;
case 0x00C1: ch = 0xA4; break;
case 0x00C4: ch = 0x8E; break;
case 0x00C5: ch = 0x8F; break;
case 0x00C6: ch = 0x92; break;
case 0x00C7: ch = 0x80; break;
case 0x00C9: ch = 0x90; break;
case 0x00CD: ch = 0xA5; break;
case 0x00D0: ch = 0x8B; break;
case 0x00D3: ch = 0xA6; break;
case 0x00D6: ch = 0x99; break;
case 0x00D8: ch = 0x9D; break;
case 0x00DA: ch = 0xA7; break;
case 0x00DC: ch = 0x9A; break;
case 0x00DD: ch = 0x97; break;
case 0x00DE: ch = 0x8D; break;
case 0x00DF: ch = 0xE1; break;
case 0x00E0: ch = 0x85; break;
case 0x00E1: ch = 0xA0; break;
case 0x00E2: ch = 0x83; break;
case 0x00E4: ch = 0x84; break;
case 0x00E5: ch = 0x86; break;
case 0x00E6: ch = 0x91; break;
case 0x00E7: ch = 0x87; break;
case 0x00E8: ch = 0x8A; break;
case 0x00E9: ch = 0x82; break;
case 0x00EA: ch = 0x88; break;
case 0x00EB: ch = 0x89; break;
case 0x00ED: ch = 0xA1; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F3: ch = 0xA2; break;
case 0x00F4: ch = 0x93; break;
case 0x00F6: ch = 0x94; break;
case 0x00F7: ch = 0xF6; break;
case 0x00F8: ch = 0x9B; break;
case 0x00FA: ch = 0xA3; break;
case 0x00FB: ch = 0x96; break;
case 0x00FC: ch = 0x81; break;
case 0x00FD: ch = 0x98; break;
case 0x00FE: ch = 0x95; break;
case 0x0192: ch = 0x9F; break;
case 0x0393: ch = 0xE2; break;
case 0x0398: ch = 0xE9; break;
case 0x03A3: ch = 0xE4; break;
case 0x03A6: ch = 0xE8; break;
case 0x03A9: ch = 0xEA; break;
case 0x03B1: ch = 0xE0; break;
case 0x03B4: ch = 0xEB; break;
case 0x03B5: ch = 0xEE; break;
case 0x03BC: ch = 0xE6; break;
case 0x03C0: ch = 0xE3; break;
case 0x03C3: ch = 0xE5; break;
case 0x03C4: ch = 0xE7; break;
case 0x03C6: ch = 0xED; break;
case 0x2022: ch = 0x07; break;
case 0x203C: ch = 0x13; break;
case 0x207F: ch = 0xFC; break;
case 0x20A7: ch = 0x9E; break;
case 0x2190: ch = 0x1B; break;
case 0x2191: ch = 0x18; break;
case 0x2192: ch = 0x1A; break;
case 0x2193: ch = 0x19; break;
case 0x2194: ch = 0x1D; break;
case 0x2195: ch = 0x12; break;
case 0x21A8: ch = 0x17; break;
case 0x2219: ch = 0xF9; break;
case 0x221A: ch = 0xFB; break;
case 0x221E: ch = 0xEC; break;
case 0x221F: ch = 0x1C; break;
case 0x2229: ch = 0xEF; break;
case 0x2248: ch = 0xF7; break;
case 0x2261: ch = 0xF0; break;
case 0x2264: ch = 0xF3; break;
case 0x2265: ch = 0xF2; break;
case 0x2302: ch = 0x7F; break;
case 0x2310: ch = 0xA9; break;
case 0x2320: ch = 0xF4; break;
case 0x2321: ch = 0xF5; break;
case 0x2500: ch = 0xC4; break;
case 0x2502: ch = 0xB3; break;
case 0x250C: ch = 0xDA; break;
case 0x2510: ch = 0xBF; break;
case 0x2514: ch = 0xC0; break;
case 0x2518: ch = 0xD9; break;
case 0x251C: ch = 0xC3; break;
case 0x2524: ch = 0xB4; break;
case 0x252C: ch = 0xC2; break;
case 0x2534: ch = 0xC1; break;
case 0x253C: ch = 0xC5; break;
case 0x2550: ch = 0xCD; break;
case 0x2551: ch = 0xBA; break;
case 0x2552: ch = 0xD5; break;
case 0x2553: ch = 0xD6; break;
case 0x2554: ch = 0xC9; break;
case 0x2555: ch = 0xB8; break;
case 0x2556: ch = 0xB7; break;
case 0x2557: ch = 0xBB; break;
case 0x2558: ch = 0xD4; break;
case 0x2559: ch = 0xD3; break;
case 0x255A: ch = 0xC8; break;
case 0x255B: ch = 0xBE; break;
case 0x255C: ch = 0xBD; break;
case 0x255D: ch = 0xBC; break;
case 0x255E: ch = 0xC6; break;
case 0x255F: ch = 0xC7; break;
case 0x2560: ch = 0xCC; break;
case 0x2561: ch = 0xB5; break;
case 0x2562: ch = 0xB6; break;
case 0x2563: ch = 0xB9; break;
case 0x2564: ch = 0xD1; break;
case 0x2565: ch = 0xD2; break;
case 0x2566: ch = 0xCB; break;
case 0x2567: ch = 0xCF; break;
case 0x2568: ch = 0xD0; break;
case 0x2569: ch = 0xCA; break;
case 0x256A: ch = 0xD8; break;
case 0x256B: ch = 0xD7; break;
case 0x256C: ch = 0xCE; break;
case 0x2580: ch = 0xDF; break;
case 0x2584: ch = 0xDC; break;
case 0x2588: ch = 0xDB; break;
case 0x258C: ch = 0xDD; break;
case 0x2590: ch = 0xDE; break;
case 0x2591: ch = 0xB0; break;
case 0x2592: ch = 0xB1; break;
case 0x2593: ch = 0xB2; break;
case 0x25A0: ch = 0xFE; break;
case 0x25AC: ch = 0x16; break;
case 0x25B2: ch = 0x1E; break;
case 0x25BA: ch = 0x10; break;
case 0x25BC: ch = 0x1F; break;
case 0x25C4: ch = 0x11; break;
case 0x25CB: ch = 0x09; break;
case 0x25D8: ch = 0x08; break;
case 0x25D9: ch = 0x0A; break;
case 0x263A: ch = 0x01; break;
case 0x263B: ch = 0x02; break;
case 0x263C: ch = 0x0F; break;
case 0x2640: ch = 0x0C; break;
case 0x2642: ch = 0x0B; break;
case 0x2660: ch = 0x06; break;
case 0x2663: ch = 0x05; break;
case 0x2665: ch = 0x03; break;
case 0x2666: ch = 0x04; break;
case 0x266A: ch = 0x0D; break;
case 0x266B: ch = 0x0E; break;
case 0xFFE8: ch = 0xB3; break;
case 0xFFE9: ch = 0x1B; break;
case 0xFFEA: ch = 0x18; break;
case 0xFFEB: ch = 0x1A; break;
case 0xFFEC: ch = 0x19; break;
case 0xFFED: ch = 0xFE; break;
case 0xFFEE: ch = 0x09; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 26) switch(ch)
{
case 0x001B:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x0020:
case 0x0021:
case 0x0022:
case 0x0023:
case 0x0024:
case 0x0025:
case 0x0026:
case 0x0027:
case 0x0028:
case 0x0029:
case 0x002A:
case 0x002B:
case 0x002C:
case 0x002D:
case 0x002E:
case 0x002F:
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
case 0x003A:
case 0x003B:
case 0x003C:
case 0x003D:
case 0x003E:
case 0x003F:
case 0x0040:
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
case 0x005B:
case 0x005C:
case 0x005D:
case 0x005E:
case 0x005F:
case 0x0060:
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
case 0x007B:
case 0x007C:
case 0x007D:
case 0x007E:
break;
case 0x001A: ch = 0x7F; break;
case 0x001C: ch = 0x1A; break;
case 0x007F: ch = 0x1C; break;
case 0x00A0: ch = 0xFF; break;
case 0x00A1: ch = 0xAD; break;
case 0x00A3: ch = 0x9C; break;
case 0x00A7: ch = 0x15; break;
case 0x00AB: ch = 0xAE; break;
case 0x00AC: ch = 0xAA; break;
case 0x00B0: ch = 0xF8; break;
case 0x00B1: ch = 0xF1; break;
case 0x00B2: ch = 0xFD; break;
case 0x00B6: ch = 0x14; break;
case 0x00B7: ch = 0xFA; break;
case 0x00BB: ch = 0xAF; break;
case 0x00BC: ch = 0xAC; break;
case 0x00BD: ch = 0xAB; break;
case 0x00BF: ch = 0xA8; break;
case 0x00C1: ch = 0xA4; break;
case 0x00C4: ch = 0x8E; break;
case 0x00C5: ch = 0x8F; break;
case 0x00C6: ch = 0x92; break;
case 0x00C7: ch = 0x80; break;
case 0x00C9: ch = 0x90; break;
case 0x00CD: ch = 0xA5; break;
case 0x00D0: ch = 0x8B; break;
case 0x00D3: ch = 0xA6; break;
case 0x00D6: ch = 0x99; break;
case 0x00D8: ch = 0x9D; break;
case 0x00DA: ch = 0xA7; break;
case 0x00DC: ch = 0x9A; break;
case 0x00DD: ch = 0x97; break;
case 0x00DE: ch = 0x8D; break;
case 0x00DF: ch = 0xE1; break;
case 0x00E0: ch = 0x85; break;
case 0x00E1: ch = 0xA0; break;
case 0x00E2: ch = 0x83; break;
case 0x00E4: ch = 0x84; break;
case 0x00E5: ch = 0x86; break;
case 0x00E6: ch = 0x91; break;
case 0x00E7: ch = 0x87; break;
case 0x00E8: ch = 0x8A; break;
case 0x00E9: ch = 0x82; break;
case 0x00EA: ch = 0x88; break;
case 0x00EB: ch = 0x89; break;
case 0x00ED: ch = 0xA1; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F3: ch = 0xA2; break;
case 0x00F4: ch = 0x93; break;
case 0x00F6: ch = 0x94; break;
case 0x00F7: ch = 0xF6; break;
case 0x00F8: ch = 0x9B; break;
case 0x00FA: ch = 0xA3; break;
case 0x00FB: ch = 0x96; break;
case 0x00FC: ch = 0x81; break;
case 0x00FD: ch = 0x98; break;
case 0x00FE: ch = 0x95; break;
case 0x0192: ch = 0x9F; break;
case 0x0393: ch = 0xE2; break;
case 0x0398: ch = 0xE9; break;
case 0x03A3: ch = 0xE4; break;
case 0x03A6: ch = 0xE8; break;
case 0x03A9: ch = 0xEA; break;
case 0x03B1: ch = 0xE0; break;
case 0x03B4: ch = 0xEB; break;
case 0x03B5: ch = 0xEE; break;
case 0x03BC: ch = 0xE6; break;
case 0x03C0: ch = 0xE3; break;
case 0x03C3: ch = 0xE5; break;
case 0x03C4: ch = 0xE7; break;
case 0x03C6: ch = 0xED; break;
case 0x2022: ch = 0x07; break;
case 0x203C: ch = 0x13; break;
case 0x207F: ch = 0xFC; break;
case 0x20A7: ch = 0x9E; break;
case 0x2190: ch = 0x1B; break;
case 0x2191: ch = 0x18; break;
case 0x2192: ch = 0x1A; break;
case 0x2193: ch = 0x19; break;
case 0x2194: ch = 0x1D; break;
case 0x2195: ch = 0x12; break;
case 0x21A8: ch = 0x17; break;
case 0x2219: ch = 0xF9; break;
case 0x221A: ch = 0xFB; break;
case 0x221E: ch = 0xEC; break;
case 0x221F: ch = 0x1C; break;
case 0x2229: ch = 0xEF; break;
case 0x2248: ch = 0xF7; break;
case 0x2261: ch = 0xF0; break;
case 0x2264: ch = 0xF3; break;
case 0x2265: ch = 0xF2; break;
case 0x2302: ch = 0x7F; break;
case 0x2310: ch = 0xA9; break;
case 0x2320: ch = 0xF4; break;
case 0x2321: ch = 0xF5; break;
case 0x2500: ch = 0xC4; break;
case 0x2502: ch = 0xB3; break;
case 0x250C: ch = 0xDA; break;
case 0x2510: ch = 0xBF; break;
case 0x2514: ch = 0xC0; break;
case 0x2518: ch = 0xD9; break;
case 0x251C: ch = 0xC3; break;
case 0x2524: ch = 0xB4; break;
case 0x252C: ch = 0xC2; break;
case 0x2534: ch = 0xC1; break;
case 0x253C: ch = 0xC5; break;
case 0x2550: ch = 0xCD; break;
case 0x2551: ch = 0xBA; break;
case 0x2552: ch = 0xD5; break;
case 0x2553: ch = 0xD6; break;
case 0x2554: ch = 0xC9; break;
case 0x2555: ch = 0xB8; break;
case 0x2556: ch = 0xB7; break;
case 0x2557: ch = 0xBB; break;
case 0x2558: ch = 0xD4; break;
case 0x2559: ch = 0xD3; break;
case 0x255A: ch = 0xC8; break;
case 0x255B: ch = 0xBE; break;
case 0x255C: ch = 0xBD; break;
case 0x255D: ch = 0xBC; break;
case 0x255E: ch = 0xC6; break;
case 0x255F: ch = 0xC7; break;
case 0x2560: ch = 0xCC; break;
case 0x2561: ch = 0xB5; break;
case 0x2562: ch = 0xB6; break;
case 0x2563: ch = 0xB9; break;
case 0x2564: ch = 0xD1; break;
case 0x2565: ch = 0xD2; break;
case 0x2566: ch = 0xCB; break;
case 0x2567: ch = 0xCF; break;
case 0x2568: ch = 0xD0; break;
case 0x2569: ch = 0xCA; break;
case 0x256A: ch = 0xD8; break;
case 0x256B: ch = 0xD7; break;
case 0x256C: ch = 0xCE; break;
case 0x2580: ch = 0xDF; break;
case 0x2584: ch = 0xDC; break;
case 0x2588: ch = 0xDB; break;
case 0x258C: ch = 0xDD; break;
case 0x2590: ch = 0xDE; break;
case 0x2591: ch = 0xB0; break;
case 0x2592: ch = 0xB1; break;
case 0x2593: ch = 0xB2; break;
case 0x25A0: ch = 0xFE; break;
case 0x25AC: ch = 0x16; break;
case 0x25B2: ch = 0x1E; break;
case 0x25BA: ch = 0x10; break;
case 0x25BC: ch = 0x1F; break;
case 0x25C4: ch = 0x11; break;
case 0x25CB: ch = 0x09; break;
case 0x25D8: ch = 0x08; break;
case 0x25D9: ch = 0x0A; break;
case 0x263A: ch = 0x01; break;
case 0x263B: ch = 0x02; break;
case 0x263C: ch = 0x0F; break;
case 0x2640: ch = 0x0C; break;
case 0x2642: ch = 0x0B; break;
case 0x2660: ch = 0x06; break;
case 0x2663: ch = 0x05; break;
case 0x2665: ch = 0x03; break;
case 0x2666: ch = 0x04; break;
case 0x266A: ch = 0x0D; break;
case 0x266B: ch = 0x0E; break;
case 0xFFE8: ch = 0xB3; break;
case 0xFFE9: ch = 0x1B; break;
case 0xFFEA: ch = 0x18; break;
case 0xFFEB: ch = 0x1A; break;
case 0xFFEC: ch = 0x19; break;
case 0xFFED: ch = 0xFE; break;
case 0xFFEE: ch = 0x09; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP861
public class ENCibm861 : CP861
{
public ENCibm861() : base() {}
}; // class ENCibm861
}; // namespace I18N.West
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
namespace Eto.Parse
{
/// <summary>
/// Arguments used for each parse operation
/// </summary>
/// <remarks>
/// This is used during the parsing process to track the current match tree, errors, scanner, etc.
/// </remarks>
public class ParseArgs
{
readonly SlimStack<MatchCollection> nodes = new SlimStack<MatchCollection>(50);
readonly List<Parser> errors = new List<Parser>();
int childErrorIndex = -1;
int errorIndex = -1;
readonly Dictionary<object, object> properties = new Dictionary<object, object>();
public Dictionary<object, object> Properties { get { return properties; } }
/// <summary>
/// Gets the root match when the grammar is matched
/// </summary>
public GrammarMatch Root { get; internal set; }
/// <summary>
/// Gets the current scanner used to parse the text
/// </summary>
/// <value>The scanner</value>
public Scanner Scanner { get; private set; }
/// <summary>
/// Gets the current grammar being parsed
/// </summary>
/// <value>The grammar.</value>
public Grammar Grammar { get; private set; }
/// <summary>
/// Gets the index of the last parser error (if any), or -1 if the error has not been set
/// </summary>
/// <remarks>
/// Use the <see cref="Errors"/> collection to get the list of parsers that had an invalid match
/// at this position.
///
/// Only parsers with the <see cref="Parser.AddError"/> flag turned on will cause the error
/// index to be updated to the position of where that parser started from.
///
/// To get where the actual error occurred, see <see cref="ChildErrorIndex"/>, which gives
/// you the exact position where the failure occurred.
///
/// Alternatively, for debugging purposes you can turn on AddError for all parsers by using
/// <see cref="Parser.SetError"/>
/// </remarks>
/// <value>The index of the error.</value>
public int ErrorIndex { get { return errorIndex; } }
/// <summary>
/// Gets the index of where the error action
/// </summary>
/// <value>The index of the error context.</value>
public int ChildErrorIndex { get { return childErrorIndex; } }
/// <summary>
/// Gets the list of parsers that failed a match at the specicified <see cref="ErrorIndex"/>
/// </summary>
/// <remarks>
/// This is only added to when the <see cref="Parser.AddError"/> boolean value is true, and failed to match.
///
/// For example, if you have a SequenceParser with <see cref="AddError"/> set to true, but none of its children,
/// then even when some of the children match (but not all otherwise there wouldn't be an error), then
/// the child won't be added to this list, only the parent.
///
/// The <see cref="ErrorIndex"/> will also indicate the position that the *parent* failed to match, not the
/// child. To get the child index, use <see cref="ChildErrorIndex"/>
/// </remarks>
/// <value>The list of parsers that have errors</value>
public List<Parser> Errors { get { return errors; } }
internal ParseArgs(Grammar grammar, Scanner scanner)
{
Grammar = grammar;
Scanner = scanner;
}
internal bool IsRoot
{
get { return nodes.Count <= 1; }
}
/// <summary>
/// Adds an error for the specified parser at the current position
/// </summary>
/// <param name="parser">Parser to add the error for</param>
public void AddError(Parser parser)
{
var pos = Scanner.Position;
if (pos > errorIndex)
{
errorIndex = pos;
errors.Clear();
errors.Add(parser);
}
else if (pos == errorIndex)
{
errors.Add(parser);
}
if (pos > childErrorIndex)
childErrorIndex = pos;
}
/// <summary>
/// Sets the child error index for parsers that have <see cref="Parser.AddError"/> set to false
/// </summary>
public void SetChildError()
{
var pos = Scanner.Position;
if (pos > childErrorIndex)
childErrorIndex = pos;
}
/// <summary>
/// Pushes a new match tree node
/// </summary>
/// <remarks>
/// Use this when there is a possibility that a child parser will not match, such as the <see cref="Parsers.OptionalParser"/>,
/// items in a <see cref="Parsers.AlternativeParser"/>
/// </remarks>
public void Push()
{
nodes.PushDefault();
}
/// <summary>
/// Pops the last match tree node, and returns its value
/// </summary>
/// <remarks>
/// Use <see cref="PopSuccess"/> or <see cref="PopFailed"/> when implementing parsers.
/// This does not perform any logic like merging the match tree with the parent node when succesful,
/// nor does it allow for re-use of the match collection for added performance.
/// </remarks>
public MatchCollection Pop()
{
return nodes.Pop();
}
/// <summary>
/// When an optional match is successful, this pops the current match tree node and merges it with the
/// parent match tree node.
/// </summary>
/// <remarks>
/// This call must be proceeded with a call to <see cref="Push"/> to push a match tree node.
/// </remarks>
public void PopSuccess()
{
var last = nodes.PopKeep();
if (last != null)
{
var node = nodes.Last;
if (node != null)
{
node.AddRange(last);
last.Clear();
}
else
{
nodes.Last = last;
nodes[nodes.Count] = null;
}
}
}
/// <summary>
/// Clears the matches of the current match tree node
/// </summary>
/// <remarks>
/// Used instead of doing a PopFailed() then another Push(), like an Alternative parser
/// </remarks>
public void ClearMatches()
{
var last = nodes.Last;
if (last != null)
last.Clear();
}
/// <summary>
/// When an optional match did not succeed, this pops the current match tree node and prepares it for re-use.
/// </summary>
/// <remarks>
/// This call must be proceeded with a call to <see cref="Push"/> to push a match tree node.
/// </remarks>
public void PopFailed()
{
var last = nodes.PopKeep();
if (last != null)
{
last.Clear();
}
}
/// <summary>
/// Pops a succesful named match node, and adds it to the parent match node
/// </summary>
/// <param name="parser">Parser with the name to add to the match tree</param>
/// <param name="index">Index of the start of the match</param>
/// <param name="length">Length of the match</param>
/// <param name="name">Name to give the match</param>
public void PopMatch(Parser parser, int index, int length, string name)
{
// always successful here, assume at least two or more nodes
var last = nodes.Pop();
if (nodes.Count > 0)
{
var node = nodes.Last;
if (node == null)
{
node = new MatchCollection();
nodes.Last = node;
}
node.Add(new Match(name, parser, Scanner, index, length, last));
}
}
/// <summary>
/// Pops a succesful named match node, and adds it to the parent match node
/// </summary>
/// <param name="parser">Parser with the name to add to the match tree</param>
/// <param name="index">Index of the start of the match</param>
/// <param name="length">Length of the match</param>
public void PopMatch(Parser parser, int index, int length)
{
// always successful here, assume at least two or more nodes
var last = nodes.Pop();
if (nodes.Count > 0)
{
var node = nodes.Last;
if (node == null)
{
node = new MatchCollection();
nodes.Last = node;
}
node.Add(new Match(parser, Scanner, index, length, last));
}
}
/// <summary>
/// Adds a match to the current result match node with the specified name
/// </summary>
/// <remarks>
/// This is used to add a parse match to the result match tree
/// </remarks>
/// <param name="parser">Parser for the match</param>
/// <param name="index">Index of the start of the match</param>
/// <param name="length">Length of the match</param>
/// <param name="name">Name of this match (usually the Parser.Match value)</param>
public void AddMatch(Parser parser, int index, int length, string name)
{
if (nodes.Count > 0)
{
var node = nodes.Last;
if (node == null)
{
node = new MatchCollection();
nodes.Last = node;
}
node.Add(new Match(name, parser, Scanner, index, length, null));
}
}
/// <summary>
/// Adds a match to the current result match node
/// </summary>
/// <remarks>
/// This is used to add a parse match to the result match tree
/// </remarks>
/// <param name="parser">Parser for the match</param>
/// <param name="index">Index of the start of the match</param>
/// <param name="length">Length of the match</param>
public void AddMatch(Parser parser, int index, int length)
{
if (nodes.Count > 0)
{
var node = nodes.Last;
if (node == null)
{
node = new MatchCollection();
nodes.Last = node;
}
node.Add(new Match(parser, Scanner, index, length));
}
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
// OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ===========================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Node.Cs.Lib.Routing.RouteDefinitions;
namespace Node.Cs.Lib.Routing
{
public class RoutingService : IRoutingService
{
private static string SanitizePath(string pathWithParams)
{
if (!pathWithParams.StartsWith("/")) pathWithParams = "/" + pathWithParams;
pathWithParams = pathWithParams.TrimEnd('/');
return pathWithParams.ToLowerInvariant();
}
private readonly Dictionary<string, ViewDescriptor> _views;
private readonly Dictionary<string, string> _controllers;
private readonly RouteTree _root;
public List<KeyValuePair<string, StaticRoute>> _staticRoutes;
public RoutingService()
{
_views = new Dictionary<string, ViewDescriptor>(StringComparer.InvariantCultureIgnoreCase);
_controllers = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
_root = new RouteTree();
_staticRoutes = new List<KeyValuePair<string, StaticRoute>>();
}
public Route GetRoute(string pathWithParams)
{
pathWithParams = SanitizePath(pathWithParams);
var staticRoute = FindStaticRoute(pathWithParams);
if (staticRoute != null)
{
return staticRoute;
}
var dict = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
return FindRoute(_root, pathWithParams, dict);
}
private Route FindStaticRoute(string pathWithParams)
{
for (int i = 0; i < _staticRoutes.Count; i++)
{
var kvp = _staticRoutes[i];
if (pathWithParams.StartsWith(kvp.Key))
{
var res = pathWithParams.Substring(kvp.Key.Length);
return new Route(kvp.Value, null, kvp.Value.Destination + res);
}
}
return null;
}
private Route FindRoute(RouteTree node, string pathWithParams, Dictionary<string, string> dict)
{
Route result = null;
var splitted = pathWithParams.Split('/');
if (splitted.Length == 0) return null;
var zero = splitted[0].ToLowerInvariant();
if (node.RouteElement == zero)
{
if (splitted.Length == 1)
{
return BuildRoute(node, dict);
}
result = CheckChildren(node, splitted, dict);
}
else if (node.RouteElement.StartsWith("{"))
{
var paramName = node.RouteElement.Trim(new[] { '{', '}' });
if (paramName.StartsWith("*"))
{
paramName = paramName.Substring(1);
dict.Add(paramName, pathWithParams);
return BuildRoute(node, dict);
}
if (paramName.StartsWith("."))
{
paramName = paramName.Substring(1);
}
dict.Add(paramName, HttpUtility.UrlDecode(splitted[0]));
if (splitted.Length == 1)
{
return BuildRoute(node, dict);
}
result = CheckChildren(node, splitted, dict);
}
return result;
}
private static Route BuildRoute(RouteTree node, Dictionary<string, string> dict)
{
return new Route(node.RouteItem, dict);
}
private Route CheckChildren(RouteTree node, IEnumerable<string> splitted, Dictionary<string, string> dict)
{
Route result = null;
if (node.Child.Count > 0)
{
var subItem = string.Join("/", splitted.Skip(1).ToArray());
for (int index = 0; index < node.Child.Count && result == null; index++)
{
var children = node.Child[index];
result = FindRoute(children, subItem, dict);
}
}
return result;
}
public List<ViewDescriptor> Views
{
get { return new List<ViewDescriptor>(_views.Values.ToArray()); }
}
public List<string> Controllers
{
get { return new List<string>(_controllers.Values.ToArray()); }
}
public void RegisterRoute(RouteDefinition definition)
{
var dynamicRoute = definition as DynamicRoute;
if (dynamicRoute != null)
{
RegisterDynamicRoute(dynamicRoute);
return;
}
var staticRoute = definition as StaticRoute;
if (staticRoute != null)
{
RegisterStaticRoute(staticRoute);
return;
}
var viewRegistration = definition as ViewRegistration;
if (viewRegistration != null)
{
RegisterView(viewRegistration);
}
}
private void RegisterView(ViewRegistration viewRegistration)
{
if (!string.IsNullOrWhiteSpace(viewRegistration.View) &&
!_views.ContainsKey(viewRegistration.View))
{
_views.Add(viewRegistration.View, new ViewDescriptor
{
View = viewRegistration.View,
});
}
}
private void RegisterStaticRoute(StaticRoute staticRoute)
{
staticRoute.RoutePath = SanitizePath(staticRoute.RoutePath);
staticRoute.Destination = staticRoute.Destination;
_staticRoutes.Add(new KeyValuePair<string, StaticRoute>(staticRoute.RoutePath, staticRoute));
}
private void RegisterDynamicRoute(DynamicRoute dynamicRoute)
{
if (!string.IsNullOrWhiteSpace(dynamicRoute.View) && !_views.ContainsKey(dynamicRoute.View))
{
_views.Add(dynamicRoute.View, new ViewDescriptor
{
View = dynamicRoute.View,
});
}
dynamicRoute.RoutePath = SanitizePath(dynamicRoute.RoutePath);
if (!CheckRouteValidity(dynamicRoute.RoutePath))
{
//throw new InvalidRouteException(dynamicRoute.RoutePath);
throw new Exception(); //TODO
}
_root.AddChild(dynamicRoute.RoutePath, dynamicRoute);
if (string.IsNullOrWhiteSpace(dynamicRoute.Controller)) return;
if (!_controllers.ContainsKey(dynamicRoute.Controller))
{
_controllers.Add(dynamicRoute.Controller, dynamicRoute.Controller);
}
}
private bool CheckRouteValidity(string route)
{
// ReSharper disable StringIndexOfIsCultureSpecific.1
var indexOfOptional = route.IndexOf("{.");
var indexOfStar = route.IndexOf("{*");
// ReSharper restore StringIndexOfIsCultureSpecific.1
if (indexOfOptional < 0 && indexOfStar < 0) return true;
if (indexOfOptional >= 0 && indexOfStar >= 0) return false;
var indexOfStdParam = -1;
var charray = route.ToCharArray();
for (int i = 0; i < (charray.Length - 1); i++)
{
var ch = charray[i];
var chNext = charray[i + 1];
if (ch == '{' && chNext != '.' && chNext != '*')
{
indexOfStdParam = Math.Max(i, indexOfStdParam);
break;
}
}
if (indexOfStdParam > indexOfOptional && indexOfOptional >= 0)
{
if (indexOfStdParam >= 0) return false;
}
if (indexOfStdParam > indexOfStar && indexOfStar >= 0)
{
if (indexOfStdParam >= 0) return false;
}
return true;
}
}
}
| |
#region License
/*
Licensed to Blue Chilli Technology Pty Ltd and the contributors under the MIT License (the "License").
You may not use this file except in compliance with the License.
See the LICENSE file in the project root for more information.
*/
#endregion
// ***********************************************************************
// Assembly : XLabs.Platform.iOS
// Author : XLabs Team
// Created : 12-27-2015
//
// Last Modified By : XLabs Team
// Last Modified On : 01-04-2016
// ***********************************************************************
// <copyright file="Geolocator.cs" company="XLabs Team">
// Copyright (c) XLabs Team. All rights reserved.
// </copyright>
// <summary>
// This project is licensed under the Apache 2.0 license
// https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/LICENSE
//
// XLabs is a open source project that aims to provide a powerfull and cross
// platform set of controls tailored to work with Xamarin Forms.
// </summary>
// ***********************************************************************
//
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ChilliSource.Mobile.Core;
using ChilliSource.Mobile.Location;
using CoreLocation;
using Foundation;
using UIKit;
using Xamarin.Forms;
[assembly: Dependency(typeof(LocationService))]
namespace ChilliSource.Mobile.Location
{
public class LocationService : ILocationService
{
Position _position;
CLLocationManager _manager;
ILogger _logger;
double _desiredAccuracy;
#region Properties
public bool IsListening { get; private set; }
public bool SupportsHeading
{
get
{
return CLLocationManager.HeadingAvailable;
}
}
public bool IsGeolocationAvailable
{
get
{
return true;
} // all iOS devices support at least wifi geolocation
}
public bool IsGeolocationEnabled
{
get
{
return CLLocationManager.Status >= CLAuthorizationStatus.Authorized;
}
}
#endregion
#region Events
public event EventHandler<PositionErrorEventArgs> ErrorOccured;
public event EventHandler<PositionEventArgs> PositionChanged;
public event EventHandler<RegionEventArgs> RegionEntered;
public event EventHandler<RegionEventArgs> RegionLeft;
public event EventHandler<AuthorizationEventArgs> LocationAuthorizationChanged;
#endregion
#region Lifecycle
public void Initialize(LocationAuthorizationType authorizationType, bool allowBackgroundLocationUpdates, bool monitorRegions = false, ILogger logger = null)
{
_logger = logger;
_manager = GetManager();
_manager.AuthorizationChanged += OnAuthorizationChanged;
_manager.Failed += OnFailed;
_manager.PausesLocationUpdatesAutomatically = false;
if (authorizationType == LocationAuthorizationType.Always)
{
_manager.RequestAlwaysAuthorization();
}
else if (authorizationType == LocationAuthorizationType.WhenInUse)
{
_manager.RequestWhenInUseAuthorization();
}
if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0) && allowBackgroundLocationUpdates)
{
_manager.AllowsBackgroundLocationUpdates = true;
}
if (monitorRegions)
{
_manager.DidStartMonitoringForRegion += LocationManager_DidStartMonitoringForRegion;
_manager.RegionEntered += LocationManager_RegionEntered;
_manager.RegionLeft += LocationManager_RegionLeft;
_manager.DidDetermineState += LocationManager_DidDetermineState;
}
}
public void Dispose()
{
if (_manager != null)
{
StopListening();
_manager.AuthorizationChanged -= OnAuthorizationChanged;
_manager.Failed -= OnFailed;
_manager.Dispose();
_manager = null;
}
}
#endregion
#region Location Monitoring
public void RequestAlwaysAuthorization()
{
if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedWhenInUse)
{
if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
{
_manager.RequestAlwaysAuthorization();
}
}
}
/// <summary>
/// Start listening for location changes
/// </summary>
/// <param name="minTime">Minimum interval in milliseconds</param>
/// <param name="minDistance">Minimum distance in meters</param>
/// <param name="includeHeading">Include heading information</param>
/// <exception cref="ArgumentOutOfRangeException">
/// minTime
/// or
/// minDistance
/// </exception>
/// <exception cref="InvalidOperationException">Already listening</exception>
public OperationResult StartListening(uint minTime, double minDistance, double desiredAccurancy = 0, bool includeHeading = false)
{
if (IsListening)
{
return OperationResult.AsFailure("Already listening");
}
if (minTime < 0)
{
return OperationResult.AsFailure(new ArgumentOutOfRangeException(nameof(minTime)));
}
if (minDistance < 0)
{
return OperationResult.AsFailure(new ArgumentOutOfRangeException(nameof(minDistance)));
}
_desiredAccuracy = desiredAccurancy;
_manager.LocationsUpdated -= OnLocationsUpdated;
_manager.UpdatedHeading -= OnHeadingUpdated;
_manager.LocationsUpdated += OnLocationsUpdated;
_manager.UpdatedHeading += OnHeadingUpdated;
IsListening = true;
_manager.DesiredAccuracy = _desiredAccuracy;
_manager.DistanceFilter = minDistance;
_manager.StartUpdatingLocation();
if (includeHeading && CLLocationManager.HeadingAvailable)
{
_manager.StartUpdatingHeading();
}
return OperationResult.AsSuccess();
}
public OperationResult StopListening()
{
if (!IsListening)
{
return OperationResult.AsFailure("Location updates already stopped");
}
_manager.LocationsUpdated -= OnLocationsUpdated;
_manager.UpdatedHeading -= OnHeadingUpdated;
IsListening = false;
if (CLLocationManager.HeadingAvailable)
{
_manager.StopUpdatingHeading();
}
_manager.StopUpdatingLocation();
_position = null;
return OperationResult.AsSuccess();
}
public void StartListeningForSignificantLocationChanges()
{
_manager.StartMonitoringSignificantLocationChanges();
}
public void StopListeningForSignificantLocationChanges()
{
_manager.StopMonitoringSignificantLocationChanges();
}
public void StartMonitoringBeaconRegion(string uuid, ushort major, ushort minor, string identifier)
{
var beaconUUID = new NSUuid(uuid);
CLBeaconRegion beaconRegion = new CLBeaconRegion(beaconUUID, major, minor, identifier)
{
NotifyEntryStateOnDisplay = true,
NotifyOnEntry = true,
NotifyOnExit = true
};
if (_manager != null)
{
_manager.StartMonitoring(beaconRegion);
_logger?.Information($"iOS: Started monitoring: {identifier}");
}
}
public void StartMonitoringCircularRegion(Position centerPosition, double radius, string identifier)
{
var coordinate = new CLLocationCoordinate2D(centerPosition.Latitude, centerPosition.Longitude);
var region = new CLCircularRegion(coordinate, radius, identifier);
if (_manager != null)
{
_manager.StartMonitoring(region);
_logger?.Information($"iOS: Started monitoring: {identifier}");
}
}
public void StopMonitoringRegion(string identifier)
{
var region = _manager.MonitoredRegions.ToArray<CLRegion>().FirstOrDefault(r => r.Identifier.Equals(identifier));
if (_manager != null && region != null)
{
_manager.StopMonitoring(region);
_logger?.Information($"iOS: Stopped monitoring: {identifier}");
}
}
#endregion
#region Position Management
public Task<OperationResult<Position>> GetPositionAsync(int timeout, bool includeHeading = false)
{
return GetPositionAsync(timeout, CancellationToken.None, includeHeading);
}
public Task<OperationResult<Position>> GetPositionAsync(CancellationToken cancelToken, bool includeHeading = false)
{
return GetPositionAsync(Timeout.Infinite, cancelToken, includeHeading);
}
public Task<OperationResult<Position>> GetPositionAsync(int timeout, CancellationToken cancelToken, bool includeHeading = false)
{
TaskCompletionSource<OperationResult<Position>> tcs;
if (timeout <= 0 && timeout != Timeout.Infinite)
{
tcs = new TaskCompletionSource<OperationResult<Position>>();
var exception = new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive or Timeout.Infinite");
tcs.SetResult(OperationResult<Position>.AsFailure(exception));
return tcs.Task;
}
if (!IsListening)
{
var manager = GetManager();
tcs = new TaskCompletionSource<OperationResult<Position>>(manager);
var singleListener = new GeolocationSingleUpdateDelegate(manager, _desiredAccuracy, includeHeading, timeout, cancelToken);
manager.Delegate = singleListener;
manager.StartUpdatingLocation();
if (includeHeading && SupportsHeading)
{
manager.StartUpdatingHeading();
}
return singleListener.Task;
}
else
{
tcs = new TaskCompletionSource<OperationResult<Position>>();
}
if (_position == null)
{
EventHandler<PositionErrorEventArgs> gotError = null;
gotError = (s, e) =>
{
tcs.SetResult(OperationResult<Position>.AsFailure(new LocationException(e.Error)));
ErrorOccured -= gotError;
};
ErrorOccured += gotError;
EventHandler<PositionEventArgs> gotPosition = null;
gotPosition = (s, e) =>
{
tcs.TrySetResult(OperationResult<Position>.AsSuccess(e.Position));
PositionChanged -= gotPosition;
};
PositionChanged += gotPosition;
}
else
{
tcs.SetResult(OperationResult<Position>.AsSuccess(_position));
}
return tcs.Task;
}
public OperationResult<double> GetDistanceFrom(Position referencePosition)
{
if (referencePosition == null)
{
return OperationResult<double>.AsFailure("Invalid reference position specified");
}
if (_position == null)
{
return OperationResult<double>.AsFailure("Current position not available");
}
var currentLocation = new CLLocation(_position.Latitude, _position.Longitude);
var referenceLocation = new CLLocation(referencePosition.Latitude, referencePosition.Longitude);
return OperationResult<double>.AsSuccess(referenceLocation.DistanceFrom(currentLocation));
}
public OperationResult<double> GetDistanceBetween(Position firstPosition, Position secondPosition)
{
if (firstPosition == null || secondPosition == null)
{
return OperationResult<double>.AsFailure("Invalid positions specified");
}
var firstLocation = new CLLocation(firstPosition.Latitude, firstPosition.Longitude);
var secondLocation = new CLLocation(secondPosition.Latitude, secondPosition.Longitude);
return OperationResult<double>.AsSuccess(firstLocation.DistanceFrom(secondLocation));
}
#endregion
#region Event Handlers
void OnHeadingUpdated(object sender, CLHeadingUpdatedEventArgs e)
{
if (e.NewHeading.TrueHeading.Equals(-1))
{
return;
}
var newPosition = (_position == null) ? new Position() : new Position(_position);
newPosition.Heading = e.NewHeading.TrueHeading;
newPosition.MagneticHeading = e.NewHeading.MagneticHeading;
newPosition.HeadingAccuracy = e.NewHeading.HeadingAccuracy;
_position = newPosition;
OnPositionChanged(new PositionEventArgs(newPosition));
}
void OnLocationsUpdated(object sender, CLLocationsUpdatedEventArgs e)
{
foreach (var location in e.Locations)
{
UpdatePosition(location);
}
}
void OnFailed(object sender, NSErrorEventArgs e)
{
if ((int)e.Error.Code == (int)CLError.Network)
{
OnPositionError(new PositionErrorEventArgs(LocationErrorType.PositionUnavailable));
}
}
void OnAuthorizationChanged(object sender, CLAuthorizationChangedEventArgs e)
{
if (e.Status == CLAuthorizationStatus.Denied || e.Status == CLAuthorizationStatus.Restricted)
{
LocationAuthorizationChanged?.Invoke(this, new AuthorizationEventArgs(LocationAuthorizationType.None));
OnPositionError(new PositionErrorEventArgs(LocationErrorType.Unauthorized));
}
else if (e.Status == CLAuthorizationStatus.AuthorizedAlways)
{
LocationAuthorizationChanged?.Invoke(this, new AuthorizationEventArgs(LocationAuthorizationType.Always));
}
else if (e.Status == CLAuthorizationStatus.AuthorizedWhenInUse)
{
LocationAuthorizationChanged?.Invoke(this, new AuthorizationEventArgs(LocationAuthorizationType.WhenInUse));
}
}
void OnPositionChanged(PositionEventArgs e)
{
PositionChanged?.Invoke(this, e);
}
void OnPositionError(PositionErrorEventArgs e)
{
StopListening();
ErrorOccured?.Invoke(this, e);
}
#endregion
#region Region Event Handlers
void LocationManager_DidDetermineState(object sender, CLRegionStateDeterminedEventArgs e)
{
_logger?.Information($"iOS: State for {e.Region.Identifier} is {e.State.ToString()}");
}
void LocationManager_RegionEntered(object sender, CLRegionEventArgs e)
{
nint taskID = UIApplication.SharedApplication.BeginBackgroundTask(() => { });
_logger?.Information($"iOS: Region entered {e.Region.Identifier}");
RegionEntered?.Invoke(this, new RegionEventArgs(e.Region.Identifier));
UIApplication.SharedApplication.EndBackgroundTask(taskID);
}
void LocationManager_RegionLeft(object sender, CLRegionEventArgs e)
{
nint taskID = UIApplication.SharedApplication.BeginBackgroundTask(() => { });
_logger?.Information($"iOS: Region left {e.Region.Identifier}");
RegionLeft?.Invoke(this, new RegionEventArgs(e.Region.Identifier));
UIApplication.SharedApplication.EndBackgroundTask(taskID);
}
void LocationManager_DidStartMonitoringForRegion(object sender, CLRegionEventArgs e)
{
_manager.RequestState(e.Region);
}
#endregion
#region Helper Methods
private CLLocationManager GetManager()
{
CLLocationManager manager = null;
new NSObject().InvokeOnMainThread(() => manager = new CLLocationManager());
return manager;
}
private void UpdatePosition(CLLocation location)
{
var newPosition = (_position == null) ? new Position() : new Position(_position);
if (location.HorizontalAccuracy > -1)
{
newPosition.Accuracy = location.HorizontalAccuracy;
newPosition.Latitude = location.Coordinate.Latitude;
newPosition.Longitude = location.Coordinate.Longitude;
newPosition.Course = location.Course;
}
if (location.VerticalAccuracy > -1)
{
newPosition.Altitude = location.Altitude;
newPosition.AltitudeAccuracy = location.VerticalAccuracy;
}
if (location.Speed > -1)
{
newPosition.Speed = location.Speed;
}
newPosition.Timestamp = new DateTimeOffset((DateTime)location.Timestamp);
_position = newPosition;
OnPositionChanged(new PositionEventArgs(newPosition));
location.Dispose();
}
#endregion
}
}
| |
//
// CMFormatDescription.cs: Implements the managed CMFormatDescription
//
// Authors:
// Miguel de Icaza ([email protected])
// Frank Krueger
// Mono Team
// Marek Safar ([email protected])
//
// Copyright 2010 Novell, Inc
// Copyright 2012 Xamarin Inc
//
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using MonoMac;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
using MonoMac.ObjCRuntime;
using MonoMac.CoreVideo;
using MonoMac.AudioToolbox;
namespace MonoMac.CoreMedia {
public enum CMFormatDescriptionError {
None = 0,
InvalidParameter = -12710,
AllocationFailed = -12711,
}
[Since (4,0)]
public class CMFormatDescription : INativeObject, IDisposable {
internal IntPtr handle;
internal CMFormatDescription (IntPtr handle)
{
this.handle = handle;
}
[Preserve (Conditional=true)]
internal CMFormatDescription (IntPtr handle, bool owns)
{
if (!owns)
CFObject.CFRetain (handle);
this.handle = handle;
}
~CMFormatDescription ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
/*[DllImport(Constants.CoreMediaLibrary)]
extern static CFPropertyListRef CMFormatDescriptionGetExtension (
CMFormatDescriptionRef desc,
CFStringRef extensionKey
);*/
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMFormatDescriptionGetExtensions (IntPtr handle);
#if !COREBUILD
public NSDictionary GetExtensions ()
{
var cfDictRef = CMFormatDescriptionGetExtensions (handle);
if (cfDictRef == IntPtr.Zero)
{
return null;
}
else
{
return (NSDictionary) Runtime.GetNSObject (cfDictRef);
}
}
#endif
[DllImport(Constants.CoreMediaLibrary)]
extern static uint CMFormatDescriptionGetMediaSubType (IntPtr handle);
public uint MediaSubType
{
get
{
return CMFormatDescriptionGetMediaSubType (handle);
}
}
public AudioFormatType AudioFormatType {
get {
return MediaType == CMMediaType.Audio ? (AudioFormatType) MediaSubType : 0;
}
}
public CMSubtitleFormatType SubtitleFormatType {
get {
return MediaType == CMMediaType.Subtitle ? (CMSubtitleFormatType) MediaSubType : 0;
}
}
public CMClosedCaptionFormatType ClosedCaptionFormatType {
get {
return MediaType == CMMediaType.ClosedCaption ? (CMClosedCaptionFormatType) MediaSubType : 0;
}
}
public CMMuxedStreamType MuxedStreamType {
get {
return MediaType == CMMediaType.Muxed ? (CMMuxedStreamType) MediaSubType : 0;
}
}
public CMVideoCodecType VideoCodecType {
get {
return MediaType == CMMediaType.Video ? (CMVideoCodecType) MediaSubType : 0;
}
}
public CMMetadataFormatType MetadataFormatType {
get {
return MediaType == CMMediaType.Metadata ? (CMMetadataFormatType) MediaSubType : 0;
}
}
public CMTimeCodeFormatType TimeCodeFormatType {
get {
return MediaType == CMMediaType.TimeCode ? (CMTimeCodeFormatType) MediaSubType : 0;
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMMediaType CMFormatDescriptionGetMediaType (IntPtr handle);
public CMMediaType MediaType
{
get
{
return CMFormatDescriptionGetMediaType (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static int CMFormatDescriptionGetTypeID ();
public static int GetTypeID ()
{
return CMFormatDescriptionGetTypeID ();
}
#if !COREBUILD
[DllImport (Constants.CoreMediaLibrary)]
extern static CMFormatDescriptionError CMFormatDescriptionCreate (IntPtr allocator, CMMediaType mediaType, uint mediaSubtype, IntPtr extensions, out IntPtr handle);
public static CMFormatDescription Create (CMMediaType mediaType, uint mediaSubtype, out CMFormatDescriptionError error)
{
IntPtr handle;
error = CMFormatDescriptionCreate (IntPtr.Zero, mediaType, mediaSubtype, IntPtr.Zero, out handle);
if (error != CMFormatDescriptionError.None)
return null;
return Create (mediaType, handle, true);
}
public static CMFormatDescription Create (IntPtr handle, bool owns)
{
return Create (CMFormatDescriptionGetMediaType (handle), handle, owns);
}
static CMFormatDescription Create (CMMediaType type, IntPtr handle, bool owns)
{
switch (type) {
case CMMediaType.Video:
return new CMVideoFormatDescription (handle);
case CMMediaType.Audio:
return new CMAudioFormatDescription (handle);
default:
return new CMFormatDescription (handle);
}
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMAudioFormatDescriptionGetStreamBasicDescription (IntPtr handle);
public AudioStreamBasicDescription? AudioStreamBasicDescription {
get {
var ret = CMAudioFormatDescriptionGetStreamBasicDescription (handle);
if (ret != IntPtr.Zero){
unsafe {
return *((AudioStreamBasicDescription *) ret);
}
}
return null;
}
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMAudioFormatDescriptionGetChannelLayout (IntPtr handle, out int size);
public AudioChannelLayout AudioChannelLayout {
get {
int size;
var res = CMAudioFormatDescriptionGetChannelLayout (handle, out size);
if (res == IntPtr.Zero || size == 0)
return null;
return AudioChannelLayout.FromHandle (res);
}
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMAudioFormatDescriptionGetFormatList (IntPtr handle, out int size);
public AudioFormat [] AudioFormats {
get {
unsafe {
int size;
var v = CMAudioFormatDescriptionGetFormatList (handle, out size);
if (v == IntPtr.Zero)
return null;
var items = size / sizeof (AudioFormat);
var ret = new AudioFormat [items];
var ptr = (AudioFormat *) v;
for (int i = 0; i < items; i++)
ret [i] = ptr [i];
return ret;
}
}
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMAudioFormatDescriptionGetMagicCookie (IntPtr handle, out int size);
public byte [] AudioMagicCookie {
get {
int size;
var h = CMAudioFormatDescriptionGetMagicCookie (handle, out size);
if (h == IntPtr.Zero)
return null;
var result = new byte [size];
for (int i = 0; i < size; i++)
result [i] = Marshal.ReadByte (h, i);
return result;
}
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMAudioFormatDescriptionGetMostCompatibleFormat (IntPtr handle);
public AudioFormat AudioMostCompatibleFormat {
get {
unsafe {
var ret = (AudioFormat *) CMAudioFormatDescriptionGetMostCompatibleFormat (handle);
if (ret == null)
return new AudioFormat ();
return *ret;
}
}
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMAudioFormatDescriptionGetRichestDecodableFormat (IntPtr handle);
public AudioFormat AudioRichestDecodableFormat {
get {
unsafe {
var ret = (AudioFormat *) CMAudioFormatDescriptionGetRichestDecodableFormat (handle);
if (ret == null)
return new AudioFormat ();
return *ret;
}
}
}
[DllImport (Constants.CoreMediaLibrary)]
internal extern static Size CMVideoFormatDescriptionGetDimensions (IntPtr handle);
[Obsolete ("Use CMVideoFormatDescription")]
public Size VideoDimensions {
get {
return CMVideoFormatDescriptionGetDimensions (handle);
}
}
[DllImport (Constants.CoreMediaLibrary)]
internal extern static RectangleF CMVideoFormatDescriptionGetCleanAperture (IntPtr handle, bool originIsAtTopLeft);
[Obsolete ("Use CMVideoFormatDescription")]
public RectangleF GetVideoCleanAperture (bool originIsAtTopLeft)
{
return CMVideoFormatDescriptionGetCleanAperture (handle, originIsAtTopLeft);
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMVideoFormatDescriptionGetExtensionKeysCommonWithImageBuffers ();
// Belongs to CMVideoFormatDescription
public static NSObject [] GetExtensionKeysCommonWithImageBuffers ()
{
var arr = CMVideoFormatDescriptionGetExtensionKeysCommonWithImageBuffers ();
return NSArray.ArrayFromHandle<NSString> (arr);
}
[DllImport (Constants.CoreMediaLibrary)]
internal extern static SizeF CMVideoFormatDescriptionGetPresentationDimensions (IntPtr handle, bool usePixelAspectRatio, bool useCleanAperture);
[Obsolete ("Use CMVideoFormatDescription")]
public SizeF GetVideoPresentationDimensions (bool usePixelAspectRatio, bool useCleanAperture)
{
return CMVideoFormatDescriptionGetPresentationDimensions (handle, usePixelAspectRatio, useCleanAperture);
}
[DllImport (Constants.CoreMediaLibrary)]
extern static int CMVideoFormatDescriptionMatchesImageBuffer (IntPtr handle, IntPtr imageBufferRef);
// Belongs to CMVideoFormatDescription
public bool VideoMatchesImageBuffer (CVImageBuffer imageBuffer)
{
if (imageBuffer == null)
throw new ArgumentNullException ("imageBuffer");
return CMVideoFormatDescriptionMatchesImageBuffer (handle, imageBuffer.Handle) != 0;
}
#endif
}
[Since (4,0)]
public class CMAudioFormatDescription : CMFormatDescription {
internal CMAudioFormatDescription (IntPtr handle)
: base (handle)
{
}
internal CMAudioFormatDescription (IntPtr handle, bool owns)
: base (handle, owns)
{
}
// TODO: Move more audio specific methods here
}
[Since (4,0)]
public class CMVideoFormatDescription : CMFormatDescription {
internal CMVideoFormatDescription (IntPtr handle)
: base (handle)
{
}
internal CMVideoFormatDescription (IntPtr handle, bool owns)
: base (handle, owns)
{
}
[DllImport (Constants.CoreMediaLibrary)]
static extern CMFormatDescriptionError CMVideoFormatDescriptionCreate (IntPtr allocator,
CMVideoCodecType codecType,
int width, int height,
IntPtr extensions,
out IntPtr outDesc);
public CMVideoFormatDescription (CMVideoCodecType codecType, Size size)
: base (IntPtr.Zero)
{
var error = CMVideoFormatDescriptionCreate (IntPtr.Zero, codecType, size.Width, size.Height, IntPtr.Zero, out handle);
if (error != CMFormatDescriptionError.None)
throw new ArgumentException (error.ToString ());
}
#if !COREBUILD
public Size Dimensions {
get {
return CMVideoFormatDescriptionGetDimensions (handle);
}
}
[DllImport (Constants.CoreMediaLibrary)]
static extern CMFormatDescriptionError CMVideoFormatDescriptionCreateForImageBuffer (IntPtr allocator,
IntPtr imageBuffer,
out IntPtr outDesc);
public static CMVideoFormatDescription CreateForImageBuffer (CVImageBuffer imageBuffer, out CMFormatDescriptionError error)
{
if (imageBuffer == null)
throw new ArgumentNullException ("imageBuffer");
IntPtr desc;
error = CMVideoFormatDescriptionCreateForImageBuffer (IntPtr.Zero, imageBuffer.handle, out desc);
if (error != CMFormatDescriptionError.None)
return null;
return new CMVideoFormatDescription (desc, true);
}
[DllImport (Constants.CoreMediaLibrary)]
extern static RectangleF CMVideoFormatDescriptionGetCleanAperture (IntPtr handle, bool originIsAtTopLeft);
public RectangleF GetCleanAperture (bool originIsAtTopLeft)
{
return CMVideoFormatDescriptionGetCleanAperture (handle, originIsAtTopLeft);
}
public SizeF GetPresentationDimensions (bool usePixelAspectRatio, bool useCleanAperture)
{
return CMVideoFormatDescriptionGetPresentationDimensions (handle, usePixelAspectRatio, useCleanAperture);
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// UInt32.Equals(System.Object)
/// </summary>
public class UInt32Equals1
{
public static int Main()
{
UInt32Equals1 ui32e1 = new UInt32Equals1();
TestLibrary.TestFramework.BeginTestCase("UInt32Equals1");
if (ui32e1.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
return retVal;
}
#region
public bool PosTest1()
{
bool retVal = true;
bool ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest1: object value is null");
try
{
UInt32 uintA = (UInt32)this.GetInt32(0, Int32.MaxValue);
object comValue = null;
ActualResult = uintA.Equals(comValue);
if (ActualResult)
{
TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
bool ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest2: object value is declaring class");
try
{
UInt32 uintA = (UInt32)this.GetInt32(0, Int32.MaxValue);
object comValue = new MyTest();
ActualResult = uintA.Equals(comValue);
if (ActualResult)
{
TestLibrary.TestFramework.LogError("003", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
bool ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest3: object value is the instance value but the types are different");
try
{
int comValue = this.GetInt32(0, Int32.MaxValue);
UInt32 uintA = (UInt32)comValue;
ActualResult = uintA.Equals(comValue);
if (ActualResult)
{
TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
bool ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest4: object and the instance have the same type but different value");
try
{
int intA = this.GetInt32(0,Int32.MaxValue);
UInt32 uintA = (UInt32)intA;
UInt32 comValue = (UInt32)(intA + 1);
ActualResult = uintA.Equals(comValue);
if (ActualResult)
{
TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
bool ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest5: object and the instance have the same type and the same value 1");
try
{
UInt32 uintA = 0xffffffff;
UInt32 comValue = UInt32.MaxValue;
ActualResult = uintA.Equals(comValue);
if (!ActualResult)
{
TestLibrary.TestFramework.LogError("009", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
bool ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest6: object and the instance have the same type and the same value 2");
try
{
UInt32 uintA = 0;
UInt32 comValue = UInt32.MinValue;
ActualResult = uintA.Equals(comValue);
if (!ActualResult)
{
TestLibrary.TestFramework.LogError("011", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region ForTestObject
public class MyTest { }
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
using Lucene.Net.Support.Threading;
using System;
#if FEATURE_SERIALIZABLE_EXCEPTIONS
using System.Runtime.Serialization;
#endif
using System.Threading;
namespace Lucene.Net.Search
{
/*
* 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 Counter = Lucene.Net.Util.Counter;
/// <summary>
/// The <see cref="TimeLimitingCollector"/> is used to timeout search requests that
/// take longer than the maximum allowed search time limit. After this time is
/// exceeded, the search thread is stopped by throwing a
/// <see cref="TimeExceededException"/>.
/// </summary>
public class TimeLimitingCollector : ICollector
{
/// <summary>
/// Thrown when elapsed search time exceeds allowed search time. </summary>
// LUCENENET: It is no longer good practice to use binary serialization.
// See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568
#if FEATURE_SERIALIZABLE_EXCEPTIONS
[Serializable]
#endif
public class TimeExceededException : Exception
{
private long timeAllowed;
private long timeElapsed;
private int lastDocCollected;
internal TimeExceededException(long timeAllowed, long timeElapsed, int lastDocCollected)
: base("Elapsed time: " + timeElapsed + "Exceeded allowed search time: " + timeAllowed + " ms.")
{
this.timeAllowed = timeAllowed;
this.timeElapsed = timeElapsed;
this.lastDocCollected = lastDocCollected;
}
// For testing purposes
internal TimeExceededException(string message)
: base(message)
{
}
#if FEATURE_SERIALIZABLE_EXCEPTIONS
/// <summary>
/// Initializes a new instance of this class with serialized data.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
public TimeExceededException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
/// <summary>
/// Returns allowed time (milliseconds). </summary>
public virtual long TimeAllowed
{
get
{
return timeAllowed;
}
}
/// <summary>
/// Returns elapsed time (milliseconds). </summary>
public virtual long TimeElapsed
{
get
{
return timeElapsed;
}
}
/// <summary>
/// Returns last doc (absolute doc id) that was collected when the search time exceeded. </summary>
public virtual int LastDocCollected
{
get
{
return lastDocCollected;
}
}
}
private long t0 = long.MinValue;
private long timeout = long.MinValue;
private ICollector collector;
private readonly Counter clock;
private readonly long ticksAllowed;
private bool greedy = false;
private int docBase;
/// <summary>
/// Create a <see cref="TimeLimitingCollector"/> wrapper over another <see cref="ICollector"/> with a specified timeout. </summary>
/// <param name="collector"> The wrapped <see cref="ICollector"/> </param>
/// <param name="clock"> The timer clock </param>
/// <param name="ticksAllowed"> Max time allowed for collecting
/// hits after which <see cref="TimeExceededException"/> is thrown </param>
public TimeLimitingCollector(ICollector collector, Counter clock, long ticksAllowed)
{
this.collector = collector;
this.clock = clock;
this.ticksAllowed = ticksAllowed;
}
/// <summary>
/// Sets the baseline for this collector. By default the collectors baseline is
/// initialized once the first reader is passed to the collector.
/// To include operations executed in prior to the actual document collection
/// set the baseline through this method in your prelude.
/// <para>
/// Example usage:
/// <code>
/// // Counter is in the Lucene.Net.Util namespace
/// Counter clock = Counter.NewCounter(true);
/// long baseline = clock.Get();
/// // ... prepare search
/// TimeLimitingCollector collector = new TimeLimitingCollector(c, clock, numTicks);
/// collector.SetBaseline(baseline);
/// indexSearcher.Search(query, collector);
/// </code>
/// </para>
/// </summary>
/// <seealso cref="SetBaseline()"/>
public virtual void SetBaseline(long clockTime)
{
t0 = clockTime;
timeout = t0 + ticksAllowed;
}
/// <summary>
/// Syntactic sugar for <see cref="SetBaseline(long)"/> using <see cref="Counter.Get()"/>
/// on the clock passed to the constructor.
/// </summary>
public virtual void SetBaseline()
{
SetBaseline(clock.Get());
}
/// <summary>
/// Checks if this time limited collector is greedy in collecting the last hit.
/// A non greedy collector, upon a timeout, would throw a <see cref="TimeExceededException"/>
/// without allowing the wrapped collector to collect current doc. A greedy one would
/// first allow the wrapped hit collector to collect current doc and only then
/// throw a <see cref="TimeExceededException"/>.
/// </summary>
public virtual bool IsGreedy
{
get
{
return greedy;
}
set
{
this.greedy = value;
}
}
/// <summary>
/// Calls <see cref="ICollector.Collect(int)"/> on the decorated <see cref="ICollector"/>
/// unless the allowed time has passed, in which case it throws an exception.
/// </summary>
/// <exception cref="TimeExceededException">
/// If the time allowed has exceeded. </exception>
public virtual void Collect(int doc)
{
long time = clock.Get();
if (timeout < time)
{
if (greedy)
{
//System.out.println(this+" greedy: before failing, collecting doc: "+(docBase + doc)+" "+(time-t0));
collector.Collect(doc);
}
//System.out.println(this+" failing on: "+(docBase + doc)+" "+(time-t0));
throw new TimeExceededException(timeout - t0, time - t0, docBase + doc);
}
//System.out.println(this+" collecting: "+(docBase + doc)+" "+(time-t0));
collector.Collect(doc);
}
public virtual void SetNextReader(AtomicReaderContext context)
{
collector.SetNextReader(context);
this.docBase = context.DocBase;
if (long.MinValue == t0)
{
SetBaseline();
}
}
public virtual void SetScorer(Scorer scorer)
{
collector.SetScorer(scorer);
}
public virtual bool AcceptsDocsOutOfOrder
{
get { return collector.AcceptsDocsOutOfOrder; }
}
/// <summary>
/// This is so the same timer can be used with a multi-phase search process such as grouping.
/// We don't want to create a new <see cref="TimeLimitingCollector"/> for each phase because that would
/// reset the timer for each phase. Once time is up subsequent phases need to timeout quickly.
/// </summary>
/// <param name="collector"> The actual collector performing search functionality. </param>
public virtual void SetCollector(ICollector collector)
{
this.collector = collector;
}
/// <summary>
/// Returns the global <see cref="TimerThread"/>'s <see cref="Counter"/>
/// <para>
/// Invoking this creates may create a new instance of <see cref="TimerThread"/> iff
/// the global <see cref="TimerThread"/> has never been accessed before. The thread
/// returned from this method is started on creation and will be alive unless
/// you stop the <see cref="TimerThread"/> via <see cref="TimerThread.StopTimer()"/>.
/// </para>
/// @lucene.experimental
/// </summary>
/// <returns> the global TimerThreads <seealso cref="Counter"/> </returns>
public static Counter GlobalCounter
{
get
{
return TimerThreadHolder.THREAD.counter;
}
}
/// <summary>
/// Returns the global <see cref="TimerThread"/>.
/// <para>
/// Invoking this creates may create a new instance of <see cref="TimerThread"/> iff
/// the global <see cref="TimerThread"/> has never been accessed before. The thread
/// returned from this method is started on creation and will be alive unless
/// you stop the <see cref="TimerThread"/> via <see cref="TimerThread.StopTimer()"/>.
/// </para>
/// @lucene.experimental
/// </summary>
/// <returns> the global <see cref="TimerThread"/> </returns>
public static TimerThread GlobalTimerThread
{
get
{
return TimerThreadHolder.THREAD;
}
}
private sealed class TimerThreadHolder
{
internal static readonly TimerThread THREAD;
static TimerThreadHolder()
{
THREAD = new TimerThread(Counter.NewCounter(true));
THREAD.Start();
}
}
/// <summary>
/// Thread used to timeout search requests.
/// Can be stopped completely with <see cref="TimerThread.StopTimer()"/>
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class TimerThread : ThreadClass
{
public const string THREAD_NAME = "TimeLimitedCollector timer thread";
public const int DEFAULT_RESOLUTION = 20;
// NOTE: we can avoid explicit synchronization here for several reasons:
// * updates to volatile long variables are atomic
// * only single thread modifies this value
// * use of volatile keyword ensures that it does not reside in
// a register, but in main memory (so that changes are visible to
// other threads).
// * visibility of changes does not need to be instantaneous, we can
// afford losing a tick or two.
//
// See section 17 of the Java Language Specification for details.
private long time = 0;
private volatile bool stop = false;
private long resolution;
internal readonly Counter counter;
public TimerThread(long resolution, Counter counter)
: base(THREAD_NAME)
{
this.resolution = resolution;
this.counter = counter;
this.SetDaemon(true);
}
public TimerThread(Counter counter)
: this(DEFAULT_RESOLUTION, counter)
{
}
public override void Run()
{
while (!stop)
{
// TODO: Use System.nanoTime() when Lucene moves to Java SE 5.
counter.AddAndGet(resolution);
//#if !NETSTANDARD1_6
// try
// {
//#endif
Thread.Sleep(TimeSpan.FromMilliseconds(Interlocked.Read(ref resolution)));
//#if !NETSTANDARD1_6 // LUCENENET NOTE: Senseless to catch and rethrow the same exception type
// }
// catch (ThreadInterruptedException ie)
// {
// throw new ThreadInterruptedException("Thread Interrupted Exception", ie);
// }
//#endif
}
}
/// <summary>
/// Get the timer value in milliseconds.
/// </summary>
public long Milliseconds
{
get
{
return time;
}
}
/// <summary>
/// Stops the timer thread
/// </summary>
public void StopTimer()
{
stop = true;
}
/// <summary>
/// Return the timer resolution. </summary>
public long Resolution
{
get
{
return resolution;
}
set
{
this.resolution = Math.Max(value, 5); // 5 milliseconds is about the minimum reasonable time for a Object.wait(long) call.
}
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Python.Runtime
{
/// <summary>
/// The AssemblyManager maintains information about loaded assemblies
/// namespaces and provides an interface for name-based type lookup.
/// </summary>
internal class AssemblyManager
{
// modified from event handlers below, potentially triggered from different .NET threads
// therefore this should be a ConcurrentDictionary
//
// WARNING: Dangerous if cross-app domain usage is ever supported
// Reusing the dictionary with assemblies accross multiple initializations is problematic.
// Loading happens from CurrentDomain (see line 53). And if the first call is from AppDomain that is later unloaded,
// than it can end up referring to assemblies that are already unloaded (default behavior after unload appDomain -
// unless LoaderOptimization.MultiDomain is used);
// So for multidomain support it is better to have the dict. recreated for each app-domain initialization
private static ConcurrentDictionary<string, ConcurrentDictionary<Assembly, string>> namespaces =
new ConcurrentDictionary<string, ConcurrentDictionary<Assembly, string>>();
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
// domain-level handlers are initialized in Initialize
private static AssemblyLoadEventHandler lhandler;
private static ResolveEventHandler rhandler;
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
// updated only under GIL?
private static Dictionary<string, int> probed = new Dictionary<string, int>(32);
// modified from event handlers below, potentially triggered from different .NET threads
private static readonly ConcurrentQueue<Assembly> assemblies = new();
internal static readonly List<string> pypath = new (capacity: 16);
private AssemblyManager()
{
}
/// <summary>
/// Initialization performed on startup of the Python runtime. Here we
/// scan all of the currently loaded assemblies to determine exported
/// names, and register to be notified of new assembly loads.
/// </summary>
internal static void Initialize()
{
pypath.Clear();
AppDomain domain = AppDomain.CurrentDomain;
lhandler = new AssemblyLoadEventHandler(AssemblyLoadHandler);
domain.AssemblyLoad += lhandler;
rhandler = new ResolveEventHandler(ResolveHandler);
domain.AssemblyResolve += rhandler;
Assembly[] items = domain.GetAssemblies();
foreach (Assembly a in items)
{
try
{
ScanAssembly(a);
assemblies.Enqueue(a);
}
catch (Exception ex)
{
Debug.WriteLine("Error scanning assembly {0}. {1}", a, ex);
}
}
}
/// <summary>
/// Cleanup resources upon shutdown of the Python runtime.
/// </summary>
internal static void Shutdown()
{
AppDomain domain = AppDomain.CurrentDomain;
domain.AssemblyLoad -= lhandler;
domain.AssemblyResolve -= rhandler;
}
/// <summary>
/// Event handler for assembly load events. At the time the Python
/// runtime loads, we scan the app domain to map the assemblies that
/// are loaded at the time. We also have to register this event handler
/// so that we can know about assemblies that get loaded after the
/// Python runtime is initialized.
/// </summary>
private static void AssemblyLoadHandler(object ob, AssemblyLoadEventArgs args)
{
Assembly assembly = args.LoadedAssembly;
assemblies.Enqueue(assembly);
ScanAssembly(assembly);
}
/// <summary>
/// Event handler for assembly resolve events. This is needed because
/// we augment the assembly search path with the PYTHONPATH when we
/// load an assembly from Python. Because of that, we need to listen
/// for failed loads, because they might be dependencies of something
/// we loaded from Python which also needs to be found on PYTHONPATH.
/// </summary>
private static Assembly? ResolveHandler(object ob, ResolveEventArgs args)
{
var name = new AssemblyName(args.Name);
foreach (var alreadyLoaded in assemblies)
{
if (AssemblyName.ReferenceMatchesDefinition(name, alreadyLoaded.GetName()))
{
return alreadyLoaded;
}
}
return LoadAssemblyPath(name.Name);
}
internal static AssemblyName? TryParseAssemblyName(string name)
{
try
{
return new AssemblyName(name);
}
catch (FileLoadException)
{
return null;
}
}
/// <summary>
/// We __really__ want to avoid using Python objects or APIs when
/// probing for assemblies to load, since our ResolveHandler may be
/// called in contexts where we don't have the Python GIL and can't
/// even safely try to get it without risking a deadlock ;(
/// To work around that, we update a managed copy of sys.path (which
/// is the main thing we care about) when UpdatePath is called. The
/// import hook calls this whenever it knows its about to use the
/// assembly manager, which lets us keep up with changes to sys.path
/// in a relatively lightweight and low-overhead way.
/// </summary>
internal static void UpdatePath()
{
BorrowedReference list = Runtime.PySys_GetObject("path");
var count = Runtime.PyList_Size(list);
if (count != pypath.Count)
{
pypath.Clear();
probed.Clear();
for (var i = 0; i < count; i++)
{
BorrowedReference item = Runtime.PyList_GetItem(list, i);
string? path = Runtime.GetManagedString(item);
if (path != null)
{
pypath.Add(path);
}
}
}
}
/// <summary>
/// Given an assembly name, try to find this assembly file using the
/// PYTHONPATH. If not found, return null to indicate implicit load
/// using standard load semantics (app base directory then GAC, etc.)
/// </summary>
public static string FindAssembly(AssemblyName name)
{
if (name is null) throw new ArgumentNullException(nameof(name));
return FindAssembly(name.Name);
}
/// <summary>
/// Given an assembly name, try to find this assembly file using the
/// PYTHONPATH. If not found, return null to indicate implicit load
/// using standard load semantics (app base directory then GAC, etc.)
/// </summary>
public static string FindAssembly(string name)
{
if (name is null) throw new ArgumentNullException(nameof(name));
return FindAssemblyCandidates(name).FirstOrDefault();
}
static IEnumerable<string> FindAssemblyCandidates(string name)
{
foreach (string head in pypath)
{
string path;
if (head == null || head.Length == 0)
{
path = name;
}
else
{
path = Path.Combine(head, name);
}
string temp = path + ".dll";
if (File.Exists(temp))
{
yield return temp;
}
temp = path + ".exe";
if (File.Exists(temp))
{
yield return temp;
}
}
}
/// <summary>
/// Loads an assembly from the application directory or the GAC
/// given its name. Returns the assembly if loaded.
/// </summary>
public static Assembly LoadAssembly(AssemblyName name)
{
return Assembly.Load(name);
}
/// <summary>
/// Loads an assembly using an augmented search path (the python path).
/// </summary>
public static Assembly? LoadAssemblyPath(string name)
{
string path = FindAssembly(name);
if (path == null) return null;
return Assembly.LoadFrom(path);
}
/// <summary>
/// Loads an assembly using full path.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static Assembly? LoadAssemblyFullPath(string name)
{
if (Path.IsPathRooted(name))
{
if (File.Exists(name))
{
return Assembly.LoadFrom(name);
}
}
return null;
}
/// <summary>
/// Returns an assembly that's already been loaded
/// </summary>
public static Assembly? FindLoadedAssembly(string name)
{
foreach (Assembly a in assemblies)
{
if (a.GetName().Name == name)
{
return a;
}
}
return null;
}
/// <summary>
/// Scans an assembly for exported namespaces, adding them to the
/// mapping of valid namespaces. Note that for a given namespace
/// a.b.c.d, each of a, a.b, a.b.c and a.b.c.d are considered to
/// be valid namespaces (to better match Python import semantics).
/// </summary>
internal static void ScanAssembly(Assembly assembly)
{
if (assembly.GetCustomAttribute<PyExportAttribute>()?.Export == false)
{
return;
}
// A couple of things we want to do here: first, we want to
// gather a list of all of the namespaces contributed to by
// the assembly.
foreach (Type t in GetTypes(assembly))
{
string ns = t.Namespace ?? "";
if (!namespaces.ContainsKey(ns))
{
string[] names = ns.Split('.');
var s = "";
for (var n = 0; n < names.Length; n++)
{
s = n == 0 ? names[0] : s + "." + names[n];
if (namespaces.TryAdd(s, new ConcurrentDictionary<Assembly, string>()))
{
ImportHook.AddNamespace(s);
}
}
}
if (ns != null)
{
namespaces[ns].TryAdd(assembly, string.Empty);
}
if (ns != null && t.IsGenericTypeDefinition)
{
GenericUtil.Register(t);
}
}
}
public static AssemblyName[] ListAssemblies()
{
var names = new List<AssemblyName>(assemblies.Count);
foreach (Assembly assembly in assemblies)
{
names.Add(assembly.GetName());
}
return names.ToArray();
}
/// <summary>
/// Returns true if the given qualified name matches a namespace
/// exported by an assembly loaded in the current app domain.
/// </summary>
public static bool IsValidNamespace(string name)
{
return !string.IsNullOrEmpty(name) && namespaces.ContainsKey(name);
}
/// <summary>
/// Returns an IEnumerable<string> containing the namepsaces exported
/// by loaded assemblies in the current app domain.
/// </summary>
public static IEnumerable<string> GetNamespaces ()
{
return namespaces.Keys;
}
/// <summary>
/// Returns list of assemblies that declare types in a given namespace
/// </summary>
public static IEnumerable<Assembly> GetAssemblies(string nsname)
{
return !namespaces.ContainsKey(nsname) ? new List<Assembly>() : namespaces[nsname].Keys;
}
/// <summary>
/// Returns the current list of valid names for the input namespace.
/// </summary>
public static List<string> GetNames(string nsname)
{
//Dictionary<string, int> seen = new Dictionary<string, int>();
var names = new List<string>(8);
List<string>? g = GenericUtil.GetGenericBaseNames(nsname);
if (g != null)
{
foreach (string n in g)
{
names.Add(n);
}
}
if (namespaces.ContainsKey(nsname))
{
foreach (Assembly a in namespaces[nsname].Keys)
{
foreach (Type t in GetTypes(a))
{
if ((t.Namespace ?? "") == nsname && !t.IsNested)
{
names.Add(t.Name);
}
}
}
int nslen = nsname.Length;
foreach (string key in namespaces.Keys)
{
if (key.Length > nslen && key.StartsWith(nsname))
{
//string tail = key.Substring(nslen);
if (key.IndexOf('.') == -1)
{
names.Add(key);
}
}
}
}
return names;
}
/// <summary>
/// Returns the <see cref="Type"/> objects for the given qualified name,
/// looking in the currently loaded assemblies for the named
/// type.
/// </summary>
public static IEnumerable<Type> LookupTypes(string qualifiedName)
=> assemblies.Select(assembly => assembly.GetType(qualifiedName)).Where(type => type != null && IsExported(type));
internal static Type[] GetTypes(Assembly a)
{
if (a.IsDynamic)
{
try
{
return a.GetTypes().Where(IsExported).ToArray();
}
catch (ReflectionTypeLoadException exc)
{
// Return all types that were successfully loaded
return exc.Types.Where(x => x != null && IsExported(x)).ToArray();
}
}
else
{
try
{
return a.GetExportedTypes().Where(IsExported).ToArray();
}
catch (FileNotFoundException)
{
return new Type[0];
}
}
}
static bool IsExported(Type type) => type.GetCustomAttribute<PyExportAttribute>()?.Export != false;
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleBitStamp.SampleBitStampPublic
File: MainWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleBitStamp
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using Ecng.Common;
using Ecng.Xaml;
using MoreLinq;
using StockSharp.BitStamp;
using StockSharp.BusinessEntities;
using StockSharp.Logging;
using StockSharp.Localization;
public partial class MainWindow
{
private bool _isConnected;
public BitStampTrader Trader;
private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow();
private readonly TradesWindow _tradesWindow = new TradesWindow();
private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow();
private readonly OrdersWindow _ordersWindow = new OrdersWindow();
private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow();
private readonly LogManager _logManager = new LogManager();
public MainWindow()
{
InitializeComponent();
Title = Title.Put("BitStamp");
_ordersWindow.MakeHideable();
_myTradesWindow.MakeHideable();
_tradesWindow.MakeHideable();
_securitiesWindow.MakeHideable();
_portfoliosWindow.MakeHideable();
Instance = this;
_logManager.Listeners.Add(new FileLogListener { LogDirectory = "StockSharp_BitStamp" });
}
protected override void OnClosing(CancelEventArgs e)
{
_ordersWindow.DeleteHideable();
_myTradesWindow.DeleteHideable();
_tradesWindow.DeleteHideable();
_securitiesWindow.DeleteHideable();
_portfoliosWindow.DeleteHideable();
_securitiesWindow.Close();
_tradesWindow.Close();
_myTradesWindow.Close();
_ordersWindow.Close();
_portfoliosWindow.Close();
if (Trader != null)
Trader.Dispose();
base.OnClosing(e);
}
public static MainWindow Instance { get; private set; }
private void ConnectClick(object sender, RoutedEventArgs e)
{
if (!_isConnected)
{
if (ClientId.Text.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str3835);
return;
}
if (Key.Text.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str2974);
return;
}
if (Secret.Password.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str2975);
return;
}
if (Trader == null)
{
// create connector
Trader = new BitStampTrader { LogLevel = LogLevels.Debug };
_logManager.Sources.Add(Trader);
Trader.Restored += () => this.GuiAsync(() =>
{
// update gui labes
ChangeConnectStatus(true);
MessageBox.Show(this, LocalizedStrings.Str2958);
});
// subscribe on connection successfully event
Trader.Connected += () =>
{
// set flag (connection is established)
_isConnected = true;
// update gui labes
this.GuiAsync(() => ChangeConnectStatus(true));
};
Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false));
// subscribe on connection error event
Trader.ConnectionError += error => this.GuiAsync(() =>
{
// update gui labes
ChangeConnectStatus(false);
MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
});
// subscribe on error event
Trader.Error += error =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));
// subscribe on error of market data subscription event
Trader.MarketDataSubscriptionFailed += (security, msg, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));
Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities);
Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades);
Trader.NewTrades += trades => _tradesWindow.TradeGrid.Trades.AddRange(trades);
Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders);
Trader.NewPortfolios += portfolios =>
{
// subscribe on portfolio updates
portfolios.ForEach(Trader.RegisterPortfolio);
_portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios);
};
Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions);
// subscribe on error of order registration event
Trader.OrdersRegisterFailed += OrdersFailed;
// subscribe on error of order cancelling event
Trader.OrdersCancelFailed += OrdersFailed;
// subscribe on error of stop-order registration event
Trader.StopOrdersRegisterFailed += OrdersFailed;
// subscribe on error of stop-order cancelling event
Trader.StopOrdersCancelFailed += OrdersFailed;
Trader.MassOrderCancelFailed += (transId, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716));
// set market data provider
_securitiesWindow.SecurityPicker.MarketDataProvider = Trader;
ShowSecurities.IsEnabled = ShowTrades.IsEnabled =
ShowMyTrades.IsEnabled = ShowOrders.IsEnabled =
ShowPortfolios.IsEnabled = true;
}
Trader.ClientId = ClientId.Text.To<int>();
Trader.Key = Key.Text;
Trader.Secret = Secret.Password;
// clear password box for security reason
//Secret.Clear();
Trader.Connect();
}
else
{
Trader.Disconnect();
}
}
private void OrdersFailed(IEnumerable<OrderFail> fails)
{
this.GuiAsync(() =>
{
foreach (var fail in fails)
MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str153);
});
}
private void ChangeConnectStatus(bool isConnected)
{
_isConnected = isConnected;
ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect;
}
private void ShowSecuritiesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_securitiesWindow);
}
private void ShowTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_tradesWindow);
}
private void ShowMyTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_myTradesWindow);
}
private void ShowOrdersClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_ordersWindow);
}
private void ShowPortfoliosClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_portfoliosWindow);
}
private static void ShowOrHide(Window window)
{
if (window == null)
throw new ArgumentNullException(nameof(window));
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
}
}
}
| |
using System;
using System.Data;
using System.Collections.Generic;
using System.IO;
using System.Text;
using LythumOSL.Core;
namespace LythumOSL.Core.IO
{
public class File : ErrorInfo
{
/*
< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
*/
public const string UnallowedFSSymbols = "<>:\"|?*";
#region Helpers
/// <summary>
/// File exist validation
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool IsExist(string path)
{
FileInfo info = new FileInfo(path);
return info.Exists;
}
/// <summary>
/// Validate directory
/// </summary>
/// <param name="path">Path with directory and file</param>
/// <returns></returns>
public static bool IsValidDirectory(string path)
{
FileInfo info = new FileInfo(path);
return info.Directory.Exists;
}
/// <summary>
/// Generate and return temporary file name
/// </summary>
/// <returns></returns>
public static string MakeTemporaryFileName()
{
return Path.GetTempFileName();
}
/// <summary>
/// If given filename or path is empty it generate temporary file name
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static void FileSolution(ref string path)
{
if (string.IsNullOrEmpty(path))
{
path = MakeTemporaryFileName();
}
}
public static void Write (string fileName, string data, bool append)
{
Write (fileName, data, append, Encoding.Unicode);
}
public static void Write (string fileName, string data, bool append, Encoding enc)
{
StreamWriter sw = new StreamWriter (fileName, append, enc);
sw.Write (data);
sw.Close ();
}
public static void Write (
string fileName,
DataTable table,
string separator,
bool append,
bool withColumnNames,
bool skipWithUnderscoreBegin)
{
if (table != null)
{
bool appendNow = append;
Dictionary<int, bool> _AddMap =
new Dictionary<int, bool> ();
string buffer = string.Empty;
if (withColumnNames)
{
for(int i=0;i<table.Columns.Count;i++)
{
string name = table.Columns[i].ColumnName;
bool addIt;
if(skipWithUnderscoreBegin &&
name.Substring(0,1).Equals("_"))
{
addIt = false;
}
else
{
addIt = true;
}
_AddMap.Add (i, addIt);
if (addIt)
{
buffer += name + separator;
}
}
buffer += "\r\n";
Write (fileName, buffer, appendNow);
appendNow = true;
}
bool first = true;
foreach (DataRow r in table.Rows)
{
buffer = string.Empty;
for (int i = 0; i < table.Columns.Count; i++)
{
#warning TODO: bugas, vyksta luzis sioje vietoje jei withColumnNames=false!
if (_AddMap[i])
{
buffer += r[i].ToString () + separator;
}
}
buffer += "\r\n";
Write (fileName, buffer, appendNow);
appendNow = true;
}
}
}
public static string Read (string filename)
{
string retVal = string.Empty;
if (File.IsExist (filename))
{
TextReader tr = new StreamReader ( filename );
retVal = tr.ReadToEnd ();
}
return retVal;
}
public static IEnumerable<string> ReadLines (string filename, Encoding enc)
{
string line = string.Empty;
if (File.IsExist (filename))
{
TextReader tr = new StreamReader (filename, enc);
do
{
line = tr.ReadLine ();
if (!string.IsNullOrEmpty (line))
{
yield return line;
}
} while (!string.IsNullOrEmpty (line));
}
}
public static string FixFileName (string fileName)
{
string retVal = fileName;
foreach (char c in UnallowedFSSymbols)
{
retVal = retVal.Replace (c, '-');
}
return retVal;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing.Template;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Routing
{
/// <summary>
/// Base class implementation of an <see cref="IRouter"/>.
/// </summary>
public abstract partial class RouteBase : IRouter, INamedRouter
{
private readonly object _loggersLock = new object();
private TemplateMatcher? _matcher;
private TemplateBinder? _binder;
private ILogger? _logger;
private ILogger? _constraintLogger;
/// <summary>
/// Creates a new <see cref="RouteBase"/> instance.
/// </summary>
/// <param name="template">The route template.</param>
/// <param name="name">The name of the route.</param>
/// <param name="constraintResolver">An <see cref="IInlineConstraintResolver"/> used for resolving inline constraints.</param>
/// <param name="defaults">The default values for parameters in the route.</param>
/// <param name="constraints">The constraints for the route.</param>
/// <param name="dataTokens">The data tokens for the route.</param>
public RouteBase(
string? template,
string? name,
IInlineConstraintResolver constraintResolver,
RouteValueDictionary? defaults,
IDictionary<string, object>? constraints,
RouteValueDictionary? dataTokens)
{
if (constraintResolver == null)
{
throw new ArgumentNullException(nameof(constraintResolver));
}
template = template ?? string.Empty;
Name = name;
ConstraintResolver = constraintResolver;
DataTokens = dataTokens ?? new RouteValueDictionary();
try
{
// Data we parse from the template will be used to fill in the rest of the constraints or
// defaults. The parser will throw for invalid routes.
ParsedTemplate = TemplateParser.Parse(template);
Constraints = GetConstraints(constraintResolver, ParsedTemplate, constraints);
Defaults = GetDefaults(ParsedTemplate, defaults);
}
catch (Exception exception)
{
throw new RouteCreationException(Resources.FormatTemplateRoute_Exception(name, template), exception);
}
}
/// <summary>
/// Gets the set of constraints associated with each route.
/// </summary>
public virtual IDictionary<string, IRouteConstraint> Constraints { get; protected set; }
/// <summary>
/// Gets the resolver used for resolving inline constraints.
/// </summary>
protected virtual IInlineConstraintResolver ConstraintResolver { get; set; }
/// <summary>
/// Gets the data tokens associated with the route.
/// </summary>
public virtual RouteValueDictionary DataTokens { get; protected set; }
/// <summary>
/// Gets the default values for each route parameter.
/// </summary>
public virtual RouteValueDictionary Defaults { get; protected set; }
/// <inheritdoc />
public virtual string? Name { get; protected set; }
/// <summary>
/// Gets the <see cref="RouteTemplate"/> associated with the route.
/// </summary>
public virtual RouteTemplate ParsedTemplate { get; protected set; }
/// <summary>
/// Executes asynchronously whenever routing occurs.
/// </summary>
/// <param name="context">A <see cref="RouteContext"/> instance.</param>
protected abstract Task OnRouteMatched(RouteContext context);
/// <summary>
/// Executes whenever a virtual path is derived from a <paramref name="context"/>.
/// </summary>
/// <param name="context">A <see cref="VirtualPathContext"/> instance.</param>
/// <returns>A <see cref="VirtualPathData"/> instance.</returns>
protected abstract VirtualPathData? OnVirtualPathGenerated(VirtualPathContext context);
/// <inheritdoc />
public virtual Task RouteAsync(RouteContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
EnsureMatcher();
EnsureLoggers(context.HttpContext);
var requestPath = context.HttpContext.Request.Path;
if (!_matcher.TryMatch(requestPath, context.RouteData.Values))
{
// If we got back a null value set, that means the URI did not match
return Task.CompletedTask;
}
// Perf: Avoid accessing dictionaries if you don't need to write to them, these dictionaries are all
// created lazily.
if (DataTokens.Count > 0)
{
MergeValues(context.RouteData.DataTokens, DataTokens);
}
if (!RouteConstraintMatcher.Match(
Constraints,
context.RouteData.Values,
context.HttpContext,
this,
RouteDirection.IncomingRequest,
_constraintLogger))
{
return Task.CompletedTask;
}
Log.RequestMatchedRoute(_logger, Name, ParsedTemplate.TemplateText);
return OnRouteMatched(context);
}
/// <inheritdoc />
public virtual VirtualPathData? GetVirtualPath(VirtualPathContext context)
{
EnsureBinder(context.HttpContext);
EnsureLoggers(context.HttpContext);
var values = _binder.GetValues(context.AmbientValues, context.Values);
if (values == null)
{
// We're missing one of the required values for this route.
return null;
}
if (!RouteConstraintMatcher.Match(
Constraints,
values.CombinedValues,
context.HttpContext,
this,
RouteDirection.UrlGeneration,
_constraintLogger))
{
return null;
}
context.Values = values.CombinedValues;
var pathData = OnVirtualPathGenerated(context);
if (pathData != null)
{
// If the target generates a value then that can short circuit.
return pathData;
}
// If we can produce a value go ahead and do it, the caller can check context.IsBound
// to see if the values were validated.
// When we still cannot produce a value, this should return null.
var virtualPath = _binder.BindValues(values.AcceptedValues);
if (virtualPath == null)
{
return null;
}
pathData = new VirtualPathData(this, virtualPath);
if (DataTokens != null)
{
foreach (var dataToken in DataTokens)
{
pathData.DataTokens.Add(dataToken.Key, dataToken.Value);
}
}
return pathData;
}
/// <summary>
/// Extracts constatins from a given <see cref="RouteTemplate"/>.
/// </summary>
/// <param name="inlineConstraintResolver">An <see cref="IInlineConstraintResolver"/> used for resolving inline constraints.</param>
/// <param name="parsedTemplate">A <see cref="RouteTemplate"/> instance.</param>
/// <param name="constraints">A collection of constraints on the route template.</param>
protected static IDictionary<string, IRouteConstraint> GetConstraints(
IInlineConstraintResolver inlineConstraintResolver,
RouteTemplate parsedTemplate,
IDictionary<string, object>? constraints)
{
var constraintBuilder = new RouteConstraintBuilder(inlineConstraintResolver, parsedTemplate.TemplateText!);
if (constraints != null)
{
foreach (var kvp in constraints)
{
constraintBuilder.AddConstraint(kvp.Key, kvp.Value);
}
}
foreach (var parameter in parsedTemplate.Parameters)
{
if (parameter.IsOptional)
{
constraintBuilder.SetOptional(parameter.Name!);
}
foreach (var inlineConstraint in parameter.InlineConstraints)
{
constraintBuilder.AddResolvedConstraint(parameter.Name!, inlineConstraint.Constraint);
}
}
return constraintBuilder.Build();
}
/// <summary>
/// Gets the default values for parameters in a templates.
/// </summary>
/// <param name="parsedTemplate">A <see cref="RouteTemplate"/> instance.</param>
/// <param name="defaults">A collection of defaults for each parameter.</param>
protected static RouteValueDictionary GetDefaults(
RouteTemplate parsedTemplate,
RouteValueDictionary? defaults)
{
var result = defaults == null ? new RouteValueDictionary() : new RouteValueDictionary(defaults);
foreach (var parameter in parsedTemplate.Parameters)
{
if (parameter.DefaultValue != null)
{
#if RVD_TryAdd
if (!result.TryAdd(parameter.Name, parameter.DefaultValue))
{
throw new InvalidOperationException(
Resources.FormatTemplateRoute_CannotHaveDefaultValueSpecifiedInlineAndExplicitly(
parameter.Name));
}
#else
if (result.ContainsKey(parameter.Name!))
{
throw new InvalidOperationException(
Resources.FormatTemplateRoute_CannotHaveDefaultValueSpecifiedInlineAndExplicitly(
parameter.Name));
}
else
{
result.Add(parameter.Name!, parameter.DefaultValue);
}
#endif
}
}
return result;
}
private static void MergeValues(
RouteValueDictionary destination,
RouteValueDictionary values)
{
foreach (var kvp in values)
{
// This will replace the original value for the specified key.
// Values from the matched route will take preference over previous
// data in the route context.
destination[kvp.Key] = kvp.Value;
}
}
[MemberNotNull(nameof(_binder))]
private void EnsureBinder(HttpContext context)
{
if (_binder == null)
{
var binderFactory = context.RequestServices.GetRequiredService<TemplateBinderFactory>();
_binder = binderFactory.Create(ParsedTemplate, Defaults);
}
}
[MemberNotNull(nameof(_logger), nameof(_constraintLogger))]
private void EnsureLoggers(HttpContext context)
{
// We check first using the _logger to see if the loggers have been initialized to avoid taking
// the lock on the most common case.
if (_logger == null)
{
// We need to lock here to ensure that _constraintLogger and _logger get initialized atomically.
lock (_loggersLock)
{
if (_logger != null)
{
// Multiple threads might have tried to acquire the lock at the same time. Technically
// there is nothing wrong if things get reinitialized by a second thread, but its easy
// to prevent by just rechecking and returning here.
Debug.Assert(_constraintLogger != null);
return;
}
var factory = context.RequestServices.GetRequiredService<ILoggerFactory>();
_constraintLogger = factory.CreateLogger(typeof(RouteConstraintMatcher).FullName!);
_logger = factory.CreateLogger(typeof(RouteBase).FullName!);
}
}
Debug.Assert(_constraintLogger != null);
}
[MemberNotNull(nameof(_matcher))]
private void EnsureMatcher()
{
if (_matcher == null)
{
_matcher = new TemplateMatcher(ParsedTemplate, Defaults);
}
}
/// <inheritdoc />
public override string ToString()
{
return ParsedTemplate.TemplateText!;
}
private static partial class Log
{
[LoggerMessage(1, LogLevel.Debug,
"Request successfully matched the route with name '{RouteName}' and template '{RouteTemplate}'",
EventName = "RequestMatchedRoute")]
public static partial void RequestMatchedRoute(ILogger logger, string? routeName, string? routeTemplate);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Appoints.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof (IDictionary))
{
return GenerateDictionary(typeof (Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof (IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof (IList) ||
type == typeof (IEnumerable) ||
type == typeof (ICollection))
{
return GenerateCollection(typeof (ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof (IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof (IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize,
Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof (Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof (KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof (IList<>) ||
genericTypeDefinition == typeof (IEnumerable<>) ||
genericTypeDefinition == typeof (ICollection<>))
{
Type collectionType = typeof (List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof (IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof (ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof (IDictionary<,>))
{
Type dictionaryType = typeof (Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof (IDictionary<,>).MakeGenericType(genericArguments[0],
genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof (Tuple<>) ||
genericTypeDefinition == typeof (Tuple<,>) ||
genericTypeDefinition == typeof (Tuple<,,>) ||
genericTypeDefinition == typeof (Tuple<,,,>) ||
genericTypeDefinition == typeof (Tuple<,,,,>) ||
genericTypeDefinition == typeof (Tuple<,,,,,>) ||
genericTypeDefinition == typeof (Tuple<,,,,,,>) ||
genericTypeDefinition == typeof (Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType,
Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size,
Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof (object);
Type typeV = typeof (object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool) containsMethod.Invoke(result, new object[] {newKey});
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] {newKey, newValue});
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size,
Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof (List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof (object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof (IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof (Queryable).GetMethod("AsQueryable", new[] {argumentType});
return asQueryableMethod.Invoke(null, new[] {list});
}
return Queryable.AsQueryable((IEnumerable) list);
}
private static object GenerateCollection(Type collectionType, int size,
Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType
? collectionType.GetGenericArguments()[0]
: typeof (object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] {element});
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity",
Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{typeof (Boolean), index => true},
{typeof (Byte), index => (Byte) 64},
{typeof (Char), index => (Char) 65},
{typeof (DateTime), index => DateTime.Now},
{typeof (DateTimeOffset), index => new DateTimeOffset(DateTime.Now)},
{typeof (DBNull), index => DBNull.Value},
{typeof (Decimal), index => (Decimal) index},
{typeof (Double), index => (Double) (index + 0.1)},
{typeof (Guid), index => Guid.NewGuid()},
{typeof (Int16), index => (Int16) (index%Int16.MaxValue)},
{typeof (Int32), index => (Int32) (index%Int32.MaxValue)},
{typeof (Int64), index => (Int64) index},
{typeof (Object), index => new object()},
{typeof (SByte), index => (SByte) 64},
{typeof (Single), index => (Single) (index + 0.1)},
{
typeof (String),
index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof (TimeSpan), index => { return TimeSpan.FromTicks(1234567); }
},
{typeof (UInt16), index => (UInt16) (index%UInt16.MaxValue)},
{typeof (UInt32), index => (UInt32) (index%UInt32.MaxValue)},
{typeof (UInt64), index => (UInt64) index},
{
typeof (Uri),
index =>
{
return
new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com",
index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using GTA;
using GTA.Native;
using GTA.Math;
using NativeUI;
using NAudio.Wave;
using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Starman {
public class Main : Script {
private static string[] starmanThemes = new string[] { "smb", "smw", "smk", "sm64", "sm64m", "mk64", "mksc", "mkdd", "mkds", "spm", "mkwii", "nsmbwii", "msm", "smg2", "mk7", "sm3dl", "mk8", "smw2", "smrpg", "smbd", "smas", "sma4", "sma2", "sma", "mss", "msma" };
private ScriptSettings ss;
private Player player = Game.Player;
private AudioFileReader audioReader = null;
private WaveOutEvent waveOut = null;
private bool activated = false;
private Random rnd = new Random();
private DateTime dateTimeThatStarmanWasInitiated;
private string previousTheme;
private DateTime janFirst1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); // this acts as an initial/unset value for dateTimeThatStarmanWasInitiated
private TimerBarPool tbPool = new TimerBarPool();
private BarTimerBar btb = null;
private TimeSpan elapsedTime;
private bool hasReloaded = false;
private float volume = 0.4f;
// modify these
private int starmanTime = 20; // seconds, I recommend: 0 < x <= 20
private int fadeOutTime = 3; // seconds, I recommend: 0 < x <= 5
private float destructionRadius = 6.0f; // game units
public Main() {
Tick += onTick;
KeyUp += onKeyUp;
dateTimeThatStarmanWasInitiated = janFirst1970; // now we set the value
ss = ScriptSettings.Load(@"scripts\Starman.ini");
if(ss.GetValue("Settings", "JumpBoost") == null) {
ss.SetValue("Settings", "JumpBoost", "true");
}
if(ss.GetValue("Settings", "Key") == null) {
ss.SetValue("Settings", "Key", "105");
}
if(ss.GetValue("Settings", "VehiclePower") == null) {
ss.SetValue("Settings", "VehiclePower", "20");
}
if(ss.GetValue("Settings", "Volume") == null) {
ss.SetValue("Settings", "Volume", "0.4");
}
ss.Save();
}
private void onTick(object sender, EventArgs e) {
if(activated && !hasReloaded) {
// how long has starman been activated?
if(dateTimeThatStarmanWasInitiated != janFirst1970) {
elapsedTime = DateTime.Now - dateTimeThatStarmanWasInitiated;
}
// update the progress bar
if(btb != null && elapsedTime.TotalSeconds <= starmanTime) {
btb.Percentage = 1 - ((float)elapsedTime.TotalSeconds / starmanTime);
float hue = ((float)elapsedTime.TotalSeconds / starmanTime);
btb.ForegroundColor = ExtendedColor.HSL2RGB(hue, 1, 0.5);
btb.BackgroundColor = ExtendedColor.HSL2RGB(hue, 1, 0.3);
}
tbPool.Draw();
if(elapsedTime.TotalSeconds > starmanTime) { // starman finished
EndStarman();
} else if(elapsedTime.TotalSeconds <= starmanTime) { // starman is still running
// particles execute every 0.5 seconds
if(Math.Round(elapsedTime.TotalSeconds, 2) % 0.5d == 0) {
if(player.Character.IsInVehicle()) {
ParticleOnEntity(player.Character.CurrentVehicle, "scr_rcbarry1", "scr_alien_teleport", 1.0f);
} else {
ParticleOnEntity(player.Character, "scr_rcbarry1", "scr_alien_teleport", 1.0f);
}
}
// is the player in a vehicle?
if(player.Character.IsInVehicle()) {
// infinite health
Vehicle vehicle = player.Character.CurrentVehicle;
vehicle.CanBeVisiblyDamaged = false;
vehicle.CanTiresBurst = false;
vehicle.CanWheelsBreak = false;
vehicle.EngineCanDegrade = false;
vehicle.IsBulletProof = true;
vehicle.IsExplosionProof = true;
vehicle.IsFireProof = true;
// explode on contact
Vehicle[] vehicles = World.GetNearbyVehicles(vehicle.Position, destructionRadius);
if(vehicles.Length > 0) {
foreach(Vehicle v in vehicles) {
if(v != player.Character.CurrentVehicle) {
if(player.Character.CurrentVehicle.IsTouching(v)) {
v.Explode();
}
}
}
}
} else {
// super jump
if(bool.Parse(ss.GetValue("Settings", "JumpBoost"))) {
player.SetSuperJumpThisFrame();
}
// kill closeby peds
Ped[] peds = World.GetNearbyPeds(player.Character.Position, destructionRadius - 4.5f);
if(peds.Length > 0) {
foreach(Ped p in peds) {
if(p != player.Character) {
p.Kill();
}
}
}
}
}
}
// if the mod has been reloaded
if(hasReloaded && activated) {
Wait(3000);
hasReloaded = false;
UI.Notify("The cooldown for the Starman mod is over.");
EndStarman();
}
}
private void onKeyUp(object sender, KeyEventArgs e) {
if(e.KeyValue == int.Parse(ss.GetValue("Settings", "Key"))) {
if(!hasReloaded && !activated) {
dateTimeThatStarmanWasInitiated = DateTime.Now;
StartStarman();
} else if(hasReloaded) {
UI.Notify("There is a 1-5 second cooldown for the Starman mod after pressing Insert.");
}
}
if(e.KeyCode == Keys.Insert && activated) { // if the mods are reloaded
hasReloaded = true;
}
}
#region Starman
private void StartStarman() {
string chosenTheme = starmanThemes[rnd.Next(1, starmanThemes.Length)];
while(chosenTheme == previousTheme) {
chosenTheme = starmanThemes[rnd.Next(1, starmanThemes.Length)];
}
previousTheme = chosenTheme;
// get the settings when Starman is activated
ScriptSettings tss = ScriptSettings.Load(@"scripts\Starman.ini");
volume = float.Parse(tss.GetValue("Settings", "Volume", "0.4"));
tss = null;
audioReader = new AudioFileReader("scripts/starman/" + chosenTheme + ".mp3");
audioReader.Volume = volume;
DelayFadeOutSampleProvider fadeOut = new DelayFadeOutSampleProvider(audioReader);
fadeOut.BeginFadeOut((starmanTime * 1000) - (fadeOutTime * 1000), fadeOutTime * 1000);
waveOut = new WaveOutEvent();
waveOut.PlaybackStopped += waveOut_PlaybackStopped;
waveOut.Init(fadeOut);
waveOut.Play();
btb = new BarTimerBar("STARMAN POWER");
btb.Percentage = 1;
btb.ForegroundColor = ExtendedColor.HSL2RGB(0, 1, 0.5);
btb.BackgroundColor = ExtendedColor.HSL2RGB(0, 1, 0.3);
tbPool.Add(btb);
activated = true;
SetInvulnerability(activated);
}
private void EndStarman() {
activated = false;
SetInvulnerability(activated);
if(btb != null) {
tbPool.Remove(btb);
btb = null;
}
dateTimeThatStarmanWasInitiated = janFirst1970;
}
#endregion
private void waveOut_PlaybackStopped(object sender, StoppedEventArgs e) {
if(activated && audioReader != null && waveOut != null) {
audioReader.Dispose();
waveOut.Dispose();
audioReader = null;
waveOut = null;
}
}
private void SetInvulnerability(bool i) {
if(player != null) {
if(player.Character != null) {
player.Character.CanBeDraggedOutOfVehicle = !i;
player.Character.CanBeShotInVehicle = !i;
player.Character.CanRagdoll = !i;
player.Character.CanSufferCriticalHits = !i;
player.Character.IsBulletProof = i;
player.Character.IsExplosionProof = i;
player.Character.IsFireProof = i;
}
SetInvincible(i);
SetSprint(i ? 1.49f : 1.0f);
SetSwim(i ? 1.49f : 1.0f);
}
if(player.Character.IsInVehicle()) {
Vehicle vehicle = player.Character.CurrentVehicle;
Function.Call(Hash.SET_ENTITY_INVINCIBLE, vehicle, i);
vehicle.CanBeVisiblyDamaged = !i;
vehicle.CanTiresBurst = !i;
vehicle.CanWheelsBreak = !i;
vehicle.EngineCanDegrade = !i;
vehicle.EnginePowerMultiplier = (i ? int.Parse(ss.GetValue("Settings", "VehiclePower")) : 1);
vehicle.IsBulletProof = i;
vehicle.IsExplosionProof = i;
vehicle.IsFireProof = !i;
}
}
private void SetInvincible(bool i) {
Function.Call(Hash.SET_PLAYER_INVINCIBLE, player, i);
}
private void SetSprint(float s) {
Function.Call(Hash.SET_RUN_SPRINT_MULTIPLIER_FOR_PLAYER, player, s);
}
private void SetSwim(float s) {
Function.Call(Hash.SET_SWIM_MULTIPLIER_FOR_PLAYER, player, s);
}
private void ParticleOnEntity(Entity entity, string argOneTwo, string argThree, float scale) {
Function.Call(Hash.REQUEST_NAMED_PTFX_ASSET, new InputArgument[] { argOneTwo });
Function.Call(Hash._SET_PTFX_ASSET_NEXT_CALL, new InputArgument[] { argOneTwo });
Function.Call(Hash.START_PARTICLE_FX_NON_LOOPED_ON_ENTITY, argThree, entity, 0, 0, 0, 0, 0, 0, scale, false, false, 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 Xunit;
namespace System.Linq.Tests
{
public class SequenceEqualTests : EnumerableTests
{
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q1 = from x1 in new int?[] { 2, 3, null, 2, null, 4, 5 }
select x1;
var q2 = from x2 in new int?[] { 1, 9, null, 4 }
select x2;
Assert.Equal(q1.SequenceEqual(q2), q1.SequenceEqual(q2));
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q1 = from x1 in new[] { "AAA", String.Empty, "q", "C", "#", "!@#$%^", "0987654321", "Calling Twice" }
select x1;
var q2 = from x2 in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS" }
select x2;
Assert.Equal(q1.SequenceEqual(q2), q1.SequenceEqual(q2));
}
[Fact]
public void BothEmpty()
{
int[] first = { };
int[] second = { };
Assert.True(first.SequenceEqual(second));
Assert.True(FlipIsCollection(first).SequenceEqual(second));
Assert.True(first.SequenceEqual(FlipIsCollection(second)));
Assert.True(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void MismatchInMiddle()
{
int?[] first = { 1, 2, 3, 4 };
int?[] second = { 1, 2, 6, 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void NullComparer()
{
string[] first = { "Bob", "Tim", "Chris" };
string[] second = { "Bbo", "mTi", "rishC" };
Assert.False(first.SequenceEqual(second, null));
Assert.False(FlipIsCollection(first).SequenceEqual(second, null));
Assert.False(first.SequenceEqual(FlipIsCollection(second), null));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second), null));
}
[Fact]
public void CustomComparer()
{
string[] first = { "Bob", "Tim", "Chris" };
string[] second = { "Bbo", "mTi", "rishC" };
Assert.True(first.SequenceEqual(second, new AnagramEqualityComparer()));
Assert.True(FlipIsCollection(first).SequenceEqual(second, new AnagramEqualityComparer()));
Assert.True(first.SequenceEqual(FlipIsCollection(second), new AnagramEqualityComparer()));
Assert.True(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second), new AnagramEqualityComparer()));
}
[Fact]
public void RunOnce()
{
string[] first = { "Bob", "Tim", "Chris" };
string[] second = { "Bbo", "mTi", "rishC" };
Assert.True(first.RunOnce().SequenceEqual(second.RunOnce(), new AnagramEqualityComparer()));
}
[Fact]
public void BothSingleNullExplicitComparer()
{
string[] first = { null };
string[] second = { null };
Assert.True(first.SequenceEqual(second, StringComparer.Ordinal));
Assert.True(FlipIsCollection(first).SequenceEqual(second, StringComparer.Ordinal));
Assert.True(first.SequenceEqual(FlipIsCollection(second), StringComparer.Ordinal));
Assert.True(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second), StringComparer.Ordinal));
}
[Fact]
public void BothMatchIncludingNullElements()
{
int?[] first = { -6, null, 0, -4, 9, 10, 20 };
int?[] second = { -6, null, 0, -4, 9, 10, 20 };
Assert.True(first.SequenceEqual(second));
Assert.True(FlipIsCollection(first).SequenceEqual(second));
Assert.True(first.SequenceEqual(FlipIsCollection(second)));
Assert.True(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void EmptyWithNonEmpty()
{
int?[] first = { };
int?[] second = { 2, 3, 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void NonEmptyWithEmpty()
{
int?[] first = { 2, 3, 4 };
int?[] second = { };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void MismatchingSingletons()
{
int?[] first = { 2 };
int?[] second = { 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void MismatchOnFirst()
{
int?[] first = { 1, 2, 3, 4, 5 };
int?[] second = { 2, 2, 3, 4, 5 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void MismatchOnLast()
{
int?[] first = { 1, 2, 3, 4, 4 };
int?[] second = { 1, 2, 3, 4, 5 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void SecondLargerThanFirst()
{
int?[] first = { 1, 2, 3, 4 };
int?[] second = { 1, 2, 3, 4, 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void FirstLargerThanSecond()
{
int?[] first = { 1, 2, 3, 4, 4 };
int?[] second = { 1, 2, 3, 4 };
Assert.False(first.SequenceEqual(second));
Assert.False(FlipIsCollection(first).SequenceEqual(second));
Assert.False(first.SequenceEqual(FlipIsCollection(second)));
Assert.False(FlipIsCollection(first).SequenceEqual(FlipIsCollection(second)));
}
[Fact]
public void FirstSourceNull()
{
int[] first = null;
int[] second = { };
Assert.Throws<ArgumentNullException>("first", () => first.SequenceEqual(second));
}
[Fact]
public void SecondSourceNull()
{
int[] first = { };
int[] second = null;
Assert.Throws<ArgumentNullException>("second", () => first.SequenceEqual(second));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Runtime.Serialization;
using System.Threading;
using NUnit.Framework;
using ServiceStack.Common.Extensions;
using ServiceStack.Text.Jsv;
namespace ServiceStack.Text.Tests
{
[TestFixture]
public class AdhocModelTests
: TestBase
{
public enum FlowPostType
{
Content,
Text,
Promo,
}
public class FlowPostTransient
{
public FlowPostTransient()
{
this.TrackUrns = new List<string>();
}
public long Id { get; set; }
public string Urn { get; set; }
public Guid UserId { get; set; }
public DateTime DateAdded { get; set; }
public DateTime DateModified { get; set; }
public Guid? TargetUserId { get; set; }
public long? ForwardedPostId { get; set; }
public Guid OriginUserId { get; set; }
public string OriginUserName { get; set; }
public Guid SourceUserId { get; set; }
public string SourceUserName { get; set; }
public string SubjectUrn { get; set; }
public string ContentUrn { get; set; }
public IList<string> TrackUrns { get; set; }
public string Caption { get; set; }
public Guid CaptionUserId { get; set; }
public string CaptionSourceName { get; set; }
public string ForwardedPostUrn { get; set; }
public FlowPostType PostType { get; set; }
public Guid? OnBehalfOfUserId { get; set; }
public static FlowPostTransient Create()
{
return new FlowPostTransient {
Caption = "Caption",
CaptionSourceName = "CaptionSourceName",
CaptionUserId = Guid.NewGuid(),
ContentUrn = "ContentUrn",
DateAdded = DateTime.Now,
DateModified = DateTime.Now,
ForwardedPostId = 1,
ForwardedPostUrn = "ForwardedPostUrn",
Id = 1,
OnBehalfOfUserId = Guid.NewGuid(),
OriginUserId = Guid.NewGuid(),
OriginUserName = "OriginUserName",
PostType = FlowPostType.Content,
SourceUserId = Guid.NewGuid(),
SourceUserName = "SourceUserName",
SubjectUrn = "SubjectUrn ",
TargetUserId = Guid.NewGuid(),
TrackUrns = new List<string> { "track1", "track2" },
Urn = "Urn ",
UserId = Guid.NewGuid(),
};
}
public bool Equals(FlowPostTransient other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.Id == Id && Equals(other.Urn, Urn) && other.UserId.Equals(UserId) && other.DateAdded.RoundToMs().Equals(DateAdded.RoundToMs()) && other.DateModified.RoundToMs().Equals(DateModified.RoundToMs()) && other.TargetUserId.Equals(TargetUserId) && other.ForwardedPostId.Equals(ForwardedPostId) && other.OriginUserId.Equals(OriginUserId) && Equals(other.OriginUserName, OriginUserName) && other.SourceUserId.Equals(SourceUserId) && Equals(other.SourceUserName, SourceUserName) && Equals(other.SubjectUrn, SubjectUrn) && Equals(other.ContentUrn, ContentUrn) && TrackUrns.EquivalentTo(other.TrackUrns) && Equals(other.Caption, Caption) && other.CaptionUserId.Equals(CaptionUserId) && Equals(other.CaptionSourceName, CaptionSourceName) && Equals(other.ForwardedPostUrn, ForwardedPostUrn) && Equals(other.PostType, PostType) && other.OnBehalfOfUserId.Equals(OnBehalfOfUserId);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(FlowPostTransient)) return false;
return Equals((FlowPostTransient)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = Id.GetHashCode();
result = (result * 397) ^ (Urn != null ? Urn.GetHashCode() : 0);
result = (result * 397) ^ UserId.GetHashCode();
result = (result * 397) ^ DateAdded.GetHashCode();
result = (result * 397) ^ DateModified.GetHashCode();
result = (result * 397) ^ (TargetUserId.HasValue ? TargetUserId.Value.GetHashCode() : 0);
result = (result * 397) ^ (ForwardedPostId.HasValue ? ForwardedPostId.Value.GetHashCode() : 0);
result = (result * 397) ^ OriginUserId.GetHashCode();
result = (result * 397) ^ (OriginUserName != null ? OriginUserName.GetHashCode() : 0);
result = (result * 397) ^ SourceUserId.GetHashCode();
result = (result * 397) ^ (SourceUserName != null ? SourceUserName.GetHashCode() : 0);
result = (result * 397) ^ (SubjectUrn != null ? SubjectUrn.GetHashCode() : 0);
result = (result * 397) ^ (ContentUrn != null ? ContentUrn.GetHashCode() : 0);
result = (result * 397) ^ (TrackUrns != null ? TrackUrns.GetHashCode() : 0);
result = (result * 397) ^ (Caption != null ? Caption.GetHashCode() : 0);
result = (result * 397) ^ CaptionUserId.GetHashCode();
result = (result * 397) ^ (CaptionSourceName != null ? CaptionSourceName.GetHashCode() : 0);
result = (result * 397) ^ (ForwardedPostUrn != null ? ForwardedPostUrn.GetHashCode() : 0);
result = (result * 397) ^ PostType.GetHashCode();
result = (result * 397) ^ (OnBehalfOfUserId.HasValue ? OnBehalfOfUserId.Value.GetHashCode() : 0);
return result;
}
}
}
[Test]
public void Can_Deserialize_text()
{
var dtoString = "[{Id:1,Urn:urn:post:3a944f18-920c-498a-832d-cf38fed3d0d7/1,UserId:3a944f18920c498a832dcf38fed3d0d7,DateAdded:2010-02-17T12:04:45.2845615Z,DateModified:2010-02-17T12:04:45.2845615Z,OriginUserId:3a944f18920c498a832dcf38fed3d0d7,OriginUserName:testuser1,SourceUserId:3a944f18920c498a832dcf38fed3d0d7,SourceUserName:testuser1,SubjectUrn:urn:track:1,ContentUrn:urn:track:1,TrackUrns:[],CaptionUserId:3a944f18920c498a832dcf38fed3d0d7,CaptionSourceName:testuser1,PostType:Content}]";
var fromString = TypeSerializer.DeserializeFromString<List<FlowPostTransient>>(dtoString);
}
[Test]
public void Can_Serialize_single_FlowPostTransient()
{
var dto = FlowPostTransient.Create();
SerializeAndCompare(dto);
}
[Test]
public void Can_serialize_jsv_dates()
{
var now = DateTime.Now;
var jsvDate = TypeSerializer.SerializeToString(now);
var fromJsvDate = TypeSerializer.DeserializeFromString<DateTime>(jsvDate);
Assert.That(fromJsvDate, Is.EqualTo(now));
}
[Test]
public void Can_serialize_json_dates()
{
var now = DateTime.Now;
var jsonDate = JsonSerializer.SerializeToString(now);
var fromJsonDate = JsonSerializer.DeserializeFromString<DateTime>(jsonDate);
Assert.That(fromJsonDate.RoundToMs(), Is.EqualTo(now.RoundToMs()));
}
[Test]
public void Can_Serialize_multiple_FlowPostTransient()
{
var dtos = new List<FlowPostTransient> {
FlowPostTransient.Create(),
FlowPostTransient.Create()
};
Serialize(dtos);
}
[DataContract]
public class TestObject
{
[DataMember]
public string Value { get; set; }
public TranslatedString ValueNoMember { get; set; }
public bool Equals(TestObject other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Value, Value);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(TestObject)) return false;
return Equals((TestObject)obj);
}
public override int GetHashCode()
{
return (Value != null ? Value.GetHashCode() : 0);
}
}
public class Test
{
public string Val { get; set; }
}
public class TestResponse
{
public TestObject Result { get; set; }
}
public class TranslatedString : ListDictionary
{
public string CurrentLanguage { get; set; }
public string Value
{
get
{
if (this.Contains(CurrentLanguage))
return this[CurrentLanguage] as string;
return null;
}
set
{
if (this.Contains(CurrentLanguage))
this[CurrentLanguage] = value;
else
Add(CurrentLanguage, value);
}
}
public TranslatedString()
{
CurrentLanguage = "en";
}
public static void SetLanguageOnStrings(string lang, params TranslatedString[] strings)
{
foreach (TranslatedString str in strings)
str.CurrentLanguage = lang;
}
}
[Test]
public void Should_ignore_non_DataMember_TranslatedString()
{
var dto = new TestObject {
Value = "value",
ValueNoMember = new TranslatedString
{
{"key1", "val1"},
{"key2", "val2"},
}
};
SerializeAndCompare(dto);
}
public interface IParent
{
int Id { get; set; }
string ParentName { get; set; }
}
public class Parent : IParent
{
public int Id { get; set; }
public string ParentName { get; set; }
public Child Child { get; set; }
}
public class Child
{
public int Id { get; set; }
public string ChildName { get; set; }
public IParent Parent { get; set; }
}
[Test]
public void Can_Serailize_Cyclical_Dependency_via_interface()
{
var dto = new Parent {
Id = 1,
ParentName = "Parent",
Child = new Child { Id = 2, ChildName = "Child" }
};
dto.Child.Parent = dto;
var fromDto = Serialize(dto, includeXml: false);
var parent = (Parent)fromDto.Child.Parent;
Assert.That(parent.Id, Is.EqualTo(dto.Id));
Assert.That(parent.ParentName, Is.EqualTo(dto.ParentName));
}
public class Exclude
{
public int Id { get; set; }
public string Key { get; set; }
}
[Test]
public void Can_exclude_properties()
{
JsConfig<Exclude>.ExcludePropertyNames = new[] { "Id" };
var dto = new Exclude { Id = 1, Key = "Value" };
Assert.That(dto.ToJson(), Is.EqualTo("{\"Key\":\"Value\"}"));
Assert.That(dto.ToJsv(), Is.EqualTo("{Key:Value}"));
}
public class HasIndex
{
public int Id { get; set; }
public int this[int id]
{
get { return Id; }
set { Id = value; }
}
}
[Test]
public void Can_serialize_type_with_indexer()
{
var dto = new HasIndex { Id = 1 };
Serialize(dto);
}
public struct Size
{
public Size(string value)
{
var parts = value.Split(',');
this.Width = parts[0];
this.Height = parts[1];
}
public Size(string width, string height)
{
Width = width;
Height = height;
}
public string Width;
public string Height;
public override string ToString()
{
return this.Width + "," + this.Height;
}
}
[Test]
public void Can_serialize_struct_in_list()
{
var structs = new[] {
new Size("10px", "10px"),
new Size("20px", "20px"),
};
Serialize(structs);
}
[Test]
public void Can_serialize_list_of_bools()
{
Serialize(new List<bool> { true, false, true });
Serialize(new[] { true, false, true });
}
public class PolarValues
{
public int Int { get; set; }
public long Long { get; set; }
public float Float { get; set; }
public double Double { get; set; }
public decimal Decimal { get; set; }
public bool Equals(PolarValues other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.Int == Int
&& other.Long == Long
&& other.Float.Equals(Float)
&& other.Double.Equals(Double)
&& other.Decimal == Decimal;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(PolarValues)) return false;
return Equals((PolarValues)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = Int;
result = (result * 397) ^ Long.GetHashCode();
result = (result * 397) ^ Float.GetHashCode();
result = (result * 397) ^ Double.GetHashCode();
result = (result * 397) ^ Decimal.GetHashCode();
return result;
}
}
}
[Test]
public void Can_serialize_max_values()
{
var dto = new PolarValues {
Int = int.MaxValue,
Long = long.MaxValue,
Float = float.MaxValue,
Double = double.MaxValue,
Decimal = decimal.MaxValue,
};
var to = Serialize(dto);
Assert.That(to, Is.EqualTo(dto));
}
[Test]
public void Can_serialize_max_values_less_1()
{
var dto = new PolarValues {
Int = int.MaxValue - 1,
Long = long.MaxValue - 1,
Float = float.MaxValue - 1,
Double = double.MaxValue - 1,
Decimal = decimal.MaxValue - 1,
};
var to = Serialize(dto);
Assert.That(to, Is.EqualTo(dto));
}
[Test]
public void Can_serialize_min_values()
{
var dto = new PolarValues {
Int = int.MinValue,
Long = long.MinValue,
Float = float.MinValue,
Double = double.MinValue,
Decimal = decimal.MinValue,
};
var to = Serialize(dto);
Assert.That(to, Is.EqualTo(dto));
}
public class TestClass
{
public string Description { get; set; }
public TestClass Inner { get; set; }
}
[Test]
public void Can_serialize_1_level_cyclical_dto()
{
var dto = new TestClass {
Description = "desc",
Inner = new TestClass { Description = "inner" }
};
var from = Serialize(dto, includeXml:false);
Assert.That(from.Description, Is.EqualTo(dto.Description));
Assert.That(from.Inner.Description, Is.EqualTo(dto.Inner.Description));
Console.WriteLine(from.Dump());
}
public enum EnumValues
{
Enum1,
Enum2,
Enum3,
}
[Test]
public void Can_Deserialize()
{
var items = TypeSerializer.DeserializeFromString<List<string>>(
"/CustomPath35/api,/CustomPath40/api,/RootPath35,/RootPath40,:82,:83,:5001/api,:5002/api,:5003,:5004");
Console.WriteLine(items.Dump());
}
[Test]
public void Can_Serialize_Array_of_enums()
{
var enumArr = new[] { EnumValues.Enum1, EnumValues.Enum2, EnumValues.Enum3, };
var json = JsonSerializer.SerializeToString(enumArr);
Assert.That(json, Is.EqualTo("[\"Enum1\",\"Enum2\",\"Enum3\"]"));
}
[Test]
public void Can_Serialize_Array_of_chars()
{
var enumArr = new[] { 'A', 'B', 'C', };
var json = JsonSerializer.SerializeToString(enumArr);
Assert.That(json, Is.EqualTo("[\"A\",\"B\",\"C\"]"));
}
[Test]
public void Can_Serialize_Array_with_nulls()
{
var t = new {
Name = "MyName",
Number = (int?)null,
Data = new object[] { 5, null, "text" }
};
ServiceStack.Text.JsConfig.IncludeNullValues = true;
var json = ServiceStack.Text.JsonSerializer.SerializeToString(t);
Assert.That(json, Is.EqualTo("{\"Name\":\"MyName\",\"Number\":null,\"Data\":[5,null,\"text\"]}"));
JsConfig.Reset();
}
class A
{
public string Value { get; set; }
}
[Test]
public void DumpFail()
{
var arrayOfA = new[] { new A { Value = "a" }, null, new A { Value = "b" } };
Console.WriteLine(arrayOfA.Dump());
}
[Test]
public void Deserialize_array_with_null_elements()
{
var json = "[{\"Value\": \"a\"},null,{\"Value\": \"b\"}]";
var o = JsonSerializer.DeserializeFromString<A[]>(json);
}
[Test]
public void Can_serialize_StringCollection()
{
var sc = new StringCollection {"one", "two", "three"};
var from = Serialize(sc, includeXml:false);
Console.WriteLine(from.Dump());
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class Character : MonoBehaviour
{
/* General Variables */
Rigidbody2D rigidBody;
private GameObject blueScreenGlow;
private EncounterManager enemyHandler;
private bool[] inputFlags;
public bool[] InputFlags { get { return inputFlags; } set { inputFlags = value; } }
private Text scoreUIText;
/* Health Variables */
private const int SECONDWIND_HITS = 3; // Number of hits taken for second wind to activate
private bool hitByLaser; // Tracks if being actively hit by laser
private int hpHit; // Times player has been hit towards second wind activation
[SerializeField] public int health;
private bool hitByMedicBullet;
[HideInInspector] public bool playerHit; // Tells the encounter manager the player has been hit
[HideInInspector] public int score;
private GameObject healthUIElement;
/* Movement and Dash Variables */
private float maxSpeed = 7f; // The fastest the player can travel in any direction
private List<Explosion> slowFields = new List<Explosion>(); // SLOB fields the player is inside
[HideInInspector] public float slowMod = 0; // Movement mod for effects (SLOB, etc)
[HideInInspector] public bool slowMovement; // ******ALEC: look at using slowmod instead of this ************
private float maxDashDist = 3f; // Uncanceled dash distance
private float dashRate = .5f; // Dash movement per frame
private float currDashDist; // Currently traveled distance of the dash
private float dashCooldown; // Cooldown timer
private int dashState;
public int DashState { get { return DashState; } } // Enum for state: 0=inactive, 1=cooldown, 2=startup, 3=active, 4=recovery
// Times- (# of frames/60)
private const float DASH_CD = .5833f; // Cooldown frames
/* Basic Attack Variables */
public GameObject[] baHitBoxes;
private float baTimer; // Duration timer
private int baState;
public int BAState { get { return baState; } } // Enum for state: 0=inactive, 1=cooldown, 2=startup, 3=active, 4=recovery
// Times- (# of frames/60)
private const float BA_STARTUP = 0.083f; // Startup frames
private const float BA_ACTIVE = 0.133333f; // Active frames
private const float BA_RECOVERY = 0.083f; // Recovery frames
/* Slice Variables */
public GameObject[] sliceHitBoxes; // Setting all hitboxes to public, so enemyhandler can have access to them -Simon; Analyze this dependency - Trevor
private const float SLICE_TIMESTEP = 0.5f; // The time needed to activate each "Level" of slice hitbox
private float sliceHoldTime; // Charge timer
private float sliceTimer; // Duration timer
private int sliceBoxes; // Number of boxes activated in current slice
private int sliceState;
public int SliceState { get { return sliceState; } } // Enum for state: 0=inactive, 1=charge, 2=startup, 3=active, 4=recovery
// Times- (# of frames/60)
private const float SLICE_STARTUP = 0.166f; // Startup frames
private const float SLICE_ACTIVE = 0.11666f; // Active frames
private const float SLICE_RECOVERY = 0.166f; // Recovery frames
/* Deflect Varibales */
public GameObject deflectHitBox;
private float deflectTimer; // Duration timer
private int deflectState;
public int DeflectState { get { return deflectState; } } // Enum for state: 0=inactive, 1=cooldown, 2=startup, 3=active, 4=recovery
// Times- (# of frames/60)
private const float DEFLECT_STARTUP = 0.066f; // Startup frames
private const float DEFLECT_ACTIVE = 0.5f; // Active frames
private const float DEFLECT_RECOVERY = 0.25f; // Recovery frames
/* Overclock Variables */
[SerializeField] public float overclockMod { get; private set; } // Game speed modifier for overclock
private float overclockTimer; // Duration timer
private float overclockCooldown; // Cooldown timer
private Slider overclockCDUISlider; // UI elements
private GameObject overclockReadyUIElement;
[HideInInspector] public bool killStunnedEnemies; // Activates to kill enemies ***CONSIDER MOVING TO ENEMY MANAGER
private int overclockState;
public int OverclockState { get { return overclockState; } } // Enum for state: 0=inactive, 1=cooldown, 2=startup frame 1, 3=startup, 4=active, 5=recovery, 6=last recovery frame
// Times- (# of frames/60)
private const float OVERCLOCK_STARTUP = 0.066f; // Startup frames
private const float OVERCLOCK_ACTIVE = 3f; // Active frames
private const float OVERCLOCK_RECOVERY = 0.05f; // Recovery frames
private const float OVERCLOCK_CD = 10f; // Cooldown frames
/* Animation Variables */
private Animator animator;
private int redTimer;
private GameObject hitSpark;
private int sliceAnimTimer;
private void Awake()
{
/* General Variables */
rigidBody = GetComponentInParent<Rigidbody2D>();
enemyHandler = GameObject.FindGameObjectWithTag("EncounterManager").GetComponent<EncounterManager>();
blueScreenGlow = GameObject.FindGameObjectWithTag("BlueScreenGlow");
blueScreenGlow.SetActive(false);
score = 0;
inputFlags = new bool[] { false, false, false, false, false, false, false }; // INPUT FLAGS, IN ORDER: SLICE[0], ATTACK[1], DEFLECT[2], INTERACT[6], OVERCLOCK[4], FIRE[5], DASH[6]
scoreUIText = GameObject.FindGameObjectWithTag("ScoreElement").GetComponent<Text>();
setScore();
/* Health Variables */
health = 9;
hitByMedicBullet = false;
healthUIElement = GameObject.FindGameObjectWithTag("HealthElement");
playerHit = false;
killStunnedEnemies = false;
hpHit = 0;
setHealth();
/* Movoement and Dash Variables */
currDashDist = 0;
dashCooldown = 0;
slowMovement = false;
/* Basic Attack Varables */
baTimer = 0;
baState = 0;
baHitBoxes = new GameObject[3]; // Populate with hitboxes
for (int i = 0; i < 3; i++)
{
baHitBoxes[i] = GameObject.Find("BAHitbox" + (i + 1));
baHitBoxes[i].gameObject.SetActive(false);
}
/* Slice Variables */
sliceHoldTime = 0;
sliceTimer = 0;
sliceState = 0;
sliceBoxes = 0;
sliceHitBoxes = new GameObject[6]; // Populate with hitboxes
for (int i = 0; i < 6; i++)
{
sliceHitBoxes[i] = GameObject.Find("SliceHitbox" + (i + 1));
sliceHitBoxes[i].gameObject.SetActive(false);
}
/* Deflect Variables */
deflectTimer = 0;
deflectState = 0;
deflectHitBox = GameObject.Find("DeflectHitbox");
deflectHitBox.gameObject.SetActive(false);
/* Overclock Variables */
overclockTimer = 0;
overclockCooldown = 0;
overclockMod = .7f;
overclockState = 0;
overclockCDUISlider = GameObject.FindGameObjectWithTag("OverclockCDElement").GetComponent<Slider>();
overclockReadyUIElement = GameObject.FindGameObjectWithTag("ReadyElement");
overclockReadyUIElement.SetActive(true);
/* Animation Variables */
animator = gameObject.GetComponent<Animator>();
hitSpark = transform.GetChild(0).gameObject;
}
public void controllerMove(float hMove, float vMove, float hLook, float vLook) // Movement and rotation with controller
{
// Only move when they are not doing these actions
if (baState < 2 && deflectState < 2 && sliceState < 2)
{
rigidBody.velocity = new Vector2(hMove * maxSpeed * (1-slowMod), vMove * maxSpeed * (1-slowMod));
}
if ((hLook != 0 || vLook != 0) && baState < 2 && sliceState < 2)
{
float angle = Mathf.Atan2(vLook, hLook) * Mathf.Rad2Deg;
rigidBody.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
}
else if ((rigidBody.velocity != Vector2.zero) && baState < 2 && sliceState < 2)
{
float angle = Mathf.Atan2(rigidBody.velocity.y, rigidBody.velocity.x) * Mathf.Rad2Deg;
rigidBody.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
public void keyboardMove(float hMove, float vMove, Vector3 mousePos) // Movement and rotation with keyboard and mouse
{
if (baState < 2 && deflectState < 2 && sliceState < 2) // Only move when they are not doing these actions
{
rigidBody.velocity = new Vector2(hMove * maxSpeed * (1 - slowMod), vMove * maxSpeed * (1 - slowMod));
}
Vector3 playerPos = Camera.main.WorldToScreenPoint(rigidBody.transform.position);
mousePos.x = mousePos.x - playerPos.x;
mousePos.y = mousePos.y - playerPos.y;
if (baState < 2 && sliceState < 2) // Rotate
{
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
rigidBody.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
}
}
private void Update()
{
//Debug.Log("Slice timer: " + sliceTimer);
//Debug.Log("BA timer: " + baTimer);
//Debug.Log("Deflect timer: " + deflectTimer);
ProcessInput();
ExecuteTimedActions();
// Enum for BA state: 0=inactive, 1=cooldown, 2=startup, 3=active, 4=recovery
// Enum for Slice state: 0=inactive, 1=charge, 2=startup, 3=active, 4=recovery
// Enum for state: 0=inactive, 1=cooldown, 2=startup frame 1, 3=startup, 4=active, 5=recovery, 6=last recovery frame
//switch (overclockState)
//{
// case 0:
// //Debug.Log("inactive");
// break;
// case 1:
// Debug.Log("cooldown");
// break;
// case 2:
// Debug.Log("startup f1");
// break;
// case 3:
// Debug.Log("startup");
// break;
// case 4:
// Debug.Log("active");
// break;
// case 5:
// Debug.Log("recovery");
// break;
// case 6:
// Debug.Log("last recovery frame");
// break;
// default:
// Debug.Log("Action Error.");
// break;
//}
if (deflectState == 3)
{
if (deflectTimer <= DEFLECT_RECOVERY && deflectTimer!=0) // If deflect is over, exit anim
animator.SetInteger("transitions", 5); // *** SEE: This check might not be necessary due to the new enums for state **** ALSO: put this where it belongs in the timedactions method
else animator.SetInteger("transitions", 4);
}
if (sliceState == 3) // Same with the rest of these animations, put it where it goes in timed actions *******************************
{
animator.SetInteger("transitions", 3);
sliceAnimTimer = 10;
//hitSpark.GetComponent<Animator>().SetInteger("hitBoxCount", sliceBoxes+1);
//Debug.Log(sliceBoxes + 1);
//Debug.Log("Slicing");
}
if (baState == 3)
{
animator.SetInteger("transitions", 1);
//Debug.Log("attacking");
//Debug.Log(animator.GetInteger("transitions"));
}
if(deflectState < 2 && baState < 2 && sliceState < 1 && !slowMovement) // If we have a sprite for charging the slice, make this sS<1 (1=charge) and do another if
{ // Why do we care about slowSpeed for this?
animator.SetInteger("transitions", 0);
// if(hitSpark.GetComponent<Animator>().GetInteger("hitBoxCount")>0)
}
if (slowMovement) // Something's wrong with the animations today and I don't know what it is, Something's wrong with our ifs, We're seeing things in a different way, And MJ knows it ain't his, It sure ain't no surprise, HUH. LIVIN IN THE CODE
{
//animator.SetInteger("transitions", 2);
}
if (redTimer>0) // What is this ?? ---- ATTN: ANYONE WHO KNOWS THE ANIMATION STUFF
{
redTimer--;
if(redTimer<=0)
{
gameObject.GetComponent<SpriteRenderer>().color = new Color(255, 255, 255);
}
}
if(sliceAnimTimer>0)
{
sliceAnimTimer--;
if(sliceAnimTimer<=0)
{
hitSpark.GetComponent<Animator>().SetInteger("hitBoxCount", 0);
}
}
//Debug.Log(animator.GetInteger("transitions"));
for (int i = 0; i < slowFields.Count; i++)
{
if (!slowFields[i].isTrigger)
{
slowFields.RemoveAt(i);
i--;
}
}
if (slowMod > 0 && slowFields.Count == 0)
{
//Debug.Log("unslowed");
slowMod = 0;
}
overclockCDUISlider.value = 20 - (overclockCooldown * 2);
}
private void ProcessInput() // Processes the current input that the character has
{
for (int i = 0; i < inputFlags.Length; i++)
{
if (i == 0 && sliceHoldTime > 0 && !inputFlags[0]) // Checks for slice release: this is what triggers the actual slice
{
if (deflectState > 1 || baState > 1 || sliceState > 1) continue;
//Debug.Log("Slice");
sliceState = 2; // Startup
sliceBoxes = Mathf.FloorToInt(sliceHoldTime / SLICE_TIMESTEP);
if (sliceBoxes > 5) sliceBoxes = 5;
sliceTimer = SLICE_STARTUP + SLICE_ACTIVE + SLICE_RECOVERY; // Start timer for slice mechanic
sliceHoldTime = 0;
}
if (inputFlags[i])
{
switch (i)
{
case 0: // Charging Slice (button held)
if (deflectState > 1 || baState > 1 || sliceState > 1) continue;
//Debug.Log("SliceHold/LowSpeed");
sliceState = 1;
sliceHoldTime += Time.deltaTime;
slowMovement = true;
animator.SetInteger("transitions", 2);
break;
case 1: // Attacking
if (sliceState > 0 || deflectState > 1 || baState > 1) continue;
//Debug.Log("Attack");
baState = 2; // Startup
baTimer = BA_STARTUP + BA_ACTIVE + BA_RECOVERY;
//animator.SetInteger("transitions", 1);
break;
case 2: // Deflecting
if (sliceState > 0 || baState > 1 || deflectState > 1) continue;
//Debug.Log("deflect");
deflectState = 2; // Startup
deflectTimer = DEFLECT_STARTUP + DEFLECT_ACTIVE + DEFLECT_RECOVERY;
//animator.SetInteger("transitions", 4);
break;
case 3: // Interacting
break;
case 4: // Overclocking
if (overclockState == 0)
{
overclockReadyUIElement.SetActive(false);
//Debug.Log("Press");
overclockState = 2; // Startup
overclockTimer = OVERCLOCK_STARTUP + OVERCLOCK_ACTIVE + OVERCLOCK_RECOVERY;
}
else if (overclockState > 1) // Manual cancel, trigger recovery
{
//Debug.Log("Unpress");
overclockState = 5; // Recovery frame 1
overclockTimer = OVERCLOCK_RECOVERY;
}
break;
case 5: // Firing
break;
case 6: // Dashing
if (dashState > 1 && (sliceState > 1 || baState > 1 || deflectState > 1)) // Cancel dash on other actions
{
//Debug.Log("Cancel");
dashState = 1; // Note that canceling dash with actions mapped to mouse buttons DOES NOT WORK on most touchpads because of system-wide accidental input suppression
currDashDist = 0; // Cooldown
dashCooldown = DASH_CD;
transform.GetComponent<SpriteRenderer>().color = Color.white;
}
else if (sliceState > 1 || baState > 1 || deflectState > 1) continue; // Do not perform dash while doing other actions
else
{
if (currDashDist == 0 && dashCooldown <= 0 && rigidBody.velocity != Vector2.zero) // Only dash if moving
{
//Debug.Log("Respeed");
slowMovement = false; // Respeed
maxSpeed = 7f; // ******* THESE VALUES SHOULD NOT BE HARD CODED-- Also, move these to a different statement if movement is supposed to come back after releasing the button (active frames)
dashRate = .5f;
maxDashDist = 3;
dashState = 3; // Active
//Debug.Log("Dash");
transform.GetComponent<SpriteRenderer>().color = Color.blue;
}
if (dashState > 1 && currDashDist < maxDashDist) // WHile dashing
{
currDashDist += dashRate;
rigidBody.transform.position += new Vector3(rigidBody.velocity.normalized.x * dashRate, rigidBody.velocity.normalized.y * dashRate, rigidBody.transform.position.z);
}
else if (currDashDist >= maxDashDist) // Dash is complete
{
dashState = 1; // Cooldown
currDashDist = 0;
dashCooldown = DASH_CD;
//Debug.Log("End");
transform.GetComponent<SpriteRenderer>().color = Color.white;
}
}
break;
default:
break;
}
}
if (!inputFlags[6] && dashState > 1)
{
//Debug.Log("Release");
dashState = 1; // Cooldown
currDashDist = 0;
dashCooldown = DASH_CD;
transform.GetComponent<SpriteRenderer>().color = Color.white;
}
}
}
private void ExecuteTimedActions() // Executes any time-based actions (slicing, dashing, basic attacking, deflecting)
{
/* Dash */
if (dashState == 1 && dashCooldown > 0) // Increment dash cooldown based on delta time
{
dashCooldown -= Time.deltaTime;
}
else if (dashState == 1 && dashCooldown <= 0)
{
dashState = 0;
}
/* Basic Attack */
if (baTimer <= 0) // If bT <= 0 then bT = 0, else = bT-dT
{
baTimer = 0;
baState = 0; // No cooldown on basic attack
}
else baTimer = baTimer - Time.deltaTime;
if (baState > 1)
{
if (baTimer <= BA_RECOVERY) // Recovery frames
{
baState = 4; // Recovery
baHitBoxes[2].gameObject.SetActive(false); // Remove hitboxes
//animator.SetInteger("transitions", 0);
}
else if (baTimer <= (BA_ACTIVE + BA_RECOVERY)) // Active frames
{
baState = 3; // Active
if (baTimer <= (BA_ACTIVE / 3) + BA_RECOVERY) // Activating hitboxes based on where we are in the anim
{
baHitBoxes[2].gameObject.SetActive(true);
baHitBoxes[1].gameObject.SetActive(false);
}
else if (baTimer <= (2 * BA_ACTIVE / 3) + BA_RECOVERY)
{
baHitBoxes[1].gameObject.SetActive(true);
baHitBoxes[0].gameObject.SetActive(false);
}
else
{
baHitBoxes[0].gameObject.SetActive(true);
}
//animator.SetInteger("transitions", 1);
}
}
/* Slice */
if (sliceTimer <= 0) // If sT <= 0 then sT = 0, else = sT-dT
{
sliceTimer = 0;
if (slowMovement == true) // ***** SHOULD NOT BE HARD CODED, TRY TO USE SPEED MOD OR HAVE A SET OF VARS
{
maxSpeed = 2f; // While unspeeded
dashRate = .3f;
maxDashDist = 2;
}
if (sliceState > 1) sliceState = 0; // No cooldown on slice
}
else sliceTimer = sliceTimer - Time.deltaTime;
if (sliceState > 1)
{
if (sliceTimer <= SLICE_RECOVERY) // Recovery frames
{
sliceState = 4; // Recovery
for (int i = 0; i < 6; i++) // End hitboxes
{
sliceHitBoxes[i].gameObject.SetActive(false);
}
}
else if (sliceTimer <= (SLICE_ACTIVE + SLICE_RECOVERY)) // Active frames
{
sliceHitBoxes[0].gameObject.SetActive(true); // Always activate the first box
for (int i = 0; i < sliceBoxes; i++) // Additional hitboxes
{
sliceHitBoxes[i + 1].gameObject.SetActive(true);
}
hitSpark.GetComponent<Animator>().SetInteger("hitBoxCount", sliceBoxes + 1);
sliceState = 3; // Active
slowMovement = false; // Respeed
maxSpeed = 7f; // ******* THESE VALUES SHOULD NOT BE HARD CODED-- Also, move these to a different statement if movement is supposed to come back after releasing the button (active frames)
dashRate = .5f;
maxDashDist = 3;
//Debug.Log("Reset speed");
//animator.SetInteger("transitions", 3);
}
if (sliceState < 4) // During active and startup
{
//Debug.Log(sliceState);
//animator.SetInteger("transitions", 2);
}
}
/* Deflect */
if (deflectTimer <= 0) // If dfT <= 0 then dfT = 0, else = dfT-dT
{
deflectState = 0; // No cooldown on deflect
deflectTimer = 0;
}
else deflectTimer = deflectTimer - Time.deltaTime;
if (deflectState > 1)
{
if (deflectTimer <= DEFLECT_RECOVERY) // Recovery frames
{
deflectState = 4; // Recovery
deflectHitBox.gameObject.SetActive(false); // Remove hitbox
animator.SetInteger("transitions", 5);
}
else if (deflectTimer <= (DEFLECT_ACTIVE + DEFLECT_RECOVERY)) // Active frames
{
deflectState = 3; // Active
deflectHitBox.gameObject.SetActive(true);
animator.SetInteger("transitions", 5);
}
}
/* Overclock */
overclockTimer = overclockTimer <= 0 ? 0 : overclockTimer - Time.deltaTime; // If bT <= 0 then bT = 0, else = bT-dT
switch (overclockState)
{
case 1: // Cooldown
if (overclockCooldown > 0) // Increment cooldown
{
//Debug.Log("Cooling: " + overclockCooldown);
overclockCooldown -= Time.deltaTime;
}
else
{
overclockState = 0; // Ready!
overclockReadyUIElement.SetActive(true);
overclockCooldown = 0;
}
break;
case 2: // Startup frame 1
overclockState = 3; // Move on to startup
enemyHandler.speedMod -= overclockMod; // Slow enemies
enemyHandler.KillStunnedEnemies();
//Debug.Log("ZA WARUDO: " + enemyHandler.speedMod);
Camera.main.GetComponent<UnityStandardAssets.ImageEffects.NoiseAndScratches>().enabled = true;
//Camera.main.GetComponent<UnityStandardAssets.ImageEffects.Grayscale>().enabled = true;
blueScreenGlow.SetActive(true);
Camera.main.GetComponent<UnityStandardAssets.ImageEffects.VignetteAndChromaticAberration>().enabled = true;
break;
case 3: // Startup
if (overclockTimer <= (OVERCLOCK_ACTIVE + OVERCLOCK_RECOVERY))
{
overclockState = 4; // Active
}
break;
case 4: // Active
if (overclockTimer <= OVERCLOCK_RECOVERY)
{
overclockState = 5; // Recovery
}
break;
case 5: // Recovery
if (overclockTimer <= 0)
{
overclockState = 6; // Last frame
}
break;
case 6: // Last recovery frame (techically a +1 frame on the end)
enemyHandler.speedMod += overclockMod; // Respeed enemies
overclockState = 1; // Cooldown
overclockTimer = 0;
overclockCooldown = OVERCLOCK_CD;
//Debug.Log("WRYYYYYY: " + enemyHandler.speedMod);
Camera.main.GetComponent<UnityStandardAssets.ImageEffects.NoiseAndScratches>().enabled = false;
//Camera.main.GetComponent<UnityStandardAssets.ImageEffects.Grayscale>().enabled = false;
blueScreenGlow.SetActive(false);
Camera.main.GetComponent<UnityStandardAssets.ImageEffects.VignetteAndChromaticAberration>().enabled = false;
break;
}
}
public void setHealth() // Update health UI element and check for death
{
if(health > 9) // Max health ***** SHOULD NOT BE HARD CODED, ADD CONST
{
health = 9;
}
healthUIElement.GetComponent<Text>().text = health.ToString();
if (health > 4) healthUIElement.transform.GetChild(0).gameObject.GetComponent<SpriteRenderer>().color = new Color(0, 201, 0); // Green
else if (health > 3) healthUIElement.transform.GetChild(0).gameObject.GetComponent<SpriteRenderer>().color = new Color(201, 201, 0); // Yellow
else healthUIElement.transform.GetChild(0).gameObject.GetComponent<SpriteRenderer>().color = new Color(201, 0, 0); // Red
if (health <= 0)
{
health = 0;
Debug.Log("GAME OVER");
UnityEngine.SceneManagement.SceneManager.LoadScene(UnityEngine.SceneManagement.SceneManager.GetSceneAt(0).name);
}
}
public void setScore() // Set UI score element
{
scoreUIText.text = "Score " + score.ToString();
}
public void resetOverclock()
{
overclockCooldown = 0;
}
void OnTriggerEnter2D(Collider2D other)
{
//Debug.Log("Collide");
if (other.tag != "Grenade" && other.gameObject.layer == 11) // Basic bullets + rocket
{
// Prevent collision with deflected bullets
if ((other.tag == "Bullet" || other.tag == "SlowBullet") && other.GetComponent<Bullet>().CanHurtEnemies) return;
//Debug.Log("Player got hit");
redTimer = 10;
gameObject.GetComponent<SpriteRenderer>().color = new Color(255, 0, 0);
health--;
setHealth();
hpHit++;
//Debug.Log(hpHit);
Cancel(); // ends active attacks when hit. This may need to be commented out if we can't get the animations to stop too
//Debug.Log("Got em. Health: " + health);
//gameObject.GetComponent<SpriteRenderer>().color = Color.red;
enemyHandler.SecondWind();
Destroy(other.gameObject); // Get rid of the bullet that was fired
return;
}
else if (other.gameObject.layer == 12 && !hitByLaser) // Laser first hit
{
//Debug.Log("LASERED");
health--;
setHealth();
hpHit++;
//Debug.Log(hpHit);
Cancel();
hitByLaser = true;
enemyHandler.SecondWind();
}
else if (other.gameObject.layer == 13) // Slow field from grenade
{
slowFields.Add(other.gameObject.GetComponent<Explosion>());
if (!other.gameObject.GetComponent<Explosion>().canHurtEnemies && slowMod <= 0)
{
//Debug.Log("Slowed");
slowMod = other.gameObject.GetComponent<Explosion>().slowFactor;
}
}
else if (other.gameObject.layer == 14 && hitByMedicBullet == false) // Medic bullet
{
health++;
setHealth();
hpHit++;
hitByMedicBullet = true;
}
if (other.gameObject.tag == "BigShield")
{
//Debug.Log("Player in");
other.GetComponent<BigShield>().playerInside = true;
}
if (other.gameObject.tag == "Dome")
{
health--;
setHealth();
hpHit++;
}
}
void OnTriggerExit2D(Collider2D other)
{
//if the medic bullet passed through us, give us 1 health
if(other.tag == "MedicBullet")
{
hitByMedicBullet = false;
return;
}
if (other.gameObject.layer == 12) hitByLaser = false; // Laser
if (other.gameObject.layer == 13) // Grenade based slow fields
{
foreach (Explosion e in slowFields)
{
if (other.GetComponent<Explosion>().id == e.id)
{
slowFields.Remove(e);
break;
}
}
if (slowFields.Count == 0)
{
//Debug.Log("unslowed");
slowMod = 0;
}
}
if (other.gameObject.tag == "BigShield")
{
//Debug.Log("Player out");
other.GetComponent<BigShield>().playerInside = false;
}
}
void Cancel()
{
baTimer = 0;
baHitBoxes[0].gameObject.SetActive(false);
baHitBoxes[1].gameObject.SetActive(false);
baHitBoxes[2].gameObject.SetActive(false);
//animator.SetInteger("transitions", 0);
}
public void Hitstop(float pauseDelay) // ********* What is this?
{
//float pauseDelay = .7f;
pauseDelay /= 60.0f;
Time.timeScale = .0000001f;
while (pauseDelay > 0)
{
pauseDelay -= Time.deltaTime;
//Debug.Log("hitstop");
//GameObject.FindGameObjectWithTag("Hitspark").SetActive(true);
}
//Debug.Log("Out");
Time.timeScale = 1.0f;
//GameObject.FindGameObjectWithTag("Hitspark").SetActive(false);
}
}
| |
//
// CTParagraphStyle.cs: Implements the managed CTParagraphStyle
//
// Authors: Mono Team
//
// Copyright 2010 Novell, Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
using MonoMac.CoreGraphics;
namespace MonoMac.CoreText {
#region Paragraph Style Values
[Since (3,2)]
public enum CTTextAlignment : byte {
Left = 0,
Right = 1,
Center = 2,
Justified = 3,
Natural = 4,
}
[Since (3,2)]
public enum CTLineBreakMode : byte {
WordWrapping = 0,
CharWrapping = 1,
Clipping = 2,
TruncatingHead = 3,
TruncatingTail = 4,
TruncatingMiddle = 5,
}
[Since (3,2)]
public enum CTWritingDirection : sbyte {
Natural = -1,
LeftToRight = 0,
RightToLeft = 1,
}
internal enum CTParagraphStyleSpecifier : uint {
Alignment = 0,
FirstLineHeadIndent = 1,
HeadIndent = 2,
TailIndent = 3,
TabStops = 4,
DefaultTabInterval = 5,
LineBreakMode = 6,
LineHeightMultiple = 7,
MaximumLineHeight = 8,
MinimumLineHeight = 9,
LineSpacing = 10,
ParagraphSpacing = 11,
ParagraphSpacingBefore = 12,
BaseWritingDirection = 13,
MaximumLineSpacing = 14,
MinimumLineSpacing = 15,
LineSpacingAdjustment = 16,
Count = 14,
}
internal struct CTParagraphStyleSetting {
public CTParagraphStyleSpecifier spec;
public uint valueSize;
public IntPtr value;
}
#endregion
[StructLayout (LayoutKind.Explicit)]
internal struct CTParagraphStyleSettingValue {
[FieldOffset (0)] public byte int8;
[FieldOffset (0)] public float single;
[FieldOffset (0)] public IntPtr pointer;
}
internal abstract class CTParagraphStyleSpecifierValue {
protected CTParagraphStyleSpecifierValue (CTParagraphStyleSpecifier spec)
{
Spec = spec;
}
internal CTParagraphStyleSpecifier Spec {get; private set;}
internal abstract int ValueSize {get;}
internal abstract void WriteValue (CTParagraphStyleSettingValue[] values, int index);
public virtual void Dispose (CTParagraphStyleSettingValue[] values, int index)
{
}
}
internal class CTParagraphStyleSpecifierByteValue : CTParagraphStyleSpecifierValue {
byte value;
public CTParagraphStyleSpecifierByteValue (CTParagraphStyleSpecifier spec, byte value)
: base (spec)
{
this.value = value;
}
internal override int ValueSize {
get {return sizeof (byte);}
}
internal override void WriteValue (CTParagraphStyleSettingValue[] values, int index)
{
values [index].int8 = value;
}
}
internal class CTParagraphStyleSpecifierSingleValue : CTParagraphStyleSpecifierValue {
float value;
public CTParagraphStyleSpecifierSingleValue (CTParagraphStyleSpecifier spec, float value)
: base (spec)
{
this.value = value;
}
internal override int ValueSize {
get {return sizeof (float);}
}
internal override void WriteValue (CTParagraphStyleSettingValue[] values, int index)
{
values [index].single = value;
}
}
internal class CTParagraphStyleSpecifierIntPtrsValue : CTParagraphStyleSpecifierValue {
CFArray value;
public CTParagraphStyleSpecifierIntPtrsValue (CTParagraphStyleSpecifier spec, IntPtr[] value)
: base (spec)
{
this.value = CFArray.FromIntPtrs (value);
}
internal override int ValueSize {
get {return IntPtr.Size;}
}
internal override void WriteValue (CTParagraphStyleSettingValue[] values, int index)
{
values [index].pointer = value.Handle;
}
public override void Dispose (CTParagraphStyleSettingValue[] values, int index)
{
values [index].pointer = IntPtr.Zero;
value.Dispose ();
value = null;
}
}
[Since (3,2)]
public class CTParagraphStyleSettings {
public CTParagraphStyleSettings ()
{
}
public IEnumerable<CTTextTab> TabStops {get; set;}
public CTTextAlignment? Alignment {get; set;}
public CTLineBreakMode? LineBreakMode {get; set;}
public CTWritingDirection? BaseWritingDirection {get; set;}
public float? FirstLineHeadIndent {get; set;}
public float? HeadIndent {get; set;}
public float? TailIndent {get; set;}
public float? DefaultTabInterval {get; set;}
public float? LineHeightMultiple {get; set;}
public float? MaximumLineHeight {get; set;}
public float? MinimumLineHeight {get; set;}
public float? LineSpacing {get; set;}
public float? ParagraphSpacing {get; set;}
public float? ParagraphSpacingBefore {get; set;}
public float? MaximumLineSpacing { get; set;}
public float? MinimumLineSpacing { get; set;}
public float? LineSpacingAdjustment { get; set; }
internal List<CTParagraphStyleSpecifierValue> GetSpecifiers ()
{
var values = new List<CTParagraphStyleSpecifierValue> ();
if (TabStops != null)
values.Add (CreateValue (CTParagraphStyleSpecifier.TabStops, TabStops));
if (Alignment.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.Alignment, (byte) Alignment.Value));
if (LineBreakMode.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.LineBreakMode, (byte) LineBreakMode.Value));
if (BaseWritingDirection.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.BaseWritingDirection, (byte) BaseWritingDirection.Value));
if (FirstLineHeadIndent.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.FirstLineHeadIndent, FirstLineHeadIndent.Value));
if (HeadIndent.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.HeadIndent, HeadIndent.Value));
if (TailIndent.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.TailIndent, TailIndent.Value));
if (DefaultTabInterval.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.DefaultTabInterval, DefaultTabInterval.Value));
if (LineHeightMultiple.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.LineHeightMultiple, LineHeightMultiple.Value));
if (MaximumLineHeight.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.MaximumLineHeight, MaximumLineHeight.Value));
if (MinimumLineHeight.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.MinimumLineHeight, MinimumLineHeight.Value));
if (LineSpacing.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.LineSpacing, LineSpacing.Value));
if (ParagraphSpacing.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.ParagraphSpacing, ParagraphSpacing.Value));
if (ParagraphSpacingBefore.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.ParagraphSpacingBefore, ParagraphSpacingBefore.Value));
if (MaximumLineSpacing.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.MaximumLineSpacing, MaximumLineSpacing.Value));
if (MinimumLineSpacing.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.MinimumLineSpacing, MinimumLineSpacing.Value));
if (LineSpacingAdjustment.HasValue)
values.Add (CreateValue (CTParagraphStyleSpecifier.LineSpacingAdjustment, LineSpacingAdjustment.Value));
return values;
}
static CTParagraphStyleSpecifierValue CreateValue (CTParagraphStyleSpecifier spec, IEnumerable<CTTextTab> value)
{
var handles = new List<IntPtr>();
foreach (var ts in value)
handles.Add (ts.Handle);
return new CTParagraphStyleSpecifierIntPtrsValue (spec, handles.ToArray ());
}
static CTParagraphStyleSpecifierValue CreateValue (CTParagraphStyleSpecifier spec, byte value)
{
return new CTParagraphStyleSpecifierByteValue (spec, value);
}
static CTParagraphStyleSpecifierValue CreateValue (CTParagraphStyleSpecifier spec, float value)
{
return new CTParagraphStyleSpecifierSingleValue (spec, value);
}
}
[Since (3,2)]
public class CTParagraphStyle : INativeObject, IDisposable {
internal IntPtr handle;
internal CTParagraphStyle (IntPtr handle, bool owns)
{
if (handle == IntPtr.Zero)
throw ConstructorError.ArgumentNull (this, "handle");
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
public IntPtr Handle {
get {return handle;}
}
~CTParagraphStyle ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
#region Paragraph Style Creation
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTParagraphStyleCreate (CTParagraphStyleSetting[] settings, int settingCount);
public CTParagraphStyle (CTParagraphStyleSettings settings)
{
handle = settings == null
? CTParagraphStyleCreate (null, 0)
: CreateFromSettings (settings);
if (handle == IntPtr.Zero)
throw ConstructorError.Unknown (this);
}
static unsafe IntPtr CreateFromSettings (CTParagraphStyleSettings s)
{
var handle = IntPtr.Zero;
var specifiers = s.GetSpecifiers ();
var settings = new CTParagraphStyleSetting [specifiers.Count];
var values = new CTParagraphStyleSettingValue [specifiers.Count];
int i = 0;
foreach (var e in specifiers) {
e.WriteValue (values, i);
settings [i].spec = e.Spec;
settings [i].valueSize = (uint) e.ValueSize;
++i;
}
fixed (CTParagraphStyleSettingValue* pv = values) {
for (i = 0; i < settings.Length; ++i) {
// TODO: is this safe on the ARM?
byte* p = &pv[i].int8;
settings[i].value = (IntPtr) p;
}
handle = CTParagraphStyleCreate (settings, settings.Length);
}
i = 0;
foreach (var e in specifiers) {
e.Dispose (values, i);
}
return handle;
}
public CTParagraphStyle ()
: this (null)
{
}
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTParagraphStyleCreateCopy (IntPtr paragraphStyle);
public CTParagraphStyle Clone ()
{
return new CTParagraphStyle (CTParagraphStyleCreateCopy (handle), true);
}
#endregion
#region Paragraph Style Access
[DllImport (Constants.CoreTextLibrary)]
static extern unsafe bool CTParagraphStyleGetValueForSpecifier (IntPtr paragraphStyle, CTParagraphStyleSpecifier spec, uint valueBufferSize, void* valueBuffer);
public unsafe CTTextTab[] GetTabStops ()
{
IntPtr cfArrayRef;
if (!CTParagraphStyleGetValueForSpecifier (handle, CTParagraphStyleSpecifier.TabStops, (uint) IntPtr.Size, (void*) &cfArrayRef))
throw new InvalidOperationException ("Unable to get property value.");
if (cfArrayRef == IntPtr.Zero)
return new CTTextTab [0];
return NSArray.ArrayFromHandle (cfArrayRef, p => new CTTextTab (p, false));
}
public CTTextAlignment Alignment {
get {return (CTTextAlignment) GetByteValue (CTParagraphStyleSpecifier.Alignment);}
}
unsafe byte GetByteValue (CTParagraphStyleSpecifier spec)
{
byte value;
if (!CTParagraphStyleGetValueForSpecifier (handle, spec, sizeof (byte), &value))
throw new InvalidOperationException ("Unable to get property value.");
return value;
}
public CTLineBreakMode LineBreakMode {
get {return (CTLineBreakMode) GetByteValue (CTParagraphStyleSpecifier.Alignment);}
}
public CTWritingDirection BaseWritingDirection {
get {return (CTWritingDirection) GetByteValue (CTParagraphStyleSpecifier.Alignment);}
}
public float FirstLineHeadIndent {
get {return GetFloatValue (CTParagraphStyleSpecifier.FirstLineHeadIndent);}
}
unsafe float GetFloatValue (CTParagraphStyleSpecifier spec)
{
float value;
if (!CTParagraphStyleGetValueForSpecifier (handle, spec, sizeof (float), &value))
throw new InvalidOperationException ("Unable to get property value.");
return value;
}
public float HeadIndent {
get {return GetFloatValue (CTParagraphStyleSpecifier.HeadIndent);}
}
public float TailIndent {
get {return GetFloatValue (CTParagraphStyleSpecifier.TailIndent);}
}
public float DefaultTabInterval {
get {return GetFloatValue (CTParagraphStyleSpecifier.DefaultTabInterval);}
}
public float LineHeightMultiple {
get {return GetFloatValue (CTParagraphStyleSpecifier.LineHeightMultiple);}
}
public float MaximumLineHeight {
get {return GetFloatValue (CTParagraphStyleSpecifier.MaximumLineHeight);}
}
public float MinimumLineHeight {
get {return GetFloatValue (CTParagraphStyleSpecifier.MinimumLineHeight);}
}
public float LineSpacing {
get {return GetFloatValue (CTParagraphStyleSpecifier.LineSpacing);}
}
public float ParagraphSpacing {
get {return GetFloatValue (CTParagraphStyleSpecifier.ParagraphSpacing);}
}
public float ParagraphSpacingBefore {
get {return GetFloatValue (CTParagraphStyleSpecifier.ParagraphSpacingBefore);}
}
#endregion
}
}
| |
#region copyright
// VZF
// Copyright (C) 2014-2016 Vladimir Zakharov
//
// http://www.code.coolhobby.ru/
// File DB.cs created on 2.6.2015 in 6:31 AM.
// Last changed on 5.21.2016 in 1:12 PM.
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#endregion
namespace YAF.Providers.Membership
{
using System;
using System.Data;
using System.Web.Security;
using YAF.Classes;
using YAF.Classes.Pattern;
using YAF.Core;
using VZF.Data.DAL;
public class MySQLDB
{
public static MySQLDB Current
{
get
{
return PageSingleton<MySQLDB>.Instance;
}
}
public void ChangePassword(string connectionStringName, string appName, string userName, string newPassword, string newSalt, int passwordFormat, string newPasswordAnswer)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
// sc.DataSource.ProviderName
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserName", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_Password", newPassword));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PasswordSalt", newSalt));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PasswordFormat", passwordFormat));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PasswordAnswer", newPasswordAnswer));
sc.CommandText.AppendObjectQuery("prov_changepassword", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
}
}
public void ChangePasswordQuestionAndAnswer(string connectionStringName, string appName, string userName, string passwordQuestion, string passwordAnswer)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
// sc.DataSource.ProviderName
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserName", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PasswordQuestion", passwordQuestion));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PasswordAnswer", passwordAnswer));
sc.CommandText.AppendObjectQuery("prov_changepasswordquestionandanswer", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
}
}
public void CreateUser(string connectionStringName, string appName, string userName, string password, string passwordSalt, int passwordFormat, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserName", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_Password", password));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PasswordSalt", passwordSalt));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PasswordFormat", passwordFormat.ToString()));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_Email", email));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PasswordQuestion", passwordQuestion));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PasswordAnswer", passwordAnswer));
sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_IsApproved", isApproved));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserKey", providerUserKey, ParameterDirection.InputOutput));
// sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "I_UTCTIMESTAMP", DateTime.UtcNow));
sc.CommandText.AppendObjectQuery("prov_createuser", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure, true);
providerUserKey = sc.Parameters["i_UserKey"].Value;
}
}
public void DeleteUser(string connectionStringName, string appName, string userName, bool deleteAllRelatedData)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserName", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_DeleteAllRelated", deleteAllRelatedData));
sc.CommandText.AppendObjectQuery("prov_deleteuser", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
}
}
public DataTable FindUsersByEmail(string connectionStringName, string appName, string emailToMatch, int pageIndex, int pageSize)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_EmailAddress", emailToMatch));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_PageIndex", pageIndex));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_PageSize", pageSize));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_TotalRecords", 0, ParameterDirection.Output));
sc.CommandText.AppendObjectQuery("prov_findusersbyemail", connectionStringName);
return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false);
}
}
public DataTable FindUsersByName(string connectionStringName, string appName, string usernameToMatch, int pageIndex, int pageSize)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserName", usernameToMatch));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_PageIndex", pageIndex));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_PageSize", pageSize));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_TotalRecords", 0, ParameterDirection.Output));
sc.CommandText.AppendObjectQuery("prov_findusersbyname", connectionStringName);
return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false);
}
}
public DataTable GetAllUsers(string connectionStringName, string appName, int pageIndex, int pageSize)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_PageIndex", pageIndex));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_PageSize", pageSize));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_TotalRecords", 0, ParameterDirection.Output));
sc.CommandText.AppendObjectQuery("prov_getallusers", connectionStringName);
return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false);
}
}
public int GetNumberOfUsersOnline(string connectionStringName, string appName, int TimeWindow)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_TimeWindow", TimeWindow));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_CurrentTimeUtc", DateTime.UtcNow));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_ReturnValue", null, ParameterDirection.ReturnValue));
sc.CommandText.AppendObjectQuery("prov_getnumberofusersonline", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
return Convert.ToInt32(sc.Parameters["i_ReturnValue"].Value);
}
}
public DataRow GetUser(string connectionStringName, string appName, object providerUserKey, string userName, bool userIsOnline)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
if (providerUserKey != null)
{
providerUserKey = MySqlHelpers.GuidConverter(new Guid(providerUserKey.ToString()));
}
// sc.DataSource.ProviderName
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserName", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserKey", providerUserKey));
sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_UserIsOnline", userIsOnline));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "I_UTCTIMESTAMP", DateTime.UtcNow));
sc.CommandText.AppendObjectQuery("prov_getuser", connectionStringName);
using (var dt = sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, true))
{
return dt.Rows.Count > 0 ? dt.Rows[0] : null;
}
}
}
public DataTable GetUserPasswordInfo(string connectionStringName, string appName, string userName, bool updateUser)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserName", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserKey", DBNull.Value));
sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_UserIsOnline", updateUser));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "I_UTCTIMESTAMP", DateTime.UtcNow));
sc.CommandText.AppendObjectQuery("prov_getuser", connectionStringName);
return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false);
}
}
public DataTable GetUserNameByEmail(string connectionStringName, string appName, string email)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_Email", email));
sc.CommandText.AppendObjectQuery("prov_getusernamebyemail", connectionStringName);
return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false);
}
}
public void ResetPassword(string connectionStringName, string appName, string userName, string password, string passwordSalt, int passwordFormat, int maxInvalidPasswordAttempts, int passwordAttemptWindow)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserName", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_Password", password));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PasswordSalt", passwordSalt));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PasswordFormat", passwordFormat));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_MaxInvalidAttempts", maxInvalidPasswordAttempts));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_passwordattemptwindow", passwordAttemptWindow));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_CurrentTimeUtc", DateTime.UtcNow));
sc.CommandText.AppendObjectQuery("prov_resetpassword", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
}
}
public void UnlockUser(string connectionStringName, string appName, string userName)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserName", userName));
sc.CommandText.AppendObjectQuery("prov_unlockuser", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
}
}
public int UpdateUser(string connectionStringName, object appName, MembershipUser user, bool requiresUniqueEmail)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
object providerUserKey = null;
if (user.ProviderUserKey != null)
{
providerUserKey = MySqlHelpers.GuidConverter(new Guid(user.ProviderUserKey.ToString())).ToString();
}
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserKey", providerUserKey));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserName", user.UserName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_Email", user.Email));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_Comment", user.Comment));
sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_IsApproved", user.IsApproved));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_LastLogin", user.LastLoginDate));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_LastActivity", user.LastActivityDate));
sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_UniqueEmail", requiresUniqueEmail));
sc.CommandText.AppendObjectQuery("prov_updateuser", connectionStringName);
return Convert.ToInt32(sc.ExecuteScalar(CommandType.StoredProcedure));
}
}
public void UpgradeMembership(int previousVersion, int newVersion)
{
UpgradeMembership(VzfMySqlMembershipProvider.ConnectionStringName, previousVersion, newVersion);
}
public void UpgradeMembership(string connectionStringName, int previousVersion, int newVersion)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
// sc.DataSource.ProviderName
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PreviousVersion", previousVersion));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_NewVersion", newVersion));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_UTCTIMESTAMP", DateTime.UtcNow));
sc.CommandText.AppendObjectQuery("prov_upgrade", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace XenAPI
{
/// <summary>
/// A virtual TPM device
/// First published in XenServer 4.0.
/// </summary>
public partial class VTPM : XenObject<VTPM>
{
public VTPM()
{
}
public VTPM(string uuid,
XenRef<VM> VM,
XenRef<VM> backend)
{
this.uuid = uuid;
this.VM = VM;
this.backend = backend;
}
/// <summary>
/// Creates a new VTPM from a Proxy_VTPM.
/// </summary>
/// <param name="proxy"></param>
public VTPM(Proxy_VTPM proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(VTPM update)
{
uuid = update.uuid;
VM = update.VM;
backend = update.backend;
}
internal void UpdateFromProxy(Proxy_VTPM proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM);
backend = proxy.backend == null ? null : XenRef<VM>.Create(proxy.backend);
}
public Proxy_VTPM ToProxy()
{
Proxy_VTPM result_ = new Proxy_VTPM();
result_.uuid = uuid ?? "";
result_.VM = VM ?? "";
result_.backend = backend ?? "";
return result_;
}
/// <summary>
/// Creates a new VTPM from a Hashtable.
/// </summary>
/// <param name="table"></param>
public VTPM(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
VM = Marshalling.ParseRef<VM>(table, "VM");
backend = Marshalling.ParseRef<VM>(table, "backend");
}
public bool DeepEquals(VTPM other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._VM, other._VM) &&
Helper.AreEqual2(this._backend, other._backend);
}
public override string SaveChanges(Session session, string opaqueRef, VTPM server)
{
if (opaqueRef == null)
{
Proxy_VTPM p = this.ToProxy();
return session.proxy.vtpm_create(session.uuid, p).parse();
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given VTPM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vtpm">The opaque_ref of the given vtpm</param>
public static VTPM get_record(Session session, string _vtpm)
{
return new VTPM((Proxy_VTPM)session.proxy.vtpm_get_record(session.uuid, _vtpm ?? "").parse());
}
/// <summary>
/// Get a reference to the VTPM instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VTPM> get_by_uuid(Session session, string _uuid)
{
return XenRef<VTPM>.Create(session.proxy.vtpm_get_by_uuid(session.uuid, _uuid ?? "").parse());
}
/// <summary>
/// Create a new VTPM instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<VTPM> create(Session session, VTPM _record)
{
return XenRef<VTPM>.Create(session.proxy.vtpm_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new VTPM instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, VTPM _record)
{
return XenRef<Task>.Create(session.proxy.async_vtpm_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified VTPM instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vtpm">The opaque_ref of the given vtpm</param>
public static void destroy(Session session, string _vtpm)
{
session.proxy.vtpm_destroy(session.uuid, _vtpm ?? "").parse();
}
/// <summary>
/// Destroy the specified VTPM instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vtpm">The opaque_ref of the given vtpm</param>
public static XenRef<Task> async_destroy(Session session, string _vtpm)
{
return XenRef<Task>.Create(session.proxy.async_vtpm_destroy(session.uuid, _vtpm ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VTPM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vtpm">The opaque_ref of the given vtpm</param>
public static string get_uuid(Session session, string _vtpm)
{
return (string)session.proxy.vtpm_get_uuid(session.uuid, _vtpm ?? "").parse();
}
/// <summary>
/// Get the VM field of the given VTPM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vtpm">The opaque_ref of the given vtpm</param>
public static XenRef<VM> get_VM(Session session, string _vtpm)
{
return XenRef<VM>.Create(session.proxy.vtpm_get_vm(session.uuid, _vtpm ?? "").parse());
}
/// <summary>
/// Get the backend field of the given VTPM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vtpm">The opaque_ref of the given vtpm</param>
public static XenRef<VM> get_backend(Session session, string _vtpm)
{
return XenRef<VM>.Create(session.proxy.vtpm_get_backend(session.uuid, _vtpm ?? "").parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// the virtual machine
/// </summary>
public virtual XenRef<VM> VM
{
get { return _VM; }
set
{
if (!Helper.AreEqual(value, _VM))
{
_VM = value;
Changed = true;
NotifyPropertyChanged("VM");
}
}
}
private XenRef<VM> _VM;
/// <summary>
/// the domain where the backend is located
/// </summary>
public virtual XenRef<VM> backend
{
get { return _backend; }
set
{
if (!Helper.AreEqual(value, _backend))
{
_backend = value;
Changed = true;
NotifyPropertyChanged("backend");
}
}
}
private XenRef<VM> _backend;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.